trusty_code/perf/mod.rs
1//! Performance instrumentation — per-phase latency + token/cost capture.
2//!
3//! Why: (#47) We need to track how long each workflow phase takes, how many
4//! tokens it consumed (prompt / completion / Anthropic cache read / cache
5//! creation), and the resulting USD cost so we can compare runs build-over-
6//! build and catch regressions or prompt-caching wins. Persisting one JSON
7//! file per run under `docs/performance/runs/` plus a one-line summary log
8//! keeps the data greppable without a database.
9//! What: `PerfCollector` is constructed at workflow start, `record_phase`
10//! appends a `PhaseRecord` after each phase, and `flush` writes the final
11//! JSON + log line. `TokenUsage` is the provider-agnostic shape captured
12//! from each LLM call (extended with Anthropic-specific `cache_read` /
13//! `cache_creation` fields which are zero for non-Anthropic models).
14//! Test: `cost_usd_known_model`, `collector_records_phases`,
15//! `collector_totals_sum_phases`, `collector_flush_writes_json_and_log`.
16//!
17//! Module layout (see #366 split):
18//! - `mod.rs` — perf record types + `PerfCollector` lifecycle
19//! - `pricing.rs` — `cost_usd` + the model pricing table + formatters
20//! - `tests.rs` — unit tests
21
22mod pricing;
23
24#[cfg(test)]
25mod tests;
26
27use std::path::Path;
28use std::time::Instant;
29
30use anyhow::{Context, Result};
31use chrono::Utc;
32use serde::{Deserialize, Serialize};
33
34use pricing::{filename_stamp, truncate_preview};
35
36pub use pricing::cost_usd;
37
38/// Token usage captured from a single LLM round-trip.
39///
40/// Why: (#50) Anthropic's OpenRouter responses carry cache_read_input_tokens
41/// and cache_creation_input_tokens alongside the standard prompt/completion
42/// counts. Exposing those as first-class fields lets `PerfCollector` track
43/// cache effectiveness over time. For non-Anthropic models these stay 0.
44/// `cost_usd` (response-side cache-usage fix) carries OpenRouter's
45/// authoritative, already cache-discounted USD cost for this one round-trip
46/// when the provider reported one; `None` means no authoritative cost was
47/// available and callers must fall back to static per-token pricing.
48/// What: Plain struct; additive (`+`-style) accumulation is done inline in
49/// `PerfCollector::totals`.
50/// Test: `token_usage_default_is_zeros`, `token_usage_accumulates`,
51/// `token_usage_cost_accumulates`.
52#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
53pub struct TokenUsage {
54 pub prompt_tokens: u32,
55 pub completion_tokens: u32,
56 pub cache_read_tokens: u32,
57 pub cache_creation_tokens: u32,
58 /// Authoritative per-call USD cost reported by the provider (OpenRouter),
59 /// already netting any cache discount. `None` when unavailable.
60 #[serde(default)]
61 pub cost_usd: Option<f64>,
62}
63
64impl TokenUsage {
65 /// Construct a `TokenUsage` from the four individual counts.
66 ///
67 /// Why: Most call sites (tests, static-pricing paths) don't have an
68 /// authoritative provider-reported cost; `cost_usd` starts `None` and
69 /// callers set it explicitly (e.g. `UsageBlock::into_token_usage`) when
70 /// one is available.
71 pub fn new(prompt: u32, completion: u32, cache_read: u32, cache_creation: u32) -> Self {
72 Self {
73 prompt_tokens: prompt,
74 completion_tokens: completion,
75 cache_read_tokens: cache_read,
76 cache_creation_tokens: cache_creation,
77 cost_usd: None,
78 }
79 }
80
81 /// Add another usage record into this one (in place).
82 ///
83 /// Why: Each phase may comprise multiple LLM turns (tool loop); we sum
84 /// them into a single `PhaseRecord`. `cost_usd` sums the two authoritative
85 /// costs when both are present; when only one side carries a cost it is
86 /// preserved rather than discarded, and the sum is `None` only when
87 /// neither side has one — a partial per-turn cost is still meaningful
88 /// signal that must not silently disappear.
89 /// What: Field-wise saturating add for token counts; `Option<f64>` sum for
90 /// cost.
91 /// Test: `token_usage_accumulates`, `token_usage_cost_accumulates`.
92 pub fn add(&mut self, other: &TokenUsage) {
93 self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
94 self.completion_tokens = self
95 .completion_tokens
96 .saturating_add(other.completion_tokens);
97 self.cache_read_tokens = self
98 .cache_read_tokens
99 .saturating_add(other.cache_read_tokens);
100 self.cache_creation_tokens = self
101 .cache_creation_tokens
102 .saturating_add(other.cache_creation_tokens);
103 self.cost_usd = match (self.cost_usd, other.cost_usd) {
104 (Some(a), Some(b)) => Some(a + b),
105 (Some(a), None) | (None, Some(a)) => Some(a),
106 (None, None) => None,
107 };
108 }
109}
110
111/// One phase's measured performance.
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct PhaseRecord {
114 pub name: String,
115 pub duration_ms: u64,
116 pub prompt_tokens: u32,
117 pub completion_tokens: u32,
118 pub cache_read_tokens: u32,
119 pub cache_creation_tokens: u32,
120 pub cost_usd: f64,
121}
122
123/// Totals rolled up from every `PhaseRecord` in a run.
124#[derive(Debug, Clone, Default, Serialize, Deserialize)]
125pub struct PerfTotals {
126 pub prompt_tokens: u32,
127 pub completion_tokens: u32,
128 pub cache_read_tokens: u32,
129 pub cache_creation_tokens: u32,
130 pub cost_usd: f64,
131}
132
133/// Full performance record persisted to `docs/performance/runs/`.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct PerfRecord {
136 pub build: u64,
137 pub version: String,
138 pub workflow: String,
139 pub task_preview: String,
140 pub started_at: String,
141 pub total_duration_ms: u64,
142 pub phases: Vec<PhaseRecord>,
143 pub totals: PerfTotals,
144 /// Run outcome (#56): "success" | "partial" | "failed".
145 ///
146 /// Why: When a phase fails mid-workflow, we still want to persist the
147 /// perf record so we can see where/how the run died. A separate `status`
148 /// field distinguishes clean completions from partial runs in tooling
149 /// that scans `runs/*.json`.
150 /// What: Defaults to "success" for back-compat with older fixtures.
151 #[serde(default = "default_status")]
152 pub status: String,
153 /// Name of the phase that failed, when `status != "success"` (#56).
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub failed_phase: Option<String>,
156 /// Distinct skill names injected into any phase prompt during this run
157 /// (#171).
158 ///
159 /// Why: Post-run persistence needs to know which skills were used so it
160 /// can increment `use_count` and refresh `last_used`. Carrying the list
161 /// through `PerfRecord` keeps the data in one place that's already
162 /// flushed to disk for analysis.
163 /// What: Deduplicated, insertion-order-preserved list of skill names.
164 /// Defaults to empty for back-compat with older fixtures.
165 #[serde(default)]
166 pub skills_used: Vec<String>,
167 /// Distinct skill names matched by the pre-plan discovery step (#173).
168 ///
169 /// Why: Discovery surfaces every skill the engine considered relevant for
170 /// a task — even if downstream prompt assembly only injected a subset (or
171 /// none). Recording the broader candidate set separately from
172 /// `skills_used` lets us measure recall vs. precision over time and
173 /// audit which signals the discovery step matched on.
174 /// What: Deduplicated, insertion-order-preserved list of skill names.
175 /// Defaults to empty for back-compat with older fixtures.
176 #[serde(default)]
177 pub skills_considered: Vec<String>,
178 /// Tests passed in the QA phase, when the QA agent emitted a parsable
179 /// JSON envelope with a `passed` count.
180 ///
181 /// Why: Run-over-run comparisons want raw test counts, not just the
182 /// pass/fail status. Tracking `tests_passed`/`tests_failed` separately
183 /// from `status` lets dashboards show "1118/1118 passing" without
184 /// re-parsing QA output.
185 /// What: `Some(N)` when QA returned a JSON envelope with `passed`,
186 /// `None` otherwise. Defaults to `None` for back-compat with older
187 /// fixtures and for runs that skip the QA phase.
188 /// Test: `test_run_record_serializes_test_counts`.
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub tests_passed: Option<u64>,
191 /// Tests failed in the QA phase, paired with `tests_passed`.
192 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub tests_failed: Option<u64>,
194}
195
196fn default_status() -> String {
197 "success".to_string()
198}
199
200/// Accumulator used during workflow execution.
201///
202/// Why: Keeping the collector off the workflow context lets us evolve perf
203/// schema without churning `WorkflowContext`; the engine just calls
204/// `record_phase`/`flush`.
205/// What: Holds the build stamp, workflow name, a 120-char preview of the
206/// user task, the wall-clock start `Instant`, and a growing `Vec<PhaseRecord>`.
207/// `flush(out_dir)` writes `runs/YYYYMMDD-HHMMSS-build<N>.json` and appends a
208/// summary line to `runs.log`.
209/// Test: see unit tests at bottom of this file.
210pub struct PerfCollector {
211 build: u64,
212 workflow: String,
213 task_preview: String,
214 started_at: Instant,
215 started_at_iso: String,
216 phases: Vec<PhaseRecord>,
217 model: String,
218 /// #56: run status; set via `set_status`. Defaults to "success".
219 status: String,
220 /// #56: name of the phase that failed, if any.
221 failed_phase: Option<String>,
222 /// #171: distinct skills injected during the run, insertion-ordered.
223 skills_used: Vec<String>,
224 /// #173: distinct skills matched by pre-plan discovery, insertion-ordered.
225 skills_considered: Vec<String>,
226 /// QA-emitted passed test count, when available.
227 tests_passed: Option<u64>,
228 /// QA-emitted failed test count, when available.
229 tests_failed: Option<u64>,
230}
231
232impl PerfCollector {
233 /// Construct a new collector.
234 ///
235 /// Why: Called at workflow start so the wall-clock anchor is the true
236 /// run start, not a lazy "first phase" moment.
237 /// What: Captures the build number, workflow name, truncated task preview,
238 /// start `Instant`, and start ISO8601 UTC timestamp.
239 /// Test: `collector_records_phases`.
240 pub fn new(build: u64, workflow: &str, task: &str) -> Self {
241 Self {
242 build,
243 workflow: workflow.to_string(),
244 task_preview: truncate_preview(task, 120),
245 started_at: Instant::now(),
246 started_at_iso: Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
247 phases: Vec::new(),
248 model: String::new(),
249 status: "success".to_string(),
250 failed_phase: None,
251 skills_used: Vec::new(),
252 skills_considered: Vec::new(),
253 tests_passed: None,
254 tests_failed: None,
255 }
256 }
257
258 /// Record QA test counts (Fix 3 / parity with claude-mpm).
259 ///
260 /// Why: When the QA agent emits a parsable JSON envelope, we want the
261 /// exact `passed`/`failed` counts on the perf record so dashboards can
262 /// chart them over time without re-parsing agent output.
263 /// What: Stores the two counts; included in the flushed JSON and the
264 /// `runs.log` summary line.
265 /// Test: `test_run_record_serializes_test_counts`.
266 pub fn set_test_counts(&mut self, passed: u64, failed: u64) {
267 self.tests_passed = Some(passed);
268 self.tests_failed = Some(failed);
269 }
270
271 /// Record that `name` was surfaced by pre-plan skill discovery (#173).
272 ///
273 /// Why: Discovery considers a broader set of skills than what is actually
274 /// injected. Tracking the full candidate set separately preserves the
275 /// recall side of the recall/precision picture for post-run analysis.
276 /// What: Appends `name` to `skills_considered` if not already present
277 /// (insertion-ordered de-dup).
278 /// Test: `collector_records_skills_considered`.
279 pub fn record_skill_considered(&mut self, name: &str) {
280 if !self.skills_considered.iter().any(|s| s == name) {
281 self.skills_considered.push(name.to_string());
282 }
283 }
284
285 /// Record that `name` was injected into a phase prompt during this run
286 /// (#171).
287 ///
288 /// Why: Post-run persistence (`update_skill_usage` in `main.rs`) needs the
289 /// list of injected skills to update `use_count` and `last_used`. Tracking
290 /// here keeps the collector the single source of truth for the run.
291 /// What: Appends `name` to `skills_used` if not already present
292 /// (insertion-ordered de-dup).
293 /// Test: Indirect via `update_skill_usage` integration in main.
294 pub fn record_skill_used(&mut self, name: &str) {
295 if !self.skills_used.iter().any(|s| s == name) {
296 self.skills_used.push(name.to_string());
297 }
298 }
299
300 /// Set the run status (#56).
301 ///
302 /// Why: The workflow engine calls this after the phase loop to record
303 /// "success" on clean completion and "partial" / "failed" when a phase
304 /// returned an error, so the flushed JSON reflects reality.
305 /// What: Stores the status string verbatim; `flush` serializes it.
306 /// Test: `collector_flush_records_failed_status`.
307 pub fn set_status(&mut self, status: &str) {
308 self.status = status.to_string();
309 }
310
311 /// Record which phase failed (#56).
312 ///
313 /// Why: Paired with `set_status`, this lets analysis tooling group failed
314 /// runs by failing phase without having to parse the last `phases` entry.
315 /// What: Stores the phase name; included in the flushed JSON when set.
316 /// Test: `collector_flush_records_failed_status`.
317 pub fn set_failed_phase(&mut self, phase: &str) {
318 self.failed_phase = Some(phase.to_string());
319 }
320
321 /// Record the dominant model used by the run for pricing.
322 ///
323 /// Why: The LLM pricing table is keyed by model substring. The workflow
324 /// engine doesn't know the model up front (each phase's agent may use a
325 /// different one), so we let the caller set/override as needed.
326 /// What: Stores the latest model string; pricing is looked up per
327 /// `record_phase` call using the `model` argument passed there, not this
328 /// field (this is retained for future aggregate analysis).
329 /// Test: implicit via `collector_flush_writes_json_and_log`.
330 #[allow(dead_code)]
331 pub fn set_model(&mut self, model: &str) {
332 self.model = model.to_string();
333 }
334
335 /// Append a phase's measurements, computing its USD cost from `model`.
336 ///
337 /// Why: Engines call this once per phase with the agent model and the
338 /// summed `TokenUsage` from all LLM turns in that phase.
339 /// What: Prefers `usage.cost_usd` (OpenRouter's authoritative,
340 /// cache-discount-aware cost) when the provider reported one; otherwise
341 /// falls back to the static per-token recompute via `cost_usd(model, ...)`
342 /// — the static table cannot see the cache discount, so it is a fallback
343 /// only, never a substitute when an authoritative figure exists. Pushes a
344 /// `PhaseRecord`.
345 /// Test: `collector_records_phases`, `record_phase_prefers_authoritative_cost`.
346 pub fn record_phase(&mut self, name: &str, duration_ms: u64, model: &str, usage: &TokenUsage) {
347 let cost = usage.cost_usd.unwrap_or_else(|| {
348 cost_usd(
349 model,
350 usage.prompt_tokens,
351 usage.completion_tokens,
352 usage.cache_read_tokens,
353 usage.cache_creation_tokens,
354 )
355 });
356 self.phases.push(PhaseRecord {
357 name: name.to_string(),
358 duration_ms,
359 prompt_tokens: usage.prompt_tokens,
360 completion_tokens: usage.completion_tokens,
361 cache_read_tokens: usage.cache_read_tokens,
362 cache_creation_tokens: usage.cache_creation_tokens,
363 cost_usd: cost,
364 });
365 }
366
367 /// Sum all phase records into a single `PerfTotals`.
368 fn totals(&self) -> PerfTotals {
369 let mut t = PerfTotals::default();
370 for p in &self.phases {
371 t.prompt_tokens = t.prompt_tokens.saturating_add(p.prompt_tokens);
372 t.completion_tokens = t.completion_tokens.saturating_add(p.completion_tokens);
373 t.cache_read_tokens = t.cache_read_tokens.saturating_add(p.cache_read_tokens);
374 t.cache_creation_tokens = t
375 .cache_creation_tokens
376 .saturating_add(p.cache_creation_tokens);
377 t.cost_usd += p.cost_usd;
378 }
379 t
380 }
381
382 /// Build the final `PerfRecord` without writing to disk.
383 ///
384 /// Why: Exposed for tests and for in-process consumers (the #151 JSON
385 /// envelope projects this record into a `PmResponse`). `flush` calls
386 /// this internally.
387 pub fn build_record(&self) -> PerfRecord {
388 let total_duration_ms = self.started_at.elapsed().as_millis() as u64;
389 PerfRecord {
390 build: self.build,
391 version: env!("CARGO_PKG_VERSION").to_string(),
392 workflow: self.workflow.clone(),
393 task_preview: self.task_preview.clone(),
394 started_at: self.started_at_iso.clone(),
395 total_duration_ms,
396 phases: self.phases.clone(),
397 totals: self.totals(),
398 status: self.status.clone(),
399 failed_phase: self.failed_phase.clone(),
400 skills_used: self.skills_used.clone(),
401 skills_considered: self.skills_considered.clone(),
402 tests_passed: self.tests_passed,
403 tests_failed: self.tests_failed,
404 }
405 }
406
407 /// Persist the record to `out_dir/runs/<stamp>.json` and append a
408 /// summary line to `out_dir/runs.log`.
409 ///
410 /// Why: A single JSON per run is easy to diff and feed to tooling; the
411 /// log line is a human-readable one-liner suitable for `tail -f`.
412 /// What: Computes total duration, serializes to pretty JSON, writes the
413 /// file atomically-ish (direct write is fine for append-only telemetry),
414 /// then appends a one-line summary to `runs.log`.
415 /// Test: `collector_flush_writes_json_and_log`.
416 pub async fn flush(&self, out_dir: &Path) -> Result<()> {
417 let record = self.build_record();
418 let runs_dir = out_dir.join("runs");
419 tokio::fs::create_dir_all(&runs_dir)
420 .await
421 .with_context(|| format!("failed to create {}", runs_dir.display()))?;
422
423 // Stamp filename: YYYYMMDD-HHMMSS-build<N>.json
424 // Derived from `started_at_iso` (UTC) so filenames are deterministic
425 // given the same start time — useful for test fixtures.
426 let stamp = filename_stamp(&self.started_at_iso, self.build);
427 let json_path = runs_dir.join(format!("{stamp}.json"));
428 let pretty = serde_json::to_vec_pretty(&record).context("serialize PerfRecord")?;
429 tokio::fs::write(&json_path, &pretty)
430 .await
431 .with_context(|| format!("failed to write {}", json_path.display()))?;
432
433 // One-line summary: tab-separated key=value pairs.
434 // `tests_passed` / `tests_failed` are appended as the LAST two columns
435 // for back-compat with log readers that only parse the first N
436 // columns. Render `None` as "-" so the column is always present.
437 let fmt_opt = |n: Option<u64>| -> String {
438 n.map(|v| v.to_string()).unwrap_or_else(|| "-".to_string())
439 };
440 let line = format!(
441 "{ts}\tbuild={b}\tworkflow={w}\tdur_ms={d}\tprompt={p}\tcompletion={c}\tcache_r={cr}\tcache_w={cc}\tcost_usd={cost:.6}\ttests_passed={tp}\ttests_failed={tf}\n",
442 ts = self.started_at_iso,
443 b = self.build,
444 w = self.workflow,
445 d = record.total_duration_ms,
446 p = record.totals.prompt_tokens,
447 c = record.totals.completion_tokens,
448 cr = record.totals.cache_read_tokens,
449 cc = record.totals.cache_creation_tokens,
450 cost = record.totals.cost_usd,
451 tp = fmt_opt(record.tests_passed),
452 tf = fmt_opt(record.tests_failed),
453 );
454 let log_path = out_dir.join("runs.log");
455 // Ensure parent exists (out_dir itself might not yet).
456 if let Some(parent) = log_path.parent() {
457 tokio::fs::create_dir_all(parent).await.ok();
458 }
459 // Append.
460 use tokio::io::AsyncWriteExt;
461 let mut f = tokio::fs::OpenOptions::new()
462 .create(true)
463 .append(true)
464 .open(&log_path)
465 .await
466 .with_context(|| format!("failed to open {}", log_path.display()))?;
467 f.write_all(line.as_bytes())
468 .await
469 .context("failed to append perf log line")?;
470 f.flush().await.ok();
471
472 tracing::info!(
473 path = %json_path.display(),
474 build = self.build,
475 total_ms = record.total_duration_ms,
476 total_cost_usd = record.totals.cost_usd,
477 "wrote perf record"
478 );
479 Ok(())
480 }
481}