vtcode_commons/runtime_diagnostics.rs
1//! Stable Tokio runtime diagnostics (no `tokio_unstable` required).
2//!
3//! Implements step 1 of the fast-Tokio principles: measure first. We capture
4//! the stable subset of [`tokio::runtime::RuntimeMetrics`] — worker count,
5//! alive tasks, global (injection) queue depth, and total worker busy time.
6//! The article's headline signal is the global queue staying deep ("in a
7//! healthy application it should generally stay close to empty"); that metric
8//! is stable, so it ships here.
9//!
10//! Per-worker local-queue depth, steal/overflow counts, blocking-pool depth,
11//! and the poll-time/schedule-latency histograms are all gated behind
12//! `RUSTFLAGS="--cfg tokio_unstable"` in current Tokio. Enabling that cfg
13//! changes the whole dependency graph build, so it stays opt-in follow-up work
14//! rather than a default here.
15
16use std::time::Duration;
17use tokio::runtime::Handle;
18
19/// Env var enabling periodic runtime snapshot logs.
20const RUNTIME_METRICS_ENV: &str = "VTCODE_RUNTIME_METRICS";
21
22/// Snapshot of stable runtime counters at one instant.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub struct RuntimeSnapshot {
25 /// Worker threads configured on the runtime.
26 pub workers_len: usize,
27 /// Currently alive tasks.
28 pub alive_tasks_len: usize,
29 /// Tasks pending in the global (injection) queue.
30 pub global_queue_depth_len: usize,
31 /// Sum of per-worker busy time since runtime creation.
32 pub total_busy: Duration,
33}
34
35/// Returns true when runtime diagnostics logging is enabled.
36///
37/// Enabled by `VTCODE_RUNTIME_METRICS=1|true|yes|on|debug` or when
38/// `VTCODE_STARTUP_TRACE=1` (startup trace already implies diagnostics).
39#[must_use]
40pub fn runtime_diagnostics_enabled() -> bool {
41 env_flag_enabled(RUNTIME_METRICS_ENV) || startup_trace_enabled()
42}
43
44fn env_flag_enabled(var_name: &str) -> bool {
45 std::env::var(var_name).ok().is_some_and(|value| {
46 matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on" | "debug")
47 })
48}
49
50fn startup_trace_enabled() -> bool {
51 std::env::var("VTCODE_STARTUP_TRACE").is_ok_and(|value| value == "1")
52}
53
54/// Env var that overrides the Tokio worker-thread count.
55const RUNTIME_WORKERS_ENV: &str = "VTCODE_RUNTIME_WORKERS";
56
57/// Resolve an explicit worker-thread count for the main runtime.
58///
59/// Returns `None` when unset or not a positive integer, so the default
60/// one-worker-per-core behaviour is preserved. Reserving cores for non-Tokio
61/// background work is the isolation lever the fast-Tokio guidance recommends
62/// ("you rarely need every core for Tokio"); operators that co-locate VT Code
63/// with other processes can lower this without rebuilding.
64#[must_use]
65pub fn configured_worker_threads() -> Option<usize> {
66 std::env::var(RUNTIME_WORKERS_ENV)
67 .ok()
68 .and_then(|value| value.trim().parse::<usize>().ok())
69 .filter(|workers| *workers > 0)
70}
71
72/// Capture stable counters from a runtime handle.
73#[must_use]
74pub fn snapshot(handle: &Handle) -> RuntimeSnapshot {
75 let metrics = handle.metrics();
76 RuntimeSnapshot {
77 workers_len: metrics.num_workers(),
78 alive_tasks_len: metrics.num_alive_tasks(),
79 global_queue_depth_len: metrics.global_queue_depth(),
80 total_busy: total_busy(&metrics),
81 }
82}
83
84#[cfg(target_has_atomic = "64")]
85fn total_busy(metrics: &tokio::runtime::RuntimeMetrics) -> Duration {
86 let mut busy = Duration::ZERO;
87 for worker in 0..metrics.num_workers() {
88 busy = busy.saturating_add(metrics.worker_total_busy_duration(worker));
89 }
90 busy
91}
92
93#[cfg(not(target_has_atomic = "64"))]
94fn total_busy(_metrics: &tokio::runtime::RuntimeMetrics) -> Duration {
95 // Worker busy duration requires 64-bit atomics; report zero otherwise.
96 Duration::ZERO
97}
98
99/// Log one snapshot at `DEBUG` level; no-op unless diagnostics are enabled.
100///
101/// Callers should gate periodic reporting on [`runtime_diagnostics_enabled`]
102/// to keep the hot path free when observability is off.
103pub fn log_snapshot(handle: &Handle, context: &str) {
104 if !runtime_diagnostics_enabled() {
105 return;
106 }
107 let snapshot = snapshot(handle);
108 let worker_busy_ms = u64::try_from(snapshot.total_busy.as_millis()).unwrap_or(u64::MAX);
109 tracing::debug!(
110 target = "vtcode.runtime",
111 context,
112 workers = snapshot.workers_len,
113 alive_tasks = snapshot.alive_tasks_len,
114 global_queue_depth = snapshot.global_queue_depth_len,
115 worker_busy_ms,
116 "tokio runtime snapshot"
117 );
118}
119
120/// Default interval between periodic runtime snapshots.
121const REPORT_INTERVAL: Duration = Duration::from_secs(60);
122
123/// Spawn a low-frequency reporter for long-lived processes.
124///
125/// The reporter ticks every 60s and logs via [`log_snapshot`]. Only spawns when
126/// [`runtime_diagnostics_enabled`] is true, otherwise returns `None`. Dropping
127/// the returned handle detaches the task; it is cancelled when the runtime
128/// drops.
129pub fn spawn_periodic_reporter(handle: &Handle) -> Option<tokio::task::JoinHandle<()>> {
130 if !runtime_diagnostics_enabled() {
131 return None;
132 }
133 Some(spawn_reporter(handle, REPORT_INTERVAL))
134}
135
136/// Spawn the reporter on the supplied runtime handle.
137///
138/// Uses [`Handle::spawn`] rather than [`tokio::spawn`]: bootstrap starts the
139/// reporter before `Runtime::block_on` establishes an ambient runtime context,
140/// and `tokio::spawn` panics when no runtime context is active (the same reason
141/// `agent::probe` uses `handle.spawn_blocking`).
142fn spawn_reporter(handle: &Handle, interval: Duration) -> tokio::task::JoinHandle<()> {
143 let metrics_handle = handle.clone();
144 handle.spawn(async move {
145 let mut ticker = tokio::time::interval(interval);
146 // Skip bursts of missed ticks rather than replaying them.
147 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
148 // `interval` yields immediately on its first tick; consume it so the
149 // first periodic snapshot lands one interval after startup instead of
150 // duplicating the caller's boot snapshot.
151 let _ = ticker.tick().await;
152 loop {
153 let _ = ticker.tick().await;
154 log_snapshot(&metrics_handle, "periodic");
155 }
156 })
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 #[test]
164 fn absent_env_flag_is_disabled() {
165 // `VTCODE_RUNTIME_METRICS_TEST_ABSENT_XYZ` is never set, so the flag
166 // parser must report disabled without mutating process env.
167 assert!(!env_flag_enabled("VTCODE_RUNTIME_METRICS_TEST_ABSENT_XYZ"));
168 }
169
170 #[test]
171 fn absent_worker_override_uses_default() {
172 // No override is configured in the isolated test env, so the default
173 // one-worker-per-core behaviour must be preserved.
174 if std::env::var("VTCODE_RUNTIME_WORKERS").is_err() {
175 assert_eq!(configured_worker_threads(), None);
176 }
177 }
178
179 #[tokio::test]
180 async fn snapshot_reflects_current_runtime() {
181 let snapshot = snapshot(&Handle::current());
182 // At least one worker exists on either runtime flavor.
183 assert!(snapshot.workers_len >= 1);
184 }
185
186 #[tokio::test]
187 async fn log_snapshot_is_quiet_when_disabled() {
188 // Must not panic and must stay a no-op when diagnostics are off.
189 log_snapshot(&Handle::current(), "test");
190 }
191
192 #[test]
193 fn reporter_spawns_outside_ambient_runtime_context() {
194 // Bootstrap starts the reporter before `Runtime::block_on`, so spawning
195 // must go through the supplied handle: `tokio::spawn` panics with
196 // "there is no reactor running" when no runtime context is active.
197 let runtime = tokio::runtime::Builder::new_current_thread()
198 .build()
199 .expect("current-thread runtime");
200 let reporter = spawn_reporter(runtime.handle(), Duration::from_secs(3600));
201 reporter.abort();
202 }
203}