| 1 | //! Process-wide session accumulators. |
| 2 | //! |
| 3 | //! Atomics rather than a lock, because every bump happens on a hot path and |
| 4 | //! must cost nothing measurable. Every bump also happens at a **call site**, |
| 5 | //! never inside a conditionally-entered handler: a counter sited above an early |
| 6 | //! return is a landmine, and the natural future optimization — hoisting the |
| 7 | //! guard to the caller — silently zeroes it for exactly the users who do not |
| 8 | //! use that feature. |
| 9 | |
| 10 | use std::sync::Mutex; |
| 11 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 12 | |
| 13 | use crate::event::{Counters, Errors, Event, ModelCounters, TurnWall}; |
| 14 | |
| 15 | /// One session's accumulated counts. |
| 16 | #[derive(Debug, Default)] |
| 17 | pub struct SessionCounters { |
| 18 | turns: AtomicU32, |
| 19 | tool_calls: AtomicU32, |
| 20 | fleet_dispatch: AtomicU32, |
| 21 | workflow_run: AtomicU32, |
| 22 | subagent_spawn: AtomicU32, |
| 23 | mcp_server_connected: AtomicU32, |
| 24 | memory_search: AtomicU32, |
| 25 | approval_modal_shown: AtomicU32, |
| 26 | approval_auto_allowed: AtomicU32, |
| 27 | command_palette_open: AtomicU32, |
| 28 | |
| 29 | auth_preflight_failed: AtomicU32, |
| 30 | provider_http_4xx: AtomicU32, |
| 31 | provider_http_5xx: AtomicU32, |
| 32 | tool_denied_by_policy: AtomicU32, |
| 33 | tool_timeout: AtomicU32, |
| 34 | network_error: AtomicU32, |
| 35 | |
| 36 | turn_wall: Mutex<TurnWall>, |
| 37 | /// Sorted, deduplicated `ProviderKind::as_str()` values. `&'static str` |
| 38 | /// only: a `String` here would be the seam through which a customer's |
| 39 | /// `[providers.<name>]` table key reaches the wire. |
| 40 | providers: Mutex<Vec<&'static str>>, |
| 41 | models: Mutex<Vec<ModelSlot>>, |
| 42 | tools: Mutex<Vec<(&'static str, u32, u32)>>, |
| 43 | } |
| 44 | |
| 45 | #[derive(Debug)] |
| 46 | struct ModelSlot { |
| 47 | provider: &'static str, |
| 48 | model: String, |
| 49 | counters: ModelCounters, |
| 50 | turn_wall: TurnWall, |
| 51 | } |
| 52 | |
| 53 | /// At most this many distinct provider and model pairs per session; later |
| 54 | /// pairs are folded into the provider's `other` row. |
| 55 | const MAX_MODEL_ROWS: usize = 16; |
| 56 | |
| 57 | /// How one model turn ended. |
| 58 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 59 | pub enum TurnOutcome { |
| 60 | /// Completed. |
| 61 | Ok, |
| 62 | /// Failed. |
| 63 | Failed, |
| 64 | /// Interrupted by the user or the runtime. |
| 65 | Interrupted, |
| 66 | } |
| 67 | |
| 68 | /// Token counts for one model turn. |
| 69 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 70 | pub struct TurnTokens { |
| 71 | /// Input tokens, including cache reads. |
| 72 | pub input: u64, |
| 73 | /// Output tokens. |
| 74 | pub output: u64, |
| 75 | /// Input tokens read from the prompt cache. |
| 76 | pub cache_read: u64, |
| 77 | /// Input tokens written to the prompt cache. |
| 78 | pub cache_write: u64, |
| 79 | } |
| 80 | |
| 81 | /// Which counter to bump. A closed enum so a call site cannot invent a key. |
| 82 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 83 | pub enum Counter { |
| 84 | /// A model turn completed. |
| 85 | Turns, |
| 86 | /// A tool call was executed. |
| 87 | ToolCalls, |
| 88 | /// A fleet dispatch started. |
| 89 | FleetDispatch, |
| 90 | /// A `workflow_run` action was parsed and executed. |
| 91 | WorkflowRun, |
| 92 | /// A sub-agent was spawned. |
| 93 | SubagentSpawn, |
| 94 | /// An MCP server reached `connected`. |
| 95 | McpServerConnected, |
| 96 | /// A native-memory search ran. |
| 97 | MemorySearch, |
| 98 | /// An approval modal was shown. |
| 99 | ApprovalModalShown, |
| 100 | /// An approval was granted by an auto-allow rule. |
| 101 | ApprovalAutoAllowed, |
| 102 | /// The command palette was opened. |
| 103 | CommandPaletteOpen, |
| 104 | } |
| 105 | |
| 106 | /// Which error counter to bump. |
| 107 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 108 | pub enum ErrorCounter { |
| 109 | /// Credential preflight rejected the route. |
| 110 | AuthPreflightFailed, |
| 111 | /// Provider responded 4xx. |
| 112 | ProviderHttp4xx, |
| 113 | /// Provider responded 5xx. |
| 114 | ProviderHttp5xx, |
| 115 | /// A tool call was denied by policy. |
| 116 | ToolDeniedByPolicy, |
| 117 | /// A tool call timed out. |
| 118 | ToolTimeout, |
| 119 | /// A request failed below HTTP. |
| 120 | NetworkError, |
| 121 | } |
| 122 | |
| 123 | impl SessionCounters { |
| 124 | /// Bump a feature counter by one. |
| 125 | pub fn bump(&self, counter: Counter) { |
| 126 | self.slot(counter).fetch_add(1, Ordering::Relaxed); |
| 127 | } |
| 128 | |
| 129 | /// Bump an error counter by one. |
| 130 | pub fn bump_error(&self, counter: ErrorCounter) { |
| 131 | self.error_slot(counter).fetch_add(1, Ordering::Relaxed); |
| 132 | } |
| 133 | |
| 134 | /// Record one turn's wall-clock time in the histogram. |
| 135 | pub fn observe_turn_secs(&self, secs: u64) { |
| 136 | if let Ok(mut wall) = self.turn_wall.lock() { |
| 137 | wall.observe_secs(secs); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// Record that a provider was routed to. |
| 142 | /// |
| 143 | /// Takes a `ProviderKind` **by value**, never a `&str`: the four |
| 144 | /// persistence and label accessors that look like the natural seam all |
| 145 | /// return the customer's own `[providers.<name>]` table key when the route |
| 146 | /// is custom, and `/status` already prints it. `ProviderKind::Custom` |
| 147 | /// yields the literal `"custom"` and nothing else. |
| 148 | pub fn record_provider(&self, provider: codewhale_config::ProviderKind) { |
| 149 | let name = provider.as_str(); |
| 150 | if let Ok(mut providers) = self.providers.lock() |
| 151 | && !providers.contains(&name) |
| 152 | { |
| 153 | providers.push(name); |
| 154 | providers.sort_unstable(); |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// Record one model turn: its provider, model, outcome, tokens and wall time. |
| 159 | pub fn record_model_turn( |
| 160 | &self, |
| 161 | provider: codewhale_config::ProviderKind, |
| 162 | model: &str, |
| 163 | outcome: TurnOutcome, |
| 164 | tokens: TurnTokens, |
| 165 | secs: u64, |
| 166 | ) { |
| 167 | let provider = provider.as_str(); |
| 168 | let mut model = crate::event::reported_model_id(model); |
| 169 | let Ok(mut models) = self.models.lock() else { |
| 170 | return; |
| 171 | }; |
| 172 | let known = models |
| 173 | .iter() |
| 174 | .any(|slot| slot.provider == provider && slot.model == model); |
| 175 | if !known && models.len() >= MAX_MODEL_ROWS { |
| 176 | model = "other".to_string(); |
| 177 | } |
| 178 | let index = match models |
| 179 | .iter() |
| 180 | .position(|slot| slot.provider == provider && slot.model == model) |
| 181 | { |
| 182 | Some(index) => index, |
| 183 | None => { |
| 184 | models.push(ModelSlot { |
| 185 | provider, |
| 186 | model, |
| 187 | counters: ModelCounters::default(), |
| 188 | turn_wall: TurnWall::default(), |
| 189 | }); |
| 190 | models.len() - 1 |
| 191 | } |
| 192 | }; |
| 193 | let slot = &mut models[index]; |
| 194 | let counters = &mut slot.counters; |
| 195 | match outcome { |
| 196 | TurnOutcome::Ok => counters.turns_ok = counters.turns_ok.saturating_add(1), |
| 197 | TurnOutcome::Failed => counters.turns_failed = counters.turns_failed.saturating_add(1), |
| 198 | TurnOutcome::Interrupted => { |
| 199 | counters.turns_interrupted = counters.turns_interrupted.saturating_add(1); |
| 200 | } |
| 201 | } |
| 202 | counters.input_tokens = counters.input_tokens.saturating_add(tokens.input); |
| 203 | counters.output_tokens = counters.output_tokens.saturating_add(tokens.output); |
| 204 | counters.cache_read_tokens = counters.cache_read_tokens.saturating_add(tokens.cache_read); |
| 205 | counters.cache_write_tokens = counters |
| 206 | .cache_write_tokens |
| 207 | .saturating_add(tokens.cache_write); |
| 208 | slot.turn_wall.observe_secs(secs); |
| 209 | } |
| 210 | |
| 211 | /// Record one tool call by name. `is_mcp` marks an MCP pool tool. |
| 212 | pub fn record_tool_call(&self, name: &str, is_mcp: bool, failed: bool) { |
| 213 | let tool = crate::event::reported_tool_name(name, is_mcp); |
| 214 | let Ok(mut tools) = self.tools.lock() else { |
| 215 | return; |
| 216 | }; |
| 217 | let index = match tools.iter().position(|(known, _, _)| *known == tool) { |
| 218 | Some(index) => index, |
| 219 | None => { |
| 220 | tools.push((tool, 0, 0)); |
| 221 | tools.len() - 1 |
| 222 | } |
| 223 | }; |
| 224 | let row = &mut tools[index]; |
| 225 | row.1 = row.1.saturating_add(1); |
| 226 | if failed { |
| 227 | row.2 = row.2.saturating_add(1); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// The `model_usage` and `tool_usage` events for this session so far. |
| 232 | #[must_use] |
| 233 | pub fn usage_events(&self) -> Vec<Event> { |
| 234 | let mut events = Vec::new(); |
| 235 | if let Ok(models) = self.models.lock() { |
| 236 | events.extend(models.iter().map(|slot| Event::ModelUsage { |
| 237 | provider: slot.provider.to_string(), |
| 238 | model: slot.model.clone(), |
| 239 | counters: slot.counters, |
| 240 | turn_wall: slot.turn_wall, |
| 241 | })); |
| 242 | } |
| 243 | if let Ok(tools) = self.tools.lock() { |
| 244 | events.extend(tools.iter().map(|(tool, calls, errors)| Event::ToolUsage { |
| 245 | tool: (*tool).to_string(), |
| 246 | calls: *calls, |
| 247 | errors: *errors, |
| 248 | })); |
| 249 | } |
| 250 | events |
| 251 | } |
| 252 | |
| 253 | /// Snapshot the feature counters. |
| 254 | #[must_use] |
| 255 | pub fn counters(&self) -> Counters { |
| 256 | Counters { |
| 257 | turns: self.turns.load(Ordering::Relaxed), |
| 258 | tool_calls: self.tool_calls.load(Ordering::Relaxed), |
| 259 | fleet_dispatch: self.fleet_dispatch.load(Ordering::Relaxed), |
| 260 | workflow_run: self.workflow_run.load(Ordering::Relaxed), |
| 261 | subagent_spawn: self.subagent_spawn.load(Ordering::Relaxed), |
| 262 | mcp_server_connected: self.mcp_server_connected.load(Ordering::Relaxed), |
| 263 | memory_search: self.memory_search.load(Ordering::Relaxed), |
| 264 | approval_modal_shown: self.approval_modal_shown.load(Ordering::Relaxed), |
| 265 | approval_auto_allowed: self.approval_auto_allowed.load(Ordering::Relaxed), |
| 266 | command_palette_open: self.command_palette_open.load(Ordering::Relaxed), |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Snapshot the error counters. |
| 271 | #[must_use] |
| 272 | pub fn errors(&self) -> Errors { |
| 273 | Errors { |
| 274 | auth_preflight_failed: self.auth_preflight_failed.load(Ordering::Relaxed), |
| 275 | provider_http_4xx: self.provider_http_4xx.load(Ordering::Relaxed), |
| 276 | provider_http_5xx: self.provider_http_5xx.load(Ordering::Relaxed), |
| 277 | tool_denied_by_policy: self.tool_denied_by_policy.load(Ordering::Relaxed), |
| 278 | tool_timeout: self.tool_timeout.load(Ordering::Relaxed), |
| 279 | network_error: self.network_error.load(Ordering::Relaxed), |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /// Snapshot the turn wall-clock histogram. |
| 284 | #[must_use] |
| 285 | pub fn turn_wall(&self) -> TurnWall { |
| 286 | self.turn_wall.lock().map(|wall| *wall).unwrap_or_default() |
| 287 | } |
| 288 | |
| 289 | /// Snapshot the sorted, deduplicated provider set. |
| 290 | #[must_use] |
| 291 | pub fn providers(&self) -> Vec<String> { |
| 292 | self.providers |
| 293 | .lock() |
| 294 | .map(|providers| providers.iter().map(|name| (*name).to_string()).collect()) |
| 295 | .unwrap_or_default() |
| 296 | } |
| 297 | |
| 298 | fn slot(&self, counter: Counter) -> &AtomicU32 { |
| 299 | match counter { |
| 300 | Counter::Turns => &self.turns, |
| 301 | Counter::ToolCalls => &self.tool_calls, |
| 302 | Counter::FleetDispatch => &self.fleet_dispatch, |
| 303 | Counter::WorkflowRun => &self.workflow_run, |
| 304 | Counter::SubagentSpawn => &self.subagent_spawn, |
| 305 | Counter::McpServerConnected => &self.mcp_server_connected, |
| 306 | Counter::MemorySearch => &self.memory_search, |
| 307 | Counter::ApprovalModalShown => &self.approval_modal_shown, |
| 308 | Counter::ApprovalAutoAllowed => &self.approval_auto_allowed, |
| 309 | Counter::CommandPaletteOpen => &self.command_palette_open, |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | fn error_slot(&self, counter: ErrorCounter) -> &AtomicU32 { |
| 314 | match counter { |
| 315 | ErrorCounter::AuthPreflightFailed => &self.auth_preflight_failed, |
| 316 | ErrorCounter::ProviderHttp4xx => &self.provider_http_4xx, |
| 317 | ErrorCounter::ProviderHttp5xx => &self.provider_http_5xx, |
| 318 | ErrorCounter::ToolDeniedByPolicy => &self.tool_denied_by_policy, |
| 319 | ErrorCounter::ToolTimeout => &self.tool_timeout, |
| 320 | ErrorCounter::NetworkError => &self.network_error, |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | /// Classify a provider HTTP status into the 4xx or 5xx counter, if either |
| 326 | /// applies. Captured from `status.as_u16() / 100` **before** the error is |
| 327 | /// built — every `LlmError` variant carries the raw provider body verbatim. |
| 328 | #[must_use] |
| 329 | pub fn http_status_counter(status: u16) -> Option<ErrorCounter> { |
| 330 | match status / 100 { |
| 331 | 4 => Some(ErrorCounter::ProviderHttp4xx), |
| 332 | 5 => Some(ErrorCounter::ProviderHttp5xx), |
| 333 | _ => None, |
| 334 | } |
| 335 | } |
| 336 |