llmp 0.1.0

Measures how well a local LLM setup uses its model: a recording proxy and a prompt-reuse analysis
Documentation
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
use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::REPORT_VERSION;
use crate::findings::{Confidence, Finding, FindingKind, add_ms};
use crate::measured::{Measured, Source};
use crate::normalize::{Api, Normalized, SkipReason};
use crate::record::Record;
use crate::table::{Client, Row, RowKind, Table, ToolUsage};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Report {
    pub v: u32,
    pub window: Option<Window>,
    pub coverage: Coverage,
    pub servers: Vec<ServerFields>,
    pub time: Time,
    pub composition: CompositionTotals,
    pub clients: Vec<Client>,
    pub tools: Vec<ToolUsage>,
    pub findings: Vec<Finding>,
    pub rows: Vec<Row>,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Window {
    pub start_ms: i64,
    pub end_ms: i64,
    pub days: f64,
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Coverage {
    pub records: u64,
    pub analysed: u64,
    pub skipped: SkippedCounts,
    pub paths: BTreeMap<String, u64>,
    pub bad_lines: u64,
    pub turns: u64,
    pub conversations: u64,
    pub turns_with_reuse: u64,
    pub turns_with_timing: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SkippedCounts {
    pub not_chat: u64,
    pub error: u64,
    pub non_2xx: u64,
    pub unparsed: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerFields {
    pub api: Api,
    pub fields: Vec<CountField>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CountField {
    PromptTokens,
    CompletionTokens,
    ReusedTokens,
    EvaluatedTokens,
    PrefillMs,
    DecodeMs,
    LoadMs,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Time {
    pub prefill_ms: Option<Measured<f64>>,
    pub lost_ms: Option<Measured<f64>>,
    pub lost_tokens: u64,
    pub by_cause: BTreeMap<String, CauseTotal>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CauseTotal {
    pub tokens: u64,
    pub ms: Option<Measured<f64>>,
    pub rows: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CompositionTotals {
    pub system: u64,
    pub tools: u64,
    pub history: u64,
    pub new_content: u64,
}

const DAY_MS: f64 = 86_400_000.0;
const SUMMARY_CAUSES: usize = 3;
const SUMMARY_FINDINGS: usize = 3;
const SUMMARY_CLIENTS: usize = 3;

pub(crate) fn assemble(
    records: &[Record],
    normalized: &Normalized,
    table: Table,
    findings: Vec<Finding>,
) -> Report {
    let window = match (
        records.iter().map(|r| r.t_start_ms).min(),
        records.iter().map(|r| r.t_end_ms.max(r.t_start_ms)).max(),
    ) {
        (Some(start_ms), Some(end_ms)) => Some(Window {
            start_ms,
            end_ms,
            days: (end_ms - start_ms) as f64 / DAY_MS,
        }),
        _ => None,
    };
    Report {
        v: REPORT_VERSION,
        window,
        coverage: coverage(records, normalized, &table.rows),
        servers: servers(&table.rows),
        time: time(&table.rows),
        composition: composition(&table.rows),
        clients: table.clients,
        tools: table.tools,
        findings,
        rows: table.rows,
    }
}

fn coverage(records: &[Record], normalized: &Normalized, rows: &[Row]) -> Coverage {
    let mut coverage = Coverage {
        records: records.len() as u64,
        analysed: normalized.exchanges.len() as u64,
        ..Coverage::default()
    };
    for skipped in &normalized.skipped {
        match skipped.reason {
            SkipReason::NotChat => {
                coverage.skipped.not_chat += 1;
                let path = skipped.path.split('?').next().unwrap_or_default();
                *coverage.paths.entry(path.to_string()).or_default() += 1;
            }
            SkipReason::Error => coverage.skipped.error += 1,
            SkipReason::Non2xx => coverage.skipped.non_2xx += 1,
            SkipReason::Unparsed => coverage.skipped.unparsed += 1,
        }
    }
    coverage.conversations = rows
        .iter()
        .filter_map(|r| r.conversation)
        .collect::<BTreeSet<_>>()
        .len() as u64;
    for row in rows.iter().filter(|r| r.kind == RowKind::Turn) {
        coverage.turns += 1;
        coverage.turns_with_reuse += u64::from(row.counts.reused_tokens.is_some());
        coverage.turns_with_timing += u64::from(row.counts.prefill_ms.is_some());
    }
    coverage
}

fn servers(rows: &[Row]) -> Vec<ServerFields> {
    let mut apis: BTreeMap<Api, BTreeSet<CountField>> = BTreeMap::new();
    for row in rows {
        let fields = apis.entry(row.api).or_default();
        let c = &row.counts;
        let reported = [
            (CountField::PromptTokens, c.prompt_tokens.map(|m| m.source)),
            (
                CountField::CompletionTokens,
                c.completion_tokens.map(|m| m.source),
            ),
            (CountField::ReusedTokens, c.reused_tokens.map(|m| m.source)),
            (
                CountField::EvaluatedTokens,
                c.evaluated_tokens.map(|m| m.source),
            ),
            (CountField::PrefillMs, c.prefill_ms.map(|m| m.source)),
            (CountField::DecodeMs, c.decode_ms.map(|m| m.source)),
            (CountField::LoadMs, c.load_ms.map(|m| m.source)),
        ];
        for (field, source) in reported {
            if source == Some(Source::Server) {
                fields.insert(field);
            }
        }
    }
    apis.into_iter()
        .map(|(api, fields)| ServerFields {
            api,
            fields: fields.into_iter().collect(),
        })
        .collect()
}

fn time(rows: &[Row]) -> Time {
    let mut prefill_ms = None;
    let mut lost_ms: Option<Measured<f64>> = None;
    let mut lost_tokens = 0u64;
    let mut by_cause: BTreeMap<String, CauseTotal> = BTreeMap::new();
    for row in rows {
        if let Some(prefill) = row.counts.prefill_ms {
            prefill_ms = Some(add_ms(prefill_ms, prefill));
        }
        if !row.loss_measured {
            continue;
        }
        if let Some(prefill) = row.counts.prefill_ms {
            lost_ms = Some(add_ms(
                lost_ms,
                Measured {
                    value: 0.0,
                    source: prefill.source,
                },
            ));
        }
        for loss in [&row.lost_client, &row.lost_external].into_iter().flatten() {
            lost_tokens += u64::from(loss.tokens);
            let total = by_cause.entry(loss.cause.clone()).or_insert(CauseTotal {
                tokens: 0,
                ms: None,
                rows: 0,
            });
            total.tokens += u64::from(loss.tokens);
            total.rows += 1;
            if let Some(ms) = loss.ms {
                total.ms = Some(add_ms(total.ms, ms));
                lost_ms = Some(add_ms(lost_ms, ms));
            }
        }
    }
    Time {
        prefill_ms,
        lost_ms,
        lost_tokens,
        by_cause,
    }
}

fn composition(rows: &[Row]) -> CompositionTotals {
    let mut totals = CompositionTotals::default();
    for row in rows {
        let c = &row.composition;
        totals.system += u64::from(c.system.value);
        totals.tools += u64::from(c.tools.value);
        totals.history += u64::from(c.history.value);
        totals.new_content += u64::from(c.new_content.value);
    }
    totals
}

impl Report {
    pub fn summary(&self) -> String {
        let mut lines = Vec::new();
        let turns = self.coverage.turns;
        let span = self
            .window
            .map(|w| {
                format!(
                    " over {}",
                    duration(w.end_ms.saturating_sub(w.start_ms) as f64)
                )
            })
            .unwrap_or_default();
        lines.push(format!(
            "llmp: {} requests{span}, {} analysed, {} in {}",
            self.coverage.records,
            self.coverage.analysed,
            plural(turns, "turn"),
            plural(self.coverage.conversations, "conversation")
        ));
        let several = self.clients.len() > 1;
        if several {
            let shown: Vec<String> = self
                .clients
                .iter()
                .take(SUMMARY_CLIENTS)
                .map(|c| {
                    format!(
                        "{} ({}, {})",
                        c.client,
                        plural(u64::from(c.requests), "request"),
                        plural(u64::from(c.conversations), "conversation")
                    )
                })
                .collect();
            let more = self.clients.len().saturating_sub(SUMMARY_CLIENTS);
            let tail = if more > 0 {
                format!(" · {more} more")
            } else {
                String::new()
            };
            lines.push(format!("clients: {}{tail}", shown.join(" · ")));
        }
        lines.push(self.time_line());
        let mut causes: Vec<(&String, &CauseTotal)> = self.time.by_cause.iter().collect();
        causes.sort_by(|a, b| {
            let ms = |c: &CauseTotal| c.ms.map_or(-1.0, |m| m.value);
            ms(b.1)
                .total_cmp(&ms(a.1))
                .then(b.1.tokens.cmp(&a.1.tokens))
                .then(a.0.cmp(b.0))
        });
        if !causes.is_empty() {
            let top: Vec<String> = causes
                .iter()
                .take(SUMMARY_CAUSES)
                .map(|(cause, total)| {
                    format!("{} {}", cause_label(cause), size(total.tokens, total.ms))
                })
                .collect();
            lines.push(format!("  by cause: {}", top.join(" · ")));
        }
        lines.push(self.coverage_line());
        if !self.findings.is_empty() {
            lines.push("findings:".into());
            for finding in self.findings.iter().take(SUMMARY_FINDINGS) {
                let client = match (&finding.client, several) {
                    (Some(client), true) => format!(" [{client}]"),
                    _ => String::new(),
                };
                lines.push(format!(
                    "  [{}] {}{client}",
                    confidence_label(finding.confidence),
                    label(finding)
                ));
            }
            if self.findings.len() > SUMMARY_FINDINGS {
                lines.push(format!(
                    "  … {} more with --json",
                    self.findings.len() - SUMMARY_FINDINGS
                ));
            }
        }
        let mut text = lines.join("\n");
        text.push('\n');
        text
    }

    fn time_line(&self) -> String {
        match (self.time.lost_ms, self.time.prefill_ms) {
            (Some(lost), Some(prefill)) if prefill.value > 0.0 => format!(
                "time lost re-processing prompts: {}{} of {} prefill ({:.0}%), {} tokens",
                duration(lost.value),
                source_note(lost.source),
                duration(prefill.value),
                100.0 * lost.value / prefill.value,
                thousands(self.time.lost_tokens)
            ),
            (Some(lost), _) => format!(
                "time lost re-processing prompts: {}{}, {} tokens",
                duration(lost.value),
                source_note(lost.source),
                thousands(self.time.lost_tokens)
            ),
            (None, _) => "time lost re-processing prompts: not measured (no turn had the server's reuse and timing counters)".into(),
        }
    }

    fn coverage_line(&self) -> String {
        let c = &self.coverage;
        let mut skipped = Vec::new();
        for (count, name) in [
            (c.skipped.not_chat, "not chat"),
            (c.skipped.error, "failed"),
            (c.skipped.non_2xx, "non-2xx"),
            (c.skipped.unparsed, "unreadable"),
        ] {
            if count > 0 {
                skipped.push(format!("{count} {name}"));
            }
        }
        let mut line = format!("coverage: {} of {} records analysed", c.analysed, c.records);
        if !skipped.is_empty() {
            line.push_str(&format!(" ({})", skipped.join(", ")));
        }
        if c.bad_lines > 0 {
            line.push_str(&format!(", {}", plural(c.bad_lines, "bad line")));
        }
        if c.turns > 0 {
            line.push_str(&format!(
                "; reuse reported on {} of {} turns, timing on {}",
                c.turns_with_reuse, c.turns, c.turns_with_timing
            ));
        }
        line
    }
}

fn label(finding: &Finding) -> String {
    let model = finding.model.as_deref().unwrap_or("?");
    let evidence = &finding.evidence;
    let text = |key: &str| {
        evidence
            .get(key)
            .and_then(|v| v.as_str())
            .unwrap_or("?")
            .to_string()
    };
    let number = |key: &str| evidence.get(key).and_then(|v| v.as_u64()).unwrap_or(0);
    let lost = match (finding.lost_tokens, finding.lost_ms) {
        (Some(tokens), ms) => format!(": {} lost", size(u64::from(tokens), ms)),
        (None, _) => ", loss not measured".into(),
    };
    let context = finding
        .context_tokens
        .map(|t| thousands(u64::from(t)))
        .unwrap_or_default();
    match finding.kind {
        FindingKind::SideCallOnConversationModel => format!(
            "{} on the conversation model {model}{lost}",
            plural(number("side_calls"), "side-call")
        ),
        FindingKind::PrefixBreak => format!(
            "prompt prefix broken by {} on {} of {} links ({model}){lost}",
            cause_label(&text("break_cause")),
            number("broken"),
            number("links")
        ),
        FindingKind::ServerCacheLoss => format!(
            "{} on {} ({model}){lost}",
            cause_label(&text("kind")),
            plural(finding.rows.len() as u64, "turn")
        ),
        FindingKind::OtherConversationEviction => format!(
            "cache lost to other conversations on {} ({model}){lost}",
            plural(finding.rows.len() as u64, "turn")
        ),
        FindingKind::OtherModelEviction => format!(
            "cache lost to other models on {} ({model}){lost}",
            plural(finding.rows.len() as u64, "turn")
        ),
        FindingKind::UnusedTool => format!(
            "tool {} offered on {}, never called ({context} tokens each)",
            text("tool"),
            plural(number("offered"), "request")
        ),
        FindingKind::LargeToolSchema => format!(
            "tool {} schema is {} tokens ({context} over {})",
            text("tool"),
            thousands(number("schema_tokens")),
            number("threshold")
        ),
        FindingKind::LargeSystemPrompt => format!(
            "system prompt of {model} is {} tokens ({context} over {})",
            thousands(number("system_tokens")),
            number("threshold")
        ),
    }
}

fn cause_label(cause: &str) -> &str {
    match cause {
        "tools_changed" => "tool list changes",
        "system_changed" => "system prompt changes",
        "history_rewritten" => "history rewrites",
        "side_call" => "side-calls",
        "other_conversation" => "other conversations",
        "other_model" => "other models",
        "server_empty" => "server cache emptied",
        "server_head_only" => "server kept only the head",
        "server_rollback" => "server cache rolled back",
        other => other,
    }
}

fn confidence_label(confidence: Confidence) -> &'static str {
    match confidence {
        Confidence::High => "high",
        Confidence::Medium => "medium",
        Confidence::Low => "low",
    }
}

fn source_note(source: Source) -> &'static str {
    match source {
        Source::Server | Source::Tokenizer => "",
        Source::Proxy => " (proxy-timed, upper bound)",
        Source::Estimate => " (estimated)",
    }
}

fn size(tokens: u64, ms: Option<Measured<f64>>) -> String {
    match ms {
        Some(ms) => format!("{} ({} tokens)", duration(ms.value), thousands(tokens)),
        None => format!("{} tokens", thousands(tokens)),
    }
}

fn duration(ms: f64) -> String {
    let ms = ms.max(0.0);
    if ms < 1000.0 {
        return format!("{ms:.0} ms");
    }
    let seconds = ms / 1000.0;
    if seconds < 60.0 {
        return format!("{seconds:.1} s");
    }
    let total = seconds.round() as u64;
    let (hours, minutes, seconds) = (total / 3600, total / 60 % 60, total % 60);
    if hours > 0 {
        format!("{hours}h {minutes}m")
    } else {
        format!("{minutes}m {seconds}s")
    }
}

fn plural(n: u64, noun: &str) -> String {
    if n == 1 {
        format!("1 {noun}")
    } else {
        format!("{} {noun}s", thousands(n))
    }
}

fn thousands(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::new();
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(c);
    }
    out
}