| 1 | //! Default-on, user-disableable aggregate product usage counting for Codewhale. |
| 2 | //! |
| 3 | //! The whole of what this crate may ever send is [`event`]. The whole of what |
| 4 | //! decides whether it may send anything is [`decision`]. Nothing else in the |
| 5 | //! tree is permitted to construct a payload or to reach the wire, and nothing in |
| 6 | //! here reads a prompt, a completion, a tool argument, a file, a path, a git |
| 7 | //! remote, a branch, a custom or private model id, a provider table name, an MCP server name, an |
| 8 | //! approval rule, an error body, a panic message, or a credential. |
| 9 | //! |
| 10 | //! # The shape of the guarantee |
| 11 | //! |
| 12 | //! Permission is a **value**, not a convention. [`decide`] is the only constructor |
| 13 | //! of [`TelemetryConsent`]; [`init`] takes one by value and there is no |
| 14 | //! bool-taking sibling. Six init sites cannot each drift from the predicate, |
| 15 | //! because they never see the predicate. |
| 16 | //! |
| 17 | //! Arming is a **`OnceLock`**, consulted by every write path including |
| 18 | //! [`record_blocking`]. This matters because the process panic hook is installed |
| 19 | //! before the command line is even parsed, long before any config resolution: it |
| 20 | //! cannot consult a resolved value, but it can consult a lock that is by |
| 21 | //! construction empty until resolution completes. A disabled user's panic |
| 22 | //! therefore writes nothing and creates no directory. |
| 23 | //! |
| 24 | //! Arming also gives the process its own spool file and, when the machine was |
| 25 | //! opted out until now, deletes every spool left from before. |
| 26 | //! |
| 27 | //! # Failure posture |
| 28 | //! |
| 29 | //! Fail-open is absolute. Every fallible step ends in `.ok()?` or `let _ =`. |
| 30 | //! Nothing here returns an error to a caller, blocks a turn, blocks a tool, or |
| 31 | //! blocks process exit. Telemetry that costs a user their session is worse than |
| 32 | //! no telemetry. |
| 33 | |
| 34 | #![deny(missing_docs)] |
| 35 | |
| 36 | mod actor; |
| 37 | pub mod buffer; |
| 38 | pub mod client; |
| 39 | pub mod counters; |
| 40 | pub mod decision; |
| 41 | pub mod envelope; |
| 42 | pub mod event; |
| 43 | pub mod notice; |
| 44 | pub mod spool; |
| 45 | |
| 46 | #[cfg(test)] |
| 47 | mod tests; |
| 48 | |
| 49 | use std::sync::OnceLock; |
| 50 | use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; |
| 51 | use std::time::{Duration, Instant}; |
| 52 | |
| 53 | pub use actor::{BATCH_MAX_BYTES, BATCH_MAX_EVENTS, FlushOutcome}; |
| 54 | pub use counters::{Counter, ErrorCounter, SessionCounters, TurnOutcome, TurnTokens}; |
| 55 | pub use decision::{ |
| 56 | EndpointError, TELEMETRY_DIR, TelemetryConsent, TelemetryDecision, decide, decide_in_home, |
| 57 | load_setup_state_for_decision, load_setup_state_for_decision_at, re_decide, validate_endpoint, |
| 58 | }; |
| 59 | pub use envelope::reduce_panic_site; |
| 60 | pub use event::{ |
| 61 | Arch, Batch, ColdStartBucket, Counters, DurationBucket, Errors, Event, ExitClass, InstallKind, |
| 62 | Libc, ModelCounters, NOTICE_VERSION, Os, ProductCounters, SCHEMA_VERSION, SessionSource, |
| 63 | Surface, TurnWall, |
| 64 | }; |
| 65 | |
| 66 | /// How long the shutdown flush may hold the process. |
| 67 | /// |
| 68 | /// The terminal is still in alt-screen while this runs. The persistence actor's |
| 69 | /// unbounded `task.await` next door is not a pattern to copy: a hung TLS |
| 70 | /// handshake would hold a user's terminal past exit. |
| 71 | pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(3); |
| 72 | |
| 73 | /// How long the send attempt on a terminating signal or a broken pipe may hold |
| 74 | /// the process. |
| 75 | /// |
| 76 | /// Shorter than [`SHUTDOWN_FLUSH_TIMEOUT`] so that, run alongside the runtime's |
| 77 | /// two second signal drain, it fits inside the two second grace a supervisor |
| 78 | /// gives SIGTERM before it escalates. |
| 79 | pub const SIGNAL_FLUSH_TIMEOUT: Duration = Duration::from_millis(1500); |
| 80 | |
| 81 | const COLD_START_UNSET: u64 = u64::MAX; |
| 82 | |
| 83 | static COLD_START_MS: AtomicU64 = AtomicU64::new(COLD_START_UNSET); |
| 84 | |
| 85 | /// Everything a write path needs once the process is armed. |
| 86 | struct Armed { |
| 87 | handle: actor::Handle, |
| 88 | root: std::path::PathBuf, |
| 89 | spool: std::path::PathBuf, |
| 90 | surface: Surface, |
| 91 | started: Instant, |
| 92 | exit_class: AtomicU8, |
| 93 | session_end_recorded: AtomicBool, |
| 94 | } |
| 95 | |
| 96 | /// The one gate. Unset means every write path is a hard no-op. |
| 97 | static ARMED: OnceLock<Armed> = OnceLock::new(); |
| 98 | |
| 99 | /// Arm telemetry for this process. |
| 100 | /// |
| 101 | /// Takes [`TelemetryConsent`] **by value**: there is no way to call this without |
| 102 | /// having gone through [`decide`], and no overload that accepts a `bool`. |
| 103 | /// |
| 104 | /// Idempotent — a second call is ignored, so a surface that dispatches twice |
| 105 | /// cannot start two writers against one buffer. |
| 106 | pub fn init(consent: TelemetryConsent) { |
| 107 | if ARMED.get().is_some() { |
| 108 | return; |
| 109 | } |
| 110 | let root = consent.root().to_path_buf(); |
| 111 | let observed_generation = consent.tombstone_generation().cloned(); |
| 112 | let config_path = consent.config_path().map(std::path::Path::to_path_buf); |
| 113 | |
| 114 | // Re-check durable permission under the same ordering lock as wipe. The |
| 115 | // generation match prevents consent resolved before a newer opt-out from |
| 116 | // clearing that opt-out; the fresh predicate preserves intentional |
| 117 | // `config set telemetry true` re-enablement. |
| 118 | if let Err(error) = buffer::arm(&root, observed_generation.as_ref(), || { |
| 119 | decision::permission_still_enabled(config_path.as_deref(), &root) |
| 120 | }) { |
| 121 | tracing::debug!("telemetry could not prepare its buffer: {error}"); |
| 122 | return; |
| 123 | } |
| 124 | |
| 125 | notice::show_startup_disclosure(consent.surface()); |
| 126 | |
| 127 | let header = spool::SpoolContext::new( |
| 128 | consent.surface(), |
| 129 | env!("CARGO_PKG_VERSION").to_string(), |
| 130 | envelope::release_build_sha(), |
| 131 | envelope::current_tty(), |
| 132 | ); |
| 133 | let (spool_path, nonce) = spool::open(&root, &header); |
| 134 | |
| 135 | let context = actor::Context { |
| 136 | root: root.clone(), |
| 137 | endpoint: consent.endpoint().map(str::to_string), |
| 138 | surface: consent.surface(), |
| 139 | config_path: consent.config_path().map(std::path::Path::to_path_buf), |
| 140 | app_version: env!("CARGO_PKG_VERSION").to_string(), |
| 141 | git_sha: envelope::release_build_sha(), |
| 142 | tty: envelope::current_tty(), |
| 143 | spool: spool_path.clone(), |
| 144 | nonce, |
| 145 | }; |
| 146 | actor::spawn_recovery(context.clone()); |
| 147 | |
| 148 | let _ = ARMED.set(Armed { |
| 149 | handle: actor::Handle::spawn(context), |
| 150 | root: root.clone(), |
| 151 | spool: spool_path, |
| 152 | surface: consent.surface(), |
| 153 | started: Instant::now(), |
| 154 | exit_class: AtomicU8::new(ExitClass::Clean.as_u8()), |
| 155 | session_end_recorded: AtomicBool::new(false), |
| 156 | }); |
| 157 | |
| 158 | record_install_or_upgrade(&root); |
| 159 | } |
| 160 | |
| 161 | /// Note that this binary's version differs from the one last seen on this |
| 162 | /// machine, at most once per version. |
| 163 | /// |
| 164 | /// The previous version comes from `$CODEWHALE_HOME/telemetry/state.json` and |
| 165 | /// from nowhere else. Session history and config mtimes would answer the same |
| 166 | /// question and carry a different privacy contract; reading them here would put |
| 167 | /// this crate one refactor away from the thread store. |
| 168 | /// |
| 169 | /// The state file is updated before the event is queued, so a process that dies |
| 170 | /// between the two reports nothing rather than reporting the same upgrade on |
| 171 | /// every launch. |
| 172 | fn record_install_or_upgrade(root: &std::path::Path) { |
| 173 | let current = env!("CARGO_PKG_VERSION"); |
| 174 | let mut state = envelope::read_state(root); |
| 175 | if state.last_version.as_deref() == Some(current) { |
| 176 | return; |
| 177 | } |
| 178 | let kind = match state.last_version.as_deref() { |
| 179 | None => InstallKind::Install, |
| 180 | Some(previous) if version_is_older(previous, current) => InstallKind::Upgrade, |
| 181 | Some(_) => InstallKind::Downgrade, |
| 182 | }; |
| 183 | let previous_version = state.last_version.clone(); |
| 184 | state.schema_version = SCHEMA_VERSION; |
| 185 | state.last_version = Some(current.to_string()); |
| 186 | if envelope::write_state(root, &state).is_err() { |
| 187 | // Nothing was recorded, so the next launch will try again. Emitting |
| 188 | // without the write would re-report the same upgrade forever. |
| 189 | return; |
| 190 | } |
| 191 | record(Event::InstallOrUpgrade { |
| 192 | kind, |
| 193 | previous_version, |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | /// Compare two dotted release numbers, ignoring any pre-release suffix. |
| 198 | /// |
| 199 | /// Deliberately not a semver dependency: the only question asked is which of |
| 200 | /// install / upgrade / downgrade to name, and a version this crate cannot parse |
| 201 | /// answers "not older", which reports a downgrade — the conservative direction, |
| 202 | /// since it never invents an upgrade that did not happen. |
| 203 | fn version_is_older(previous: &str, current: &str) -> bool { |
| 204 | fn parts(value: &str) -> Vec<u64> { |
| 205 | value |
| 206 | .split(['-', '+']) |
| 207 | .next() |
| 208 | .unwrap_or_default() |
| 209 | .split('.') |
| 210 | .map(|part| part.parse::<u64>().unwrap_or_default()) |
| 211 | .collect() |
| 212 | } |
| 213 | let (previous, current) = (parts(previous), parts(current)); |
| 214 | let width = previous.len().max(current.len()); |
| 215 | for index in 0..width { |
| 216 | let left = previous.get(index).copied().unwrap_or_default(); |
| 217 | let right = current.get(index).copied().unwrap_or_default(); |
| 218 | if left != right { |
| 219 | return left < right; |
| 220 | } |
| 221 | } |
| 222 | false |
| 223 | } |
| 224 | |
| 225 | /// Whether this process is armed. Every write path checks this first. |
| 226 | #[must_use] |
| 227 | pub fn is_armed() -> bool { |
| 228 | ARMED.get().is_some() |
| 229 | } |
| 230 | |
| 231 | /// This process's session accumulators. |
| 232 | /// |
| 233 | /// Deliberately **not** behind the arming gate. Every bump is a relaxed atomic |
| 234 | /// increment on a counter that never leaves this process unless [`init`] was |
| 235 | /// reached, so gating them would buy nothing and would put an `is_armed()` |
| 236 | /// branch on eleven hot call sites. The gate that matters is on the write |
| 237 | /// paths, and a snapshot of these numbers only ever reaches a payload through |
| 238 | /// one. |
| 239 | pub fn session_counters() -> &'static SessionCounters { |
| 240 | static COUNTERS: OnceLock<SessionCounters> = OnceLock::new(); |
| 241 | COUNTERS.get_or_init(SessionCounters::default) |
| 242 | } |
| 243 | |
| 244 | /// Queue an event for the writer thread. |
| 245 | /// |
| 246 | /// Non-blocking, and a no-op when unarmed. |
| 247 | pub fn record(event: Event) { |
| 248 | let Some(armed) = ARMED.get() else { |
| 249 | return; |
| 250 | }; |
| 251 | armed.handle.record(event); |
| 252 | } |
| 253 | |
| 254 | /// Write an event synchronously, without the writer thread. |
| 255 | /// |
| 256 | /// The synchronous escape hatch for the three paths where the async world is |
| 257 | /// gone or going: the panic hook, `record_caught_panic`, and the signal task |
| 258 | /// immediately before `std::process::exit`. One `O_APPEND` `write(2)` under |
| 259 | /// `PIPE_BUF`, a `sync_data`, and return — microseconds. |
| 260 | /// |
| 261 | /// The append takes the shared privacy lock with `try_write()`, never a blocking |
| 262 | /// acquisition. If the actor, a wipe, or another Codewhale process sharing |
| 263 | /// `CODEWHALE_HOME` holds it, the event is dropped immediately. This preserves |
| 264 | /// the panic/SIGINT liveness contract without allowing a write to race past a |
| 265 | /// completed opt-out. |
| 266 | /// |
| 267 | /// A no-op when unarmed, which is what makes a disabled user's panic write |
| 268 | /// nothing and create no directory. |
| 269 | pub fn record_blocking(event: Event) { |
| 270 | let Some(armed) = ARMED.get() else { |
| 271 | return; |
| 272 | }; |
| 273 | let Ok(line) = serde_json::to_string(&event) else { |
| 274 | return; |
| 275 | }; |
| 276 | let _ = buffer::append(&armed.root, &armed.spool, &line); |
| 277 | } |
| 278 | |
| 279 | /// Record how this process is ending. |
| 280 | /// |
| 281 | /// Set by the panic hook, by the signal task before `std::process::exit`, and on |
| 282 | /// the clean path from the run's termination reason. **Never derived from an |
| 283 | /// exit code**. |
| 284 | pub fn set_exit_class(class: ExitClass) { |
| 285 | let Some(armed) = ARMED.get() else { |
| 286 | return; |
| 287 | }; |
| 288 | armed.exit_class.store(class.as_u8(), Ordering::Relaxed); |
| 289 | } |
| 290 | |
| 291 | /// The exit class recorded so far. `Clean` when unarmed or unset. |
| 292 | #[must_use] |
| 293 | pub fn exit_class() -> ExitClass { |
| 294 | ARMED.get().map_or(ExitClass::Clean, |armed| { |
| 295 | ExitClass::from_u8(armed.exit_class.load(Ordering::Relaxed)) |
| 296 | }) |
| 297 | } |
| 298 | |
| 299 | /// Report how long the interactive event loop took to start. The terminal UI is |
| 300 | /// the only caller; every other surface leaves the cold-start bucket absent. |
| 301 | pub fn set_cold_start_ms(millis: u64) { |
| 302 | let _ = COLD_START_MS.compare_exchange( |
| 303 | COLD_START_UNSET, |
| 304 | millis, |
| 305 | Ordering::Relaxed, |
| 306 | Ordering::Relaxed, |
| 307 | ); |
| 308 | } |
| 309 | |
| 310 | /// Build `session_end` from what this process actually accumulated. |
| 311 | /// |
| 312 | /// The exit class is read from the process-wide atomic and never derived from |
| 313 | /// an exit code. Building the event writes nothing; an unarmed process reports a |
| 314 | /// zero duration and nothing reaches a sink. |
| 315 | #[must_use] |
| 316 | pub fn session_end_event() -> Event { |
| 317 | let counters = session_counters(); |
| 318 | let cold_start = COLD_START_MS.load(Ordering::Relaxed); |
| 319 | Event::SessionEnd { |
| 320 | duration_bucket: DurationBucket::from_secs( |
| 321 | ARMED |
| 322 | .get() |
| 323 | .map_or(0, |armed| armed.started.elapsed().as_secs()), |
| 324 | ), |
| 325 | exit_class: exit_class(), |
| 326 | cold_start_bucket: (cold_start != COLD_START_UNSET) |
| 327 | .then(|| ColdStartBucket::from_millis(cold_start)), |
| 328 | providers: counters.providers(), |
| 329 | counters: counters.counters(), |
| 330 | errors: counters.errors(), |
| 331 | turn_wall: counters.turn_wall(), |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | /// Queue this session's usage rows and `session_end` once. |
| 336 | /// |
| 337 | /// Whichever of the clean path, the signal path or a broken pipe gets here |
| 338 | /// first reports; later callers do nothing, so one session never ends twice. |
| 339 | /// A no-op when unarmed. |
| 340 | pub fn record_session_end() { |
| 341 | let Some(armed) = ARMED.get() else { |
| 342 | return; |
| 343 | }; |
| 344 | if armed.session_end_recorded.swap(true, Ordering::AcqRel) { |
| 345 | return; |
| 346 | } |
| 347 | for event in session_counters().usage_events() { |
| 348 | record(event); |
| 349 | } |
| 350 | record(session_end_event()); |
| 351 | } |
| 352 | |
| 353 | /// Close the session synchronously, for a path that cannot wait for the writer. |
| 354 | /// |
| 355 | /// States `class`, then appends the usage rows and `session_end` to the local |
| 356 | /// buffer with the same lock-free-for-the-caller write as [`record_blocking`]. |
| 357 | /// A no-op when unarmed, and a no-op for the events when the session already |
| 358 | /// ended. |
| 359 | pub fn record_session_end_blocking(class: ExitClass) { |
| 360 | let Some(armed) = ARMED.get() else { |
| 361 | return; |
| 362 | }; |
| 363 | set_exit_class(class); |
| 364 | if armed.session_end_recorded.swap(true, Ordering::AcqRel) { |
| 365 | return; |
| 366 | } |
| 367 | for event in session_counters().usage_events() { |
| 368 | record_blocking(event); |
| 369 | } |
| 370 | record_blocking(session_end_event()); |
| 371 | } |
| 372 | |
| 373 | /// One bounded network attempt for a process that is being terminated. |
| 374 | /// |
| 375 | /// Runs the ordinary flush, so consent, the opt-out tombstone and the run kill |
| 376 | /// switch are re-checked immediately beforehand and a person who has opted out |
| 377 | /// sends nothing. Short CLI commands stay disk-only. Never retried, and the |
| 378 | /// caller is released after `deadline` whether or not the request finished. |
| 379 | #[must_use] |
| 380 | pub fn flush_for_termination(deadline: Duration) -> FlushOutcome { |
| 381 | let Some(armed) = ARMED.get() else { |
| 382 | return FlushOutcome::Empty; |
| 383 | }; |
| 384 | if armed.surface == Surface::Cli { |
| 385 | return FlushOutcome::Buffered; |
| 386 | } |
| 387 | armed.handle.shutdown(deadline) |
| 388 | } |
| 389 | |
| 390 | /// Record the session end and make the one bounded send attempt, for a process |
| 391 | /// that is about to be ended by a signal. Returns [`FlushOutcome::Empty`] when |
| 392 | /// unarmed. |
| 393 | pub fn report_termination(class: ExitClass, deadline: Duration) -> FlushOutcome { |
| 394 | record_session_end_blocking(class); |
| 395 | flush_for_termination(deadline) |
| 396 | } |
| 397 | |
| 398 | /// Final flush, then stop the writer thread. |
| 399 | /// |
| 400 | /// Returns [`FlushOutcome::Empty`] when unarmed. |
| 401 | pub fn shutdown_blocking(deadline: Duration) -> FlushOutcome { |
| 402 | ARMED |
| 403 | .get() |
| 404 | .map_or(FlushOutcome::Empty, |armed| armed.handle.shutdown(deadline)) |
| 405 | } |
| 406 | |
| 407 | /// Persist every queued event locally, then stop the writer without networking. |
| 408 | /// |
| 409 | /// With an explicitly empty endpoint this finalizes the local dry-run batch. |
| 410 | /// With a configured endpoint it leaves events in the pending buffer for the |
| 411 | /// next full flush. Returns [`FlushOutcome::Empty`] when unarmed. |
| 412 | /// |
| 413 | /// This joins the writer instead of racing it (#6269). The local path seals |
| 414 | /// at most a consent re-check, a tombstone probe, and one fsync append — |
| 415 | /// bounded disk work with no network in it. A deadline here buys nothing the |
| 416 | /// rest of the CLI does not already forgo: startup reads config from the |
| 417 | /// same disk with no timeout either. The writer always acknowledges, even on |
| 418 | /// panic, so the only fail-open outcome is a writer that is already gone. |
| 419 | /// Only the network flush keeps a deadline. |
| 420 | #[must_use] |
| 421 | pub fn persist_local_blocking() -> FlushOutcome { |
| 422 | ARMED |
| 423 | .get() |
| 424 | .map_or(FlushOutcome::Empty, |armed| armed.handle.persist_local()) |
| 425 | } |
| 426 |