1use std::fs;
16use std::path::PathBuf;
17use std::process;
18use std::time::{Duration, Instant};
19
20use serde::Serialize;
21
22use crate::cli::TimeRunArgs;
23use crate::commands::run::{
24 execute_run_with_timing, prepare_eval_temp_file, StdoutPassthroughGuard,
25};
26use crate::env_guard::ScopedEnvVar;
27use crate::json_envelope::{to_string_pretty, JsonEnvelope};
28
29pub const TIME_RUN_SCHEMA_VERSION: u32 = 2;
32
33#[derive(Debug, Default, Clone)]
37pub struct RunTiming {
38 pub parse: Duration,
39 pub typecheck: Duration,
40 pub bytecode_compile: Duration,
41 pub run_setup: Duration,
42 pub run_main: Duration,
43 pub input_bytes: u64,
46 pub cache_hit: bool,
48 pub(crate) module_phases: Option<harn_vm::ModulePhaseRecorder>,
51}
52
53pub(crate) fn record_run_setup_elapsed(timing: Option<&mut RunTiming>, started: Instant) {
54 if let Some(timing) = timing {
55 timing.run_setup = started.elapsed();
56 }
57}
58
59#[derive(Debug, Serialize)]
60pub struct TimingReport {
61 pub command: String,
64 #[serde(skip_serializing_if = "Option::is_none")]
66 pub target: Option<String>,
67 pub phases: Vec<PhaseRecord>,
68 pub llm_calls: Vec<LlmCallTiming>,
69 pub tool_calls: Vec<ToolCallTiming>,
70 pub totals: TimingTotals,
71 pub exit_code: i32,
75}
76
77#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
78#[serde(rename_all = "snake_case")]
79pub enum PhaseRecordKind {
80 TopLevel,
82 Attribution,
84}
85
86#[derive(Debug, Serialize)]
87pub struct PhaseRecord {
88 pub name: String,
89 pub kind: PhaseRecordKind,
91 pub duration_ms: u64,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub input_bytes: Option<u64>,
94 #[serde(skip_serializing_if = "Option::is_none")]
96 pub cache: Option<String>,
97 #[serde(skip_serializing_if = "Option::is_none")]
99 pub events: Option<u64>,
100}
101
102#[derive(Debug, Serialize)]
103pub struct LlmCallTiming {
104 pub model: String,
105 pub latency_ms: u64,
106 pub tokens: i64,
110}
111
112#[derive(Debug, Serialize)]
113pub struct ToolCallTiming {
114 pub name: String,
115 pub latency_ms: u64,
116}
117
118#[derive(Debug, Serialize)]
119pub struct TimingTotals {
120 pub wall_ms: u64,
121 pub cpu_ms: u64,
122 pub cache_hits: u64,
123 pub cache_misses: u64,
124}
125
126pub(crate) async fn run(args: TimeRunArgs) {
127 let _cache_guard = args
132 .no_cache
133 .then(|| ScopedEnvVar::set(harn_vm::bytecode_cache::CACHE_ENABLED_ENV, "0"));
134
135 harn_vm::llm::enable_tracing();
138 harn_vm::tracing::set_tracing_enabled(true);
139 let _ = harn_vm::tracing::take_spans();
140 let _ = harn_vm::llm::take_trace();
141
142 let mut timing = RunTiming::default();
143 let cpu_start = cpu_ms();
144 let wall_start = std::time::Instant::now();
145 let sandbox = if args.no_sandbox {
146 crate::commands::run::RunSandboxOptions::disabled()
147 } else {
148 crate::commands::run::RunSandboxOptions::default()
149 .with_write_roots(args.write_root.iter().cloned())
150 .with_read_only_roots(args.read_only_root.iter().cloned())
151 };
152
153 let _stdout_guard = (!args.json).then(StdoutPassthroughGuard::enable);
158
159 let (target, outcome) = match (args.eval.as_deref(), args.file.as_deref()) {
160 (Some(code), None) => {
161 let (wrapped, tmp) = prepare_eval_temp_file(code).unwrap_or_else(|e| {
162 eprintln!("error: {e}");
163 process::exit(1);
164 });
165 let tmp_path: PathBuf = tmp.path().to_path_buf();
166 if let Err(e) = fs::write(&tmp_path, &wrapped) {
167 eprintln!("error: failed to write temp file for -e: {e}");
168 process::exit(1);
169 }
170 let path_str = tmp_path.to_string_lossy().into_owned();
171 let outcome = execute_run_with_timing(
172 &path_str,
173 args.argv.clone(),
174 Some(&mut timing),
175 sandbox.clone(),
176 )
177 .await;
178 drop(tmp);
179 (None, outcome)
180 }
181 (None, Some(file)) => {
182 let outcome =
183 execute_run_with_timing(file, args.argv.clone(), Some(&mut timing), sandbox).await;
184 (Some(file.to_string()), outcome)
185 }
186 (Some(_), Some(_)) => {
187 eprintln!(
188 "error: `harn time run` accepts either `-e <code>` or `<file.harn>`, not both"
189 );
190 process::exit(2);
191 }
192 (None, None) => {
193 eprintln!("error: `harn time run` requires either `-e <code>` or `<file.harn>`");
194 process::exit(2);
195 }
196 };
197
198 let wall_ms = wall_start.elapsed().as_millis() as u64;
199 let cpu_ms_total = cpu_ms().saturating_sub(cpu_start);
200
201 if !outcome.stderr.is_empty() {
202 eprint!("{}", outcome.stderr);
203 }
204 if !outcome.stdout.is_empty() {
205 if args.json {
206 eprint!("{}", outcome.stdout);
210 } else {
211 print!("{}", outcome.stdout);
217 }
218 }
219
220 let llm_trace = harn_vm::llm::take_trace();
221 let spans = harn_vm::tracing::take_spans();
222
223 let llm_calls: Vec<LlmCallTiming> = llm_trace
224 .iter()
225 .map(|entry| LlmCallTiming {
226 model: entry.model.clone(),
227 latency_ms: entry.duration_ms,
228 tokens: entry.input_tokens + entry.output_tokens,
229 })
230 .collect();
231
232 let tool_calls: Vec<ToolCallTiming> = spans
233 .iter()
234 .filter(|span| span.kind.as_str() == "tool_call")
235 .map(|span| ToolCallTiming {
236 name: span.name.clone(),
237 latency_ms: span.duration_ms,
238 })
239 .collect();
240
241 let cache_hit = timing.cache_hit;
242 let phases = build_phase_records(&timing, spans.len() as u64);
243
244 let report = TimingReport {
245 command: "run".into(),
246 target,
247 phases,
248 llm_calls,
249 tool_calls,
250 totals: TimingTotals {
251 wall_ms,
252 cpu_ms: cpu_ms_total,
253 cache_hits: u64::from(cache_hit),
254 cache_misses: u64::from(!cache_hit),
255 },
256 exit_code: outcome.exit_code,
257 };
258
259 if args.json {
260 println!(
261 "{}",
262 to_string_pretty(&JsonEnvelope::ok(TIME_RUN_SCHEMA_VERSION, &report))
263 );
264 } else {
265 eprint!("{}", render_human(&report));
266 }
267
268 if outcome.exit_code != 0 {
269 process::exit(outcome.exit_code);
270 }
271}
272
273fn render_human(report: &TimingReport) -> String {
274 use std::fmt::Write;
275
276 let mut out = String::new();
277 let _ = writeln!(out, "\n\x1b[2m─── harn time ───\x1b[0m");
278 let _ = writeln!(
279 out,
280 " wall {} · cpu {} · {} cache",
281 format_ms(report.totals.wall_ms),
282 format_ms(report.totals.cpu_ms),
283 if report.totals.cache_hits > 0 {
284 "hit"
285 } else {
286 "miss"
287 },
288 );
289 let _ = writeln!(out, "\n Phases:");
290 for phase in &report.phases {
291 let suffix = if phase.kind == PhaseRecordKind::Attribution {
292 format!(
293 " ({} events; attribution overlaps top-level)",
294 phase.events.unwrap_or_default()
295 )
296 } else {
297 match (phase.input_bytes, phase.cache.as_deref(), phase.events) {
298 (Some(bytes), _, _) => format!(" ({bytes} input bytes)"),
299 (_, Some(cache), _) => format!(" (cache {cache})"),
300 (_, _, Some(events)) => format!(" ({events} events)"),
301 _ => String::new(),
302 }
303 };
304 let _ = writeln!(
305 out,
306 " {:<18} {:>10}{suffix}",
307 phase.name,
308 format_ms(phase.duration_ms),
309 );
310 }
311 if !report.llm_calls.is_empty() {
312 let _ = writeln!(out, "\n LLM calls:");
313 for call in &report.llm_calls {
314 let _ = writeln!(
315 out,
316 " {:<24} {:>10} ({} tokens)",
317 call.model,
318 format_ms(call.latency_ms),
319 call.tokens,
320 );
321 }
322 }
323 if !report.tool_calls.is_empty() {
324 let _ = writeln!(out, "\n Tool calls:");
325 for call in &report.tool_calls {
326 let _ = writeln!(
327 out,
328 " {:<24} {:>10}",
329 call.name,
330 format_ms(call.latency_ms),
331 );
332 }
333 }
334 out
335}
336
337fn format_ms(ms: u64) -> String {
338 if ms < 1000 {
339 format!("{ms} ms")
340 } else {
341 format!("{:.3} s", ms as f64 / 1000.0)
342 }
343}
344
345#[cfg(unix)]
349pub(crate) fn cpu_ms() -> u64 {
350 use std::mem::MaybeUninit;
351 unsafe {
354 let mut ru = MaybeUninit::<libc::rusage>::zeroed();
355 if libc::getrusage(libc::RUSAGE_SELF, ru.as_mut_ptr()) != 0 {
356 return 0;
357 }
358 let ru = ru.assume_init();
359 let user = duration_ms(ru.ru_utime.tv_sec, ru.ru_utime.tv_usec);
360 let system = duration_ms(ru.ru_stime.tv_sec, ru.ru_stime.tv_usec);
361 user.saturating_add(system)
362 }
363}
364
365#[cfg(not(unix))]
366pub(crate) fn cpu_ms() -> u64 {
367 0
368}
369
370#[cfg(unix)]
371fn duration_ms(secs: libc::time_t, micros: libc::suseconds_t) -> u64 {
372 let secs_ms = i128::from(secs).saturating_mul(1000);
377 let micros_ms = i128::from(micros) / 1000;
378 secs_ms.saturating_add(micros_ms).max(0) as u64
379}
380
381pub(crate) fn build_phase_records(timing: &RunTiming, main_events: u64) -> Vec<PhaseRecord> {
382 let cache_hit = timing.cache_hit;
383 let modules = timing
384 .module_phases
385 .as_ref()
386 .map(harn_vm::ModulePhaseRecorder::snapshot)
387 .unwrap_or_default();
388 vec![
389 PhaseRecord {
390 name: "parse".into(),
391 kind: PhaseRecordKind::TopLevel,
392 duration_ms: timing.parse.as_millis() as u64,
393 input_bytes: if cache_hit {
394 None
395 } else {
396 Some(timing.input_bytes)
397 },
398 cache: None,
399 events: None,
400 },
401 PhaseRecord {
402 name: "typecheck".into(),
403 kind: PhaseRecordKind::TopLevel,
404 duration_ms: timing.typecheck.as_millis() as u64,
405 input_bytes: None,
406 cache: None,
407 events: None,
408 },
409 PhaseRecord {
410 name: "bytecode_compile".into(),
411 kind: PhaseRecordKind::TopLevel,
412 duration_ms: timing.bytecode_compile.as_millis() as u64,
413 input_bytes: None,
414 cache: Some(if cache_hit {
415 "hit".into()
416 } else {
417 "miss".into()
418 }),
419 events: None,
420 },
421 PhaseRecord {
422 name: "run_setup".into(),
423 kind: PhaseRecordKind::TopLevel,
424 duration_ms: timing.run_setup.as_millis() as u64,
425 input_bytes: None,
426 cache: None,
427 events: None,
428 },
429 PhaseRecord {
430 name: "run_main".into(),
431 kind: PhaseRecordKind::TopLevel,
432 duration_ms: timing.run_main.as_millis() as u64,
433 input_bytes: None,
434 cache: None,
435 events: Some(main_events),
436 },
437 PhaseRecord {
440 name: "module_compile".into(),
441 kind: PhaseRecordKind::Attribution,
442 duration_ms: modules.module_compile_ms,
443 input_bytes: None,
444 cache: None,
445 events: Some(modules.modules_compiled),
446 },
447 PhaseRecord {
448 name: "module_load".into(),
449 kind: PhaseRecordKind::Attribution,
450 duration_ms: modules.module_load_ms,
451 input_bytes: None,
452 cache: None,
453 events: Some(modules.modules_loaded),
454 },
455 ]
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use crate::tests::common::json_envelope::assert_envelope;
462
463 fn fixture_timing(cache_hit: bool) -> RunTiming {
464 RunTiming {
465 parse: if cache_hit {
466 Duration::default()
467 } else {
468 Duration::from_millis(12)
469 },
470 typecheck: if cache_hit {
471 Duration::default()
472 } else {
473 Duration::from_millis(80)
474 },
475 bytecode_compile: Duration::from_millis(35),
476 run_setup: Duration::from_millis(8),
477 run_main: Duration::from_millis(1200),
478 input_bytes: 4096,
479 cache_hit,
480 module_phases: None,
481 }
482 }
483
484 fn make_report(cache_hit: bool) -> TimingReport {
485 let timing = fixture_timing(cache_hit);
486 TimingReport {
487 command: "run".into(),
488 target: Some("examples/hello.harn".into()),
489 phases: build_phase_records(&timing, 14),
490 llm_calls: vec![LlmCallTiming {
491 model: "claude-sonnet-4-6".into(),
492 latency_ms: 850,
493 tokens: 1500,
494 }],
495 tool_calls: vec![ToolCallTiming {
496 name: "mcp_call".into(),
497 latency_ms: 200,
498 }],
499 totals: TimingTotals {
500 wall_ms: 1335,
501 cpu_ms: 320,
502 cache_hits: u64::from(cache_hit),
503 cache_misses: u64::from(!cache_hit),
504 },
505 exit_code: 0,
506 }
507 }
508
509 #[test]
510 fn miss_envelope_has_top_level_and_module_attribution_phases() {
511 let envelope = JsonEnvelope::ok(TIME_RUN_SCHEMA_VERSION, make_report(false));
512 let value = serde_json::to_value(&envelope).unwrap();
513 let data = assert_envelope(&value, TIME_RUN_SCHEMA_VERSION);
514 let phases = data["phases"].as_array().expect("phases is array");
515 assert_eq!(phases.len(), 7);
516 assert_eq!(phases[0]["name"], "parse");
517 assert_eq!(phases[0]["input_bytes"], 4096);
518 assert_eq!(phases[2]["name"], "bytecode_compile");
519 assert_eq!(phases[2]["cache"], "miss");
520 assert_eq!(phases[5]["name"], "module_compile");
521 assert_eq!(phases[5]["kind"], "attribution");
522 assert_eq!(phases[5]["events"], 0);
523 assert!(phases[5].get("cache").is_none());
524 assert_eq!(phases[6]["name"], "module_load");
525 assert_eq!(data["totals"]["cache_misses"], 1);
526 assert_eq!(data["totals"]["cache_hits"], 0);
527 }
528
529 #[test]
530 fn hit_envelope_zeros_parse_typecheck_and_marks_cache_hit() {
531 let envelope = JsonEnvelope::ok(TIME_RUN_SCHEMA_VERSION, make_report(true));
532 let value = serde_json::to_value(&envelope).unwrap();
533 let data = assert_envelope(&value, TIME_RUN_SCHEMA_VERSION);
534 let phases = data["phases"].as_array().expect("phases is array");
535 assert_eq!(phases[0]["duration_ms"], 0);
536 assert_eq!(phases[1]["duration_ms"], 0);
537 assert!(phases[0].get("input_bytes").is_none());
539 assert_eq!(phases[2]["cache"], "hit");
540 assert_eq!(data["totals"]["cache_hits"], 1);
541 }
542
543 #[test]
544 fn render_human_lists_phases_and_calls() {
545 let rendered = render_human(&make_report(false));
546 assert!(rendered.contains("harn time"));
547 assert!(rendered.contains("parse"));
548 assert!(rendered.contains("bytecode_compile"));
549 assert!(rendered.contains("cache miss"));
550 assert!(rendered.contains("attribution overlaps top-level"));
551 assert!(rendered.contains("claude-sonnet-4-6"));
552 assert!(rendered.contains("mcp_call"));
553 }
554
555 #[test]
556 fn render_human_for_hit_includes_cache_hit_marker() {
557 let rendered = render_human(&make_report(true));
558 assert!(rendered.contains("cache hit"));
559 }
560}