| 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | |
| 4 | use anyhow::{Context, Result, bail}; |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use codewhale_engine::cost_status::{UsageSourceContribution, usage_source_fingerprint}; |
| 7 | use codewhale_engine::llm_client::ProviderUsageCoverage; |
| 8 | use codewhale_engine::runtime_threads::{ |
| 9 | RuntimeDiagnosticRecord, RuntimeEventRecord, RuntimeThreadStore, ThreadRecord, TurnItemKind, |
| 10 | TurnItemLifecycleStatus, TurnItemRecord, TurnRecord, |
| 11 | }; |
| 12 | use codewhale_engine::session_manager::{ |
| 13 | SESSION_METADATA_READ_LIMIT, SessionManager, SessionMetadata, |
| 14 | }; |
| 15 | use serde::Serialize; |
| 16 | use serde_json::{Value, json}; |
| 17 | |
| 18 | use super::MetricsArgs; |
| 19 | |
| 20 | #[derive(Debug, Default, Serialize)] |
| 21 | pub(super) struct InspectionCoverage { |
| 22 | pub gaps: BTreeMap<String, u64>, |
| 23 | pub unknown_fields: BTreeSet<String>, |
| 24 | pub inherited_runtime_turns_excluded: u64, |
| 25 | pub source_copies_deduplicated: u64, |
| 26 | pub source_conflicts: u64, |
| 27 | pub project_ownership_ambiguous_sources: u64, |
| 28 | pub legacy_session_projections: u64, |
| 29 | pub unlinked_runtime_threads: u64, |
| 30 | pub inspection_cap_reached: bool, |
| 31 | pub retained_bytes: usize, |
| 32 | pub retention_limit_bytes: usize, |
| 33 | #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] |
| 34 | pub skipped_after_cap: BTreeMap<String, u64>, |
| 35 | } |
| 36 | |
| 37 | impl InspectionCoverage { |
| 38 | pub(super) fn gap(&mut self, kind: &str) { |
| 39 | let count = self.gaps.entry(kind.to_string()).or_default(); |
| 40 | *count = count.saturating_add(1); |
| 41 | } |
| 42 | |
| 43 | pub(super) fn skip_after_cap(&mut self, stage: &str) { |
| 44 | let count = self.skipped_after_cap.entry(stage.to_string()).or_default(); |
| 45 | *count = count.saturating_add(1); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Default, Serialize)] |
| 50 | pub(super) struct MoneyUsage { |
| 51 | pub identified_sources: u64, |
| 52 | pub reported_usage_sources: u64, |
| 53 | pub incomplete_usage_sources: u64, |
| 54 | pub missing_usage_sources: u64, |
| 55 | pub not_dispatched_sources: u64, |
| 56 | pub rejected_sources: u64, |
| 57 | pub zero_usage_presence_ambiguous_sources: u64, |
| 58 | pub observed_physical_attempts: u64, |
| 59 | pub omitted_physical_attempt_rows: u64, |
| 60 | pub input_tokens_known: u64, |
| 61 | pub output_tokens_known: u64, |
| 62 | pub cache_read_tokens_known: Option<u64>, |
| 63 | pub cache_miss_tokens_known: Option<u64>, |
| 64 | pub cache_write_tokens_known: Option<u64>, |
| 65 | pub cache_read_coverage_sources: u64, |
| 66 | pub inconsistent_cache_partition_sources: u64, |
| 67 | pub cache_input_partition_known: u64, |
| 68 | pub reasoning_tokens_known: Option<u64>, |
| 69 | pub reasoning_coverage_sources: u64, |
| 70 | pub reasoning_replay_tokens_known: Option<u64>, |
| 71 | pub reasoning_replay_coverage_sources: u64, |
| 72 | pub known_subtotal_usd: f64, |
| 73 | pub known_subtotal_cny: f64, |
| 74 | pub usd_price_unknown_sources: u64, |
| 75 | pub cny_price_unknown_sources: u64, |
| 76 | pub quote_unavailable_sources: u64, |
| 77 | pub cache_hit_percent_of_reported_subset: Option<f64>, |
| 78 | } |
| 79 | |
| 80 | #[derive(Debug, Default, Serialize)] |
| 81 | pub(super) struct SessionOverview { |
| 82 | pub saved_documents: u64, |
| 83 | pub messages_in_saved_documents: u64, |
| 84 | pub runtime_threads: u64, |
| 85 | pub runtime_turns: u64, |
| 86 | pub runtime_message_items: u64, |
| 87 | pub average_saved_session_tokens: Option<f64>, |
| 88 | pub median_saved_session_tokens: Option<f64>, |
| 89 | pub unique_conversations: Option<u64>, |
| 90 | } |
| 91 | |
| 92 | #[derive(Debug, Default, Serialize)] |
| 93 | pub(super) struct LegacyDisplay { |
| 94 | pub document: String, |
| 95 | pub workspace: String, |
| 96 | pub known_session_and_agent_usd: f64, |
| 97 | pub known_session_and_agent_cny: f64, |
| 98 | pub global_charge_identity_unproved: bool, |
| 99 | pub recorded_session_coverage: bool, |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug, Default, Serialize)] |
| 103 | pub(super) struct ToolReport { |
| 104 | pub identified_executions: u64, |
| 105 | pub successful_executions: u64, |
| 106 | pub failed_executions: u64, |
| 107 | pub unknown_outcomes: u64, |
| 108 | pub retained_text_token_estimate_known: Option<u64>, |
| 109 | pub retained_text_samples: u64, |
| 110 | pub original_output_bytes_known: Option<u64>, |
| 111 | pub truncated_samples: u64, |
| 112 | pub spooled_samples: u64, |
| 113 | pub output_shape_unknown_executions: u64, |
| 114 | pub failure_categories: BTreeMap<String, u64>, |
| 115 | pub exact_error_signature_recovery_rate: Option<f64>, |
| 116 | pub failure_rate_percent: Option<f64>, |
| 117 | } |
| 118 | |
| 119 | #[derive(Debug, Default, Serialize)] |
| 120 | pub(super) struct CompactionReport { |
| 121 | pub completed_items: u64, |
| 122 | pub before_messages_known: Option<u64>, |
| 123 | pub after_messages_known: Option<u64>, |
| 124 | pub summarizer_input_tokens_known: Option<u64>, |
| 125 | pub summarizer_output_tokens_known: Option<u64>, |
| 126 | pub attributable_cost_usd: Option<f64>, |
| 127 | pub attributable_cost_cny: Option<f64>, |
| 128 | pub history_tokens_dropped: Option<u64>, |
| 129 | } |
| 130 | |
| 131 | #[derive(Debug, Default, Serialize)] |
| 132 | pub(super) struct RoleReport { |
| 133 | pub recorded_tasks: u64, |
| 134 | pub usage_report_samples: Option<u64>, |
| 135 | pub input_tokens_known: Option<u64>, |
| 136 | pub output_tokens_known: Option<u64>, |
| 137 | pub task_states: BTreeMap<String, u64>, |
| 138 | pub failure_sources: BTreeMap<String, u64>, |
| 139 | pub known_cost_usd: Option<f64>, |
| 140 | pub known_cost_cny: Option<f64>, |
| 141 | pub recovery_rate: Option<f64>, |
| 142 | } |
| 143 | |
| 144 | #[derive(Debug, Default, Serialize)] |
| 145 | pub(super) struct StatsReport { |
| 146 | pub since: Option<DateTime<Utc>>, |
| 147 | pub project: Option<String>, |
| 148 | pub workspace_ids: BTreeSet<String>, |
| 149 | pub overview: SessionOverview, |
| 150 | pub accounting: Option<MoneyUsage>, |
| 151 | pub models: BTreeMap<String, MoneyUsage>, |
| 152 | pub legacy_display_subtotals_not_added_to_accounting: Vec<LegacyDisplay>, |
| 153 | pub latest_prepared_request_components: Option<Value>, |
| 154 | pub tools: BTreeMap<String, ToolReport>, |
| 155 | pub unattributed_tool_receipts: u64, |
| 156 | pub compaction: CompactionReport, |
| 157 | pub roles: BTreeMap<String, RoleReport>, |
| 158 | pub conflicting_source_views_not_added_to_accounting: Vec<Value>, |
| 159 | pub coverage: InspectionCoverage, |
| 160 | pub historical_coverage_complete: bool, |
| 161 | pub accounting_basis: &'static str, |
| 162 | pub project_filter_basis: &'static str, |
| 163 | pub legacy_receipt_projections_included: bool, |
| 164 | } |
| 165 | |
| 166 | #[derive(Serialize)] |
| 167 | struct SourceEntry { |
| 168 | contribution: UsageSourceContribution, |
| 169 | conflict: bool, |
| 170 | } |
| 171 | |
| 172 | #[derive(Clone, Serialize)] |
| 173 | struct ThreadScope { |
| 174 | workspace: PathBuf, |
| 175 | } |
| 176 | |
| 177 | #[derive(Clone, Serialize)] |
| 178 | struct TurnScope { |
| 179 | workspace: Option<PathBuf>, |
| 180 | inherited: bool, |
| 181 | } |
| 182 | |
| 183 | #[derive(Default, Serialize)] |
| 184 | struct ToolObservation { |
| 185 | name: String, |
| 186 | outcome: Option<bool>, |
| 187 | history_estimate: Option<u64>, |
| 188 | original_bytes: Option<u64>, |
| 189 | truncated: Option<bool>, |
| 190 | spooled: Option<bool>, |
| 191 | category: Option<String>, |
| 192 | identity_conflicted: bool, |
| 193 | outcome_conflicted: bool, |
| 194 | history_conflicted: bool, |
| 195 | } |
| 196 | |
| 197 | struct Collector<'a> { |
| 198 | args: &'a MetricsArgs, |
| 199 | report: StatsReport, |
| 200 | sources: BTreeMap<String, BTreeMap<u64, SourceEntry>>, |
| 201 | tools: BTreeMap<String, ToolObservation>, |
| 202 | threads: BTreeMap<String, ThreadScope>, |
| 203 | turns: BTreeMap<String, TurnScope>, |
| 204 | workspaces: BTreeSet<PathBuf>, |
| 205 | matched_session_ids: BTreeSet<String>, |
| 206 | session_tokens: Vec<u64>, |
| 207 | retained_bytes: usize, |
| 208 | retention_limit: usize, |
| 209 | fleet_replay_limit: usize, |
| 210 | inspection_cap_reached: bool, |
| 211 | compaction_items: BTreeSet<String>, |
| 212 | compaction_details: BTreeSet<String>, |
| 213 | compaction_identities: BTreeSet<String>, |
| 214 | compaction_usage_identities: BTreeSet<String>, |
| 215 | session_sources: BTreeMap<String, BTreeSet<String>>, |
| 216 | session_roles: BTreeMap<String, String>, |
| 217 | } |
| 218 | |
| 219 | fn path_id(path: &Path) -> String { |
| 220 | path.canonicalize() |
| 221 | .unwrap_or_else(|_| path.to_path_buf()) |
| 222 | .to_string_lossy() |
| 223 | .into_owned() |
| 224 | } |
| 225 | |
| 226 | fn scoped(root: &Path, id: &str) -> String { |
| 227 | format!("{}:{id}", usage_source_fingerprint(&path_id(root))) |
| 228 | } |
| 229 | |
| 230 | fn checked_sum(total: &mut u64, value: u64) -> Result<()> { |
| 231 | *total = total |
| 232 | .checked_add(value) |
| 233 | .context("Stats token/count overflow; report refused")?; |
| 234 | Ok(()) |
| 235 | } |
| 236 | |
| 237 | fn optional_sum(total: &mut Option<u64>, value: u64) -> Result<()> { |
| 238 | let next = total |
| 239 | .unwrap_or(0) |
| 240 | .checked_add(value) |
| 241 | .context("Stats optional count overflow; report refused")?; |
| 242 | *total = Some(next); |
| 243 | Ok(()) |
| 244 | } |
| 245 | |
| 246 | fn money_sum(total: &mut f64, value: f64) -> Result<()> { |
| 247 | let next = *total + value; |
| 248 | if !value.is_finite() || value < 0.0 || !next.is_finite() { |
| 249 | bail!("Stats invalid/overflowed monetary subtotal; report refused"); |
| 250 | } |
| 251 | *total = next; |
| 252 | Ok(()) |
| 253 | } |
| 254 | |
| 255 | impl MoneyUsage { |
| 256 | fn add(&mut self, contribution: &UsageSourceContribution) -> Result<()> { |
| 257 | contribution.validate()?; |
| 258 | let record = &contribution.record; |
| 259 | let revision = record |
| 260 | .settlement |
| 261 | .as_ref() |
| 262 | .context("Stats source has no native revision")?; |
| 263 | checked_sum(&mut self.identified_sources, 1)?; |
| 264 | checked_sum( |
| 265 | &mut self.observed_physical_attempts, |
| 266 | revision.physical_requests.len() as u64, |
| 267 | )?; |
| 268 | checked_sum( |
| 269 | &mut self.omitted_physical_attempt_rows, |
| 270 | revision.physical_requests_dropped, |
| 271 | )?; |
| 272 | let mut usage_known = match revision.coverage { |
| 273 | ProviderUsageCoverage::Reported => { |
| 274 | checked_sum(&mut self.reported_usage_sources, 1)?; |
| 275 | true |
| 276 | } |
| 277 | ProviderUsageCoverage::Incomplete => { |
| 278 | checked_sum(&mut self.incomplete_usage_sources, 1)?; |
| 279 | true |
| 280 | } |
| 281 | ProviderUsageCoverage::Missing => { |
| 282 | checked_sum(&mut self.missing_usage_sources, 1)?; |
| 283 | false |
| 284 | } |
| 285 | ProviderUsageCoverage::NotDispatched => { |
| 286 | checked_sum(&mut self.not_dispatched_sources, 1)?; |
| 287 | false |
| 288 | } |
| 289 | ProviderUsageCoverage::Rejected => { |
| 290 | checked_sum(&mut self.rejected_sources, 1)?; |
| 291 | false |
| 292 | } |
| 293 | }; |
| 294 | let usage = &record.usage.usage; |
| 295 | let zero_presence_ambiguous = usage_known |
| 296 | && usage.input_tokens == 0 |
| 297 | && usage.output_tokens == 0 |
| 298 | && [ |
| 299 | usage.prompt_cache_hit_tokens, |
| 300 | usage.prompt_cache_miss_tokens, |
| 301 | usage.prompt_cache_write_tokens, |
| 302 | usage.reasoning_tokens, |
| 303 | usage.input_audio_tokens, |
| 304 | usage.output_audio_tokens, |
| 305 | usage.reasoning_replay_tokens, |
| 306 | ] |
| 307 | .into_iter() |
| 308 | .flatten() |
| 309 | .all(|tokens| tokens == 0) |
| 310 | && usage |
| 311 | .request_usages |
| 312 | .iter() |
| 313 | .all(|usage| usage.input_tokens == 0 && usage.output_tokens == 0); |
| 314 | if zero_presence_ambiguous { |
| 315 | checked_sum(&mut self.zero_usage_presence_ambiguous_sources, 1)?; |
| 316 | usage_known = false; |
| 317 | } |
| 318 | let zero_money_unknown = zero_presence_ambiguous |
| 319 | && record |
| 320 | .usage |
| 321 | .route |
| 322 | .audit_frozen(&record.usage.usage) |
| 323 | .unpriced_reason |
| 324 | .is_none_or(|reason| reason.counts_toward_money_coverage()); |
| 325 | if usage_known { |
| 326 | let usage = &record.usage.usage; |
| 327 | checked_sum(&mut self.input_tokens_known, u64::from(usage.input_tokens))?; |
| 328 | checked_sum( |
| 329 | &mut self.output_tokens_known, |
| 330 | u64::from(usage.output_tokens), |
| 331 | )?; |
| 332 | let classes = codewhale_engine::pricing::token_usage_for_pricing(usage); |
| 333 | let cache_consistent = |
| 334 | codewhale_engine::pricing::usage_cache_partition_is_consistent(usage); |
| 335 | if !cache_consistent { |
| 336 | checked_sum(&mut self.inconsistent_cache_partition_sources, 1)?; |
| 337 | } |
| 338 | if cache_consistent && usage.prompt_cache_hit_tokens.is_some() { |
| 339 | optional_sum(&mut self.cache_read_tokens_known, classes.cache_read)?; |
| 340 | checked_sum(&mut self.cache_read_coverage_sources, 1)?; |
| 341 | checked_sum( |
| 342 | &mut self.cache_input_partition_known, |
| 343 | classes |
| 344 | .cache_read |
| 345 | .saturating_add(classes.input) |
| 346 | .saturating_add(classes.cache_write), |
| 347 | )?; |
| 348 | } |
| 349 | if cache_consistent && let Some(miss) = usage.prompt_cache_miss_tokens { |
| 350 | optional_sum(&mut self.cache_miss_tokens_known, u64::from(miss))?; |
| 351 | } |
| 352 | if cache_consistent && usage.prompt_cache_write_tokens.is_some() { |
| 353 | optional_sum(&mut self.cache_write_tokens_known, classes.cache_write)?; |
| 354 | } |
| 355 | if let Some(reasoning) = usage.reasoning_tokens { |
| 356 | optional_sum(&mut self.reasoning_tokens_known, u64::from(reasoning))?; |
| 357 | checked_sum(&mut self.reasoning_coverage_sources, 1)?; |
| 358 | } |
| 359 | if let Some(replay) = usage.reasoning_replay_tokens { |
| 360 | optional_sum(&mut self.reasoning_replay_tokens_known, u64::from(replay))?; |
| 361 | checked_sum(&mut self.reasoning_replay_coverage_sources, 1)?; |
| 362 | } |
| 363 | } |
| 364 | money_sum(&mut self.known_subtotal_usd, contribution.usd)?; |
| 365 | money_sum(&mut self.known_subtotal_cny, contribution.cny)?; |
| 366 | checked_sum( |
| 367 | &mut self.usd_price_unknown_sources, |
| 368 | u64::from(contribution.unpriced > 0 || zero_money_unknown), |
| 369 | )?; |
| 370 | checked_sum( |
| 371 | &mut self.cny_price_unknown_sources, |
| 372 | u64::from(contribution.cny_unpriced > 0 || zero_money_unknown), |
| 373 | )?; |
| 374 | if record.usage.route.provider_live_pricing.is_none() { |
| 375 | checked_sum(&mut self.quote_unavailable_sources, 1)?; |
| 376 | } |
| 377 | self.cache_hit_percent_of_reported_subset = |
| 378 | (self.cache_input_partition_known > 0).then(|| { |
| 379 | 100.0 * self.cache_read_tokens_known.unwrap_or(0) as f64 |
| 380 | / self.cache_input_partition_known as f64 |
| 381 | }); |
| 382 | Ok(()) |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | impl<'a> Collector<'a> { |
| 387 | fn new(args: &'a MetricsArgs) -> Self { |
| 388 | let mut report = StatsReport { |
| 389 | since: args.since, |
| 390 | project: args.project.as_deref().map(path_id), |
| 391 | historical_coverage_complete: false, |
| 392 | accounting: args.project.is_none().then(MoneyUsage::default), |
| 393 | accounting_basis: "identified persisted native source contributions; known estimates are subtotals, not invoice charges; receipt, transcript, Fleet and legacy display projections are not added again", |
| 394 | project_filter_basis: "current saved/thread/workspace-ledger views; native money and model subtotals unavailable without captured original source workspace", |
| 395 | legacy_receipt_projections_included: args.project.is_none(), |
| 396 | ..StatsReport::default() |
| 397 | }; |
| 398 | for field in [ |
| 399 | "complete historical coverage/retirement", |
| 400 | "legacy source contributions and historical quotes", |
| 401 | "explicit all-zero transport usage presence", |
| 402 | "cache warm/cold classification and churn causes", |
| 403 | "latest prepared-request component capture", |
| 404 | "tool bytes actually replayed on each provider request", |
| 405 | "exact repeated-error signature/recovery linkage", |
| 406 | "compaction source-to-money linkage", |
| 407 | "Fleet role-to-native-money linkage without a saved worker session", |
| 408 | "Fleet worker/run attempt lifecycle and recovery linkage", |
| 409 | ] { |
| 410 | report.coverage.unknown_fields.insert(field.to_string()); |
| 411 | } |
| 412 | Self { |
| 413 | args, |
| 414 | report, |
| 415 | sources: BTreeMap::new(), |
| 416 | tools: BTreeMap::new(), |
| 417 | threads: BTreeMap::new(), |
| 418 | turns: BTreeMap::new(), |
| 419 | workspaces: BTreeSet::new(), |
| 420 | matched_session_ids: BTreeSet::new(), |
| 421 | session_tokens: Vec::new(), |
| 422 | retained_bytes: 0, |
| 423 | retention_limit: SESSION_METADATA_READ_LIMIT, |
| 424 | fleet_replay_limit: SESSION_METADATA_READ_LIMIT, |
| 425 | inspection_cap_reached: false, |
| 426 | compaction_items: BTreeSet::new(), |
| 427 | compaction_details: BTreeSet::new(), |
| 428 | compaction_identities: BTreeSet::new(), |
| 429 | compaction_usage_identities: BTreeSet::new(), |
| 430 | session_sources: BTreeMap::new(), |
| 431 | session_roles: BTreeMap::new(), |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | fn retained_size<T: Serialize>(value: &T) -> Result<usize> { |
| 436 | serde_json::to_vec(value)? |
| 437 | .len() |
| 438 | .checked_add(128) |
| 439 | .context("Stats retained size overflow") |
| 440 | } |
| 441 | |
| 442 | fn admit_retained_bytes(&mut self, bytes: usize) -> bool { |
| 443 | if self.inspection_cap_reached { |
| 444 | return false; |
| 445 | } |
| 446 | let next = self.retained_bytes.checked_add(bytes); |
| 447 | if next.is_none_or(|total| total > self.retention_limit) { |
| 448 | self.inspection_cap_reached = true; |
| 449 | self.report.coverage.inspection_cap_reached = true; |
| 450 | self.report.coverage.gap("inspection_limit_reached"); |
| 451 | return false; |
| 452 | } |
| 453 | self.retained_bytes = next.unwrap_or(self.retention_limit); |
| 454 | true |
| 455 | } |
| 456 | |
| 457 | fn retain<T: Serialize>(&mut self, value: &T) -> Result<bool> { |
| 458 | if self.inspection_cap_reached { |
| 459 | return Ok(false); |
| 460 | } |
| 461 | let size = Self::retained_size(value)?; |
| 462 | Ok(self.admit_retained_bytes(size)) |
| 463 | } |
| 464 | |
| 465 | fn in_window(&self, timestamp: DateTime<Utc>) -> bool { |
| 466 | self.args.since.is_none_or(|cutoff| timestamp >= cutoff) |
| 467 | } |
| 468 | |
| 469 | fn in_project(&self, workspace: Option<&Path>) -> bool { |
| 470 | self.args.project.as_deref().is_none_or(|expected| { |
| 471 | workspace.is_some_and(|workspace| path_id(workspace) == path_id(expected)) |
| 472 | }) |
| 473 | } |
| 474 | |
| 475 | fn remember_workspace(&mut self, workspace: &Path) -> Result<()> { |
| 476 | if !self.workspaces.contains(workspace) { |
| 477 | if !self.retain(&(workspace, path_id(workspace)))? { |
| 478 | return Ok(()); |
| 479 | } |
| 480 | self.workspaces.insert(workspace.to_path_buf()); |
| 481 | self.report.workspace_ids.insert(path_id(workspace)); |
| 482 | } |
| 483 | Ok(()) |
| 484 | } |
| 485 | |
| 486 | fn source(&mut self, contribution: UsageSourceContribution) -> Result<Option<String>> { |
| 487 | if self.inspection_cap_reached { |
| 488 | return Ok(None); |
| 489 | } |
| 490 | if contribution.validate().is_err() { |
| 491 | self.report.coverage.gap("invalid_source_contribution"); |
| 492 | return Ok(None); |
| 493 | } |
| 494 | let record = &contribution.record; |
| 495 | let Some(revision) = record.settlement.as_ref() else { |
| 496 | self.report.coverage.gap("legacy_unidentified_source"); |
| 497 | return Ok(None); |
| 498 | }; |
| 499 | if !self.in_window(record.usage.route.dispatched_at) { |
| 500 | return Ok(None); |
| 501 | } |
| 502 | if self.args.project.is_some() { |
| 503 | checked_sum( |
| 504 | &mut self.report.coverage.project_ownership_ambiguous_sources, |
| 505 | 1, |
| 506 | )?; |
| 507 | return Ok(None); |
| 508 | } |
| 509 | let key = format!( |
| 510 | "{}:{}", |
| 511 | usage_source_fingerprint(&record.source_id), |
| 512 | revision.lineage() |
| 513 | ); |
| 514 | let revision = revision.revision(); |
| 515 | if let Some(old) = self |
| 516 | .sources |
| 517 | .get_mut(&key) |
| 518 | .and_then(|versions| versions.get_mut(&revision)) |
| 519 | { |
| 520 | checked_sum(&mut self.report.coverage.source_copies_deduplicated, 1)?; |
| 521 | if old.contribution.record != contribution.record { |
| 522 | old.conflict = true; |
| 523 | } |
| 524 | } else { |
| 525 | let entry = SourceEntry { |
| 526 | contribution, |
| 527 | conflict: false, |
| 528 | }; |
| 529 | if !self.retain(&entry)? { |
| 530 | return Ok(None); |
| 531 | } |
| 532 | self.sources |
| 533 | .entry(key.clone()) |
| 534 | .or_default() |
| 535 | .insert(revision, entry); |
| 536 | } |
| 537 | Ok(Some(key)) |
| 538 | } |
| 539 | |
| 540 | fn session(&mut self, root: &Path, metadata: SessionMetadata) -> Result<bool> { |
| 541 | if self.inspection_cap_reached |
| 542 | || !self.in_project(Some(&metadata.workspace)) |
| 543 | || !self.in_window(metadata.updated_at) |
| 544 | { |
| 545 | return Ok(false); |
| 546 | } |
| 547 | let display = LegacyDisplay { |
| 548 | document: usage_source_fingerprint(&scoped(root, &metadata.id)), |
| 549 | workspace: path_id(&metadata.workspace), |
| 550 | known_session_and_agent_usd: metadata.cost.session_cost_usd |
| 551 | + metadata.cost.subagent_cost_usd, |
| 552 | known_session_and_agent_cny: metadata.cost.session_cost_cny |
| 553 | + metadata.cost.subagent_cost_cny, |
| 554 | global_charge_identity_unproved: true, |
| 555 | recorded_session_coverage: metadata.cost.coverage_recorded, |
| 556 | }; |
| 557 | let display_valid = display.known_session_and_agent_usd.is_finite() |
| 558 | && display.known_session_and_agent_cny.is_finite() |
| 559 | && display.known_session_and_agent_usd >= 0.0 |
| 560 | && display.known_session_and_agent_cny >= 0.0; |
| 561 | let new_workspace = !self.workspaces.contains(&metadata.workspace); |
| 562 | let mut required_bytes = Self::retained_size(&metadata.total_tokens)?; |
| 563 | if new_workspace { |
| 564 | required_bytes = required_bytes |
| 565 | .checked_add(Self::retained_size(&( |
| 566 | &metadata.workspace, |
| 567 | &display.workspace, |
| 568 | ))?) |
| 569 | .context("Stats retained size overflow")?; |
| 570 | } |
| 571 | if display_valid { |
| 572 | required_bytes = required_bytes |
| 573 | .checked_add(Self::retained_size(&display)?) |
| 574 | .context("Stats retained size overflow")?; |
| 575 | } |
| 576 | if !self.admit_retained_bytes(required_bytes) { |
| 577 | return Ok(false); |
| 578 | } |
| 579 | if new_workspace { |
| 580 | self.workspaces.insert(metadata.workspace.clone()); |
| 581 | self.report.workspace_ids.insert(display.workspace.clone()); |
| 582 | } |
| 583 | self.matched_session_ids.insert(metadata.id.clone()); |
| 584 | checked_sum(&mut self.report.overview.saved_documents, 1)?; |
| 585 | checked_sum( |
| 586 | &mut self.report.overview.messages_in_saved_documents, |
| 587 | metadata.message_count as u64, |
| 588 | )?; |
| 589 | self.session_tokens.push(metadata.total_tokens); |
| 590 | if !display_valid { |
| 591 | self.report.coverage.gap("invalid_legacy_display_subtotal"); |
| 592 | } else { |
| 593 | self.report |
| 594 | .legacy_display_subtotals_not_added_to_accounting |
| 595 | .push(display); |
| 596 | } |
| 597 | if !metadata.cost.coverage_recorded { |
| 598 | checked_sum(&mut self.report.coverage.legacy_session_projections, 1)?; |
| 599 | } |
| 600 | if !metadata.cost.unpriced_reasons.is_empty() { |
| 601 | self.report.coverage.gap("session_usage_coverage_gap"); |
| 602 | } |
| 603 | for contribution in metadata.cost.accounted_usage_sources.into_values() { |
| 604 | if self.inspection_cap_reached { |
| 605 | break; |
| 606 | } |
| 607 | if let Some(key) = self.source(contribution)? |
| 608 | && self.retain(&(&metadata.id, &key))? |
| 609 | { |
| 610 | self.session_sources |
| 611 | .entry(metadata.id.clone()) |
| 612 | .or_default() |
| 613 | .insert(key); |
| 614 | } |
| 615 | } |
| 616 | Ok(true) |
| 617 | } |
| 618 | |
| 619 | fn runtime(&mut self, root: &Path, record: RuntimeDiagnosticRecord) -> Result<()> { |
| 620 | if self.inspection_cap_reached { |
| 621 | return Ok(()); |
| 622 | } |
| 623 | match record { |
| 624 | RuntimeDiagnosticRecord::Thread(thread) => self.thread(root, *thread), |
| 625 | RuntimeDiagnosticRecord::Turn(turn) => self.turn(root, *turn), |
| 626 | RuntimeDiagnosticRecord::Item(item) => self.item(root, *item), |
| 627 | RuntimeDiagnosticRecord::Event(event) => self.event(root, *event), |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | fn thread(&mut self, root: &Path, thread: ThreadRecord) -> Result<()> { |
| 632 | if self.inspection_cap_reached |
| 633 | || !self.in_project(Some(&thread.workspace)) |
| 634 | || !self.in_window(thread.updated_at) |
| 635 | { |
| 636 | return Ok(()); |
| 637 | } |
| 638 | let row = ThreadScope { |
| 639 | workspace: thread.workspace, |
| 640 | }; |
| 641 | let new_workspace = !self.workspaces.contains(&row.workspace); |
| 642 | let workspace_id = new_workspace.then(|| path_id(&row.workspace)); |
| 643 | let mut required_bytes = Self::retained_size(&row)?; |
| 644 | if let Some(workspace_id) = workspace_id.as_ref() { |
| 645 | required_bytes = required_bytes |
| 646 | .checked_add(Self::retained_size(&(&row.workspace, workspace_id))?) |
| 647 | .context("Stats retained size overflow")?; |
| 648 | } |
| 649 | if !self.admit_retained_bytes(required_bytes) { |
| 650 | return Ok(()); |
| 651 | } |
| 652 | if let Some(workspace_id) = workspace_id { |
| 653 | self.workspaces.insert(row.workspace.clone()); |
| 654 | self.report.workspace_ids.insert(workspace_id); |
| 655 | } |
| 656 | self.threads.insert(scoped(root, &thread.id), row); |
| 657 | checked_sum(&mut self.report.overview.runtime_threads, 1)?; |
| 658 | if thread.session_id.is_none() { |
| 659 | checked_sum(&mut self.report.coverage.unlinked_runtime_threads, 1)?; |
| 660 | } |
| 661 | Ok(()) |
| 662 | } |
| 663 | |
| 664 | fn tool(&mut self, execution: Option<&str>, row: ToolObservation) -> Result<()> { |
| 665 | if self.inspection_cap_reached { |
| 666 | return Ok(()); |
| 667 | } |
| 668 | let Some(execution) = execution.filter(|execution| !execution.is_empty()) else { |
| 669 | checked_sum(&mut self.report.unattributed_tool_receipts, 1)?; |
| 670 | return Ok(()); |
| 671 | }; |
| 672 | let key = usage_source_fingerprint(execution); |
| 673 | if let Some(old) = self.tools.get_mut(&key) { |
| 674 | if old.name == "unknown" && row.name != "unknown" { |
| 675 | old.name = row.name.clone(); |
| 676 | } else if row.name != "unknown" && old.name != row.name { |
| 677 | old.identity_conflicted = true; |
| 678 | self.report.coverage.gap("tool_execution_identity_conflict"); |
| 679 | } |
| 680 | if old.outcome.is_some() && row.outcome.is_some() && old.outcome != row.outcome { |
| 681 | old.outcome_conflicted = true; |
| 682 | self.report.coverage.gap("tool_execution_outcome_conflict"); |
| 683 | } else if row.outcome.is_some() { |
| 684 | old.outcome = row.outcome; |
| 685 | } |
| 686 | if row.history_estimate.is_some() { |
| 687 | if old.history_estimate.is_some() && old.history_estimate != row.history_estimate { |
| 688 | old.history_conflicted = true; |
| 689 | self.report.coverage.gap("tool_retained_projection_differs"); |
| 690 | } else { |
| 691 | old.history_estimate = row.history_estimate; |
| 692 | } |
| 693 | } |
| 694 | old.original_bytes = old.original_bytes.or(row.original_bytes); |
| 695 | old.truncated = old.truncated.or(row.truncated); |
| 696 | old.spooled = old.spooled.or(row.spooled); |
| 697 | old.category = old.category.take().or(row.category); |
| 698 | } else { |
| 699 | if !self.retain(&row)? { |
| 700 | return Ok(()); |
| 701 | } |
| 702 | self.tools.insert(key, row); |
| 703 | } |
| 704 | Ok(()) |
| 705 | } |
| 706 | |
| 707 | fn item(&mut self, root: &Path, item: TurnItemRecord) -> Result<()> { |
| 708 | if self.inspection_cap_reached { |
| 709 | return Ok(()); |
| 710 | } |
| 711 | let Some(scope) = self.turns.get(&scoped(root, &item.turn_id)) else { |
| 712 | if self.args.project.is_none() && self.args.since.is_none() { |
| 713 | self.report.coverage.gap("runtime_item_turn_unavailable"); |
| 714 | } |
| 715 | return Ok(()); |
| 716 | }; |
| 717 | if scope.inherited || !self.in_project(scope.workspace.as_deref()) { |
| 718 | return Ok(()); |
| 719 | } |
| 720 | let timestamp = item.started_at.or(item.ended_at); |
| 721 | if self.args.since.is_some() && timestamp.is_none() { |
| 722 | self.report |
| 723 | .coverage |
| 724 | .gap("runtime_item_timestamp_unavailable"); |
| 725 | return Ok(()); |
| 726 | } |
| 727 | if timestamp.is_some_and(|time| !self.in_window(time)) { |
| 728 | return Ok(()); |
| 729 | } |
| 730 | if matches!( |
| 731 | item.kind, |
| 732 | TurnItemKind::UserMessage | TurnItemKind::AgentMessage |
| 733 | ) { |
| 734 | checked_sum(&mut self.report.overview.runtime_message_items, 1)?; |
| 735 | return Ok(()); |
| 736 | } |
| 737 | if item.kind == TurnItemKind::ContextCompaction { |
| 738 | if item.status == TurnItemLifecycleStatus::Completed { |
| 739 | let key = scoped(root, &item.id); |
| 740 | if !self.compaction_items.contains(&key) { |
| 741 | if !self.retain(&key)? { |
| 742 | return Ok(()); |
| 743 | } |
| 744 | self.compaction_items.insert(key); |
| 745 | checked_sum(&mut self.report.compaction.completed_items, 1)?; |
| 746 | } |
| 747 | } |
| 748 | return Ok(()); |
| 749 | } |
| 750 | if !matches!( |
| 751 | item.kind, |
| 752 | TurnItemKind::ToolCall | TurnItemKind::FileChange | TurnItemKind::CommandExecution |
| 753 | ) { |
| 754 | return Ok(()); |
| 755 | } |
| 756 | let metadata = item.metadata.as_ref(); |
| 757 | let field = |name| metadata.and_then(|metadata| metadata.get(name)); |
| 758 | let result = field("tool_result_for").is_some(); |
| 759 | let outcome = item |
| 760 | .recorded_tool_error() |
| 761 | .map(|error| !error) |
| 762 | .or_else(|| (item.status == TurnItemLifecycleStatus::Failed).then_some(false)); |
| 763 | let detail = item.detail.as_deref(); |
| 764 | let row = ToolObservation { |
| 765 | name: label( |
| 766 | field("tool_name") |
| 767 | .and_then(Value::as_str) |
| 768 | .unwrap_or("unknown"), |
| 769 | ), |
| 770 | outcome, |
| 771 | history_estimate: result.then(|| detail.map(history_tokens)).flatten(), |
| 772 | original_bytes: field("original_byte_count").and_then(Value::as_u64), |
| 773 | truncated: field("truncated").and_then(Value::as_bool), |
| 774 | spooled: field("spooled").and_then(Value::as_bool).or_else(|| { |
| 775 | field("spillover_path") |
| 776 | .and_then(Value::as_str) |
| 777 | .map(|_| true) |
| 778 | }), |
| 779 | category: (outcome == Some(false)) |
| 780 | .then(|| detail.and_then(failure_category)) |
| 781 | .flatten(), |
| 782 | ..ToolObservation::default() |
| 783 | }; |
| 784 | self.tool(field("execution_id").and_then(Value::as_str), row) |
| 785 | } |
| 786 | |
| 787 | fn event(&mut self, root: &Path, event: RuntimeEventRecord) -> Result<()> { |
| 788 | if self.inspection_cap_reached || event.event != "item.completed" { |
| 789 | return Ok(()); |
| 790 | } |
| 791 | let Some(turn) = event |
| 792 | .turn_id |
| 793 | .as_ref() |
| 794 | .and_then(|id| self.turns.get(&scoped(root, id))) |
| 795 | else { |
| 796 | return Ok(()); |
| 797 | }; |
| 798 | if turn.inherited |
| 799 | || !self.in_project(turn.workspace.as_deref()) |
| 800 | || !self.in_window(event.timestamp) |
| 801 | { |
| 802 | return Ok(()); |
| 803 | } |
| 804 | if event.payload.pointer("/item/kind").and_then(Value::as_str) != Some("context_compaction") |
| 805 | { |
| 806 | return Ok(()); |
| 807 | } |
| 808 | let Some(id) = event.item_id.as_deref() else { |
| 809 | self.report.coverage.gap("compaction_identity_unavailable"); |
| 810 | return Ok(()); |
| 811 | }; |
| 812 | let key = scoped(root, id); |
| 813 | if self.compaction_details.contains(&key) { |
| 814 | return Ok(()); |
| 815 | } |
| 816 | if !self.retain(&key)? { |
| 817 | return Ok(()); |
| 818 | } |
| 819 | self.compaction_details.insert(key.clone()); |
| 820 | if let Some(cid) = event |
| 821 | .payload |
| 822 | .pointer("/item/metadata/compaction_id") |
| 823 | .and_then(Value::as_str) |
| 824 | { |
| 825 | self.compaction_identities |
| 826 | .insert(format!("{}:{cid}", event.thread_id)); |
| 827 | } |
| 828 | if self.compaction_items.insert(key) { |
| 829 | checked_sum(&mut self.report.compaction.completed_items, 1)?; |
| 830 | } |
| 831 | if let Some(before) = event.payload.get("messages_before").and_then(Value::as_u64) { |
| 832 | optional_sum(&mut self.report.compaction.before_messages_known, before)?; |
| 833 | } |
| 834 | if let Some(after) = event.payload.get("messages_after").and_then(Value::as_u64) { |
| 835 | optional_sum(&mut self.report.compaction.after_messages_known, after)?; |
| 836 | } |
| 837 | Ok(()) |
| 838 | } |
| 839 | |
| 840 | fn audit_compaction(&mut self, value: &Value) -> Result<()> { |
| 841 | if self.inspection_cap_reached { |
| 842 | return Ok(()); |
| 843 | } |
| 844 | let event = value.get("event").and_then(Value::as_str).unwrap_or(""); |
| 845 | if !matches!(event, "compaction.completed" | "context.compaction") { |
| 846 | return Ok(()); |
| 847 | } |
| 848 | let ts = super::parse_ts_field(value, "ts"); |
| 849 | if self.args.since.is_some() && ts.is_none() { |
| 850 | self.report |
| 851 | .coverage |
| 852 | .gap("audit_compaction_timestamp_unavailable"); |
| 853 | return Ok(()); |
| 854 | } |
| 855 | if ts.is_some_and(|t| !self.in_window(t)) { |
| 856 | return Ok(()); |
| 857 | } |
| 858 | if self.args.project.is_some() { |
| 859 | let session_id = value.pointer("/details/session_id").and_then(Value::as_str); |
| 860 | if session_id.is_none_or(|id| !self.matched_session_ids.contains(id)) { |
| 861 | return Ok(()); |
| 862 | } |
| 863 | } |
| 864 | let identity = super::compaction_receipt_identity(value, false); |
| 865 | let is_new_completion = match identity.as_ref() { |
| 866 | Some(id) => !self.compaction_identities.contains(id), |
| 867 | None => true, |
| 868 | }; |
| 869 | if is_new_completion { |
| 870 | if let Some(id) = identity.as_ref() { |
| 871 | if !self.retain(id)? { |
| 872 | return Ok(()); |
| 873 | } |
| 874 | self.compaction_identities.insert(id.clone()); |
| 875 | } |
| 876 | checked_sum(&mut self.report.compaction.completed_items, 1)?; |
| 877 | if let Some(before) = value |
| 878 | .pointer("/details/messages_before") |
| 879 | .and_then(Value::as_u64) |
| 880 | { |
| 881 | optional_sum(&mut self.report.compaction.before_messages_known, before)?; |
| 882 | } |
| 883 | if let Some(after) = value |
| 884 | .pointer("/details/messages_after") |
| 885 | .and_then(Value::as_u64) |
| 886 | { |
| 887 | optional_sum(&mut self.report.compaction.after_messages_known, after)?; |
| 888 | } |
| 889 | } |
| 890 | let is_new_usage = match identity.as_ref() { |
| 891 | Some(id) => !self.compaction_usage_identities.contains(id), |
| 892 | None => true, |
| 893 | }; |
| 894 | if is_new_usage |
| 895 | && let (Some(input), Some(output)) = ( |
| 896 | value |
| 897 | .pointer("/details/summarizer_usage/input_tokens") |
| 898 | .and_then(Value::as_u64), |
| 899 | value |
| 900 | .pointer("/details/summarizer_usage/output_tokens") |
| 901 | .and_then(Value::as_u64), |
| 902 | ) |
| 903 | && (input > 0 |
| 904 | || output > 0 |
| 905 | || value.pointer("/details/path").and_then(Value::as_str) == Some("summary")) |
| 906 | { |
| 907 | if let Some(id) = identity { |
| 908 | if !self.retain(&id)? { |
| 909 | return Ok(()); |
| 910 | } |
| 911 | self.compaction_usage_identities.insert(id); |
| 912 | } |
| 913 | optional_sum( |
| 914 | &mut self.report.compaction.summarizer_input_tokens_known, |
| 915 | input, |
| 916 | )?; |
| 917 | optional_sum( |
| 918 | &mut self.report.compaction.summarizer_output_tokens_known, |
| 919 | output, |
| 920 | )?; |
| 921 | } |
| 922 | Ok(()) |
| 923 | } |
| 924 | |
| 925 | fn session_tools(&mut self, value: &Value, workspace: &Path) -> Result<()> { |
| 926 | use codewhale_runtime::session_tree::{SessionEntryKind, SessionJournal}; |
| 927 | if self.inspection_cap_reached || !self.in_project(Some(workspace)) { |
| 928 | return Ok(()); |
| 929 | } |
| 930 | let mut names = BTreeMap::new(); |
| 931 | if let Some(journal) = value.get("journal").filter(|journal| !journal.is_null()) { |
| 932 | let journal: SessionJournal = match serde_json::from_value(journal.clone()) { |
| 933 | Ok(journal) => journal, |
| 934 | Err(_) => { |
| 935 | self.report.coverage.gap("session_tool_journal_unreadable"); |
| 936 | return Ok(()); |
| 937 | } |
| 938 | }; |
| 939 | if journal.validate().is_err() { |
| 940 | self.report.coverage.gap("session_tool_journal_invalid"); |
| 941 | return Ok(()); |
| 942 | } |
| 943 | for entry in journal.root_to_leaf() { |
| 944 | if self.inspection_cap_reached { |
| 945 | break; |
| 946 | } |
| 947 | if let SessionEntryKind::Message { message } = entry.kind.as_ref() { |
| 948 | self.session_message_tools( |
| 949 | &serde_json::to_value(message)?, |
| 950 | Some(entry.created_at), |
| 951 | &mut names, |
| 952 | )?; |
| 953 | } |
| 954 | } |
| 955 | return Ok(()); |
| 956 | } |
| 957 | if let Some(messages) = value.get("messages").and_then(Value::as_array) { |
| 958 | for message in messages { |
| 959 | if self.inspection_cap_reached { |
| 960 | break; |
| 961 | } |
| 962 | self.session_message_tools(message, None, &mut names)?; |
| 963 | } |
| 964 | } |
| 965 | Ok(()) |
| 966 | } |
| 967 | |
| 968 | fn session_message_tools( |
| 969 | &mut self, |
| 970 | message: &Value, |
| 971 | timestamp: Option<DateTime<Utc>>, |
| 972 | names: &mut BTreeMap<String, String>, |
| 973 | ) -> Result<()> { |
| 974 | if self.inspection_cap_reached { |
| 975 | return Ok(()); |
| 976 | } |
| 977 | let include = match timestamp { |
| 978 | Some(timestamp) => self.in_window(timestamp), |
| 979 | None if self.args.since.is_some() => { |
| 980 | self.report |
| 981 | .coverage |
| 982 | .gap("legacy_tool_timestamp_unavailable"); |
| 983 | false |
| 984 | } |
| 985 | None => true, |
| 986 | }; |
| 987 | for block in message |
| 988 | .get("content") |
| 989 | .and_then(Value::as_array) |
| 990 | .into_iter() |
| 991 | .flatten() |
| 992 | { |
| 993 | if self.inspection_cap_reached { |
| 994 | break; |
| 995 | } |
| 996 | match block.get("type").and_then(Value::as_str) { |
| 997 | Some("tool_use") => { |
| 998 | if let Some(execution) = block.get("execution_id").and_then(Value::as_str) { |
| 999 | let name = label( |
| 1000 | block |
| 1001 | .get("name") |
| 1002 | .and_then(Value::as_str) |
| 1003 | .unwrap_or("unknown"), |
| 1004 | ); |
| 1005 | if include { |
| 1006 | self.tool( |
| 1007 | Some(execution), |
| 1008 | ToolObservation { |
| 1009 | name: name.clone(), |
| 1010 | ..Default::default() |
| 1011 | }, |
| 1012 | )?; |
| 1013 | if self.inspection_cap_reached { |
| 1014 | break; |
| 1015 | } |
| 1016 | } |
| 1017 | names.insert(execution.to_string(), name); |
| 1018 | } else if include { |
| 1019 | checked_sum(&mut self.report.unattributed_tool_receipts, 1)?; |
| 1020 | } |
| 1021 | } |
| 1022 | Some("tool_result") if include => { |
| 1023 | let execution = block.get("execution_id").and_then(Value::as_str); |
| 1024 | let name = execution |
| 1025 | .and_then(|id| names.get(id)) |
| 1026 | .cloned() |
| 1027 | .unwrap_or_else(|| "unknown".to_string()); |
| 1028 | let content = block.get("content").and_then(Value::as_str); |
| 1029 | let outcome = block |
| 1030 | .get("is_error") |
| 1031 | .and_then(Value::as_bool) |
| 1032 | .map(|error| !error); |
| 1033 | self.tool( |
| 1034 | execution, |
| 1035 | ToolObservation { |
| 1036 | name, |
| 1037 | outcome, |
| 1038 | history_estimate: content.map(history_tokens), |
| 1039 | category: (outcome == Some(false)) |
| 1040 | .then(|| content.and_then(failure_category)) |
| 1041 | .flatten(), |
| 1042 | ..Default::default() |
| 1043 | }, |
| 1044 | )?; |
| 1045 | } |
| 1046 | _ => {} |
| 1047 | } |
| 1048 | } |
| 1049 | Ok(()) |
| 1050 | } |
| 1051 | |
| 1052 | fn fleet(&mut self, workspace: &Path) -> Result<()> { |
| 1053 | use codewhale_engine::fleet::ledger::{FleetLedger, FleetLedgerState, apply_record}; |
| 1054 | if self.inspection_cap_reached || !self.in_project(Some(workspace)) { |
| 1055 | return Ok(()); |
| 1056 | } |
| 1057 | let mut state = FleetLedgerState::default(); |
| 1058 | let mut replay_bytes = 0usize; |
| 1059 | let mut replay_cap_hit = false; |
| 1060 | let replay_limit = self.fleet_replay_limit; |
| 1061 | let result = FleetLedger::visit_diagnostic_records(workspace, |record| { |
| 1062 | let record = match record { |
| 1063 | Ok(record) => record, |
| 1064 | Err(error) => { |
| 1065 | if error |
| 1066 | .downcast_ref::<std::io::Error>() |
| 1067 | .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::FileTooLarge) |
| 1068 | { |
| 1069 | replay_cap_hit = true; |
| 1070 | } |
| 1071 | return Err(error); |
| 1072 | } |
| 1073 | }; |
| 1074 | let record_bytes = serde_json::to_vec(&record)?.len(); |
| 1075 | match replay_bytes.checked_add(record_bytes) { |
| 1076 | Some(total) if total <= replay_limit => { |
| 1077 | replay_bytes = total; |
| 1078 | } |
| 1079 | _ => { |
| 1080 | replay_cap_hit = true; |
| 1081 | bail!("Stats Fleet replay exceeds the bounded inspection limit"); |
| 1082 | } |
| 1083 | } |
| 1084 | apply_record(&mut state, record); |
| 1085 | Ok(()) |
| 1086 | }); |
| 1087 | if replay_cap_hit { |
| 1088 | self.report.coverage.inspection_cap_reached = true; |
| 1089 | self.report |
| 1090 | .coverage |
| 1091 | .gap("fleet_replay_inspection_limit_reached"); |
| 1092 | self.report.coverage.skip_after_cap("fleet_workspaces"); |
| 1093 | } else if result.is_err() { |
| 1094 | self.report |
| 1095 | .coverage |
| 1096 | .gap("fleet_replay_unavailable_or_inspection_limit"); |
| 1097 | return Ok(()); |
| 1098 | } |
| 1099 | for task in state.tasks.values() { |
| 1100 | let timestamp = chrono::DateTime::parse_from_rfc3339(&task.entry.enqueued_at) |
| 1101 | .ok() |
| 1102 | .map(|time| time.with_timezone(&Utc)); |
| 1103 | if self.args.since.is_some() && timestamp.is_none() { |
| 1104 | self.report.coverage.gap("fleet_task_timestamp_unavailable"); |
| 1105 | continue; |
| 1106 | } |
| 1107 | if timestamp.is_some_and(|time| !self.in_window(time)) { |
| 1108 | continue; |
| 1109 | } |
| 1110 | let run = state.runs.get(&task.entry.run_id.0); |
| 1111 | let role = run |
| 1112 | .and_then(|run| { |
| 1113 | run.task_specs |
| 1114 | .iter() |
| 1115 | .find(|spec| spec.id == task.entry.task_id) |
| 1116 | }) |
| 1117 | .and_then(|spec| spec.worker.as_ref()) |
| 1118 | .and_then(|worker| worker.role.as_deref()); |
| 1119 | let name = label(role.unwrap_or("unknown-role")); |
| 1120 | if role.is_none() { |
| 1121 | self.report.coverage.gap("fleet_task_role_unavailable"); |
| 1122 | } |
| 1123 | let status = serde_json::to_value(task.status)? |
| 1124 | .as_str() |
| 1125 | .unwrap_or("unknown") |
| 1126 | .to_string(); |
| 1127 | let receipt = state.receipts.values().find(|receipt| { |
| 1128 | receipt.run_id == task.entry.run_id && receipt.task_id == task.entry.task_id |
| 1129 | }); |
| 1130 | let failure = receipt |
| 1131 | .and_then(|receipt| receipt.failure_kind.as_ref()) |
| 1132 | .map(serde_json::to_value) |
| 1133 | .transpose()?; |
| 1134 | let failure = failure.as_ref().and_then(Value::as_str).map(label); |
| 1135 | if !self.report.roles.contains_key(&name) && !self.retain(&name)? { |
| 1136 | if !replay_cap_hit { |
| 1137 | self.report.coverage.skip_after_cap("fleet_workspaces"); |
| 1138 | } |
| 1139 | break; |
| 1140 | } |
| 1141 | if let Some(session) = receipt.and_then(|receipt| receipt.saved_session_id.as_ref()) { |
| 1142 | if self.session_roles.contains_key(session) { |
| 1143 | self.report.coverage.gap("fleet_saved_session_shared"); |
| 1144 | } else { |
| 1145 | if !self.retain(&(session, &name))? { |
| 1146 | if !replay_cap_hit { |
| 1147 | self.report.coverage.skip_after_cap("fleet_workspaces"); |
| 1148 | } |
| 1149 | break; |
| 1150 | } |
| 1151 | self.session_roles.insert(session.clone(), name.clone()); |
| 1152 | } |
| 1153 | } |
| 1154 | let report = self.report.roles.entry(name).or_default(); |
| 1155 | checked_sum(&mut report.recorded_tasks, 1)?; |
| 1156 | checked_sum(report.task_states.entry(status).or_default(), 1)?; |
| 1157 | if let Some(failure) = failure { |
| 1158 | checked_sum(report.failure_sources.entry(failure).or_default(), 1)?; |
| 1159 | } |
| 1160 | } |
| 1161 | Ok(()) |
| 1162 | } |
| 1163 | |
| 1164 | fn turn(&mut self, root: &Path, turn: TurnRecord) -> Result<()> { |
| 1165 | if self.inspection_cap_reached { |
| 1166 | return Ok(()); |
| 1167 | } |
| 1168 | let workspace = self |
| 1169 | .threads |
| 1170 | .get(&scoped(root, &turn.thread_id)) |
| 1171 | .map(|scope| scope.workspace.clone()); |
| 1172 | if (self.args.project.is_some() || self.args.since.is_some()) && workspace.is_none() { |
| 1173 | return Ok(()); |
| 1174 | } |
| 1175 | if self.args.project.is_some() && !self.in_project(workspace.as_deref()) { |
| 1176 | return Ok(()); |
| 1177 | } |
| 1178 | let turn_in_window = self.in_window(turn.created_at) |
| 1179 | || turn.started_at.is_some_and(|time| self.in_window(time)) |
| 1180 | || turn.ended_at.is_some_and(|time| self.in_window(time)) |
| 1181 | || turn |
| 1182 | .effective_dispatched_at |
| 1183 | .is_some_and(|time| self.in_window(time)); |
| 1184 | if !turn_in_window { |
| 1185 | return Ok(()); |
| 1186 | } |
| 1187 | let inherited = turn |
| 1188 | .source_usage_origin_turn_id |
| 1189 | .as_deref() |
| 1190 | .is_some_and(|original| original != turn.id); |
| 1191 | let row = TurnScope { |
| 1192 | workspace: workspace.clone(), |
| 1193 | inherited, |
| 1194 | }; |
| 1195 | if !self.retain(&row)? { |
| 1196 | return Ok(()); |
| 1197 | } |
| 1198 | self.turns.insert(scoped(root, &turn.id), row); |
| 1199 | if codewhale_engine::runtime_threads::runtime_usage_partition_parent(&turn).is_none() |
| 1200 | && self.in_project(workspace.as_deref()) |
| 1201 | { |
| 1202 | checked_sum(&mut self.report.overview.runtime_turns, 1)?; |
| 1203 | } |
| 1204 | if inherited { |
| 1205 | if codewhale_engine::runtime_threads::runtime_usage_partition_parent(&turn).is_none() { |
| 1206 | checked_sum( |
| 1207 | &mut self.report.coverage.inherited_runtime_turns_excluded, |
| 1208 | 1, |
| 1209 | )?; |
| 1210 | } |
| 1211 | return Ok(()); |
| 1212 | } |
| 1213 | if !turn.source_accounting || turn.routed_usage_dropped_records > 0 { |
| 1214 | self.report.coverage.gap("runtime_usage_coverage_gap"); |
| 1215 | } |
| 1216 | for (key, record) in turn.source_usage_records { |
| 1217 | if self.inspection_cap_reached { |
| 1218 | break; |
| 1219 | } |
| 1220 | if key != usage_source_fingerprint(&record.source_id) { |
| 1221 | self.report.coverage.gap("runtime_source_key_mismatch"); |
| 1222 | continue; |
| 1223 | } |
| 1224 | self.source(UsageSourceContribution::for_record(&record))?; |
| 1225 | } |
| 1226 | Ok(()) |
| 1227 | } |
| 1228 | |
| 1229 | fn finish(mut self) -> Result<StatsReport> { |
| 1230 | let mut selected_sources = BTreeMap::new(); |
| 1231 | for (source, versions) in &self.sources { |
| 1232 | let mut selected: Option<&SourceEntry> = None; |
| 1233 | let mut conflict = false; |
| 1234 | for entry in versions.values() { |
| 1235 | conflict |= entry.conflict; |
| 1236 | if let Some(previous) = selected { |
| 1237 | let prev_rec = &previous.contribution.record; |
| 1238 | let curr_rec = &entry.contribution.record; |
| 1239 | let prior_rev = prev_rec |
| 1240 | .settlement |
| 1241 | .as_ref() |
| 1242 | .map(|r| (r.lineage(), r.owner, r.revision())); |
| 1243 | let curr_rev = curr_rec |
| 1244 | .settlement |
| 1245 | .as_ref() |
| 1246 | .map(|r| (r.lineage(), r.owner, r.revision())); |
| 1247 | let valid_advance = match (prior_rev, curr_rev) { |
| 1248 | (Some((pl, po, pr)), Some((cl, co, cr))) => { |
| 1249 | prev_rec.usage.route == curr_rec.usage.route |
| 1250 | && pl == cl |
| 1251 | && po == co |
| 1252 | && pr.checked_add(1) == Some(cr) |
| 1253 | } |
| 1254 | _ => false, |
| 1255 | }; |
| 1256 | conflict |= !valid_advance; |
| 1257 | } |
| 1258 | selected = Some(entry); |
| 1259 | } |
| 1260 | if conflict { |
| 1261 | checked_sum(&mut self.report.coverage.source_conflicts, 1)?; |
| 1262 | for (revision, entry) in versions { |
| 1263 | self.report.conflicting_source_views_not_added_to_accounting.push(json!({"source": usage_source_fingerprint(source), "revision": revision, "known_usd": entry.contribution.usd, "known_cny": entry.contribution.cny, "usd_unknown": entry.contribution.unpriced > 0, "cny_unknown": entry.contribution.cny_unpriced > 0})); |
| 1264 | } |
| 1265 | continue; |
| 1266 | } |
| 1267 | let Some(entry) = selected else { |
| 1268 | continue; |
| 1269 | }; |
| 1270 | selected_sources.insert(source.as_str(), &entry.contribution); |
| 1271 | checked_sum( |
| 1272 | &mut self.report.coverage.project_ownership_ambiguous_sources, |
| 1273 | 1, |
| 1274 | )?; |
| 1275 | if self.args.project.is_some() { |
| 1276 | continue; |
| 1277 | } |
| 1278 | let route = &entry.contribution.record.usage.route; |
| 1279 | let key = format!( |
| 1280 | "{}/{} @ {}", |
| 1281 | route.provider_identity, |
| 1282 | route.model, |
| 1283 | route |
| 1284 | .endpoint_fingerprint |
| 1285 | .as_deref() |
| 1286 | .unwrap_or("unknown-endpoint") |
| 1287 | ); |
| 1288 | self.report |
| 1289 | .accounting |
| 1290 | .as_mut() |
| 1291 | .context("global Stats accounting projection unavailable")? |
| 1292 | .add(&entry.contribution)?; |
| 1293 | self.report |
| 1294 | .models |
| 1295 | .entry(key) |
| 1296 | .or_default() |
| 1297 | .add(&entry.contribution)?; |
| 1298 | } |
| 1299 | let known_usage = |usage: &MoneyUsage| { |
| 1300 | usage.reported_usage_sources + usage.incomplete_usage_sources |
| 1301 | - usage.zero_usage_presence_ambiguous_sources |
| 1302 | }; |
| 1303 | let mut role_usage = BTreeMap::<&str, (u64, [u64; 2], MoneyUsage)>::new(); |
| 1304 | for (session, role) in &self.session_roles { |
| 1305 | let (samples, priced, usage) = role_usage.entry(role.as_str()).or_default(); |
| 1306 | let known_before = known_usage(usage); |
| 1307 | for key in self.session_sources.get(session).into_iter().flatten() { |
| 1308 | if let Some(contribution) = selected_sources.remove(key.as_str()) { |
| 1309 | usage.add(contribution)?; |
| 1310 | checked_sum(&mut priced[0], contribution.priced.into())?; |
| 1311 | checked_sum(&mut priced[1], contribution.cny_priced.into())?; |
| 1312 | } |
| 1313 | } |
| 1314 | if known_usage(usage) > known_before { |
| 1315 | checked_sum(samples, 1)?; |
| 1316 | } |
| 1317 | } |
| 1318 | for (role, (samples, priced, usage)) in role_usage { |
| 1319 | let Some(report) = self.report.roles.get_mut(role).filter(|_| samples > 0) else { |
| 1320 | continue; |
| 1321 | }; |
| 1322 | report.usage_report_samples = Some(samples); |
| 1323 | report.input_tokens_known = Some(usage.input_tokens_known); |
| 1324 | report.output_tokens_known = Some(usage.output_tokens_known); |
| 1325 | report.known_cost_usd = (priced[0] > 0 && usage.usd_price_unknown_sources == 0) |
| 1326 | .then_some(usage.known_subtotal_usd); |
| 1327 | report.known_cost_cny = (priced[1] > 0 && usage.cny_price_unknown_sources == 0) |
| 1328 | .then_some(usage.known_subtotal_cny); |
| 1329 | } |
| 1330 | for row in self.tools.values() { |
| 1331 | let report = self.report.tools.entry(row.name.clone()).or_default(); |
| 1332 | checked_sum(&mut report.identified_executions, 1)?; |
| 1333 | match row |
| 1334 | .outcome |
| 1335 | .filter(|_| !row.identity_conflicted && !row.outcome_conflicted) |
| 1336 | { |
| 1337 | Some(true) => checked_sum(&mut report.successful_executions, 1)?, |
| 1338 | Some(false) => checked_sum(&mut report.failed_executions, 1)?, |
| 1339 | None => checked_sum(&mut report.unknown_outcomes, 1)?, |
| 1340 | } |
| 1341 | if let Some(tokens) = row |
| 1342 | .history_estimate |
| 1343 | .filter(|_| !row.identity_conflicted && !row.history_conflicted) |
| 1344 | { |
| 1345 | optional_sum(&mut report.retained_text_token_estimate_known, tokens)?; |
| 1346 | checked_sum(&mut report.retained_text_samples, 1)?; |
| 1347 | } |
| 1348 | if let Some(bytes) = row.original_bytes { |
| 1349 | optional_sum(&mut report.original_output_bytes_known, bytes)?; |
| 1350 | } |
| 1351 | if row.truncated == Some(true) { |
| 1352 | checked_sum(&mut report.truncated_samples, 1)?; |
| 1353 | } |
| 1354 | if row.spooled == Some(true) { |
| 1355 | checked_sum(&mut report.spooled_samples, 1)?; |
| 1356 | } |
| 1357 | if row.truncated.is_none() || row.spooled.is_none() { |
| 1358 | checked_sum(&mut report.output_shape_unknown_executions, 1)?; |
| 1359 | } |
| 1360 | if let Some(category) = row.category.as_ref().filter(|_| { |
| 1361 | row.outcome == Some(false) && !row.identity_conflicted && !row.outcome_conflicted |
| 1362 | }) { |
| 1363 | checked_sum( |
| 1364 | report |
| 1365 | .failure_categories |
| 1366 | .entry(category.clone()) |
| 1367 | .or_default(), |
| 1368 | 1, |
| 1369 | )?; |
| 1370 | } |
| 1371 | let judged = report.successful_executions + report.failed_executions; |
| 1372 | report.failure_rate_percent = |
| 1373 | (judged > 0).then(|| 100.0 * report.failed_executions as f64 / judged as f64); |
| 1374 | } |
| 1375 | self.session_tokens.sort_unstable(); |
| 1376 | let mut total = 0u64; |
| 1377 | for tokens in &self.session_tokens { |
| 1378 | checked_sum(&mut total, *tokens)?; |
| 1379 | } |
| 1380 | if !self.session_tokens.is_empty() { |
| 1381 | self.report.overview.average_saved_session_tokens = |
| 1382 | Some(total as f64 / self.session_tokens.len() as f64); |
| 1383 | let mid = self.session_tokens.len() / 2; |
| 1384 | self.report.overview.median_saved_session_tokens = |
| 1385 | Some(if self.session_tokens.len().is_multiple_of(2) { |
| 1386 | self.session_tokens[mid - 1] as f64 / 2.0 |
| 1387 | + self.session_tokens[mid] as f64 / 2.0 |
| 1388 | } else { |
| 1389 | self.session_tokens[mid] as f64 |
| 1390 | }); |
| 1391 | } |
| 1392 | limit_models(&mut self.report.models, self.args.models); |
| 1393 | limit_tools(&mut self.report.tools, self.args.tools); |
| 1394 | limit_roles(&mut self.report.roles, self.args.roles); |
| 1395 | self.report.coverage.retained_bytes = self.retained_bytes; |
| 1396 | self.report.coverage.retention_limit_bytes = self.retention_limit; |
| 1397 | Ok(self.report) |
| 1398 | } |
| 1399 | } |
| 1400 | |
| 1401 | fn label(value: &str) -> String { |
| 1402 | codewhale_runtime::safe_label::sanitize_persisted_route_label(value) |
| 1403 | } |
| 1404 | |
| 1405 | fn history_tokens(value: &str) -> u64 { |
| 1406 | codewhale_engine::compaction::estimate_text_tokens_conservative(value) as u64 |
| 1407 | } |
| 1408 | |
| 1409 | fn failure_category(value: &str) -> Option<String> { |
| 1410 | let signal = json!({"event": "tool_error", "is_error": true, "message": value}).to_string(); |
| 1411 | codewhale_runtime::session_diagnostics::analyze_session_failure_jsonl(&signal) |
| 1412 | .counts |
| 1413 | .keys() |
| 1414 | .next() |
| 1415 | .map(ToString::to_string) |
| 1416 | } |
| 1417 | |
| 1418 | fn keep_top<T>(values: &mut BTreeMap<String, T>, count: Option<usize>, score: impl Fn(&T) -> u64) { |
| 1419 | let Some(count) = count else { |
| 1420 | return; |
| 1421 | }; |
| 1422 | let mut selected = values |
| 1423 | .iter() |
| 1424 | .map(|(name, value)| (name.clone(), score(value))) |
| 1425 | .collect::<Vec<_>>(); |
| 1426 | selected.sort_by(|(a_name, a_score), (b_name, b_score)| { |
| 1427 | b_score.cmp(a_score).then_with(|| a_name.cmp(b_name)) |
| 1428 | }); |
| 1429 | let names = selected |
| 1430 | .into_iter() |
| 1431 | .take(count) |
| 1432 | .map(|(name, _)| name) |
| 1433 | .collect::<BTreeSet<_>>(); |
| 1434 | values.retain(|name, _| names.contains(name)); |
| 1435 | } |
| 1436 | |
| 1437 | fn limit_models(values: &mut BTreeMap<String, MoneyUsage>, count: Option<usize>) { |
| 1438 | keep_top(values, count, |value| { |
| 1439 | value |
| 1440 | .input_tokens_known |
| 1441 | .saturating_add(value.output_tokens_known) |
| 1442 | }); |
| 1443 | } |
| 1444 | |
| 1445 | fn limit_tools(values: &mut BTreeMap<String, ToolReport>, count: Option<usize>) { |
| 1446 | keep_top(values, count, |value| value.identified_executions); |
| 1447 | } |
| 1448 | |
| 1449 | fn limit_roles(values: &mut BTreeMap<String, RoleReport>, count: Option<usize>) { |
| 1450 | keep_top(values, count, |value| value.recorded_tasks); |
| 1451 | } |
| 1452 | |
| 1453 | pub(super) fn collect( |
| 1454 | args: &MetricsArgs, |
| 1455 | sessions: &Path, |
| 1456 | events: &[PathBuf], |
| 1457 | audit_roots: &[PathBuf], |
| 1458 | ) -> Result<StatsReport> { |
| 1459 | let mut collector = Collector::new(args); |
| 1460 | collect_into(&mut collector, sessions, events, audit_roots)?; |
| 1461 | collector.finish() |
| 1462 | } |
| 1463 | |
| 1464 | fn collect_into( |
| 1465 | collector: &mut Collector<'_>, |
| 1466 | sessions: &Path, |
| 1467 | events: &[PathBuf], |
| 1468 | audit_roots: &[PathBuf], |
| 1469 | ) -> Result<()> { |
| 1470 | let args = collector.args; |
| 1471 | if let Some(workspace) = args.project.as_deref() { |
| 1472 | collector.remember_workspace(workspace)?; |
| 1473 | } |
| 1474 | match SessionManager::open_read_only(sessions.to_path_buf()) { |
| 1475 | Ok(Some(manager)) => { |
| 1476 | for entry in std::fs::read_dir(manager.sessions_dir())? { |
| 1477 | let entry = match entry { |
| 1478 | Ok(entry) => entry, |
| 1479 | Err(_) => { |
| 1480 | if collector.inspection_cap_reached { |
| 1481 | break; |
| 1482 | } |
| 1483 | collector |
| 1484 | .report |
| 1485 | .coverage |
| 1486 | .gap("session_directory_entry_unreadable"); |
| 1487 | continue; |
| 1488 | } |
| 1489 | }; |
| 1490 | if entry |
| 1491 | .path() |
| 1492 | .extension() |
| 1493 | .is_none_or(|extension| extension != "json") |
| 1494 | { |
| 1495 | continue; |
| 1496 | } |
| 1497 | if collector.inspection_cap_reached { |
| 1498 | collector.report.coverage.skip_after_cap("sessions"); |
| 1499 | continue; |
| 1500 | } |
| 1501 | if !entry.file_type().is_ok_and(|kind| kind.is_file()) { |
| 1502 | collector.report.coverage.gap("session_record_not_regular"); |
| 1503 | continue; |
| 1504 | } |
| 1505 | let filename = entry.file_name(); |
| 1506 | let Some(id) = Path::new(&filename).file_stem().and_then(|id| id.to_str()) else { |
| 1507 | collector |
| 1508 | .report |
| 1509 | .coverage |
| 1510 | .gap("session_filename_unavailable"); |
| 1511 | continue; |
| 1512 | }; |
| 1513 | if manager.validated_session_id(id).is_err() { |
| 1514 | continue; |
| 1515 | } |
| 1516 | let metadata = match manager.load_usage_metadata(id) { |
| 1517 | Ok(metadata) => metadata, |
| 1518 | Err(_) => { |
| 1519 | collector |
| 1520 | .report |
| 1521 | .coverage |
| 1522 | .gap("session_metadata_or_accounting_unreadable"); |
| 1523 | continue; |
| 1524 | } |
| 1525 | }; |
| 1526 | let workspace = metadata.workspace.clone(); |
| 1527 | if !collector.session(manager.sessions_dir(), metadata)? { |
| 1528 | if collector.inspection_cap_reached { |
| 1529 | collector.report.coverage.skip_after_cap("sessions"); |
| 1530 | } |
| 1531 | continue; |
| 1532 | } |
| 1533 | if collector.inspection_cap_reached { |
| 1534 | continue; |
| 1535 | } |
| 1536 | match super::read_diagnostic_json(&entry.path()) { |
| 1537 | Ok(value) => { |
| 1538 | if value |
| 1539 | .get("schema_version") |
| 1540 | .and_then(Value::as_u64) |
| 1541 | .is_some_and(|version| { |
| 1542 | version |
| 1543 | > u64::from( |
| 1544 | codewhale_engine::session_manager::CURRENT_SESSION_SCHEMA_VERSION, |
| 1545 | ) |
| 1546 | }) |
| 1547 | { |
| 1548 | collector.report.coverage.gap("session_schema_unsupported"); |
| 1549 | continue; |
| 1550 | } |
| 1551 | collector.session_tools(&value, &workspace)?; |
| 1552 | } |
| 1553 | Err(_) => collector |
| 1554 | .report |
| 1555 | .coverage |
| 1556 | .gap("session_tool_projection_unreadable"), |
| 1557 | } |
| 1558 | } |
| 1559 | } |
| 1560 | Ok(None) => {} |
| 1561 | Err(_) => collector.report.coverage.gap("session_store_unreadable"), |
| 1562 | } |
| 1563 | let mut roots = BTreeSet::new(); |
| 1564 | for directory in events { |
| 1565 | let Some(root) = directory.parent() else { |
| 1566 | if !collector.inspection_cap_reached { |
| 1567 | collector.report.coverage.gap("runtime_root_unavailable"); |
| 1568 | } |
| 1569 | continue; |
| 1570 | }; |
| 1571 | if !roots.insert(path_id(root)) { |
| 1572 | continue; |
| 1573 | } |
| 1574 | if collector.inspection_cap_reached { |
| 1575 | if root.join("threads").is_dir() { |
| 1576 | collector.report.coverage.skip_after_cap("runtime_records"); |
| 1577 | break; |
| 1578 | } |
| 1579 | continue; |
| 1580 | } |
| 1581 | match RuntimeThreadStore::open_read_only(root.to_path_buf()) { |
| 1582 | Ok(Some(store)) => { |
| 1583 | store.visit_diagnostic_records_while(|record| { |
| 1584 | if collector.inspection_cap_reached { |
| 1585 | collector.report.coverage.skip_after_cap("runtime_records"); |
| 1586 | return Ok(std::ops::ControlFlow::Break(())); |
| 1587 | } |
| 1588 | match record { |
| 1589 | Ok(record) => collector.runtime(root, record)?, |
| 1590 | Err(_) => { |
| 1591 | collector.report.coverage.gap("runtime_record_unreadable"); |
| 1592 | } |
| 1593 | } |
| 1594 | if collector.inspection_cap_reached { |
| 1595 | collector.report.coverage.skip_after_cap("runtime_records"); |
| 1596 | return Ok(std::ops::ControlFlow::Break(())); |
| 1597 | } |
| 1598 | Ok(std::ops::ControlFlow::Continue(())) |
| 1599 | })?; |
| 1600 | if collector.inspection_cap_reached { |
| 1601 | break; |
| 1602 | } |
| 1603 | } |
| 1604 | Ok(None) => match std::fs::symlink_metadata(root) { |
| 1605 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 1606 | _ => collector |
| 1607 | .report |
| 1608 | .coverage |
| 1609 | .gap("runtime_thread_index_unavailable"), |
| 1610 | }, |
| 1611 | Err(_) => collector.report.coverage.gap("runtime_store_unreadable"), |
| 1612 | } |
| 1613 | } |
| 1614 | 'audit: for root in audit_roots { |
| 1615 | for name in ["audit.log.1", "audit.log"] { |
| 1616 | let path = root.join(name); |
| 1617 | if collector.inspection_cap_reached { |
| 1618 | if path.is_file() { |
| 1619 | collector.report.coverage.skip_after_cap("audit_lines"); |
| 1620 | break 'audit; |
| 1621 | } |
| 1622 | continue; |
| 1623 | } |
| 1624 | let Ok(file) = super::open_diagnostic_file(&path) else { |
| 1625 | continue; |
| 1626 | }; |
| 1627 | for raw_line in super::diagnostic_lines(file) { |
| 1628 | let Ok(raw_line) = raw_line else { |
| 1629 | break; |
| 1630 | }; |
| 1631 | let line = raw_line.trim(); |
| 1632 | if line.is_empty() { |
| 1633 | continue; |
| 1634 | } |
| 1635 | let Ok(value) = serde_json::from_str::<Value>(line) else { |
| 1636 | continue; |
| 1637 | }; |
| 1638 | collector.audit_compaction(&value)?; |
| 1639 | if collector.inspection_cap_reached { |
| 1640 | collector.report.coverage.skip_after_cap("audit_lines"); |
| 1641 | break 'audit; |
| 1642 | } |
| 1643 | } |
| 1644 | } |
| 1645 | } |
| 1646 | let workspaces = collector.workspaces.iter().cloned().collect::<Vec<_>>(); |
| 1647 | for workspace in workspaces { |
| 1648 | if collector.inspection_cap_reached { |
| 1649 | if codewhale_engine::fleet::ledger::fleet_ledger_path(&workspace).is_file() { |
| 1650 | collector.report.coverage.skip_after_cap("fleet_workspaces"); |
| 1651 | } |
| 1652 | continue; |
| 1653 | } |
| 1654 | collector.fleet(&workspace)?; |
| 1655 | } |
| 1656 | Ok(()) |
| 1657 | } |
| 1658 | |
| 1659 | fn format_byte_size(bytes: usize) -> String { |
| 1660 | const MIB: usize = 1024 * 1024; |
| 1661 | if bytes >= MIB && bytes.is_multiple_of(MIB) { |
| 1662 | format!("{} MiB", bytes / MIB) |
| 1663 | } else if bytes >= MIB { |
| 1664 | format!("{:.2} MiB", bytes as f64 / MIB as f64) |
| 1665 | } else { |
| 1666 | format!("{bytes} B") |
| 1667 | } |
| 1668 | } |
| 1669 | |
| 1670 | fn format_human_header(report: &StatsReport) -> String { |
| 1671 | use std::fmt::Write as _; |
| 1672 | let mut out = String::new(); |
| 1673 | if report.coverage.inspection_cap_reached { |
| 1674 | let limit_bytes = if report.coverage.retention_limit_bytes > 0 { |
| 1675 | report.coverage.retention_limit_bytes |
| 1676 | } else { |
| 1677 | SESSION_METADATA_READ_LIMIT |
| 1678 | }; |
| 1679 | let retained = format_byte_size(report.coverage.retained_bytes); |
| 1680 | let limit = format_byte_size(limit_bytes); |
| 1681 | let skipped = if report.coverage.skipped_after_cap.is_empty() { |
| 1682 | String::new() |
| 1683 | } else { |
| 1684 | let details = report |
| 1685 | .coverage |
| 1686 | .skipped_after_cap |
| 1687 | .iter() |
| 1688 | .map(|(stage, count)| format!("{stage}={count}")) |
| 1689 | .collect::<Vec<_>>() |
| 1690 | .join(", "); |
| 1691 | format!("; skipped after cap: {details}") |
| 1692 | }; |
| 1693 | let _ = writeln!( |
| 1694 | out, |
| 1695 | "Warning: partial report — retained inspection index reached the {limit} cap ({retained} / {limit}{skipped}); remaining records were skipped without evicting collected evidence (narrow --days, --since, or --project)." |
| 1696 | ); |
| 1697 | } |
| 1698 | if let Some(since) = report.since { |
| 1699 | let _ = writeln!(out, "Since: {}", since.format("%Y-%m-%d %H:%M UTC")); |
| 1700 | } |
| 1701 | out |
| 1702 | } |
| 1703 | |
| 1704 | pub(super) fn print_human(report: &StatsReport) { |
| 1705 | print!("{}", format_human_header(report)); |
| 1706 | if let Some(accounting) = &report.accounting { |
| 1707 | println!( |
| 1708 | "Known native-source subtotals: USD {:.6} ({} identified sources with unknown USD coverage), CNY {:.6} ({} identified sources with unknown CNY coverage)", |
| 1709 | accounting.known_subtotal_usd, |
| 1710 | accounting.usd_price_unknown_sources, |
| 1711 | accounting.known_subtotal_cny, |
| 1712 | accounting.cny_price_unknown_sources |
| 1713 | ); |
| 1714 | println!( |
| 1715 | "Known source tokens: {} input, {} output; cache read {}, cache write {}, reasoning {}, reasoning replay {}.", |
| 1716 | accounting.input_tokens_known, |
| 1717 | accounting.output_tokens_known, |
| 1718 | optional_count(accounting.cache_read_tokens_known), |
| 1719 | optional_count(accounting.cache_write_tokens_known), |
| 1720 | optional_count(accounting.reasoning_tokens_known), |
| 1721 | optional_count(accounting.reasoning_replay_tokens_known) |
| 1722 | ); |
| 1723 | } else { |
| 1724 | println!( |
| 1725 | "Native source money and model subtotals: unavailable for a workspace filter; original source workspace is not captured." |
| 1726 | ); |
| 1727 | } |
| 1728 | println!( |
| 1729 | "Historical coverage: incomplete; estimates from identified persisted sources, not provider invoice totals." |
| 1730 | ); |
| 1731 | println!( |
| 1732 | "Observed views: {} saved documents, {} saved messages, {} Runtime threads, {} Runtime turns; unique conversations unknown.", |
| 1733 | report.overview.saved_documents, |
| 1734 | report.overview.messages_in_saved_documents, |
| 1735 | report.overview.runtime_threads, |
| 1736 | report.overview.runtime_turns |
| 1737 | ); |
| 1738 | for (name, usage) in &report.models { |
| 1739 | println!("{}", model_line(name, usage)); |
| 1740 | } |
| 1741 | println!( |
| 1742 | "Latest prepared-request components: unavailable; no layer estimate is inferred from prefix hashes." |
| 1743 | ); |
| 1744 | for (name, tool) in &report.tools { |
| 1745 | println!( |
| 1746 | "Tool {}: {} identified executions, {} success, {} failure, {} unknown outcomes; retained-text token estimate {} ({} samples).", |
| 1747 | serde_json::to_string(name).unwrap_or_default(), |
| 1748 | tool.identified_executions, |
| 1749 | tool.successful_executions, |
| 1750 | tool.failed_executions, |
| 1751 | tool.unknown_outcomes, |
| 1752 | optional_count(tool.retained_text_token_estimate_known), |
| 1753 | tool.retained_text_samples |
| 1754 | ); |
| 1755 | } |
| 1756 | match ( |
| 1757 | report.compaction.summarizer_input_tokens_known, |
| 1758 | report.compaction.summarizer_output_tokens_known, |
| 1759 | ) { |
| 1760 | (Some(input), Some(output)) => { |
| 1761 | println!( |
| 1762 | "Compaction: {} completed observations; summarizer {} input / {} output tokens; attributable cost and dropped-history tokens unavailable.", |
| 1763 | report.compaction.completed_items, input, output |
| 1764 | ); |
| 1765 | } |
| 1766 | _ => { |
| 1767 | println!( |
| 1768 | "Compaction: {} completed observations; summarizer usage, attributable cost and dropped-history tokens unavailable.", |
| 1769 | report.compaction.completed_items |
| 1770 | ); |
| 1771 | } |
| 1772 | } |
| 1773 | for (name, role) in &report.roles { |
| 1774 | println!("{}", role_line(name, role)); |
| 1775 | } |
| 1776 | if !report.coverage.gaps.is_empty() { |
| 1777 | println!( |
| 1778 | "Inspection gaps: {}", |
| 1779 | serde_json::to_string(&report.coverage.gaps).unwrap_or_default() |
| 1780 | ); |
| 1781 | } |
| 1782 | println!( |
| 1783 | "Unavailable or unproven fields: {}", |
| 1784 | report |
| 1785 | .coverage |
| 1786 | .unknown_fields |
| 1787 | .iter() |
| 1788 | .cloned() |
| 1789 | .collect::<Vec<_>>() |
| 1790 | .join("; ") |
| 1791 | ); |
| 1792 | } |
| 1793 | |
| 1794 | fn model_line(name: &str, usage: &MoneyUsage) -> String { |
| 1795 | let hit = usage |
| 1796 | .cache_hit_percent_of_reported_subset |
| 1797 | .map_or_else(|| "unknown".to_string(), |percent| format!("{percent:.1}%")); |
| 1798 | format!( |
| 1799 | "Model {}: USD {:.6}, CNY {:.6}; {} input, {} output; cache read {} (hit {} of reported subset), cache write {}, reasoning {}; unknown USD/CNY sources {}/{}.", |
| 1800 | serde_json::to_string(name).unwrap_or_default(), |
| 1801 | usage.known_subtotal_usd, |
| 1802 | usage.known_subtotal_cny, |
| 1803 | usage.input_tokens_known, |
| 1804 | usage.output_tokens_known, |
| 1805 | optional_count(usage.cache_read_tokens_known), |
| 1806 | hit, |
| 1807 | optional_count(usage.cache_write_tokens_known), |
| 1808 | optional_count(usage.reasoning_tokens_known), |
| 1809 | usage.usd_price_unknown_sources, |
| 1810 | usage.cny_price_unknown_sources |
| 1811 | ) |
| 1812 | } |
| 1813 | |
| 1814 | fn optional_count(value: Option<u64>) -> String { |
| 1815 | value.map_or_else(|| "unknown".to_string(), |count| count.to_string()) |
| 1816 | } |
| 1817 | |
| 1818 | fn optional_money(value: Option<f64>) -> String { |
| 1819 | value.map_or_else(|| "unknown".to_string(), |money| format!("{money:.6}")) |
| 1820 | } |
| 1821 | |
| 1822 | fn role_line(name: &str, role: &RoleReport) -> String { |
| 1823 | let usage = match role.usage_report_samples { |
| 1824 | Some(samples) => format!( |
| 1825 | "usage from {samples} of {} tasks: {} input, {} output; USD {}, CNY {}", |
| 1826 | role.recorded_tasks, |
| 1827 | optional_count(role.input_tokens_known), |
| 1828 | optional_count(role.output_tokens_known), |
| 1829 | optional_money(role.known_cost_usd), |
| 1830 | optional_money(role.known_cost_cny) |
| 1831 | ), |
| 1832 | None => "source-linked cost/usage unavailable".to_string(), |
| 1833 | }; |
| 1834 | format!( |
| 1835 | "Role {}: {} observed tasks; states {}; {usage}; recovery rate unavailable.", |
| 1836 | serde_json::to_string(name).unwrap_or_default(), |
| 1837 | role.recorded_tasks, |
| 1838 | serde_json::to_string(&role.task_states).unwrap_or_default() |
| 1839 | ) |
| 1840 | } |
| 1841 | |
| 1842 | #[cfg(test)] |
| 1843 | mod tests { |
| 1844 | use super::*; |
| 1845 | |
| 1846 | fn runtime_tool_item( |
| 1847 | id: &str, |
| 1848 | status: TurnItemLifecycleStatus, |
| 1849 | detail: Option<&str>, |
| 1850 | metadata: Value, |
| 1851 | ) -> TurnItemRecord { |
| 1852 | TurnItemRecord { |
| 1853 | schema_version: 2, |
| 1854 | id: id.to_string(), |
| 1855 | turn_id: "turn_1".to_string(), |
| 1856 | kind: TurnItemKind::ToolCall, |
| 1857 | status, |
| 1858 | summary: String::new(), |
| 1859 | detail: detail.map(ToString::to_string), |
| 1860 | metadata: Some(metadata), |
| 1861 | artifact_refs: Vec::new(), |
| 1862 | artifacts: Vec::new(), |
| 1863 | started_at: None, |
| 1864 | ended_at: None, |
| 1865 | } |
| 1866 | } |
| 1867 | |
| 1868 | fn record_session_tool_pair( |
| 1869 | collector: &mut Collector<'_>, |
| 1870 | names: &mut BTreeMap<String, String>, |
| 1871 | id: &str, |
| 1872 | tool_name: &str, |
| 1873 | is_error: Option<Value>, |
| 1874 | content: &str, |
| 1875 | ) { |
| 1876 | let call = json!({ |
| 1877 | "role": "assistant", |
| 1878 | "content": [{ |
| 1879 | "type": "tool_use", |
| 1880 | "id": format!("call_{id}"), |
| 1881 | "execution_id": format!("exec_{id}"), |
| 1882 | "name": tool_name, |
| 1883 | "input": {} |
| 1884 | }] |
| 1885 | }); |
| 1886 | let mut result_block = json!({ |
| 1887 | "type": "tool_result", |
| 1888 | "tool_use_id": format!("call_{id}"), |
| 1889 | "execution_id": format!("exec_{id}"), |
| 1890 | "content": content |
| 1891 | }); |
| 1892 | if let Some(flag) = is_error { |
| 1893 | result_block["is_error"] = flag; |
| 1894 | } |
| 1895 | let result = json!({ |
| 1896 | "role": "user", |
| 1897 | "content": [result_block] |
| 1898 | }); |
| 1899 | collector |
| 1900 | .session_message_tools(&call, None, names) |
| 1901 | .expect("record tool_use"); |
| 1902 | collector |
| 1903 | .session_message_tools(&result, None, names) |
| 1904 | .expect("record tool_result"); |
| 1905 | } |
| 1906 | |
| 1907 | #[test] |
| 1908 | fn failed_tool_result_populates_command_exit_failure_category() { |
| 1909 | let args = MetricsArgs::default(); |
| 1910 | let mut collector = Collector::new(&args); |
| 1911 | let mut names = BTreeMap::new(); |
| 1912 | record_session_tool_pair( |
| 1913 | &mut collector, |
| 1914 | &mut names, |
| 1915 | "1", |
| 1916 | "exec_shell", |
| 1917 | Some(json!(true)), |
| 1918 | "stdout mentioning sandbox approval\n\nCommand exited with code 7", |
| 1919 | ); |
| 1920 | let report = collector.finish().expect("finish report"); |
| 1921 | let tool = &report.tools["exec_shell"]; |
| 1922 | assert_eq!(tool.successful_executions, 0); |
| 1923 | assert_eq!(tool.failed_executions, 1); |
| 1924 | assert_eq!(tool.unknown_outcomes, 0); |
| 1925 | assert_eq!(tool.failure_categories.get("command_exit"), Some(&1)); |
| 1926 | assert_eq!(tool.failure_categories.get("sandbox_approval"), None); |
| 1927 | } |
| 1928 | |
| 1929 | #[test] |
| 1930 | fn missing_or_invalid_outcomes_need_a_matching_runtime_receipt() { |
| 1931 | let args = MetricsArgs::default(); |
| 1932 | let mut collector = Collector::new(&args); |
| 1933 | let mut names = BTreeMap::new(); |
| 1934 | for (id, flag) in [ |
| 1935 | ("ok", Some(json!(false))), |
| 1936 | ("legacy", None), |
| 1937 | ("null", Some(Value::Null)), |
| 1938 | ("str", Some(json!("yes"))), |
| 1939 | ] { |
| 1940 | record_session_tool_pair(&mut collector, &mut names, id, "read_file", flag, "hello"); |
| 1941 | } |
| 1942 | let root = Path::new("runtime"); |
| 1943 | collector.turns.insert( |
| 1944 | scoped(root, "turn_1"), |
| 1945 | TurnScope { |
| 1946 | workspace: None, |
| 1947 | inherited: false, |
| 1948 | }, |
| 1949 | ); |
| 1950 | for (id, failed, live) in [ |
| 1951 | ("live_success", false, true), |
| 1952 | ("live_failure", true, true), |
| 1953 | ("legacy_seed", false, false), |
| 1954 | ("explicit_seed", false, false), |
| 1955 | ] { |
| 1956 | let execution_id = format!("exec_{id}"); |
| 1957 | let mut metadata = json!({ |
| 1958 | "execution_id": execution_id, |
| 1959 | "tool_result_for": execution_id, |
| 1960 | "is_error": failed |
| 1961 | }); |
| 1962 | if live { |
| 1963 | metadata["tool_use_id"] = json!(execution_id); |
| 1964 | metadata["tool_name"] = json!("read_file"); |
| 1965 | } else if id == "explicit_seed" { |
| 1966 | metadata["is_error_explicit"] = json!(true); |
| 1967 | } |
| 1968 | record_session_tool_pair(&mut collector, &mut names, id, "read_file", None, "hello"); |
| 1969 | collector |
| 1970 | .item( |
| 1971 | root, |
| 1972 | runtime_tool_item( |
| 1973 | id, |
| 1974 | if failed { |
| 1975 | TurnItemLifecycleStatus::Failed |
| 1976 | } else { |
| 1977 | TurnItemLifecycleStatus::Completed |
| 1978 | }, |
| 1979 | Some("hello"), |
| 1980 | metadata, |
| 1981 | ), |
| 1982 | ) |
| 1983 | .expect("record corroborating receipt"); |
| 1984 | } |
| 1985 | let report = collector.finish().expect("finish report"); |
| 1986 | let tool = &report.tools["read_file"]; |
| 1987 | assert_eq!(tool.identified_executions, 8); |
| 1988 | assert_eq!(tool.successful_executions, 3); |
| 1989 | assert_eq!(tool.failed_executions, 1); |
| 1990 | assert_eq!(tool.unknown_outcomes, 4); |
| 1991 | } |
| 1992 | |
| 1993 | #[test] |
| 1994 | fn tool_result_with_is_error_true_counts_as_failure() { |
| 1995 | let args = MetricsArgs::default(); |
| 1996 | let mut collector = Collector::new(&args); |
| 1997 | let mut names = BTreeMap::new(); |
| 1998 | record_session_tool_pair( |
| 1999 | &mut collector, |
| 2000 | &mut names, |
| 2001 | "err", |
| 2002 | "read_file", |
| 2003 | Some(json!(true)), |
| 2004 | "No such file or directory", |
| 2005 | ); |
| 2006 | let report = collector.finish().expect("finish report"); |
| 2007 | let tool = &report.tools["read_file"]; |
| 2008 | assert_eq!(tool.successful_executions, 0); |
| 2009 | assert_eq!(tool.failed_executions, 1); |
| 2010 | assert_eq!(tool.unknown_outcomes, 0); |
| 2011 | assert_eq!(tool.failure_categories.get("missing_dependency"), Some(&1)); |
| 2012 | } |
| 2013 | |
| 2014 | #[test] |
| 2015 | fn conflicting_outcomes_count_unknown_without_failure_category() { |
| 2016 | let args = MetricsArgs::default(); |
| 2017 | let mut collector = Collector::new(&args); |
| 2018 | let mut names = BTreeMap::new(); |
| 2019 | record_session_tool_pair( |
| 2020 | &mut collector, |
| 2021 | &mut names, |
| 2022 | "c", |
| 2023 | "exec_shell", |
| 2024 | Some(json!(false)), |
| 2025 | "ok output", |
| 2026 | ); |
| 2027 | let root = Path::new("runtime"); |
| 2028 | collector.turns.insert( |
| 2029 | scoped(root, "turn_1"), |
| 2030 | TurnScope { |
| 2031 | workspace: None, |
| 2032 | inherited: false, |
| 2033 | }, |
| 2034 | ); |
| 2035 | collector |
| 2036 | .item( |
| 2037 | root, |
| 2038 | runtime_tool_item( |
| 2039 | "item_c", |
| 2040 | TurnItemLifecycleStatus::Failed, |
| 2041 | Some("Command exited with code 7"), |
| 2042 | json!({ |
| 2043 | "tool_name": "exec_shell", |
| 2044 | "execution_id": "exec_c", |
| 2045 | "tool_result_for": "exec_c", |
| 2046 | "is_error": true |
| 2047 | }), |
| 2048 | ), |
| 2049 | ) |
| 2050 | .expect("record runtime item"); |
| 2051 | let report = collector.finish().expect("finish report"); |
| 2052 | let tool = &report.tools["exec_shell"]; |
| 2053 | assert_eq!(tool.unknown_outcomes, 1); |
| 2054 | assert_eq!(tool.failed_executions, 0); |
| 2055 | assert!(tool.failure_categories.is_empty()); |
| 2056 | } |
| 2057 | |
| 2058 | #[test] |
| 2059 | fn unanswered_tool_call_and_non_result_runtime_items_stay_unknown() { |
| 2060 | let args = MetricsArgs::default(); |
| 2061 | let mut collector = Collector::new(&args); |
| 2062 | let mut names = BTreeMap::new(); |
| 2063 | let call = json!({ |
| 2064 | "role": "assistant", |
| 2065 | "content": [{ |
| 2066 | "type": "tool_use", |
| 2067 | "id": "call_open", |
| 2068 | "execution_id": "exec_open", |
| 2069 | "name": "exec_shell", |
| 2070 | "input": {"command": "sleep 10"} |
| 2071 | }] |
| 2072 | }); |
| 2073 | collector |
| 2074 | .session_message_tools(&call, None, &mut names) |
| 2075 | .expect("record unanswered tool_use"); |
| 2076 | |
| 2077 | let root = Path::new("runtime"); |
| 2078 | collector.turns.insert( |
| 2079 | scoped(root, "turn_1"), |
| 2080 | TurnScope { |
| 2081 | workspace: None, |
| 2082 | inherited: false, |
| 2083 | }, |
| 2084 | ); |
| 2085 | collector |
| 2086 | .item( |
| 2087 | root, |
| 2088 | runtime_tool_item( |
| 2089 | "item_seed_use", |
| 2090 | TurnItemLifecycleStatus::Completed, |
| 2091 | Some("{}"), |
| 2092 | json!({ |
| 2093 | "tool_name": "exec_shell", |
| 2094 | "execution_id": "exec_seed_use", |
| 2095 | "tool_use_id": "exec_seed_use" |
| 2096 | }), |
| 2097 | ), |
| 2098 | ) |
| 2099 | .expect("record seeded tool_use item"); |
| 2100 | collector |
| 2101 | .item( |
| 2102 | root, |
| 2103 | runtime_tool_item( |
| 2104 | "item_interrupted", |
| 2105 | TurnItemLifecycleStatus::Interrupted, |
| 2106 | Some("{}"), |
| 2107 | json!({ |
| 2108 | "tool_name": "exec_shell", |
| 2109 | "execution_id": "exec_interrupted", |
| 2110 | "tool_use_id": "exec_interrupted" |
| 2111 | }), |
| 2112 | ), |
| 2113 | ) |
| 2114 | .expect("record interrupted tool item"); |
| 2115 | |
| 2116 | let report = collector.finish().expect("finish report"); |
| 2117 | let tool = &report.tools["exec_shell"]; |
| 2118 | assert_eq!(tool.identified_executions, 3); |
| 2119 | assert_eq!(tool.successful_executions, 0); |
| 2120 | assert_eq!(tool.failed_executions, 0); |
| 2121 | assert_eq!(tool.unknown_outcomes, 3); |
| 2122 | } |
| 2123 | |
| 2124 | #[test] |
| 2125 | fn audit_compaction_populates_native_stats_and_deduplicates_runtime() { |
| 2126 | let args = MetricsArgs::default(); |
| 2127 | let mut collector = Collector::new(&args); |
| 2128 | let audit_event = json!({ |
| 2129 | "ts": "2026-11-29T12:00:00Z", |
| 2130 | "event": "compaction.completed", |
| 2131 | "details": { |
| 2132 | "session_id": "sess-1", |
| 2133 | "compaction_id": "cmp-1", |
| 2134 | "path": "summary", |
| 2135 | "messages_before": 40, |
| 2136 | "messages_after": 12, |
| 2137 | "summarizer_usage": { |
| 2138 | "input_tokens": 50000, |
| 2139 | "output_tokens": 1200 |
| 2140 | } |
| 2141 | } |
| 2142 | }); |
| 2143 | collector |
| 2144 | .audit_compaction(&audit_event) |
| 2145 | .expect("first audit compaction"); |
| 2146 | collector |
| 2147 | .audit_compaction(&audit_event) |
| 2148 | .expect("duplicate audit compaction"); |
| 2149 | let report = collector.finish().expect("finish report"); |
| 2150 | assert_eq!(report.compaction.completed_items, 1); |
| 2151 | assert_eq!(report.compaction.before_messages_known, Some(40)); |
| 2152 | assert_eq!(report.compaction.after_messages_known, Some(12)); |
| 2153 | assert_eq!(report.compaction.summarizer_input_tokens_known, Some(50000)); |
| 2154 | assert_eq!(report.compaction.summarizer_output_tokens_known, Some(1200)); |
| 2155 | } |
| 2156 | |
| 2157 | #[test] |
| 2158 | fn retention_cap_returns_partial_report_instead_of_error() { |
| 2159 | let args = MetricsArgs::default(); |
| 2160 | let mut collector = Collector::new(&args); |
| 2161 | collector.retention_limit = 512; |
| 2162 | let mut names = BTreeMap::new(); |
| 2163 | for idx in 0..10 { |
| 2164 | record_session_tool_pair( |
| 2165 | &mut collector, |
| 2166 | &mut names, |
| 2167 | &idx.to_string(), |
| 2168 | "exec_shell", |
| 2169 | None, |
| 2170 | "ok", |
| 2171 | ); |
| 2172 | } |
| 2173 | let report = collector.finish().expect("partial report succeeds"); |
| 2174 | assert!(report.coverage.inspection_cap_reached); |
| 2175 | assert_eq!( |
| 2176 | report.coverage.gaps.get("inspection_limit_reached"), |
| 2177 | Some(&1) |
| 2178 | ); |
| 2179 | let recorded = report |
| 2180 | .tools |
| 2181 | .get("exec_shell") |
| 2182 | .map_or(0, |tool| tool.identified_executions); |
| 2183 | assert!(recorded > 0 && recorded < 10); |
| 2184 | } |
| 2185 | |
| 2186 | #[test] |
| 2187 | fn session_collect_skips_unmatched_session_bodies_before_parsing() { |
| 2188 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2189 | let sessions = temp.path().join("sessions"); |
| 2190 | std::fs::create_dir_all(&sessions).expect("sessions dir"); |
| 2191 | let kept_workspace = temp.path().join("kept-project"); |
| 2192 | let skipped_workspace = temp.path().join("other-project"); |
| 2193 | std::fs::create_dir_all(&kept_workspace).expect("kept workspace"); |
| 2194 | std::fs::create_dir_all(&skipped_workspace).expect("skipped workspace"); |
| 2195 | |
| 2196 | let kept = json!({ |
| 2197 | "schema_version": codewhale_engine::session_manager::CURRENT_SESSION_SCHEMA_VERSION, |
| 2198 | "metadata": { |
| 2199 | "id": "sess-kept", |
| 2200 | "title": "kept", |
| 2201 | "created_at": "2026-11-29T10:00:00Z", |
| 2202 | "updated_at": "2026-11-29T10:00:00Z", |
| 2203 | "message_count": 2, |
| 2204 | "total_tokens": 100, |
| 2205 | "model": "test-model", |
| 2206 | "workspace": kept_workspace |
| 2207 | }, |
| 2208 | "messages": [ |
| 2209 | { |
| 2210 | "role": "assistant", |
| 2211 | "content": [{ |
| 2212 | "type": "tool_use", |
| 2213 | "id": "call_1", |
| 2214 | "execution_id": "exec_kept", |
| 2215 | "name": "read_file", |
| 2216 | "input": {} |
| 2217 | }] |
| 2218 | }, |
| 2219 | { |
| 2220 | "role": "user", |
| 2221 | "content": [{ |
| 2222 | "type": "tool_result", |
| 2223 | "tool_use_id": "call_1", |
| 2224 | "execution_id": "exec_kept", |
| 2225 | "is_error": false, |
| 2226 | "content": "ok" |
| 2227 | }] |
| 2228 | } |
| 2229 | ] |
| 2230 | }); |
| 2231 | let skipped = json!({ |
| 2232 | "schema_version": 99999, |
| 2233 | "metadata": { |
| 2234 | "id": "sess-skipped", |
| 2235 | "title": "skipped", |
| 2236 | "created_at": "2026-11-29T10:00:00Z", |
| 2237 | "updated_at": "2026-11-29T10:00:00Z", |
| 2238 | "message_count": 2, |
| 2239 | "total_tokens": 200, |
| 2240 | "model": "test-model", |
| 2241 | "workspace": skipped_workspace |
| 2242 | }, |
| 2243 | "messages": [] |
| 2244 | }); |
| 2245 | std::fs::write(sessions.join("sess-kept.json"), kept.to_string()).expect("write kept"); |
| 2246 | std::fs::write(sessions.join("sess-skipped.json"), skipped.to_string()) |
| 2247 | .expect("write skipped"); |
| 2248 | |
| 2249 | let args = MetricsArgs { |
| 2250 | project: Some(kept_workspace), |
| 2251 | ..Default::default() |
| 2252 | }; |
| 2253 | let report = collect(&args, &sessions, &[], &[]).expect("collect"); |
| 2254 | assert_eq!(report.overview.saved_documents, 1); |
| 2255 | assert_eq!( |
| 2256 | report |
| 2257 | .tools |
| 2258 | .get("read_file") |
| 2259 | .map(|tool| tool.successful_executions), |
| 2260 | Some(1) |
| 2261 | ); |
| 2262 | assert_eq!(report.coverage.gaps.get("session_schema_unsupported"), None); |
| 2263 | } |
| 2264 | |
| 2265 | #[test] |
| 2266 | fn project_and_since_filters_isolate_unmatched_session_accounted_usage_sources() { |
| 2267 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2268 | let kept_workspace = temp.path().join("kept-project"); |
| 2269 | let other_workspace = temp.path().join("other-project"); |
| 2270 | std::fs::create_dir_all(&kept_workspace).expect("kept workspace"); |
| 2271 | std::fs::create_dir_all(&other_workspace).expect("other workspace"); |
| 2272 | |
| 2273 | let dispatched_at = "2026-11-29T10:00:00Z".parse::<DateTime<Utc>>().unwrap(); |
| 2274 | let route = codewhale_engine::cost_status::EffectiveRouteEnvelope::capture_observed( |
| 2275 | codewhale_config::ProviderKind::Deepseek, |
| 2276 | "deepseek", |
| 2277 | "deepseek-chat", |
| 2278 | Some("https://api.deepseek.com/v1"), |
| 2279 | dispatched_at, |
| 2280 | ); |
| 2281 | let usage = serde_json::from_value(json!({ |
| 2282 | "input_tokens": 100, |
| 2283 | "output_tokens": 40 |
| 2284 | })) |
| 2285 | .expect("usage"); |
| 2286 | let valid_record = codewhale_engine::cost_status::NativeUsageSource::capture( |
| 2287 | "src-valid", |
| 2288 | codewhale_engine::cost_status::UsageSpendOwner::Primary, |
| 2289 | ) |
| 2290 | .reported(&route, &usage) |
| 2291 | .persisted(); |
| 2292 | let valid_contribution = UsageSourceContribution::for_record(&valid_record); |
| 2293 | |
| 2294 | let mut legacy_record = valid_record.clone(); |
| 2295 | legacy_record.source_id = "src-legacy".to_string(); |
| 2296 | legacy_record.settlement = None; |
| 2297 | let legacy_contribution = UsageSourceContribution::for_record(&legacy_record); |
| 2298 | |
| 2299 | let mut invalid_contribution = valid_contribution.clone(); |
| 2300 | invalid_contribution.usd = f64::NAN; |
| 2301 | |
| 2302 | let mut other_meta: SessionMetadata = serde_json::from_value(json!({ |
| 2303 | "id": "sess-other", |
| 2304 | "title": "other", |
| 2305 | "created_at": "2026-11-29T10:00:00Z", |
| 2306 | "updated_at": "2026-11-29T10:05:00Z", |
| 2307 | "message_count": 2, |
| 2308 | "total_tokens": 140, |
| 2309 | "model": "deepseek-chat", |
| 2310 | "workspace": other_workspace |
| 2311 | })) |
| 2312 | .expect("other metadata"); |
| 2313 | other_meta |
| 2314 | .cost |
| 2315 | .accounted_usage_sources |
| 2316 | .insert("k_valid".to_string(), valid_contribution); |
| 2317 | other_meta |
| 2318 | .cost |
| 2319 | .accounted_usage_sources |
| 2320 | .insert("k_legacy".to_string(), legacy_contribution); |
| 2321 | other_meta |
| 2322 | .cost |
| 2323 | .accounted_usage_sources |
| 2324 | .insert("k_invalid".to_string(), invalid_contribution); |
| 2325 | |
| 2326 | let kept_meta: SessionMetadata = serde_json::from_value(json!({ |
| 2327 | "id": "sess-kept", |
| 2328 | "title": "kept", |
| 2329 | "created_at": "2026-11-29T10:00:00Z", |
| 2330 | "updated_at": "2026-11-29T10:05:00Z", |
| 2331 | "message_count": 1, |
| 2332 | "total_tokens": 50, |
| 2333 | "model": "deepseek-chat", |
| 2334 | "workspace": kept_workspace |
| 2335 | })) |
| 2336 | .expect("kept metadata"); |
| 2337 | |
| 2338 | let project_args = MetricsArgs { |
| 2339 | project: Some(kept_workspace.clone()), |
| 2340 | ..Default::default() |
| 2341 | }; |
| 2342 | let mut collector = Collector::new(&project_args); |
| 2343 | collector |
| 2344 | .session(temp.path(), other_meta.clone()) |
| 2345 | .expect("skip other project session"); |
| 2346 | collector |
| 2347 | .session(temp.path(), kept_meta) |
| 2348 | .expect("keep project session"); |
| 2349 | let report = collector.finish().expect("finish project report"); |
| 2350 | assert_eq!(report.overview.saved_documents, 1); |
| 2351 | assert_eq!(report.coverage.project_ownership_ambiguous_sources, 0); |
| 2352 | assert_eq!( |
| 2353 | report.coverage.gaps.get("invalid_source_contribution"), |
| 2354 | None |
| 2355 | ); |
| 2356 | assert_eq!(report.coverage.gaps.get("legacy_unidentified_source"), None); |
| 2357 | |
| 2358 | let since_args = MetricsArgs { |
| 2359 | since: Some("2026-11-30T00:00:00Z".parse::<DateTime<Utc>>().unwrap()), |
| 2360 | ..Default::default() |
| 2361 | }; |
| 2362 | let mut since_collector = Collector::new(&since_args); |
| 2363 | since_collector |
| 2364 | .session(temp.path(), other_meta) |
| 2365 | .expect("skip out-of-window session"); |
| 2366 | let since_report = since_collector.finish().expect("finish since report"); |
| 2367 | assert_eq!(since_report.overview.saved_documents, 0); |
| 2368 | assert_eq!( |
| 2369 | since_report |
| 2370 | .coverage |
| 2371 | .gaps |
| 2372 | .get("invalid_source_contribution"), |
| 2373 | None |
| 2374 | ); |
| 2375 | assert_eq!( |
| 2376 | since_report.coverage.gaps.get("legacy_unidentified_source"), |
| 2377 | None |
| 2378 | ); |
| 2379 | } |
| 2380 | |
| 2381 | #[test] |
| 2382 | fn since_filter_prefilters_old_turns_before_retention_and_preserves_straddling_turn() { |
| 2383 | let cutoff = "2026-11-29T12:00:00Z".parse::<DateTime<Utc>>().unwrap(); |
| 2384 | let args = MetricsArgs { |
| 2385 | since: Some(cutoff), |
| 2386 | ..Default::default() |
| 2387 | }; |
| 2388 | let mut collector = Collector::new(&args); |
| 2389 | collector.retention_limit = 1024; |
| 2390 | let root = Path::new("runtime"); |
| 2391 | let workspace = PathBuf::from("/tmp/cw-stats-turn-test"); |
| 2392 | |
| 2393 | let thread: ThreadRecord = serde_json::from_value(json!({ |
| 2394 | "id": "thread-1", |
| 2395 | "created_at": "2026-10-01T00:00:00Z", |
| 2396 | "updated_at": "2026-11-29T12:10:00Z", |
| 2397 | "model": "deepseek-chat", |
| 2398 | "workspace": workspace, |
| 2399 | "mode": "agent", |
| 2400 | "allow_shell": false, |
| 2401 | "trust_mode": false, |
| 2402 | "auto_approve": false |
| 2403 | })) |
| 2404 | .expect("thread record"); |
| 2405 | collector.thread(root, thread).expect("collect thread"); |
| 2406 | |
| 2407 | for idx in 0..40 { |
| 2408 | let old_turn: TurnRecord = serde_json::from_value(json!({ |
| 2409 | "id": format!("old-turn-{idx}"), |
| 2410 | "thread_id": "thread-1", |
| 2411 | "status": "completed", |
| 2412 | "input_summary": "old", |
| 2413 | "created_at": "2026-11-01T10:00:00Z", |
| 2414 | "started_at": "2026-11-01T10:00:01Z", |
| 2415 | "ended_at": "2026-11-01T10:00:10Z", |
| 2416 | "source_accounting": false, |
| 2417 | "routed_usage_dropped_records": 2 |
| 2418 | })) |
| 2419 | .expect("old turn"); |
| 2420 | collector.turn(root, old_turn).expect("skip old turn"); |
| 2421 | |
| 2422 | let old_item = TurnItemRecord { |
| 2423 | schema_version: 2, |
| 2424 | id: format!("old-item-{idx}"), |
| 2425 | turn_id: format!("old-turn-{idx}"), |
| 2426 | kind: TurnItemKind::UserMessage, |
| 2427 | status: TurnItemLifecycleStatus::Completed, |
| 2428 | summary: String::new(), |
| 2429 | detail: None, |
| 2430 | metadata: None, |
| 2431 | artifact_refs: Vec::new(), |
| 2432 | artifacts: Vec::new(), |
| 2433 | started_at: Some("2026-11-01T10:00:02Z".parse::<DateTime<Utc>>().unwrap()), |
| 2434 | ended_at: None, |
| 2435 | }; |
| 2436 | collector.item(root, old_item).expect("skip old item"); |
| 2437 | } |
| 2438 | |
| 2439 | let straddling_turn: TurnRecord = serde_json::from_value(json!({ |
| 2440 | "id": "turn-straddling", |
| 2441 | "thread_id": "thread-1", |
| 2442 | "status": "completed", |
| 2443 | "input_summary": "straddling", |
| 2444 | "created_at": "2026-11-29T11:59:50Z", |
| 2445 | "started_at": "2026-11-29T11:59:51Z", |
| 2446 | "ended_at": "2026-11-29T12:00:10Z", |
| 2447 | "source_accounting": true |
| 2448 | })) |
| 2449 | .expect("straddling turn"); |
| 2450 | collector |
| 2451 | .turn(root, straddling_turn) |
| 2452 | .expect("keep straddling turn"); |
| 2453 | |
| 2454 | let straddling_item = TurnItemRecord { |
| 2455 | schema_version: 2, |
| 2456 | id: "item-straddling".to_string(), |
| 2457 | turn_id: "turn-straddling".to_string(), |
| 2458 | kind: TurnItemKind::AgentMessage, |
| 2459 | status: TurnItemLifecycleStatus::Completed, |
| 2460 | summary: String::new(), |
| 2461 | detail: None, |
| 2462 | metadata: None, |
| 2463 | artifact_refs: Vec::new(), |
| 2464 | artifacts: Vec::new(), |
| 2465 | started_at: Some("2026-11-29T12:00:05Z".parse::<DateTime<Utc>>().unwrap()), |
| 2466 | ended_at: None, |
| 2467 | }; |
| 2468 | collector |
| 2469 | .item(root, straddling_item) |
| 2470 | .expect("count straddling item"); |
| 2471 | |
| 2472 | let report = collector.finish().expect("finish report"); |
| 2473 | assert!(!report.coverage.inspection_cap_reached); |
| 2474 | assert_eq!(report.coverage.gaps.get("inspection_limit_reached"), None); |
| 2475 | assert_eq!(report.coverage.gaps.get("runtime_usage_coverage_gap"), None); |
| 2476 | assert_eq!( |
| 2477 | report.coverage.gaps.get("runtime_item_turn_unavailable"), |
| 2478 | None |
| 2479 | ); |
| 2480 | assert_eq!(report.overview.runtime_turns, 1); |
| 2481 | assert_eq!(report.overview.runtime_message_items, 1); |
| 2482 | } |
| 2483 | |
| 2484 | #[test] |
| 2485 | fn print_human_header_renders_resolved_since_cutoff_for_empty_and_project_reports() { |
| 2486 | let cutoff = "2026-11-29T15:42:07Z".parse::<DateTime<Utc>>().unwrap(); |
| 2487 | let empty_args = MetricsArgs { |
| 2488 | since: Some(cutoff), |
| 2489 | ..Default::default() |
| 2490 | }; |
| 2491 | let empty_report = Collector::new(&empty_args).finish().expect("empty report"); |
| 2492 | assert_eq!( |
| 2493 | format_human_header(&empty_report), |
| 2494 | "Since: 2026-11-29 15:42 UTC\n" |
| 2495 | ); |
| 2496 | |
| 2497 | let project_args = MetricsArgs { |
| 2498 | since: Some(cutoff), |
| 2499 | project: Some(PathBuf::from("/tmp/cw-project")), |
| 2500 | ..Default::default() |
| 2501 | }; |
| 2502 | let project_report = Collector::new(&project_args) |
| 2503 | .finish() |
| 2504 | .expect("project report"); |
| 2505 | assert_eq!( |
| 2506 | format_human_header(&project_report), |
| 2507 | "Since: 2026-11-29 15:42 UTC\n" |
| 2508 | ); |
| 2509 | |
| 2510 | let unbounded_report = Collector::new(&MetricsArgs::default()) |
| 2511 | .finish() |
| 2512 | .expect("unbounded report"); |
| 2513 | assert_eq!(format_human_header(&unbounded_report), ""); |
| 2514 | } |
| 2515 | |
| 2516 | #[test] |
| 2517 | fn session_cap_hit_during_session_tools_preserves_saved_document_and_stops_post_cap_mutations() |
| 2518 | { |
| 2519 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2520 | let sessions = temp.path().join("sessions"); |
| 2521 | let workspace = temp.path().join("project"); |
| 2522 | std::fs::create_dir_all(&sessions).expect("sessions dir"); |
| 2523 | std::fs::create_dir_all(&workspace).expect("workspace dir"); |
| 2524 | |
| 2525 | let make_session = |id: &str, exec_prefix: &str| { |
| 2526 | json!({ |
| 2527 | "schema_version": codewhale_engine::session_manager::CURRENT_SESSION_SCHEMA_VERSION, |
| 2528 | "metadata": { |
| 2529 | "id": id, |
| 2530 | "title": "cap test", |
| 2531 | "created_at": "2026-11-29T10:00:00Z", |
| 2532 | "updated_at": "2026-11-29T10:05:00Z", |
| 2533 | "message_count": 3, |
| 2534 | "total_tokens": 100, |
| 2535 | "model": "test-model", |
| 2536 | "workspace": workspace |
| 2537 | }, |
| 2538 | "messages": [ |
| 2539 | { |
| 2540 | "role": "assistant", |
| 2541 | "content": [ |
| 2542 | { |
| 2543 | "type": "tool_use", |
| 2544 | "id": "call_1", |
| 2545 | "execution_id": format!("{exec_prefix}_1"), |
| 2546 | "name": "read_file", |
| 2547 | "input": {} |
| 2548 | }, |
| 2549 | { |
| 2550 | "type": "tool_use", |
| 2551 | "id": "call_2", |
| 2552 | "execution_id": format!("{exec_prefix}_2"), |
| 2553 | "name": "read_file", |
| 2554 | "input": {} |
| 2555 | }, |
| 2556 | { |
| 2557 | "type": "tool_use", |
| 2558 | "id": "call_unattributed", |
| 2559 | "name": "read_file", |
| 2560 | "input": {} |
| 2561 | } |
| 2562 | ] |
| 2563 | }, |
| 2564 | { |
| 2565 | "role": "assistant", |
| 2566 | "content": [ |
| 2567 | { |
| 2568 | "type": "tool_use", |
| 2569 | "id": "call_unattributed_next_msg", |
| 2570 | "name": "read_file", |
| 2571 | "input": {} |
| 2572 | } |
| 2573 | ] |
| 2574 | } |
| 2575 | ] |
| 2576 | }) |
| 2577 | }; |
| 2578 | |
| 2579 | let sess_a = make_session("sess-a", "exec_a"); |
| 2580 | let sess_b = make_session("sess-b", "exec_b"); |
| 2581 | std::fs::write(sessions.join("sess-a.json"), sess_a.to_string()).expect("write sess-a"); |
| 2582 | std::fs::write(sessions.join("sess-b.json"), sess_b.to_string()).expect("write sess-b"); |
| 2583 | |
| 2584 | let probe_meta: SessionMetadata = |
| 2585 | serde_json::from_value(sess_a["metadata"].clone()).expect("probe metadata"); |
| 2586 | let args = MetricsArgs::default(); |
| 2587 | let mut probe = Collector::new(&args); |
| 2588 | assert!( |
| 2589 | probe |
| 2590 | .session(&sessions, probe_meta.clone()) |
| 2591 | .expect("probe session") |
| 2592 | ); |
| 2593 | let session_bytes = probe.retained_bytes; |
| 2594 | let one_tool_bytes = Collector::retained_size(&ToolObservation { |
| 2595 | name: "read_file".to_string(), |
| 2596 | ..Default::default() |
| 2597 | }) |
| 2598 | .expect("tool size"); |
| 2599 | |
| 2600 | let mut rejected_collector = Collector::new(&args); |
| 2601 | rejected_collector.retention_limit = session_bytes - 1; |
| 2602 | assert!( |
| 2603 | !rejected_collector |
| 2604 | .session(&sessions, probe_meta) |
| 2605 | .expect("reject over-cap session") |
| 2606 | ); |
| 2607 | let rejected_report = rejected_collector.finish().expect("finish rejected report"); |
| 2608 | assert!(rejected_report.coverage.inspection_cap_reached); |
| 2609 | assert_eq!(rejected_report.overview.saved_documents, 0); |
| 2610 | assert!(rejected_report.workspace_ids.is_empty()); |
| 2611 | assert_eq!(rejected_report.coverage.retained_bytes, 0); |
| 2612 | |
| 2613 | let mut collector = Collector::new(&args); |
| 2614 | collector.retention_limit = session_bytes + one_tool_bytes; |
| 2615 | collect_into(&mut collector, &sessions, &[], &[]).expect("collect into"); |
| 2616 | let report = collector.finish().expect("finish report"); |
| 2617 | |
| 2618 | assert!(report.coverage.inspection_cap_reached); |
| 2619 | assert_eq!(report.overview.saved_documents, 1); |
| 2620 | assert_eq!(report.unattributed_tool_receipts, 0); |
| 2621 | assert_eq!( |
| 2622 | report |
| 2623 | .tools |
| 2624 | .get("read_file") |
| 2625 | .map(|tool| tool.identified_executions), |
| 2626 | Some(1) |
| 2627 | ); |
| 2628 | assert_eq!(report.coverage.skipped_after_cap.get("sessions"), Some(&1)); |
| 2629 | assert_eq!( |
| 2630 | report.coverage.retained_bytes, |
| 2631 | session_bytes + one_tool_bytes |
| 2632 | ); |
| 2633 | assert_eq!( |
| 2634 | report.coverage.retention_limit_bytes, |
| 2635 | session_bytes + one_tool_bytes |
| 2636 | ); |
| 2637 | let header = format_human_header(&report); |
| 2638 | assert!(header.contains("skipped after cap: sessions=1"), "{header}"); |
| 2639 | |
| 2640 | let since_args = MetricsArgs { |
| 2641 | since: Some("2026-11-29T00:00:00Z".parse::<DateTime<Utc>>().unwrap()), |
| 2642 | ..Default::default() |
| 2643 | }; |
| 2644 | let mut since_collector = Collector::new(&since_args); |
| 2645 | since_collector.inspection_cap_reached = true; |
| 2646 | let mut names = BTreeMap::new(); |
| 2647 | since_collector |
| 2648 | .session_tools(&sess_a, &workspace) |
| 2649 | .expect("session_tools after cap"); |
| 2650 | since_collector |
| 2651 | .session_message_tools(&sess_a["messages"][0], None, &mut names) |
| 2652 | .expect("session_message_tools after cap"); |
| 2653 | let since_report = since_collector.finish().expect("finish since report"); |
| 2654 | assert!(names.is_empty()); |
| 2655 | assert_eq!(since_report.unattributed_tool_receipts, 0); |
| 2656 | assert_eq!( |
| 2657 | since_report |
| 2658 | .coverage |
| 2659 | .gaps |
| 2660 | .get("legacy_tool_timestamp_unavailable"), |
| 2661 | None |
| 2662 | ); |
| 2663 | } |
| 2664 | |
| 2665 | #[test] |
| 2666 | fn thread_cap_hit_does_not_inflate_runtime_thread_or_unlinked_counters() { |
| 2667 | let args = MetricsArgs::default(); |
| 2668 | let root = Path::new("runtime"); |
| 2669 | let workspace_one = PathBuf::from("/tmp/cw-stats-thread-cap-1"); |
| 2670 | let workspace_two = PathBuf::from("/tmp/cw-stats-thread-cap-2"); |
| 2671 | |
| 2672 | let make_thread = |id: &str, workspace: &Path| -> ThreadRecord { |
| 2673 | serde_json::from_value(json!({ |
| 2674 | "id": id, |
| 2675 | "created_at": "2026-11-29T10:00:00Z", |
| 2676 | "updated_at": "2026-11-29T12:10:00Z", |
| 2677 | "model": "deepseek-chat", |
| 2678 | "workspace": workspace, |
| 2679 | "mode": "agent", |
| 2680 | "allow_shell": false, |
| 2681 | "trust_mode": false, |
| 2682 | "auto_approve": false |
| 2683 | })) |
| 2684 | .expect("thread record") |
| 2685 | }; |
| 2686 | |
| 2687 | let thread_one = make_thread("thread-1", &workspace_one); |
| 2688 | let thread_two = make_thread("thread-2", &workspace_two); |
| 2689 | |
| 2690 | let mut probe = Collector::new(&args); |
| 2691 | probe |
| 2692 | .thread(root, thread_one.clone()) |
| 2693 | .expect("probe thread 1"); |
| 2694 | let first_thread_bytes = probe.retained_bytes; |
| 2695 | |
| 2696 | let mut collector = Collector::new(&args); |
| 2697 | collector.retention_limit = first_thread_bytes; |
| 2698 | collector.thread(root, thread_one).expect("admit thread 1"); |
| 2699 | collector.thread(root, thread_two).expect("reject thread 2"); |
| 2700 | let report = collector.finish().expect("finish report"); |
| 2701 | |
| 2702 | assert!(report.coverage.inspection_cap_reached); |
| 2703 | assert_eq!( |
| 2704 | report.coverage.gaps.get("inspection_limit_reached"), |
| 2705 | Some(&1) |
| 2706 | ); |
| 2707 | assert_eq!(report.overview.runtime_threads, 1); |
| 2708 | assert_eq!(report.coverage.unlinked_runtime_threads, 1); |
| 2709 | assert_eq!(report.workspace_ids.len(), 1); |
| 2710 | assert_eq!(report.coverage.retained_bytes, first_thread_bytes); |
| 2711 | assert_eq!(report.coverage.retention_limit_bytes, first_thread_bytes); |
| 2712 | } |
| 2713 | |
| 2714 | #[test] |
| 2715 | fn visit_diagnostic_records_while_short_circuits_immediately_on_break() { |
| 2716 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2717 | let root = temp.path().join("runtime"); |
| 2718 | let threads_dir = root.join("threads"); |
| 2719 | let turns_dir = root.join("turns"); |
| 2720 | let items_dir = root.join("items"); |
| 2721 | let events_dir = root.join("events"); |
| 2722 | std::fs::create_dir_all(&threads_dir).expect("threads dir"); |
| 2723 | std::fs::create_dir_all(&turns_dir).expect("turns dir"); |
| 2724 | std::fs::create_dir_all(&items_dir).expect("items dir"); |
| 2725 | std::fs::create_dir_all(&events_dir).expect("events dir"); |
| 2726 | |
| 2727 | let workspace = temp.path().join("workspace"); |
| 2728 | std::fs::create_dir_all(&workspace).expect("workspace dir"); |
| 2729 | let write_thread = |id: &str| { |
| 2730 | let payload = json!({ |
| 2731 | "id": id, |
| 2732 | "created_at": "2026-11-29T10:00:00Z", |
| 2733 | "updated_at": "2026-11-29T12:10:00Z", |
| 2734 | "model": "deepseek-chat", |
| 2735 | "workspace": workspace, |
| 2736 | "mode": "agent", |
| 2737 | "allow_shell": false, |
| 2738 | "trust_mode": false, |
| 2739 | "auto_approve": false |
| 2740 | }); |
| 2741 | std::fs::write(threads_dir.join(format!("{id}.json")), payload.to_string()) |
| 2742 | .expect("write thread"); |
| 2743 | }; |
| 2744 | write_thread("thread-1"); |
| 2745 | write_thread("thread-2"); |
| 2746 | std::fs::write(threads_dir.join("thread-3.json"), "{not-valid-json") |
| 2747 | .expect("write corrupt thread"); |
| 2748 | std::fs::write(turns_dir.join("turn-1.json"), "{not-valid-json") |
| 2749 | .expect("write corrupt turn"); |
| 2750 | |
| 2751 | let store = RuntimeThreadStore::open_read_only(root.clone()) |
| 2752 | .expect("open read-only store") |
| 2753 | .expect("store exists"); |
| 2754 | let mut visited = 0usize; |
| 2755 | store |
| 2756 | .visit_diagnostic_records_while(|record| { |
| 2757 | visited += 1; |
| 2758 | assert!(record.is_ok(), "first sorted record should parse cleanly"); |
| 2759 | Ok(std::ops::ControlFlow::Break(())) |
| 2760 | }) |
| 2761 | .expect("visit with early break"); |
| 2762 | assert_eq!(visited, 1); |
| 2763 | |
| 2764 | let args = MetricsArgs::default(); |
| 2765 | let thread_one: ThreadRecord = serde_json::from_str( |
| 2766 | &std::fs::read_to_string(threads_dir.join("thread-1.json")).expect("read thread-1"), |
| 2767 | ) |
| 2768 | .expect("parse thread-1"); |
| 2769 | let mut probe = Collector::new(&args); |
| 2770 | probe.thread(&root, thread_one).expect("probe thread-1"); |
| 2771 | let first_thread_bytes = probe.retained_bytes; |
| 2772 | |
| 2773 | let empty_sessions = temp.path().join("sessions"); |
| 2774 | let mut collector = Collector::new(&args); |
| 2775 | collector.retention_limit = first_thread_bytes; |
| 2776 | collect_into(&mut collector, &empty_sessions, &[events_dir], &[]) |
| 2777 | .expect("collect runtime store"); |
| 2778 | let report = collector.finish().expect("finish report"); |
| 2779 | |
| 2780 | assert!(report.coverage.inspection_cap_reached); |
| 2781 | assert_eq!(report.overview.runtime_threads, 1); |
| 2782 | assert_eq!( |
| 2783 | report.coverage.skipped_after_cap.get("runtime_records"), |
| 2784 | Some(&1) |
| 2785 | ); |
| 2786 | assert_eq!(report.coverage.gaps.get("runtime_record_unreadable"), None); |
| 2787 | } |
| 2788 | |
| 2789 | #[test] |
| 2790 | fn fleet_replay_cap_sets_inspection_cap_reached_and_preserves_partial_tasks() { |
| 2791 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2792 | let workspace = temp.path().join("workspace"); |
| 2793 | let fleet_dir = workspace.join(".codewhale"); |
| 2794 | std::fs::create_dir_all(&fleet_dir).expect("fleet dir"); |
| 2795 | std::fs::write(fleet_dir.join("fleet.lock"), b"").expect("fleet lock"); |
| 2796 | |
| 2797 | let run_record = json!({ |
| 2798 | "record": "run_created", |
| 2799 | "run": { |
| 2800 | "id": "run-1", |
| 2801 | "name": "smoke", |
| 2802 | "status": "running", |
| 2803 | "task_specs": [ |
| 2804 | { |
| 2805 | "id": "task-1", |
| 2806 | "name": "review", |
| 2807 | "instructions": "review change", |
| 2808 | "worker": { "role": "reviewer" } |
| 2809 | }, |
| 2810 | { |
| 2811 | "id": "task-2", |
| 2812 | "name": "implement", |
| 2813 | "instructions": "implement change", |
| 2814 | "worker": { "role": "implement" } |
| 2815 | } |
| 2816 | ], |
| 2817 | "created_at": "2026-11-29T10:00:00Z" |
| 2818 | } |
| 2819 | }); |
| 2820 | let task_one_record = json!({ |
| 2821 | "record": "task_enqueued", |
| 2822 | "entry": { |
| 2823 | "run_id": "run-1", |
| 2824 | "task_id": "task-1", |
| 2825 | "priority": 0, |
| 2826 | "enqueued_at": "2026-11-29T10:00:01Z" |
| 2827 | } |
| 2828 | }); |
| 2829 | let task_two_record = json!({ |
| 2830 | "record": "task_enqueued", |
| 2831 | "entry": { |
| 2832 | "run_id": "run-1", |
| 2833 | "task_id": "task-2", |
| 2834 | "priority": 0, |
| 2835 | "enqueued_at": "2026-11-29T10:00:02Z" |
| 2836 | } |
| 2837 | }); |
| 2838 | |
| 2839 | let rec_run: codewhale_engine::fleet::ledger::FleetLedgerRecord = |
| 2840 | serde_json::from_value(run_record.clone()).expect("run record"); |
| 2841 | let rec_task_one: codewhale_engine::fleet::ledger::FleetLedgerRecord = |
| 2842 | serde_json::from_value(task_one_record.clone()).expect("task 1 record"); |
| 2843 | let _rec_task_two: codewhale_engine::fleet::ledger::FleetLedgerRecord = |
| 2844 | serde_json::from_value(task_two_record.clone()).expect("task 2 record"); |
| 2845 | let replay_limit = serde_json::to_vec(&rec_run).expect("serialize run").len() |
| 2846 | + serde_json::to_vec(&rec_task_one) |
| 2847 | .expect("serialize task 1") |
| 2848 | .len(); |
| 2849 | |
| 2850 | std::fs::write( |
| 2851 | fleet_dir.join("fleet.jsonl"), |
| 2852 | format!("{run_record}\n{task_one_record}\n{task_two_record}\n"), |
| 2853 | ) |
| 2854 | .expect("write fleet ledger"); |
| 2855 | |
| 2856 | let args = MetricsArgs::default(); |
| 2857 | let mut collector = Collector::new(&args); |
| 2858 | collector.fleet_replay_limit = replay_limit; |
| 2859 | collector.fleet(&workspace).expect("partial fleet replay"); |
| 2860 | let report = collector.finish().expect("finish report"); |
| 2861 | |
| 2862 | assert!(report.coverage.inspection_cap_reached); |
| 2863 | assert_eq!( |
| 2864 | report |
| 2865 | .coverage |
| 2866 | .gaps |
| 2867 | .get("fleet_replay_inspection_limit_reached"), |
| 2868 | Some(&1) |
| 2869 | ); |
| 2870 | assert_eq!( |
| 2871 | report |
| 2872 | .coverage |
| 2873 | .gaps |
| 2874 | .get("fleet_replay_unavailable_or_inspection_limit"), |
| 2875 | None |
| 2876 | ); |
| 2877 | assert_eq!( |
| 2878 | report.coverage.skipped_after_cap.get("fleet_workspaces"), |
| 2879 | Some(&1) |
| 2880 | ); |
| 2881 | assert_eq!( |
| 2882 | report.roles.get("reviewer").map(|role| role.recorded_tasks), |
| 2883 | Some(1) |
| 2884 | ); |
| 2885 | assert!(!report.roles.contains_key("implement")); |
| 2886 | } |
| 2887 | |
| 2888 | #[test] |
| 2889 | fn audit_compaction_skips_undated_rows_under_since_and_records_gap() { |
| 2890 | let args = MetricsArgs { |
| 2891 | since: Some("2026-11-29T00:00:00Z".parse::<DateTime<Utc>>().unwrap()), |
| 2892 | ..Default::default() |
| 2893 | }; |
| 2894 | let mut collector = Collector::new(&args); |
| 2895 | let undated = json!({ |
| 2896 | "event": "compaction.completed", |
| 2897 | "details": { |
| 2898 | "session_id": "sess-1", |
| 2899 | "compaction_id": "cmp-undated", |
| 2900 | "messages_before": 30, |
| 2901 | "messages_after": 10 |
| 2902 | } |
| 2903 | }); |
| 2904 | collector |
| 2905 | .audit_compaction(&undated) |
| 2906 | .expect("skip undated audit compaction"); |
| 2907 | let report = collector.finish().expect("finish report"); |
| 2908 | assert_eq!(report.compaction.completed_items, 0); |
| 2909 | assert_eq!( |
| 2910 | report |
| 2911 | .coverage |
| 2912 | .gaps |
| 2913 | .get("audit_compaction_timestamp_unavailable"), |
| 2914 | Some(&1) |
| 2915 | ); |
| 2916 | } |
| 2917 | |
| 2918 | #[test] |
| 2919 | fn legacy_reported_reason_deduplicates_without_source_conflict() { |
| 2920 | let dispatched_at = "2026-11-29T10:00:00Z".parse::<DateTime<Utc>>().unwrap(); |
| 2921 | let route = codewhale_engine::cost_status::EffectiveRouteEnvelope::capture_observed( |
| 2922 | codewhale_config::ProviderKind::Deepseek, |
| 2923 | "deepseek", |
| 2924 | "deepseek-chat", |
| 2925 | Some("https://api.deepseek.com/v1"), |
| 2926 | dispatched_at, |
| 2927 | ); |
| 2928 | let usage = serde_json::from_value(json!({ |
| 2929 | "input_tokens": 100, |
| 2930 | "output_tokens": 40 |
| 2931 | })) |
| 2932 | .expect("usage"); |
| 2933 | let record = codewhale_engine::cost_status::NativeUsageSource::capture( |
| 2934 | "src-legacy-reported-reason", |
| 2935 | codewhale_engine::cost_status::UsageSpendOwner::Primary, |
| 2936 | ) |
| 2937 | .reported(&route, &usage) |
| 2938 | .persisted(); |
| 2939 | let fresh = UsageSourceContribution::for_record(&record); |
| 2940 | let mut legacy_json = serde_json::to_value(&fresh).expect("serialize contribution"); |
| 2941 | legacy_json["record"]["settlement"]["reason"] = json!("success_without_usage"); |
| 2942 | let legacy: UsageSourceContribution = |
| 2943 | serde_json::from_value(legacy_json).expect("decode legacy contribution"); |
| 2944 | |
| 2945 | let args = MetricsArgs::default(); |
| 2946 | let mut collector = Collector::new(&args); |
| 2947 | collector.source(legacy).expect("legacy source"); |
| 2948 | collector.source(fresh).expect("fresh source"); |
| 2949 | let report = collector.finish().expect("finish report"); |
| 2950 | assert_eq!(report.coverage.source_conflicts, 0); |
| 2951 | assert_eq!(report.coverage.source_copies_deduplicated, 1); |
| 2952 | assert_eq!( |
| 2953 | report |
| 2954 | .accounting |
| 2955 | .as_ref() |
| 2956 | .map(|usage| usage.reported_usage_sources), |
| 2957 | Some(1) |
| 2958 | ); |
| 2959 | } |
| 2960 | |
| 2961 | #[test] |
| 2962 | fn fleet_roles_take_usage_and_cost_from_the_worker_saved_session() { |
| 2963 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2964 | let workspace = temp.path().join("workspace"); |
| 2965 | let fleet_dir = workspace.join(".codewhale"); |
| 2966 | std::fs::create_dir_all(&fleet_dir).expect("fleet dir"); |
| 2967 | std::fs::write(fleet_dir.join("fleet.lock"), b"").expect("fleet lock"); |
| 2968 | |
| 2969 | let dispatched_at = "2026-11-29T10:00:00Z".parse::<DateTime<Utc>>().unwrap(); |
| 2970 | let route = |model: &str| { |
| 2971 | codewhale_engine::cost_status::EffectiveRouteEnvelope::capture_observed( |
| 2972 | codewhale_config::ProviderKind::Deepseek, |
| 2973 | "deepseek", |
| 2974 | model, |
| 2975 | Some("https://api.deepseek.com/v1"), |
| 2976 | dispatched_at, |
| 2977 | ) |
| 2978 | }; |
| 2979 | let contribution = |route: &codewhale_engine::cost_status::EffectiveRouteEnvelope, |
| 2980 | source: &str, |
| 2981 | input: u64, |
| 2982 | output: u64| { |
| 2983 | let usage = serde_json::from_value(json!({ |
| 2984 | "input_tokens": input, |
| 2985 | "output_tokens": output |
| 2986 | })) |
| 2987 | .expect("usage"); |
| 2988 | UsageSourceContribution::for_record( |
| 2989 | &codewhale_engine::cost_status::NativeUsageSource::capture( |
| 2990 | source, |
| 2991 | codewhale_engine::cost_status::UsageSpendOwner::Primary, |
| 2992 | ) |
| 2993 | .reported(route, &usage) |
| 2994 | .persisted(), |
| 2995 | ) |
| 2996 | }; |
| 2997 | let session = |id: &str, source: UsageSourceContribution| { |
| 2998 | let mut metadata: SessionMetadata = serde_json::from_value(json!({ |
| 2999 | "id": id, |
| 3000 | "title": id, |
| 3001 | "created_at": "2026-11-29T10:00:00Z", |
| 3002 | "updated_at": "2026-11-29T10:05:00Z", |
| 3003 | "message_count": 2, |
| 3004 | "total_tokens": 140, |
| 3005 | "model": "deepseek-chat", |
| 3006 | "workspace": workspace |
| 3007 | })) |
| 3008 | .expect("metadata"); |
| 3009 | metadata |
| 3010 | .cost |
| 3011 | .accounted_usage_sources |
| 3012 | .insert(source.record.source_id.clone(), source); |
| 3013 | metadata |
| 3014 | }; |
| 3015 | let priced = route("deepseek-chat"); |
| 3016 | let reviewer_source = contribution(&priced, "src-review", 100, 40); |
| 3017 | assert!(reviewer_source.usd > 0.0 && reviewer_source.cny > 0.0); |
| 3018 | let implement_source = contribution(&route("unpriced-test-model"), "src-implement", 30, 10); |
| 3019 | assert!(implement_source.unpriced > 0 && implement_source.cny_unpriced > 0); |
| 3020 | let planner_source = UsageSourceContribution::for_record( |
| 3021 | &codewhale_engine::cost_status::NativeUsageSource::capture( |
| 3022 | "src-planner", |
| 3023 | codewhale_engine::cost_status::UsageSpendOwner::Primary, |
| 3024 | ) |
| 3025 | .prepare( |
| 3026 | &priced, |
| 3027 | &serde_json::from_value(json!({"input_tokens": 0, "output_tokens": 0})) |
| 3028 | .expect("zero usage"), |
| 3029 | ProviderUsageCoverage::Reported, |
| 3030 | codewhale_engine::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 3031 | ) |
| 3032 | .persisted(), |
| 3033 | ); |
| 3034 | let mut local = route("deepseek-chat"); |
| 3035 | local.billing_mode = codewhale_engine::cost_status::RouteBillingMode::Local; |
| 3036 | |
| 3037 | let task = |id: &str, role: &str| json!({"id": id, "name": id, "instructions": id, "worker": { "role": role }}); |
| 3038 | let mut ledger = vec![json!({ |
| 3039 | "record": "run_created", |
| 3040 | "run": { |
| 3041 | "id": "run-1", |
| 3042 | "name": "smoke", |
| 3043 | "status": "running", |
| 3044 | "task_specs": [ |
| 3045 | task("task-1", "reviewer"), |
| 3046 | task("task-2", "implement"), |
| 3047 | task("task-3", "reviewer"), |
| 3048 | task("task-4", "planner"), |
| 3049 | task("task-5", "local"), |
| 3050 | task("task-6", "mixed") |
| 3051 | ], |
| 3052 | "created_at": "2026-11-29T10:00:00Z" |
| 3053 | } |
| 3054 | })]; |
| 3055 | for (task_id, session_id) in [ |
| 3056 | ("task-1", "sess-review"), |
| 3057 | ("task-2", "sess-implement"), |
| 3058 | ("task-3", "sess-implement"), |
| 3059 | ("task-4", "sess-planner"), |
| 3060 | ("task-5", "sess-local"), |
| 3061 | ("task-6", "sess-mixed"), |
| 3062 | ] { |
| 3063 | ledger.push(json!({ |
| 3064 | "record": "task_enqueued", |
| 3065 | "entry": { |
| 3066 | "run_id": "run-1", |
| 3067 | "task_id": task_id, |
| 3068 | "priority": 0, |
| 3069 | "enqueued_at": "2026-11-29T10:00:01Z" |
| 3070 | } |
| 3071 | })); |
| 3072 | ledger.push(json!({ |
| 3073 | "record": "receipt_recorded", |
| 3074 | "receipt": { |
| 3075 | "run_id": "run-1", |
| 3076 | "task_id": task_id, |
| 3077 | "worker_id": "worker-1", |
| 3078 | "completed_at": "2026-11-29T10:04:00Z", |
| 3079 | "result": "pass", |
| 3080 | "saved_session_id": session_id |
| 3081 | } |
| 3082 | })); |
| 3083 | } |
| 3084 | let ledger = ledger |
| 3085 | .iter() |
| 3086 | .map(|record| format!("{record}\n")) |
| 3087 | .collect::<String>(); |
| 3088 | std::fs::write(fleet_dir.join("fleet.jsonl"), ledger).expect("write fleet ledger"); |
| 3089 | |
| 3090 | let args = MetricsArgs::default(); |
| 3091 | let mut collector = Collector::new(&args); |
| 3092 | for (id, source) in [ |
| 3093 | ("sess-review", reviewer_source.clone()), |
| 3094 | ("sess-implement", implement_source), |
| 3095 | ("sess-planner", planner_source), |
| 3096 | ("sess-local", contribution(&local, "src-local", 50, 20)), |
| 3097 | ] { |
| 3098 | collector |
| 3099 | .session(temp.path(), session(id, source)) |
| 3100 | .expect("saved session"); |
| 3101 | } |
| 3102 | let mut mixed_session = session( |
| 3103 | "sess-mixed", |
| 3104 | contribution(&priced, "src-mixed-priced", 20, 5), |
| 3105 | ); |
| 3106 | let mixed_unpriced = |
| 3107 | contribution(&route("unpriced-test-model"), "src-mixed-unpriced", 7, 3); |
| 3108 | mixed_session |
| 3109 | .cost |
| 3110 | .accounted_usage_sources |
| 3111 | .insert(mixed_unpriced.record.source_id.clone(), mixed_unpriced); |
| 3112 | collector |
| 3113 | .session(temp.path(), mixed_session) |
| 3114 | .expect("mixed saved session"); |
| 3115 | collector.fleet(&workspace).expect("fleet replay"); |
| 3116 | let report = collector.finish().expect("finish report"); |
| 3117 | |
| 3118 | let reviewer = &report.roles["reviewer"]; |
| 3119 | assert_eq!(reviewer.recorded_tasks, 2); |
| 3120 | assert_eq!(reviewer.usage_report_samples, Some(1)); |
| 3121 | assert_eq!(reviewer.input_tokens_known, Some(100)); |
| 3122 | assert_eq!(reviewer.output_tokens_known, Some(40)); |
| 3123 | assert_eq!(reviewer.known_cost_usd, Some(reviewer_source.usd)); |
| 3124 | assert_eq!(reviewer.known_cost_cny, Some(reviewer_source.cny)); |
| 3125 | let implement = &report.roles["implement"]; |
| 3126 | assert_eq!(implement.recorded_tasks, 1); |
| 3127 | assert_eq!(implement.usage_report_samples, Some(1)); |
| 3128 | assert_eq!(implement.input_tokens_known, Some(30)); |
| 3129 | assert_eq!(implement.output_tokens_known, Some(10)); |
| 3130 | assert_eq!(implement.known_cost_usd, None); |
| 3131 | assert_eq!(implement.known_cost_cny, None); |
| 3132 | assert_eq!( |
| 3133 | report.coverage.gaps.get("fleet_saved_session_shared"), |
| 3134 | Some(&1) |
| 3135 | ); |
| 3136 | let planner = &report.roles["planner"]; |
| 3137 | assert_eq!(planner.recorded_tasks, 1); |
| 3138 | assert_eq!(planner.usage_report_samples, None); |
| 3139 | assert_eq!(planner.input_tokens_known, None); |
| 3140 | assert_eq!(planner.known_cost_usd, None); |
| 3141 | let local = &report.roles["local"]; |
| 3142 | assert_eq!(local.input_tokens_known, Some(50)); |
| 3143 | assert_eq!((local.known_cost_usd, local.known_cost_cny), (None, None)); |
| 3144 | let mixed = &report.roles["mixed"]; |
| 3145 | assert_eq!(mixed.usage_report_samples, Some(1)); |
| 3146 | assert_eq!(mixed.input_tokens_known, Some(27)); |
| 3147 | assert_eq!(mixed.output_tokens_known, Some(8)); |
| 3148 | assert_eq!((mixed.known_cost_usd, mixed.known_cost_cny), (None, None)); |
| 3149 | |
| 3150 | let mut bare = session("sess-review", reviewer_source.clone()); |
| 3151 | bare.cost.accounted_usage_sources.clear(); |
| 3152 | let mut collector = Collector::new(&args); |
| 3153 | collector |
| 3154 | .session(temp.path(), bare) |
| 3155 | .expect("session without sources"); |
| 3156 | let source_key = format!( |
| 3157 | "{}:{}", |
| 3158 | usage_source_fingerprint(&reviewer_source.record.source_id), |
| 3159 | reviewer_source |
| 3160 | .record |
| 3161 | .settlement |
| 3162 | .as_ref() |
| 3163 | .expect("settled source") |
| 3164 | .lineage() |
| 3165 | ); |
| 3166 | let unlinked_bytes = collector.retained_bytes |
| 3167 | + Collector::retained_size(&SourceEntry { |
| 3168 | contribution: reviewer_source.clone(), |
| 3169 | conflict: false, |
| 3170 | }) |
| 3171 | .expect("source size"); |
| 3172 | let link_bytes = Collector::retained_size(&(&"sess-review".to_string(), &source_key)) |
| 3173 | .expect("link size"); |
| 3174 | let mut collector = Collector::new(&args); |
| 3175 | collector |
| 3176 | .session(temp.path(), session("sess-review", reviewer_source.clone())) |
| 3177 | .expect("unbounded reviewer session"); |
| 3178 | assert_eq!(collector.retained_bytes, unlinked_bytes + link_bytes); |
| 3179 | assert_eq!( |
| 3180 | collector.session_sources["sess-review"], |
| 3181 | BTreeSet::from([source_key]) |
| 3182 | ); |
| 3183 | let mut collector = Collector::new(&args); |
| 3184 | collector.retention_limit = unlinked_bytes + link_bytes - 1; |
| 3185 | collector |
| 3186 | .session(temp.path(), session("sess-review", reviewer_source.clone())) |
| 3187 | .expect("capped reviewer session"); |
| 3188 | assert_eq!(collector.sources.len(), 1); |
| 3189 | assert!(collector.session_sources.is_empty()); |
| 3190 | assert!(collector.inspection_cap_reached); |
| 3191 | |
| 3192 | let mut collector = Collector::new(&args); |
| 3193 | collector.retention_limit = |
| 3194 | Collector::retained_size(&"reviewer".to_string()).expect("role size"); |
| 3195 | collector.fleet(&workspace).expect("capped fleet replay"); |
| 3196 | let report = collector.finish().expect("finish capped report"); |
| 3197 | assert!(report.roles.is_empty()); |
| 3198 | assert!(report.coverage.inspection_cap_reached); |
| 3199 | assert_eq!( |
| 3200 | report.coverage.skipped_after_cap.get("fleet_workspaces"), |
| 3201 | Some(&1) |
| 3202 | ); |
| 3203 | |
| 3204 | let project_args = MetricsArgs { |
| 3205 | project: Some(workspace.clone()), |
| 3206 | ..Default::default() |
| 3207 | }; |
| 3208 | let mut collector = Collector::new(&project_args); |
| 3209 | collector |
| 3210 | .session(temp.path(), session("sess-review", reviewer_source)) |
| 3211 | .expect("project reviewer session"); |
| 3212 | collector.fleet(&workspace).expect("project fleet replay"); |
| 3213 | let report = collector.finish().expect("finish project report"); |
| 3214 | assert_eq!(report.roles["reviewer"].usage_report_samples, None); |
| 3215 | assert_eq!(report.roles["reviewer"].known_cost_usd, None); |
| 3216 | } |
| 3217 | |
| 3218 | #[test] |
| 3219 | fn role_line_shows_linked_usage_or_unavailable() { |
| 3220 | let mut role = RoleReport { |
| 3221 | recorded_tasks: 12, |
| 3222 | ..Default::default() |
| 3223 | }; |
| 3224 | role.task_states.insert("completed".to_string(), 12); |
| 3225 | assert_eq!( |
| 3226 | role_line("reviewer", &role), |
| 3227 | "Role \"reviewer\": 12 observed tasks; states {\"completed\":12}; source-linked cost/usage unavailable; recovery rate unavailable." |
| 3228 | ); |
| 3229 | role.usage_report_samples = Some(9); |
| 3230 | role.input_tokens_known = Some(120_400); |
| 3231 | role.output_tokens_known = Some(8_800); |
| 3232 | role.known_cost_usd = Some(0.0412); |
| 3233 | assert_eq!( |
| 3234 | role_line("reviewer", &role), |
| 3235 | "Role \"reviewer\": 12 observed tasks; states {\"completed\":12}; usage from 9 of 12 tasks: 120400 input, 8800 output; USD 0.041200, CNY unknown; recovery rate unavailable." |
| 3236 | ); |
| 3237 | } |
| 3238 | |
| 3239 | #[test] |
| 3240 | fn model_line_shows_cache_and_reasoning_or_unknown() { |
| 3241 | let cached = MoneyUsage { |
| 3242 | known_subtotal_usd: 0.4123, |
| 3243 | input_tokens_known: 1_204_331, |
| 3244 | output_tokens_known: 88_210, |
| 3245 | cache_read_tokens_known: Some(1_012_004), |
| 3246 | cache_write_tokens_known: Some(3_120), |
| 3247 | reasoning_tokens_known: Some(40_112), |
| 3248 | cache_hit_percent_of_reported_subset: Some(84.04), |
| 3249 | ..Default::default() |
| 3250 | }; |
| 3251 | assert_eq!( |
| 3252 | model_line("deepseek-v4", &cached), |
| 3253 | "Model \"deepseek-v4\": USD 0.412300, CNY 0.000000; 1204331 input, 88210 output; cache read 1012004 (hit 84.0% of reported subset), cache write 3120, reasoning 40112; unknown USD/CNY sources 0/0." |
| 3254 | ); |
| 3255 | |
| 3256 | let unreported = MoneyUsage { |
| 3257 | input_tokens_known: 10, |
| 3258 | output_tokens_known: 5, |
| 3259 | usd_price_unknown_sources: 1, |
| 3260 | cny_price_unknown_sources: 1, |
| 3261 | ..Default::default() |
| 3262 | }; |
| 3263 | assert_eq!( |
| 3264 | model_line("local", &unreported), |
| 3265 | "Model \"local\": USD 0.000000, CNY 0.000000; 10 input, 5 output; cache read unknown (hit unknown of reported subset), cache write unknown, reasoning unknown; unknown USD/CNY sources 1/1." |
| 3266 | ); |
| 3267 | } |
| 3268 | } |
| 3269 |