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 startup
38/// tracing is on (`VTCODE_STARTUP_TRACE`, same canonical set — startup trace
39/// already implies diagnostics).
40#[must_use]
41pub fn runtime_diagnostics_enabled() -> bool {
42 crate::utils::env_flag_enabled(RUNTIME_METRICS_ENV) || crate::startup_trace::startup_trace_enabled()
43}
44
45/// Env var that overrides the Tokio worker-thread count.
46const RUNTIME_WORKERS_ENV: &str = "VTCODE_RUNTIME_WORKERS";
47
48/// Resolve an explicit worker-thread count for the main runtime.
49///
50/// Returns `None` when unset or not a positive integer, so the default
51/// one-worker-per-core behaviour is preserved. Reserving cores for non-Tokio
52/// background work is the isolation lever the fast-Tokio guidance recommends
53/// ("you rarely need every core for Tokio"); operators that co-locate VT Code
54/// with other processes can lower this without rebuilding.
55#[must_use]
56pub fn configured_worker_threads() -> Option<usize> {
57 std::env::var(RUNTIME_WORKERS_ENV)
58 .ok()
59 .and_then(|value| value.trim().parse::<usize>().ok())
60 .filter(|workers| *workers > 0)
61}
62
63/// Capture stable counters from a runtime handle.
64#[must_use]
65pub fn snapshot(handle: &Handle) -> RuntimeSnapshot {
66 let metrics = handle.metrics();
67 RuntimeSnapshot {
68 workers_len: metrics.num_workers(),
69 alive_tasks_len: metrics.num_alive_tasks(),
70 global_queue_depth_len: metrics.global_queue_depth(),
71 total_busy: total_busy(&metrics),
72 }
73}
74
75#[cfg(target_has_atomic = "64")]
76fn total_busy(metrics: &tokio::runtime::RuntimeMetrics) -> Duration {
77 let mut busy = Duration::ZERO;
78 for worker in 0..metrics.num_workers() {
79 busy = busy.saturating_add(metrics.worker_total_busy_duration(worker));
80 }
81 busy
82}
83
84#[cfg(not(target_has_atomic = "64"))]
85fn total_busy(_metrics: &tokio::runtime::RuntimeMetrics) -> Duration {
86 // Worker busy duration requires 64-bit atomics; report zero otherwise.
87 Duration::ZERO
88}
89
90/// Log one snapshot at `DEBUG` level; no-op unless diagnostics are enabled.
91///
92/// Callers should gate periodic reporting on [`runtime_diagnostics_enabled`]
93/// to keep the hot path free when observability is off.
94pub fn log_snapshot(handle: &Handle, context: &str) {
95 if !runtime_diagnostics_enabled() {
96 return;
97 }
98 let snapshot = snapshot(handle);
99 let worker_busy_ms = u64::try_from(snapshot.total_busy.as_millis()).unwrap_or(u64::MAX);
100 tracing::debug!(
101 target = "vtcode.runtime",
102 context,
103 workers = snapshot.workers_len,
104 alive_tasks = snapshot.alive_tasks_len,
105 global_queue_depth = snapshot.global_queue_depth_len,
106 worker_busy_ms,
107 "tokio runtime snapshot"
108 );
109}
110
111/// Default interval between periodic runtime snapshots.
112const REPORT_INTERVAL: Duration = Duration::from_secs(60);
113
114/// Spawn a low-frequency reporter for long-lived processes.
115///
116/// The reporter ticks every 60s and logs via [`log_snapshot`]. Only spawns when
117/// [`runtime_diagnostics_enabled`] is true, otherwise returns `None`. Dropping
118/// the returned handle detaches the task; it is cancelled when the runtime
119/// drops.
120pub fn spawn_periodic_reporter(handle: &Handle) -> Option<tokio::task::JoinHandle<()>> {
121 if !runtime_diagnostics_enabled() {
122 return None;
123 }
124 Some(spawn_reporter(handle, REPORT_INTERVAL))
125}
126
127/// Spawn the reporter on the supplied runtime handle.
128///
129/// Uses [`Handle::spawn`] rather than [`tokio::spawn`]: bootstrap starts the
130/// reporter before `Runtime::block_on` establishes an ambient runtime context,
131/// and `tokio::spawn` panics when no runtime context is active (the same reason
132/// `agent::probe` uses `handle.spawn_blocking`).
133fn spawn_reporter(handle: &Handle, interval: Duration) -> tokio::task::JoinHandle<()> {
134 let metrics_handle = handle.clone();
135 handle.spawn(async move {
136 let mut ticker = tokio::time::interval(interval);
137 // Skip bursts of missed ticks rather than replaying them.
138 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
139 // `interval` yields immediately on its first tick; consume it so the
140 // first periodic snapshot lands one interval after startup instead of
141 // duplicating the caller's boot snapshot.
142 let _ = ticker.tick().await;
143 loop {
144 let _ = ticker.tick().await;
145 log_snapshot(&metrics_handle, "periodic");
146 }
147 })
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 #[test]
155 fn absent_env_flag_is_disabled() {
156 // `VTCODE_RUNTIME_METRICS_TEST_ABSENT_XYZ` is never set, so the flag
157 // parser must report disabled without mutating process env.
158 assert!(!crate::utils::env_flag_enabled("VTCODE_RUNTIME_METRICS_TEST_ABSENT_XYZ"));
159 }
160
161 #[test]
162 fn absent_worker_override_uses_default() {
163 // No override is configured in the isolated test env, so the default
164 // one-worker-per-core behaviour must be preserved.
165 if std::env::var("VTCODE_RUNTIME_WORKERS").is_err() {
166 assert_eq!(configured_worker_threads(), None);
167 }
168 }
169
170 #[tokio::test]
171 async fn snapshot_reflects_current_runtime() {
172 let snapshot = snapshot(&Handle::current());
173 // At least one worker exists on either runtime flavor.
174 assert!(snapshot.workers_len >= 1);
175 }
176
177 #[tokio::test]
178 async fn log_snapshot_is_quiet_when_disabled() {
179 // Must not panic and must stay a no-op when diagnostics are off.
180 log_snapshot(&Handle::current(), "test");
181 }
182
183 #[test]
184 fn reporter_spawns_outside_ambient_runtime_context() {
185 // Bootstrap starts the reporter before `Runtime::block_on`, so spawning
186 // must go through the supplied handle: `tokio::spawn` panics with
187 // "there is no reactor running" when no runtime context is active.
188 let runtime = tokio::runtime::Builder::new_current_thread()
189 .build()
190 .expect("current-thread runtime");
191 let reporter = spawn_reporter(runtime.handle(), Duration::from_secs(3600));
192 reporter.abort();
193 }
194}