mod pricing;
#[cfg(test)]
mod tests;
use std::path::Path;
use std::time::Instant;
use anyhow::{Context, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use pricing::{filename_stamp, truncate_preview};
pub use pricing::cost_usd;
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct TokenUsage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cache_read_tokens: u32,
pub cache_creation_tokens: u32,
#[serde(default)]
pub cost_usd: Option<f64>,
}
impl TokenUsage {
pub fn new(prompt: u32, completion: u32, cache_read: u32, cache_creation: u32) -> Self {
Self {
prompt_tokens: prompt,
completion_tokens: completion,
cache_read_tokens: cache_read,
cache_creation_tokens: cache_creation,
cost_usd: None,
}
}
pub fn add(&mut self, other: &TokenUsage) {
self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
self.completion_tokens = self
.completion_tokens
.saturating_add(other.completion_tokens);
self.cache_read_tokens = self
.cache_read_tokens
.saturating_add(other.cache_read_tokens);
self.cache_creation_tokens = self
.cache_creation_tokens
.saturating_add(other.cache_creation_tokens);
self.cost_usd = match (self.cost_usd, other.cost_usd) {
(Some(a), Some(b)) => Some(a + b),
(Some(a), None) | (None, Some(a)) => Some(a),
(None, None) => None,
};
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhaseRecord {
pub name: String,
pub duration_ms: u64,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cache_read_tokens: u32,
pub cache_creation_tokens: u32,
pub cost_usd: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PerfTotals {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cache_read_tokens: u32,
pub cache_creation_tokens: u32,
pub cost_usd: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerfRecord {
pub build: u64,
pub version: String,
pub workflow: String,
pub task_preview: String,
pub started_at: String,
pub total_duration_ms: u64,
pub phases: Vec<PhaseRecord>,
pub totals: PerfTotals,
#[serde(default = "default_status")]
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed_phase: Option<String>,
#[serde(default)]
pub skills_used: Vec<String>,
#[serde(default)]
pub skills_considered: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tests_passed: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tests_failed: Option<u64>,
}
fn default_status() -> String {
"success".to_string()
}
pub struct PerfCollector {
build: u64,
workflow: String,
task_preview: String,
started_at: Instant,
started_at_iso: String,
phases: Vec<PhaseRecord>,
model: String,
status: String,
failed_phase: Option<String>,
skills_used: Vec<String>,
skills_considered: Vec<String>,
tests_passed: Option<u64>,
tests_failed: Option<u64>,
}
impl PerfCollector {
pub fn new(build: u64, workflow: &str, task: &str) -> Self {
Self {
build,
workflow: workflow.to_string(),
task_preview: truncate_preview(task, 120),
started_at: Instant::now(),
started_at_iso: Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
phases: Vec::new(),
model: String::new(),
status: "success".to_string(),
failed_phase: None,
skills_used: Vec::new(),
skills_considered: Vec::new(),
tests_passed: None,
tests_failed: None,
}
}
pub fn set_test_counts(&mut self, passed: u64, failed: u64) {
self.tests_passed = Some(passed);
self.tests_failed = Some(failed);
}
pub fn record_skill_considered(&mut self, name: &str) {
if !self.skills_considered.iter().any(|s| s == name) {
self.skills_considered.push(name.to_string());
}
}
pub fn record_skill_used(&mut self, name: &str) {
if !self.skills_used.iter().any(|s| s == name) {
self.skills_used.push(name.to_string());
}
}
pub fn set_status(&mut self, status: &str) {
self.status = status.to_string();
}
pub fn set_failed_phase(&mut self, phase: &str) {
self.failed_phase = Some(phase.to_string());
}
#[allow(dead_code)]
pub fn set_model(&mut self, model: &str) {
self.model = model.to_string();
}
pub fn record_phase(&mut self, name: &str, duration_ms: u64, model: &str, usage: &TokenUsage) {
let cost = usage.cost_usd.unwrap_or_else(|| {
cost_usd(
model,
usage.prompt_tokens,
usage.completion_tokens,
usage.cache_read_tokens,
usage.cache_creation_tokens,
)
});
self.phases.push(PhaseRecord {
name: name.to_string(),
duration_ms,
prompt_tokens: usage.prompt_tokens,
completion_tokens: usage.completion_tokens,
cache_read_tokens: usage.cache_read_tokens,
cache_creation_tokens: usage.cache_creation_tokens,
cost_usd: cost,
});
}
fn totals(&self) -> PerfTotals {
let mut t = PerfTotals::default();
for p in &self.phases {
t.prompt_tokens = t.prompt_tokens.saturating_add(p.prompt_tokens);
t.completion_tokens = t.completion_tokens.saturating_add(p.completion_tokens);
t.cache_read_tokens = t.cache_read_tokens.saturating_add(p.cache_read_tokens);
t.cache_creation_tokens = t
.cache_creation_tokens
.saturating_add(p.cache_creation_tokens);
t.cost_usd += p.cost_usd;
}
t
}
pub fn build_record(&self) -> PerfRecord {
let total_duration_ms = self.started_at.elapsed().as_millis() as u64;
PerfRecord {
build: self.build,
version: env!("CARGO_PKG_VERSION").to_string(),
workflow: self.workflow.clone(),
task_preview: self.task_preview.clone(),
started_at: self.started_at_iso.clone(),
total_duration_ms,
phases: self.phases.clone(),
totals: self.totals(),
status: self.status.clone(),
failed_phase: self.failed_phase.clone(),
skills_used: self.skills_used.clone(),
skills_considered: self.skills_considered.clone(),
tests_passed: self.tests_passed,
tests_failed: self.tests_failed,
}
}
pub async fn flush(&self, out_dir: &Path) -> Result<()> {
let record = self.build_record();
let runs_dir = out_dir.join("runs");
tokio::fs::create_dir_all(&runs_dir)
.await
.with_context(|| format!("failed to create {}", runs_dir.display()))?;
let stamp = filename_stamp(&self.started_at_iso, self.build);
let json_path = runs_dir.join(format!("{stamp}.json"));
let pretty = serde_json::to_vec_pretty(&record).context("serialize PerfRecord")?;
tokio::fs::write(&json_path, &pretty)
.await
.with_context(|| format!("failed to write {}", json_path.display()))?;
let fmt_opt = |n: Option<u64>| -> String {
n.map(|v| v.to_string()).unwrap_or_else(|| "-".to_string())
};
let line = format!(
"{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",
ts = self.started_at_iso,
b = self.build,
w = self.workflow,
d = record.total_duration_ms,
p = record.totals.prompt_tokens,
c = record.totals.completion_tokens,
cr = record.totals.cache_read_tokens,
cc = record.totals.cache_creation_tokens,
cost = record.totals.cost_usd,
tp = fmt_opt(record.tests_passed),
tf = fmt_opt(record.tests_failed),
);
let log_path = out_dir.join("runs.log");
if let Some(parent) = log_path.parent() {
tokio::fs::create_dir_all(parent).await.ok();
}
use tokio::io::AsyncWriteExt;
let mut f = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)
.await
.with_context(|| format!("failed to open {}", log_path.display()))?;
f.write_all(line.as_bytes())
.await
.context("failed to append perf log line")?;
f.flush().await.ok();
tracing::info!(
path = %json_path.display(),
build = self.build,
total_ms = record.total_duration_ms,
total_cost_usd = record.totals.cost_usd,
"wrote perf record"
);
Ok(())
}
}