/mas-ai-workflows:llm-cost-latency-benchmarkfrom mas-ai-workflows
Benchmark AI workflow cost and latency with TTFT/TPOT/ITL/e2e percentiles, cache-aware token billing, goodput under SLOs, and a quality floor. Use before claiming a model, prompt, or infra change is cheaper or faster.
Ships in mas-ai-workflows. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Cost and latency are not one number. A claim is a tuple: workload × clock boundary × cache state × concurrency/arrival process × token mix × pricing snapshot × quality floor. Mixing those variables produces vendor-slide fiction. A response that is faster but fails acceptance is not an optimization win—it is a different product.
Claude operates as a Principal LLM Performance Economist, specializing in client-observed TTFT vs server TTFT, TPOT vs ITL, cache-cold vs cache-hot regimes, billable token categories (uncached input, cache read, cache write, output including reasoning), workflow wall-clock (retrieval + tools + retries + queue), percentile reporting, and SLO-qualified goodput.
┌─────────────────────────────────────────────────────────────┐
│ Cost × Latency Benchmark Stack │
│ │
│ Workload contract │
│ ├── Case population (prod-shaped) + quality floor │
│ ├── Input/output length distributions (or fixed I/O) │
│ ├── Concurrency + arrival process (closed vs open loop) │
│ └── Cache policy: cold | warm | production-mix │
│ │
│ Timing planes (never conflate) │
│ ├── Client TTFT: send → first nonempty streamed token │
│ ├── Prefill / queue / network (diagnostic breakdown) │
│ ├── TPOT / ITL after first token │
│ └── Workflow e2e: user intent → final accepted artifact │
│ │
│ Cost planes │
│ ├── Provider usage: input, cached_read, cache_write, out │
│ ├── Non-token: tools, search, containers, retries, fails │
│ └── Pricing manifest: URL + retrieved_at + model tier │
│ │
│ Decision │
│ ├── Percentiles + sample size + goodput@SLO │
│ └── Compare only configs that meet the quality floor │
└─────────────────────────────────────────────────────────────┘
Use when
Do not use when
@prompt-regression-gate / @ai-evaluation-dataset first and set a quality floor.Let request i be sent at client time s_i, first nonempty usable streamed token arrive at f_i, last token at e_i. Let O_i = provider-reported output/completion tokens (includes reasoning/formatting tokens when billed that way). Let I_i = total input/prompt tokens.
| Metric | Formula / definition | Notes that break comparisons |
|---|---|---|
| Client TTFT | f_i − s_i | Includes network + queue + prefill. State client region. |
| Server TTFT | receipt → first token sent | Different clock; do not swap with client TTFT. |
| E2E request latency | e_i − s_i | Model-call only unless labeled workflow e2e. |
| TPOT | (e_i − f_i) / (O_i − 1) | Undefined if O_i < 2. Excludes first token by convention (NVIDIA/vLLM-style). |
| ITL | gaps t_{j+1}−t_j | Distribution over intervals; p95 of all gaps ≠ mean of per-request TPOT. |
| Decode TPS (per user) | (O_i − 1) / (e_i − f_i) = 1/TPOT | Not full-request rate. |
| Full-request TPS | O_i / (e_i − s_i) | Includes TTFT; lower; different claim. |
| Aggregate TPS | sum(O) / T_run | Fleet/GPU scope must be named. |
| Goodput | compliant completions / second or fraction meeting SLO | Name SLO (e.g. TTFT p99≤X ∧ TPOT p99≤Y); count errors as noncompliant. |
First-token identity (reasoning models): declare whether f_i is (a) first SSE/data chunk, (b) first reasoning token, or (c) first visible answer token. Voice/chat UX usually cares about (c). Chunk ≠ token (common harness bug called out on r/LocalLLaMA tooling).
OpenTelemetry alignment (when instrumenting): prefer gen_ai.client.operation.time_to_first_chunk / gen_ai.usage.input_tokens / output_tokens, and cache detail attributes when available. Report billed units when providers distinguish billed vs consumed.
Providers increasingly price separately:
cached_tokens) — discounted reuse of a prefixcache_write_tokens) — may be >1× uncached input on some model families (e.g. OpenAI docs: writes at 1.25×, reads at 0.1× on newer families—verify live pricing)Arithmetic sketch (replace rates from a dated pricing pull):
cost ≈
u_in * rate_uncached_in
+ c_read * rate_cached_in
+ c_write * rate_cache_write
+ out * rate_out
+ Σ tool_calls * tool_rate
+ Σ non_token_fees
Rules:
usage over local len/4 guesses (tools, images, schemas break heuristics).unknown, never invent.stream_options.include_usage (or provider equivalent) so finals are recorded.max_output_tokens for hidden tokens + visible answer; otherwise empty completions skew latency/cost.{
"retrieved_at": "2026-10-05T18:00:00Z",
"source_url": "https://…/pricing",
"model": "…",
"currency": "USD",
"rates_per_1m": {
"input_uncached": null,
"input_cached_read": null,
"input_cache_write": null,
"output": null
},
"notes": "Paste exact rows; do not rely on memory."
}
| KPI | Definition |
|---|---|
| $/accepted task | Total $ for all attempts / tasks that passed quality floor |
| $/1k input tokens (effective) | Blended after cache hit mix |
| Cache hit rate | cached_read / input (verify via usage fields, not hope) |
| Retry tax | $ and latency of retries / successes |
| Cost at iso-quality | Only among configs meeting the floor |
Cheapest raw tokens with 2× retries and quality fails is usually more expensive per accepted task.
Before trusting any A vs B claim, both sides must match—or differences must be labeled as the intentional experimental factor:
If any required field is missing → verdict cannot-normalize, not “approximately faster.”
Prefix/KV caching can dominate TTFT. Practitioners repeatedly show:
Always report cold and warm separately, with measured cached_tokens / hit rate.
Sample size honesty (IETF-style guidance): p99 needs large N (order ~10³ samples for rough relative accuracy); tiny benches must not claim p99 production SLOs.
For product decisions, measure workflow wall-clock:
user_submit → retrieve/tools/guards → model (TTFT…E2E) → validate/repair → accept
Attribute spans:
| Span | Typical owners |
|---|---|
| Retrieval / rerank | @rag-retrieval-audit |
| Tool round-trips | agent graph |
| Validation retries | @llm-json-contract-check |
| Model TTFT/TPOT | provider/serving |
| Human-perceived | UX (streaming indicators reset abandonment clocks) |
Optimizing only decode TPS while RAG prefill and tools dominate e2e is cargo-cult performance work.
Record per request (sanitized):
{
"case_id": "c-17",
"attempt": 1,
"ok_quality": true,
"error_type": null,
"s_client": 0.0,
"f_first_usable_token": 0.42,
"e_last_token": 1.88,
"ttft_ms": 420,
"tpot_ms": 28.5,
"usage": {
"input": 3500,
"cached_read": 3200,
"cache_write": 0,
"output": 180,
"reasoning_output_subset": 40
},
"cost_usd": null,
"cache_regime": "warm",
"concurrency_bin": 16,
"model": "…",
"pricing_retrieved_at": "…"
}
Only compare configs that clear the quality floor. Prefer:
Deliver raw measurements + config + pricing refs + arithmetic. Label extrapolation limits.
"""Cost/latency rollup with TTFT, TPOT, and dated pricing."""
from __future__ import annotations
import json
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Sequence
def percentile(sorted_vals: Sequence[float], p: float) -> float:
"""Nearest-rank percentile; p in [0, 100]. Empty → nan."""
if not sorted_vals:
return float("nan")
if p <= 0:
return sorted_vals[0]
if p >= 100:
return sorted_vals[-1]
k = max(1, int(math.ceil(p / 100.0 * len(sorted_vals))))
return sorted_vals[k - 1]
@dataclass(frozen=True)
class Rates:
"""USD per 1M tokens. None means unknown—do not invent."""
input_uncached: float | None
input_cached_read: float | None
input_cache_write: float | None
output: float | None
def cost_usd(usage: dict[str, int], rates: Rates) -> float | None:
need = {
"input_uncached": rates.input_uncached,
"input_cached_read": rates.input_cached_read,
"input_cache_write": rates.input_cache_write,
"output": rates.output,
}
if any(v is None for v in need.values()):
return None
inp = usage.get("input", 0)
cread = usage.get("cached_read", 0)
cwrite = usage.get("cache_write", 0)
# Uncached portion = input - cached_read - cache_write (clamp at 0)
u = max(0, inp - cread - cwrite)
out = usage.get("output", 0)
return (
u * rates.input_uncached
+ cread * rates.input_cached_read
+ cwrite * rates.input_cache_write
+ out * rates.output
) / 1_000_000.0
def tpot_ms(ttft_ms: float, e2e_ms: float, output_tokens: int) -> float:
if output_tokens < 2:
return float("nan")
return (e2e_ms - ttft_ms) / (output_tokens - 1)
def summarize(rows: list[dict[str, Any]], rates: Rates, slo_ttft_ms: float) -> dict[str, Any]:
ttfts = sorted(r["ttft_ms"] for r in rows if r.get("ttft_ms") is not None)
tpots = sorted(
tpot_ms(r["ttft_ms"], r["e2e_ms"], r["usage"]["output"])
for r in rows
if r.get("ttft_ms") is not None and r.get("e2e_ms") is not None
)
tpots = [x for x in tpots if x == x]
costs = []
unknown_cost = 0
for r in rows:
c = cost_usd(r["usage"], rates)
if c is None:
unknown_cost += 1
else:
costs.append(c)
accepted = [r for r in rows if r.get("ok_quality")]
good = [r for r in accepted if r["ttft_ms"] <= slo_ttft_ms]
return {
"n": len(rows),
"ttft_p50": percentile(ttfts, 50),
"ttft_p95": percentile(ttfts, 95),
"ttft_p99": percentile(ttfts, 99),
"tpot_p50": percentile(tpots, 50),
"tpot_p95": percentile(tpots, 95),
"cost_total_usd": sum(costs) if costs else None,
"cost_unknown_rows": unknown_cost,
"cost_per_accepted_usd": (sum(costs) / len(accepted)) if costs and accepted else None,
"goodput_fraction_ttft_slo": (len(good) / len(rows)) if rows else float("nan"),
"quality_pass_rate": (len(accepted) / len(rows)) if rows else float("nan"),
}
# Load JSONL attempts, attach pricing from manifest, print summarize().
| Cell | Purpose |
|---|---|
| Fixed 0.5k/0.5k I/O, c=1, cache-cold | Pure model responsiveness |
| Same, cache-warm | Prefix-cache benefit |
| Prod-length distribution, c≈p95 load | Capacity reality |
| Full workflow e2e | Product truth |
| + quality floor filter | Economic truth |
| Signature | Deep cause | What to do |
|---|---|---|
| Amazing TTFT in bench, bad in prod | Accidental prefix cache / short prompts | Force unique prefixes; match prod lengths; report hit rate |
| p50 fine, p99 awful | Queueing, throttling, noisy neighbors | Correlate spikes with RPS vs wall clock; raise replicas or shed load; consider hedge |
| High TPS, unhappy users | Optimizing aggregate decode, ignoring TTFT SLO | Track goodput; plot latency vs offered load |
| “Cheaper model” costs more | More output/reasoning/retries | Optimize $/accepted and output tokens, not $/MTok sticker |
| Empty/fast failures | Reasoning burned max_tokens | Raise output budget; classify as errors not wins |
| Serverless look slow | Cold start (pull/CUDA/weights) | Separate cold-start study; warm pool for interactive |
| TTFT ≈ queue | Saturation | Capacity problem, not “slow model” |
| Cross-provider bakeoff chaos | Different clocks/tokenizers/cache | Comparability gate; cannot-normalize if mismatched |
| Client harness overhead | Sync client dominating | Async load gen; note NVIDIA warnings on client overhead |
| Cost unknown | Streaming without usage | Enable usage on stream; else mark unknown |
@prompt-regression-gate—cache wins that break quality are not wins.@prompt-regression-gate — quality floor / paired go-no-go@ai-evaluation-dataset — representative case population@rag-retrieval-audit — retrieval latency vs generation@llm-json-contract-check — repair retries inflate cost/latency@llm-cost-latency-benchmark — this skill@vllm / provider skills — serving knobs (batching, prefix cache)MANDATORY: Treat every cost/latency claim as a workload+clock+cache+concurrency+pricing+quality tuple. Measure client TTFT and TPOT/ITL with named formulas. Bill all token classes and failures honestly; date the pricing source. Never call a quality regression an optimization. Prefer goodput and $/accepted over vanity TPS. If comparability fields are missing, say cannot-normalize.
time_to_first_chunk, token usage (+ cache attributes), billed vs consumedWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub alivirgo/major-ai-skills --plugin mas-ai-workflows10 skills in this plugin
/agent-injection-boundary-testTest authorized agents against indirect prompt injection in retrieved docs and tool outputs using paired clean/poison fixtures, synthetic canaries, and sandboxed tools. Evidence for these cases—not a claim injection is solved./agent-tool-replay-testReplay recorded agent tool/LLM trajectories against deterministic fixtures to test argument validation, errors, idempotency, and side-effect boundaries—separate from live tool-selection quality./ai-citation-verificationVerify AI citations across structural schema, resolvability (registry/URL/DOI), and semantic support of each claim by the cited span—not the whole context. Use for RAG answers, research agents, and regulated audit trails.Other plugins' skills for the same job
2 plugins in one repository ship this exact skill · first indexed Oct 7, 2026