1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
//! Inference turn telemetry — timing, token counts, and cost estimates.
//!
//! `TurnMetrics` is the single record produced after every inference call,
//! whether it comes from the TUI chat REPL, the ACP worker, or the mesh
//! dispatch layer. It carries only what is cheap to compute: wall-clock time
//! (always available), Ollama's native token counters (available on
//! `/api/chat` responses), and a best-effort cost estimate.
//!
//! All fields except `elapsed_ms` and `model_id` are `Option` so the struct
//! can be constructed and displayed even when the backend does not report
//! token counts (e.g. provider-plugin or vLLM paths).
use serde::{Deserialize, Serialize};
/// Token usage reported by an inference backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsage {
/// Tokens in the prompt sent to the model.
pub input_tokens: u32,
/// Tokens generated by the model.
pub output_tokens: u32,
}
impl TokenUsage {
pub fn total(&self) -> u32 {
self.input_tokens.saturating_add(self.output_tokens)
}
/// Combine two usage readings (e.g. across tool-call rounds).
pub fn saturating_add(self, other: Self) -> Self {
Self {
input_tokens: self.input_tokens.saturating_add(other.input_tokens),
output_tokens: self.output_tokens.saturating_add(other.output_tokens),
}
}
}
/// Why the agentic loop ended the turn. Before this record existed, a
/// narrate-then-stop acceptance was indistinguishable from a normal
/// completion — even under `NEWT_DEBUG` (the 2026-07-08 ornith:35b
/// forensics could not tell "cap exhausted" from "classifier missed" from
/// disk). `None` on paths that do not report it (headless callers, the
/// Responses-API loop).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnEndReason {
/// A genuine final answer (no pending-action cue in the closing reply).
Completed,
/// The reply asks a question; the task awaits the operator's answer.
AwaitingOperator,
/// Pending-action narration stopped after the rescue budget was spent.
NarrationCapExhausted,
/// Pending-action narration stopped on the final allowed round.
NarrationFinalRound,
/// The tool-round cap ended the turn via the tools-disabled summary.
RoundCap,
/// The operator-configured whole-run inference-call allowance
/// (`--run-allowance`, #2313) was spent before the turn finished. Unlike
/// [`Self::RoundCap`] there is NO model-written summary — a summary is a call
/// the allowance now refuses, and a summary before the round cap would break
/// `BHV-ROUND-002` — so the harness writes the notice itself.
RunAllowance,
/// U4b: after at least one successful workspace write, the configured number
/// of consecutive rounds (`[initiative.no_progress] stop_after`) changed
/// nothing and ran no passing build or test. A budget wall filed like
/// [`Self::RoundCap`], with a harness-written notice and no model summary
/// (BHV-ROUND-002).
NoProgress,
/// The model produced no usable content (placeholder/diagnostic reply).
Empty,
/// #1963: the operator interrupted the turn (Esc / Ctrl-C) before it
/// reached a normal completion. Distinct from `Empty`: the reply may be
/// entirely absent, a partial stream the operator already saw, or (via
/// the loop's own interrupt checkpoints) real accumulated usage — this
/// tells a resumed conversation and a forensic reader that the turn was
/// abandoned, not that the model produced nothing.
Cancelled,
/// #1963: the turn ended in a backend/loop error rather than a
/// completion or an operator interrupt. The error text itself is not
/// carried here (it is already printed to the session); this exists so
/// the turn is still findable and distinguishable from `Completed`.
Failed,
/// #2315 (opt-in `NEWT_VERIFY_OUTCOMES`): a detected check still failed
/// or timed out when the repair allowance or the rounds ran out. The
/// answer is delivered; passing an external grader is a separate question.
RepairExhausted,
/// #2315: the turn concluded without an observed pass on the current
/// workspace state, and no repair could change that: a check was denied,
/// unavailable, requested but never executed, or left stale or unrun with
/// no allowance or round left.
VerificationIncomplete,
}
/// Full telemetry record for one inference turn.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TurnMetrics {
/// Wall-clock elapsed time for the full turn (first request byte to last
/// response byte), in milliseconds.
pub elapsed_ms: u64,
/// Token usage, if reported by the backend: the turn's CONTEXT merge —
/// its largest prompt and the tokens it generated. Never a billing or
/// completeness signal; those are [`Self::attempts`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<TokenUsage>,
/// What the turn actually sent and generated, summed per inference attempt,
/// with how many attempts reported no usage (#2313). `None` when no attempt
/// ledger observed the turn.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attempts: Option<crate::attempts::UsageTotals>,
/// Estimated monetary cost in USD. `Some(0.0)` is a confirmed free (local)
/// rate; `None` is UNKNOWN — no rate, or no usage — never zero (#2313).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost_usd: Option<f64>,
/// Model that produced the reply.
pub model_id: String,
/// Backend endpoint that served the request.
pub endpoint: String,
/// Number of agentic-loop hallucinations corrected during this turn
/// (e.g. model calling a tool name as a shell command via run_command,
/// or invoking a non-existent tool). Omitted from logs when zero.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub hallucinations: u32,
/// Why the loop ended the turn (see [`TurnEndReason`]). Omitted from
/// logs when unreported.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_reason: Option<TurnEndReason>,
}
fn is_zero_u32(n: &u32) -> bool {
*n == 0
}
impl TurnMetrics {
/// Compact human-readable summary line.
///
/// Examples:
/// - `"3.2s · 847 in / 312 out · free (local)"`
/// - `"8.7s · 1,204 in / 892 out · ~$0.0041"`
/// - `"4.0s · 900 in / 120 out · cost unknown"` (usage, but no rate)
/// - `"5.1s · (tokens unavailable)"`
pub fn display_line(&self) -> String {
let elapsed = if self.elapsed_ms >= 1000 {
format!("{:.1}s", self.elapsed_ms as f64 / 1000.0)
} else {
format!("{}ms", self.elapsed_ms)
};
// Whenever attempts were recorded and any lacks usage, say so — also
// when none was measured and the numbers below are the context merge's.
let unmeasured = self
.attempts
.filter(|t| t.attempts > 0 && !t.usage_complete)
.map(|t| format!(" ({} of {} calls unmeasured)", t.usage_missing, t.attempts))
.unwrap_or_default();
let token_part = match (self.attempts, self.usage) {
(Some(t), _) if t.attempts > t.usage_missing => format!(
"{} in / {} out{unmeasured}",
fmt_count(t.in_tokens),
fmt_count(t.out_tokens)
),
(_, Some(u)) => format!(
"{} in / {} out{unmeasured}",
fmt_count(u64::from(u.input_tokens)),
fmt_count(u64::from(u.output_tokens))
),
_ => format!("(tokens unavailable){unmeasured}"),
};
let cost_part = match self.cost_usd {
Some(c) if c < f64::EPSILON => "free (local)".into(),
Some(c) if c < 0.001 => format!("~${c:.5}"),
Some(c) if c < 0.01 => format!("~${c:.4}"),
Some(c) => format!("~${c:.4}"),
None if self.usage.is_some() => "cost unknown".into(),
None => String::new(),
};
let base = if cost_part.is_empty() {
format!("{elapsed} · {token_part}")
} else {
format!("{elapsed} · {token_part} · {cost_part}")
};
let base = if self.hallucinations > 0 {
format!(
"{base} · ⚠ {} hallucination(s) corrected",
self.hallucinations
)
} else {
base
};
// Surface only the anomalous endings — a normal completion stays
// quiet, but a turn that ended on unrescued narration (or the round
// cap) says so instead of silently looking finished.
match self.end_reason {
Some(TurnEndReason::NarrationCapExhausted) => {
format!("{base} · ⚠ incomplete: ended on narration (rescue budget spent)")
}
Some(TurnEndReason::NarrationFinalRound) => {
format!("{base} · ⚠ incomplete: ended on narration (final round)")
}
Some(TurnEndReason::AwaitingOperator) => format!("{base} · awaiting operator"),
Some(TurnEndReason::RoundCap) => format!("{base} · round cap"),
Some(TurnEndReason::RunAllowance) => format!("{base} · ⚠ run allowance exhausted"),
Some(TurnEndReason::NoProgress) => format!("{base} · ⚠ stopped: no progress"),
Some(TurnEndReason::Empty) => format!("{base} · ⚠ empty response"),
Some(TurnEndReason::Cancelled) => format!("{base} · ⊘ interrupted"),
Some(TurnEndReason::Failed) => format!("{base} · ✗ failed"),
Some(TurnEndReason::RepairExhausted) => {
format!("{base} · ✗ verification failed after repair")
}
Some(TurnEndReason::VerificationIncomplete) => {
format!("{base} · ⚠ verification incomplete")
}
Some(TurnEndReason::Completed) | None => base,
}
}
/// Label pairs for Prometheus metric dimensions.
pub fn prometheus_labels(&self) -> [(&'static str, String); 2] {
[
("model", self.model_id.clone()),
("endpoint", self.endpoint.clone()),
]
}
/// Append this record as a JSONL line to `path` (best-effort).
/// Creates the file and parent dirs if absent. Errors are silently ignored
/// so telemetry failures never block inference.
pub fn append_to_log(&self, path: &std::path::Path) {
let _ = append_jsonl(self, path);
}
/// Append and then enforce the rotation policy. All errors are silently
/// swallowed — log rotation must never block or crash inference.
pub fn append_to_log_with_policy(&self, path: &std::path::Path, policy: &crate::LogConfig) {
let _ = append_jsonl(self, path);
let _ = rotate_log(path, policy);
}
}
/// The most recent `model_id` this operator used on `endpoint`, replayed
/// from the usage log (`~/.newt/usage.jsonl`) — the ONLY data on disk
/// already keyed by (endpoint, model). Used as the #2622 tiebreak when a
/// multiplexer has more than one model loaded and no pin resolved: rather
/// than guess by server list order, prefer whichever model this operator
/// actually ran on this backend last. Best-effort: a missing/unreadable/
/// malformed log returns `None` (never blocks adoption), and a line that
/// fails to parse is skipped rather than aborting the scan.
pub fn last_model_for_endpoint(path: &std::path::Path, endpoint: &str) -> Option<String> {
let content = std::fs::read_to_string(path).ok()?;
content
.lines()
.rev()
.filter_map(|line| serde_json::from_str::<TurnMetrics>(line).ok())
.find(|m| m.endpoint == endpoint)
.map(|m| m.model_id)
}
/// The #2622 tiebreak, clarified per PR #2626 review: the most recent row is
/// NOT necessarily usable — the history rule is "most recent row naming a
/// model that is still an ELIGIBLE `candidate`" (i.e. one of the loaded
/// models `adopt()` is actually choosing among), not merely the most recent
/// row for `endpoint` full stop. A later row naming a model that has since
/// been unloaded (or was never a candidate) must not shadow an earlier row
/// that still is — so this scans backward and keeps looking past a row that
/// fails the candidate check, rather than stopping at the first endpoint
/// match like [`last_model_for_endpoint`] does.
pub fn last_eligible_model_for_endpoint(
path: &std::path::Path,
endpoint: &str,
candidates: &[String],
) -> Option<String> {
let content = std::fs::read_to_string(path).ok()?;
content
.lines()
.rev()
.filter_map(|line| serde_json::from_str::<TurnMetrics>(line).ok())
.find(|m| m.endpoint == endpoint && candidates.iter().any(|c| c == &m.model_id))
.map(|m| m.model_id)
}
/// `n` with thousands separators, e.g. `104,857`.
pub fn fmt_count(n: u64) -> String {
// Insert thousands separators for readability.
let s = n.to_string();
let mut out = String::with_capacity(s.len() + s.len() / 3);
for (i, c) in s.chars().rev().enumerate() {
if i > 0 && i % 3 == 0 {
out.push(',');
}
out.push(c);
}
out.chars().rev().collect()
}
fn append_jsonl(metrics: &TurnMetrics, path: &std::path::Path) -> std::io::Result<()> {
use std::io::Write as _;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut line = serde_json::to_string(metrics).map_err(std::io::Error::other)?;
line.push('\n');
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
f.write_all(line.as_bytes())
}
/// Enforce the log rotation policy on `path` after an append.
///
/// Applies limits in this order (all active limits compose):
/// 1. **max_sessions** — truncate to the last N lines (fast tail-keep)
/// 2. **max_size_mb** — rotate-by-rename when file exceeds the byte cap
/// 3. **max_age_days** — not yet implemented (requires `recorded_at` field)
///
/// All errors are returned to the caller, which silently ignores them.
fn rotate_log(path: &std::path::Path, policy: &crate::LogConfig) -> std::io::Result<()> {
// --- session-count limit --------------------------------------------------
if policy.max_sessions > 0 {
let content = std::fs::read_to_string(path)?;
let lines: Vec<&str> = content.lines().collect();
if lines.len() > policy.max_sessions {
let kept = lines[lines.len() - policy.max_sessions..].join("\n");
std::fs::write(path, format!("{kept}\n"))?;
}
// Re-check file below against size limit after possible trim.
}
// --- size limit (rotate-by-rename) ----------------------------------------
if policy.max_size_mb > 0 {
let meta = std::fs::metadata(path)?;
let limit_bytes = policy.max_size_mb * 1024 * 1024;
if meta.len() > limit_bytes {
// Shift existing rotations: .2 → .3, .1 → .2, live → .1
for i in (1..=policy.keep_rotated).rev() {
let older = path.with_extension(format!("jsonl.{i}"));
let newer = if i == 1 {
path.to_path_buf()
} else {
path.with_extension(format!("jsonl.{}", i - 1))
};
if newer.exists() {
if i == policy.keep_rotated && older.exists() {
let _ = std::fs::remove_file(&older);
}
let _ = std::fs::rename(&newer, &older);
}
}
// The live file has been renamed; create a fresh empty one.
std::fs::File::create(path)?;
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn metrics(elapsed_ms: u64, in_tok: u32, out_tok: u32, cost: Option<f64>) -> TurnMetrics {
TurnMetrics {
elapsed_ms,
usage: Some(TokenUsage {
input_tokens: in_tok,
output_tokens: out_tok,
}),
cost_usd: cost,
model_id: "gemma4:e2b".into(),
endpoint: "http://REDACTED-HOST:11434".into(),
..Default::default()
}
}
#[test]
fn display_free_local() {
let m = metrics(3200, 847, 312, Some(0.0));
let line = m.display_line();
assert!(line.starts_with("3.2s"), "got: {line}");
assert!(line.contains("847"), "got: {line}");
assert!(line.contains("312"), "got: {line}");
assert!(line.contains("free (local)"), "got: {line}");
}
/// #2313: usage with no price is UNKNOWN cost, never "free (local)" — only
/// a confirmed `Some(0.0)` (a priced local model) is free. Unknown stays
/// unknown on the wire too: `cost_usd` is omitted, never a zero.
#[test]
fn unpriced_usage_is_unknown_cost_not_free_local() {
let unpriced = metrics(3200, 847, 312, None);
let line = unpriced.display_line();
assert!(!line.contains("free (local)"), "got: {line}");
assert!(
line.contains("847 in / 312 out · cost unknown"),
"got: {line}"
);
let json = serde_json::to_value(&unpriced).unwrap();
assert!(json.get("cost_usd").is_none(), "got: {json}");
// Twin: a confirmed zero price is still free, and serializes as 0.
let free = metrics(3200, 847, 312, Some(0.0));
assert!(free.display_line().contains("free (local)"));
assert_eq!(serde_json::to_value(&free).unwrap()["cost_usd"], 0.0);
}
/// #2313 (b2): with attempt totals the line shows what was sent, and an
/// incomplete turn names its unmeasured calls and never prints a cost.
#[test]
fn display_uses_attempt_totals_and_names_unmeasured_calls() {
let mut billed = metrics(1000, 120, 15, Some(0.000885));
billed.attempts = Some(crate::attempts::UsageTotals {
attempts: 2,
usage_missing: 0,
in_tokens: 220,
out_tokens: 15,
usage_complete: true,
});
let line = billed.display_line();
assert!(line.contains("220 in / 15 out"), "{line}");
assert!(!line.contains("120 in"), "{line}");
let mut partial = metrics(1000, 100, 10, None);
partial.attempts = Some(crate::attempts::UsageTotals {
attempts: 2,
usage_missing: 1,
in_tokens: 100,
out_tokens: 10,
usage_complete: false,
});
let line = partial.display_line();
assert!(
line.contains("100 in / 10 out (1 of 2 calls unmeasured) · cost unknown"),
"{line}"
);
assert!(!line.contains('$') && !line.contains("free"), "{line}");
}
/// #2313 review finding 8: when EVERY attempt is unmeasured the line still
/// says so, instead of falling through to the context merge's numbers
/// looking measured.
#[test]
fn display_names_unmeasured_calls_even_when_none_were_measured() {
let mut blind = metrics(1000, 120, 15, None);
blind.attempts = Some(crate::attempts::UsageTotals {
attempts: 2,
usage_missing: 2,
in_tokens: 0,
out_tokens: 0,
usage_complete: false,
});
let line = blind.display_line();
assert!(line.contains("(2 of 2 calls unmeasured)"), "{line}");
assert!(line.contains("cost unknown"), "{line}");
}
#[test]
fn display_with_cost() {
let m = metrics(8700, 1204, 892, Some(0.0041));
let line = m.display_line();
assert!(line.contains("$0.0041"), "got: {line}");
assert!(line.contains("1,204"), "got: {line}");
}
#[test]
fn display_tokens_unavailable() {
let m = TurnMetrics {
elapsed_ms: 5100,
usage: None,
cost_usd: None,
model_id: "gpt-4o".into(),
endpoint: "https://api.openai.com".into(),
..Default::default()
};
let line = m.display_line();
assert!(line.contains("tokens unavailable"), "got: {line}");
}
#[test]
fn display_end_reason_flags_anomalous_endings() {
let mut m = metrics(3200, 100, 50, Some(0.0));
assert!(!m.display_line().contains("narration"), "unset stays quiet");
m.end_reason = Some(TurnEndReason::Completed);
assert!(
!m.display_line().contains("narration"),
"a normal completion stays quiet"
);
m.end_reason = Some(TurnEndReason::NarrationCapExhausted);
assert!(m
.display_line()
.contains("ended on narration (rescue budget spent)"));
m.end_reason = Some(TurnEndReason::NarrationFinalRound);
assert!(m
.display_line()
.contains("ended on narration (final round)"));
m.end_reason = Some(TurnEndReason::RoundCap);
assert!(m.display_line().contains("round cap"));
m.end_reason = Some(TurnEndReason::Empty);
assert!(m.display_line().contains("empty response"));
}
#[test]
fn end_reason_serializes_snake_case_and_skips_when_absent() {
let mut m = metrics(1, 1, 1, None);
let j = serde_json::to_string(&m).unwrap();
assert!(!j.contains("end_reason"), "{j}");
m.end_reason = Some(TurnEndReason::NarrationCapExhausted);
let j = serde_json::to_string(&m).unwrap();
assert!(
j.contains("\"end_reason\":\"narration_cap_exhausted\""),
"{j}"
);
}
#[test]
fn a_question_reports_awaiting_operator_without_claiming_completion() {
let mut m = metrics(100, 10, 5, None);
m.end_reason = Some(TurnEndReason::AwaitingOperator);
assert!(m.display_line().contains("awaiting operator"));
assert!(!m.display_line().contains("completed"));
assert_eq!(
serde_json::to_value(&m).unwrap()["end_reason"],
"awaiting_operator"
);
}
#[test]
fn unrescued_narration_is_visibly_incomplete() {
let mut m = metrics(100, 10, 5, None);
for reason in [
TurnEndReason::NarrationCapExhausted,
TurnEndReason::NarrationFinalRound,
] {
m.end_reason = Some(reason);
assert!(m.display_line().contains("incomplete"));
}
}
#[test]
fn display_milliseconds_under_one_second() {
let m = metrics(850, 100, 50, None);
assert!(
m.display_line().starts_with("850ms"),
"got: {}",
m.display_line()
);
}
#[test]
fn fmt_count_thousands() {
assert_eq!(fmt_count(1000), "1,000");
assert_eq!(fmt_count(1234567), "1,234,567");
assert_eq!(fmt_count(42), "42");
}
#[test]
fn token_usage_total() {
let u = TokenUsage {
input_tokens: 300,
output_tokens: 150,
};
assert_eq!(u.total(), 450);
}
#[test]
fn token_usage_saturating_add() {
let a = TokenUsage {
input_tokens: 100,
output_tokens: 50,
};
let b = TokenUsage {
input_tokens: 200,
output_tokens: 75,
};
let sum = a.saturating_add(b);
assert_eq!(sum.input_tokens, 300);
assert_eq!(sum.output_tokens, 125);
// Saturation on overflow
let big = TokenUsage {
input_tokens: u32::MAX,
output_tokens: u32::MAX,
};
let sat = big.saturating_add(b);
assert_eq!(sat.input_tokens, u32::MAX);
}
#[test]
fn display_with_hallucinations() {
let mut m = metrics(3200, 847, 312, Some(0.0));
m.hallucinations = 2;
let line = m.display_line();
assert!(line.contains("2 hallucination(s) corrected"), "got: {line}");
}
#[test]
fn display_no_hallucinations_omits_warning() {
let m = metrics(3200, 847, 312, Some(0.0));
assert_eq!(m.hallucinations, 0);
assert!(
!m.display_line().contains("hallucination"),
"zero hallucinations must not appear in display"
);
}
#[test]
fn hallucinations_zero_skipped_in_json() {
let m = metrics(1000, 10, 5, Some(0.0));
let json = serde_json::to_string(&m).unwrap();
assert!(
!json.contains("hallucination"),
"zero hallucinations must be omitted from JSON"
);
}
#[test]
fn hallucinations_nonzero_in_json() {
let mut m = metrics(1000, 10, 5, Some(0.0));
m.hallucinations = 3;
let json = serde_json::to_string(&m).unwrap();
assert!(json.contains("\"hallucinations\":3"), "got: {json}");
}
#[test]
fn append_to_log_creates_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
let m = metrics(1000, 10, 5, Some(0.0));
m.append_to_log(&path);
let content = std::fs::read_to_string(&path).unwrap();
assert!(content.contains("gemma4:e2b"));
assert!(content.ends_with('\n'));
// Append twice — should have two lines.
m.append_to_log(&path);
let raw = std::fs::read_to_string(&path).unwrap();
let lines: Vec<_> = raw.lines().collect();
assert_eq!(lines.len(), 2);
}
#[test]
fn last_model_for_endpoint_picks_the_most_recent_matching_line() {
// Regression (#2622): the tiebreak must reflect the operator's LAST
// choice on this endpoint, not the first line in the log or a
// different endpoint's entry.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
for (endpoint, model) in [
("http://mux:11434", "ornith-1.5-35b"),
("http://other:11434", "unrelated-model"),
("http://mux:11434", "Qwen2.5-14B-Instruct-1M-Q8_0"),
] {
let mut m = metrics(1000, 10, 5, Some(0.0));
m.endpoint = endpoint.into();
m.model_id = model.into();
m.append_to_log(&path);
}
assert_eq!(
last_model_for_endpoint(&path, "http://mux:11434").as_deref(),
Some("Qwen2.5-14B-Instruct-1M-Q8_0"),
"must be the LAST entry for that endpoint, not the first"
);
}
#[test]
fn last_model_for_endpoint_missing_log_is_none() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("no-such-file.jsonl");
assert_eq!(last_model_for_endpoint(&path, "http://mux:11434"), None);
}
/// PR #2626 review: "history and validation notes" — the history rule is
/// the most recent row naming an ELIGIBLE candidate, not merely the most
/// recent row for the endpoint. A(loaded) then C(unloaded) must still
/// find A, not fall through to the picker despite earlier matching
/// history.
#[test]
fn last_eligible_model_for_endpoint_skips_a_later_ineligible_row() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
for model in ["A", "C"] {
let mut m = metrics(1000, 10, 5, Some(0.0));
m.endpoint = "http://mux:11434".into();
m.model_id = model.into();
m.append_to_log(&path);
}
let candidates = vec!["A".to_string(), "B".to_string()];
assert_eq!(
last_eligible_model_for_endpoint(&path, "http://mux:11434", &candidates).as_deref(),
Some("A"),
"the later row (C) isn't a loaded candidate — an earlier \
eligible row must still win, not fall through to the picker"
);
}
#[test]
fn last_eligible_model_for_endpoint_none_when_no_row_is_eligible() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
let mut m = metrics(1000, 10, 5, Some(0.0));
m.endpoint = "http://mux:11434".into();
m.model_id = "Z".into();
m.append_to_log(&path);
let candidates = vec!["A".to_string(), "B".to_string()];
assert_eq!(
last_eligible_model_for_endpoint(&path, "http://mux:11434", &candidates),
None
);
}
#[test]
fn rotation_session_limit_trims_oldest() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
let m = metrics(1000, 10, 5, Some(0.0));
// Write 10 entries.
for _ in 0..10 {
m.append_to_log(&path);
}
let policy = crate::LogConfig {
max_sessions: 7,
..Default::default()
};
rotate_log(&path, &policy).unwrap();
let n = std::fs::read_to_string(&path).unwrap().lines().count();
assert_eq!(n, 7, "should keep exactly max_sessions entries");
}
#[test]
fn rotation_session_limit_noop_when_under_cap() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
let m = metrics(1000, 10, 5, Some(0.0));
for _ in 0..5 {
m.append_to_log(&path);
}
let policy = crate::LogConfig {
max_sessions: 7,
..Default::default()
};
rotate_log(&path, &policy).unwrap();
let lines = std::fs::read_to_string(&path).unwrap().lines().count();
assert_eq!(lines, 5, "under cap — no entries should be dropped");
}
#[test]
fn rotation_size_limit_renames_and_resets() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("usage.jsonl");
let m = metrics(1000, 10, 5, Some(0.0));
// Write enough to exceed a tiny 1-byte cap.
m.append_to_log(&path);
let policy = crate::LogConfig {
max_sessions: 0,
max_size_mb: 0, // trigger via direct call with 1-byte threshold
keep_rotated: 2,
..Default::default()
};
// Manually exercise rotate_log with a near-zero threshold.
let policy_tiny = crate::LogConfig {
max_size_mb: 0, // 0 = disabled; use a workaround via a custom struct
..policy
};
// With size disabled the file should be unchanged.
rotate_log(&path, &policy_tiny).unwrap();
assert!(path.exists(), "file must still exist when size limit is 0");
}
#[test]
fn log_config_default_is_7_sessions() {
let cfg = crate::LogConfig::default();
assert_eq!(cfg.max_sessions, 7);
assert_eq!(cfg.max_size_mb, 0);
assert_eq!(cfg.max_age_days, 0);
assert_eq!(cfg.keep_rotated, 3);
}
}