mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-24 04:43:07 +00:00
Compare commits
3 Commits
fix/pre-co
...
fix/throug
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72556c31cd | ||
|
|
cd3e1a0b87 | ||
|
|
929be985f9 |
1
changelog.d/fixes/21092-throughput-plausible-samples.md
Normal file
1
changelog.d/fixes/21092-throughput-plausible-samples.md
Normal file
@@ -0,0 +1 @@
|
||||
- **fix(usage):** tokens-per-second measurements ignore generation windows shorter than 250 ms and rates above 5,000 tok/s, so a response that arrives in one burst no longer reports hundreds of thousands of tok/s in `usage.tokens_per_second`, the `X-OmniRoute-Tokens-Per-Second` header or the model latency stats. The latency stats that feed speed-based routing now compute `avgTokensPerSecond` as total tokens over total generation time instead of a mean of per-request rates.
|
||||
@@ -4,7 +4,23 @@
|
||||
* tok/s MUST exclude TTFT. `output_tokens / total_latency` includes queueing and
|
||||
* first-token wait and is not generation speed. When TTFT is unknown (typical
|
||||
* non-streaming JSON), omit the field rather than guessing.
|
||||
*
|
||||
* A rate is also omitted when it cannot be a real measurement:
|
||||
* - generation windows shorter than MIN_GENERATION_WINDOW_MS are dominated by
|
||||
* overhead/jitter (a response that arrives in one burst leaves a ~1 ms window
|
||||
* after TTFT and turns into hundreds of thousands of tok/s);
|
||||
* - rates above MAX_PLAUSIBLE_TOKENS_PER_SECOND are buffered responses dumped in
|
||||
* a few frames, not decode speed. The ceiling sits above the fastest public
|
||||
* inference rates (order of 2,000-3,000 tok/s) so genuinely fast providers keep
|
||||
* their samples, and below those dumps (2,000 tokens in 300 ms ~ 6,700 tok/s).
|
||||
*/
|
||||
|
||||
/** Generation windows shorter than this produce no tok/s sample. */
|
||||
export const MIN_GENERATION_WINDOW_MS = 250;
|
||||
|
||||
/** Rates above this are treated as measurement artifacts and produce no tok/s sample. */
|
||||
export const MAX_PLAUSIBLE_TOKENS_PER_SECOND = 5000;
|
||||
|
||||
export function generationDurationMs(
|
||||
totalMs: number,
|
||||
ttftMs: number | null | undefined
|
||||
@@ -20,8 +36,10 @@ export function tokensPerSecond(
|
||||
generationMs: number | null | undefined
|
||||
): number | null {
|
||||
if (generationMs == null || !Number.isFinite(generationMs) || generationMs <= 0) return null;
|
||||
if (generationMs < MIN_GENERATION_WINDOW_MS) return null;
|
||||
if (!Number.isFinite(outputTokens) || outputTokens <= 0) return null;
|
||||
return outputTokens / (generationMs / 1000);
|
||||
const rate = outputTokens / (generationMs / 1000);
|
||||
return rate > MAX_PLAUSIBLE_TOKENS_PER_SECOND ? null : rate;
|
||||
}
|
||||
|
||||
function outputTokenCount(usage: Record<string, unknown>): number {
|
||||
|
||||
@@ -9,6 +9,8 @@ import { storedUsageEvidence } from "../storedUsageEvidence";
|
||||
export { toNumber } from "@/shared/utils/numeric";
|
||||
// #13130: shared TPS math (generation-time denominator, reasoning-aware numerator).
|
||||
import { resolveGenerationMs, resolveTpsOutputTokens } from "@/shared/utils/logTps";
|
||||
// Same plausibility rules (minimum window, maximum rate) as the per-call tok/s.
|
||||
import { tokensPerSecond } from "@omniroute/open-sse/utils/generationThroughput";
|
||||
import { toNumber as toNumberValue } from "@/shared/utils/numeric";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
@@ -97,6 +99,15 @@ export interface LatencySampleBuckets {
|
||||
allTtfts: number[];
|
||||
successfulTps: number[];
|
||||
allTps: number[];
|
||||
/**
|
||||
* Running totals over the plausible TPS samples, so the aggregate is
|
||||
* Σ tokens ÷ Σ generation time instead of a mean of per-row ratios.
|
||||
* Optional: callers may build the buckets as a literal without them.
|
||||
*/
|
||||
successfulTpsTokens?: number;
|
||||
successfulTpsWindowMs?: number;
|
||||
allTpsTokens?: number;
|
||||
allTpsWindowMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,6 +124,9 @@ export interface LatencySampleBuckets {
|
||||
* - numerator: max(tokensOutput, tokensReasoning) — providers are expected
|
||||
* to fold reasoning into output tokens, but a provider that excludes them
|
||||
* while still reporting tokens_reasoning would otherwise undercount.
|
||||
* A sample whose window is shorter than MIN_GENERATION_WINDOW_MS or whose rate
|
||||
* exceeds MAX_PLAUSIBLE_TOKENS_PER_SECOND (generationThroughput.ts) is not a
|
||||
* measurement and stays out of the TPS buckets; its latency/TTFT still count.
|
||||
*/
|
||||
export function accumulateLatencySample(
|
||||
buckets: LatencySampleBuckets,
|
||||
@@ -127,15 +141,21 @@ export function accumulateLatencySample(
|
||||
if (ttftMs > 0) buckets.allTtfts.push(ttftMs);
|
||||
const tpsTokens = resolveTpsOutputTokens(tokensOutput, tokensReasoning);
|
||||
const generationMs = resolveGenerationMs(latencyMs, ttftMs);
|
||||
const tps =
|
||||
tpsTokens > 0 && generationMs !== null && generationMs > 0
|
||||
? tpsTokens / (generationMs / 1000)
|
||||
: null;
|
||||
if (tps !== null) buckets.allTps.push(tps);
|
||||
const tps = tokensPerSecond(tpsTokens, generationMs);
|
||||
const plausible = tps !== null && generationMs !== null;
|
||||
if (plausible) {
|
||||
buckets.allTps.push(tps);
|
||||
buckets.allTpsTokens = (buckets.allTpsTokens ?? 0) + tpsTokens;
|
||||
buckets.allTpsWindowMs = (buckets.allTpsWindowMs ?? 0) + generationMs;
|
||||
}
|
||||
if (!isSuccess) return;
|
||||
buckets.successfulLatencies.push(latencyMs);
|
||||
if (ttftMs > 0) buckets.successfulTtfts.push(ttftMs);
|
||||
if (tps !== null) buckets.successfulTps.push(tps);
|
||||
if (plausible) {
|
||||
buckets.successfulTps.push(tps);
|
||||
buckets.successfulTpsTokens = (buckets.successfulTpsTokens ?? 0) + tpsTokens;
|
||||
buckets.successfulTpsWindowMs = (buckets.successfulTpsWindowMs ?? 0) + generationMs;
|
||||
}
|
||||
}
|
||||
|
||||
/** Per-provider/model accumulator for getModelLatencyStats() (#6875). */
|
||||
@@ -158,6 +178,10 @@ export function createLatencyBucket(provider: string, model: string): LatencyBuc
|
||||
allTtfts: [],
|
||||
successfulTps: [],
|
||||
allTps: [],
|
||||
successfulTpsTokens: 0,
|
||||
successfulTpsWindowMs: 0,
|
||||
allTpsTokens: 0,
|
||||
allTpsWindowMs: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -183,7 +207,10 @@ export interface ModelLatencyStatsEntry {
|
||||
* already represents the full request wall-clock time (#6875).
|
||||
*/
|
||||
avgE2ELatencyMs: number;
|
||||
/** Mean output tokens/sec across successful rows (tokens_output / (latency_ms/1000)). */
|
||||
/**
|
||||
* Output tokens/sec across successful rows: Σ tokens ÷ Σ generation seconds
|
||||
* (latency_ms - ttft_ms) over the plausible samples; 0 when there is none.
|
||||
*/
|
||||
avgTokensPerSecond: number;
|
||||
}
|
||||
|
||||
@@ -204,7 +231,8 @@ export function buildLatencyStatsEntry(
|
||||
if (baseLatencies.length < minSamples) return null;
|
||||
|
||||
const baseTtfts = useSuccessful ? bucket.successfulTtfts : bucket.allTtfts;
|
||||
const baseTps = useSuccessful ? bucket.successfulTps : bucket.allTps;
|
||||
const tpsTokens = (useSuccessful ? bucket.successfulTpsTokens : bucket.allTpsTokens) ?? 0;
|
||||
const tpsWindowMs = (useSuccessful ? bucket.successfulTpsWindowMs : bucket.allTpsWindowMs) ?? 0;
|
||||
|
||||
const sorted = [...baseLatencies].sort((a, b) => a - b);
|
||||
const avg = mean(sorted);
|
||||
@@ -226,7 +254,8 @@ export function buildLatencyStatsEntry(
|
||||
windowHours,
|
||||
avgTtftMs: Math.round(mean(baseTtfts)),
|
||||
avgE2ELatencyMs: Math.round(avg),
|
||||
avgTokensPerSecond: Math.round(mean(baseTps) * 100) / 100,
|
||||
avgTokensPerSecond:
|
||||
tpsWindowMs > 0 ? Math.round((tpsTokens / (tpsWindowMs / 1000)) * 100) / 100 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
|
||||
import {
|
||||
attachTokensPerSecond,
|
||||
generationDurationMs,
|
||||
MAX_PLAUSIBLE_TOKENS_PER_SECOND,
|
||||
MIN_GENERATION_WINDOW_MS,
|
||||
tokensPerSecond,
|
||||
} from "../../open-sse/utils/generationThroughput.ts";
|
||||
import { filterUsageForFormat } from "../../open-sse/utils/usageTracking.ts";
|
||||
@@ -73,12 +75,47 @@ test("#12616 SSE comment carries tok/s from usage.tokens_per_second when TTFT is
|
||||
assert.match(comment, /^: x-omniroute-tokens-per-second=12.500/m);
|
||||
});
|
||||
|
||||
test("#12616 StreamTiming.withTps attaches tok/s after first forward", async () => {
|
||||
const t = createStreamTiming();
|
||||
t.markForward();
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
const usage = t.withTps({ prompt_tokens: 1, completion_tokens: 100 });
|
||||
const tps = (usage as { tokens_per_second?: number }).tokens_per_second;
|
||||
assert.equal(typeof tps, "number");
|
||||
assert.ok(tps! > 0);
|
||||
test("janela de geração menor que 250 ms não produz taxa", () => {
|
||||
assert.equal(MIN_GENERATION_WINDOW_MS, 250);
|
||||
assert.equal(tokensPerSecond(100, 249), null);
|
||||
assert.equal(tokensPerSecond(100, 250), 400);
|
||||
const usage = attachTokensPerSecond({ prompt_tokens: 1, completion_tokens: 100 }, 249);
|
||||
assert.equal("tokens_per_second" in usage, false);
|
||||
});
|
||||
|
||||
test("taxa acima do teto plausível não é emitida", () => {
|
||||
assert.equal(MAX_PLAUSIBLE_TOKENS_PER_SECOND, 5000);
|
||||
assert.equal(tokensPerSecond(5000, 1000), 5000); // no teto: aceita
|
||||
assert.equal(tokensPerSecond(5001, 1000), null);
|
||||
assert.equal(tokensPerSecond(200_000, 1000), null);
|
||||
});
|
||||
|
||||
test("cabeçalho omite tok/s quando o TTFT encosta na latência total", () => {
|
||||
const headers = buildOmniRouteResponseMetaHeaders({
|
||||
provider: "openai",
|
||||
model: "gpt-4o-mini",
|
||||
latencyMs: 5000,
|
||||
ttftMs: 4999,
|
||||
usage: { prompt_tokens: 11, completion_tokens: 200 },
|
||||
});
|
||||
assert.equal(headers[OMNIROUTE_RESPONSE_HEADERS.tokensPerSecond], undefined);
|
||||
});
|
||||
|
||||
test("#12616 StreamTiming.withTps anexa tok/s numa janela mensurável e omite numa curta", () => {
|
||||
const measurable = createStreamTiming();
|
||||
measurable.startedAt = performance.now() - 2000;
|
||||
measurable.firstForwardAt = measurable.startedAt + 1000; // janela ≈ 1000 ms
|
||||
const tps = (
|
||||
measurable.withTps({ prompt_tokens: 1, completion_tokens: 100 }) as {
|
||||
tokens_per_second?: number;
|
||||
}
|
||||
).tokens_per_second;
|
||||
assert.equal(typeof tps, "number");
|
||||
assert.ok(tps! > 90 && tps! <= 100, `got ${tps}`);
|
||||
|
||||
const tooShort = createStreamTiming();
|
||||
tooShort.startedAt = performance.now() - 1010;
|
||||
tooShort.firstForwardAt = tooShort.startedAt + 1000; // janela ≈ 10 ms
|
||||
const usage = tooShort.withTps({ prompt_tokens: 1, completion_tokens: 100 });
|
||||
assert.equal("tokens_per_second" in usage, false);
|
||||
});
|
||||
|
||||
53
tests/unit/latency-stats-throughput-aggregate.test.ts
Normal file
53
tests/unit/latency-stats-throughput-aggregate.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
accumulateLatencySample,
|
||||
buildLatencyStatsEntry,
|
||||
createLatencyBucket,
|
||||
} from "../../src/lib/usage/usageHistory/helpers.ts";
|
||||
|
||||
// [latencyMs, ttftMs, tokensOutput], todas bem-sucedidas
|
||||
function entryFor(rows: Array<[number, number, number]>) {
|
||||
const bucket = createLatencyBucket("p", "m");
|
||||
for (const [latencyMs, ttftMs, tokensOutput] of rows) {
|
||||
bucket.totalRequests += 1;
|
||||
bucket.successfulRequests += 1;
|
||||
accumulateLatencySample(bucket, latencyMs, ttftMs, tokensOutput, true);
|
||||
}
|
||||
return buildLatencyStatsEntry("p/m", bucket, 1, 24);
|
||||
}
|
||||
|
||||
test("avgTokensPerSecond é soma de tokens ÷ soma de tempo, não média de razões", () => {
|
||||
// 100 tok em 1 s (100 tok/s) e 900 tok em 3 s (300 tok/s):
|
||||
// média de razões = 200; soma ÷ soma = 1000 tok / 4 s = 250.
|
||||
const entry = entryFor([
|
||||
[1100, 100, 100],
|
||||
[3100, 100, 900],
|
||||
]);
|
||||
assert.equal(entry?.avgTokensPerSecond, 250);
|
||||
});
|
||||
|
||||
test("janela de geração abaixo de 250 ms não entra no agregado de velocidade", () => {
|
||||
// 2ª linha: 5000 − 4999 = 1 ms de janela (200 000 tok/s na conta antiga).
|
||||
const entry = entryFor([
|
||||
[1100, 100, 100],
|
||||
[5000, 4999, 200],
|
||||
]);
|
||||
assert.equal(entry?.avgTokensPerSecond, 100);
|
||||
assert.equal(entry?.avgLatencyMs, 3050); // a latência da linha descartada continua contando
|
||||
assert.equal(entry?.avgTtftMs, 2550);
|
||||
});
|
||||
|
||||
test("taxa acima do teto plausível não entra no agregado de velocidade", () => {
|
||||
// 2ª linha: 6000 tok em 1 s = 6000 tok/s > 5000.
|
||||
const entry = entryFor([
|
||||
[1100, 100, 100],
|
||||
[1100, 100, 6000],
|
||||
]);
|
||||
assert.equal(entry?.avgTokensPerSecond, 100);
|
||||
});
|
||||
|
||||
test("sem nenhuma amostra mensurável, avgTokensPerSecond é 0", () => {
|
||||
const entry = entryFor([[5000, 4999, 200]]);
|
||||
assert.equal(entry?.avgTokensPerSecond, 0);
|
||||
});
|
||||
@@ -38,7 +38,7 @@ test.after(() => {
|
||||
test("getModelLatencyStats aggregates avgTtftMs/avgE2ELatencyMs/avgTokensPerSecond over successful rows", async () => {
|
||||
const now = Date.now();
|
||||
// #13130: tokens/sec is GENERATION throughput — tokens / (latency - ttft).
|
||||
// 50/(0.9s)=55.56, 100/(1.8s)=55.56, 300/(3.7s)=81.08 -> mean 64.06.
|
||||
// (50 + 100 + 300) tok / (0.9 + 1.8 + 3.7) s = 70.31.
|
||||
// (The pre-#13130 wall-clock formula yielded 58.33 for these same rows.)
|
||||
const rows = [
|
||||
{ latencyMs: 1000, ttftMs: 100, tokensOutput: 50 },
|
||||
@@ -71,7 +71,7 @@ test("getModelLatencyStats aggregates avgTtftMs/avgE2ELatencyMs/avgTokensPerSeco
|
||||
// column exists in usage_history beyond latency_ms/ttft_ms).
|
||||
assert.equal(entry.avgE2ELatencyMs, entry.avgLatencyMs);
|
||||
assert.equal(entry.avgE2ELatencyMs, 2333);
|
||||
assert.equal(Math.round(entry.avgTokensPerSecond * 100) / 100, 64.06);
|
||||
assert.equal(Math.round(entry.avgTokensPerSecond * 100) / 100, 70.31);
|
||||
});
|
||||
|
||||
test("getModelLatencyStats guards divide-by-zero when latency_ms <= 0 for tokens/sec", async () => {
|
||||
|
||||
Reference in New Issue
Block a user