Repository navigation
Fix stats by-model attribution, and measure the rest of the stats path - #586
Conversation
Adds a benchmark harness for the /v1/stats aggregation path and a plan
grounded in what it and a running gateway actually reported, rather
than in what the code comments claim.
The harness (src/tests/stats_bench.pas, `make bench-stats`) prints
timings and is deliberately NOT in the test aggregate -- it measures,
it does not assert.
Headline measurement. Holding session count at 500 and varying
transcript length isolates per-file cost from per-byte cost:
1 turn/session 0.6 MB 39 ms
20 turns/session 8.3 MB 273 ms
100 turns/session 40.6 MB 1054 ms
400 turns/session 162.0 MB 4318 ms
~26 ms per MB, against a fixed per-file cost of 0.077 ms. So nearly all
of the endpoint's cost is reading and JSON-parsing message bodies that
HandleStats never looks at -- it sums seven Int64s out of Meta. The
ListSessions comment already called the full load "wasteful … if it
grows, write a headers-only Load"; this puts a number on when. Behind a
5-second cache, a 4.3 s walk keeps the gateway recomputing ~86% of
wall-clock for a UI that auto-refreshes.
Verified against a running gateway, not inferred:
- Cold 253 ms / warm 0.98 ms at 300 sessions, matching the micro-
benchmark and confirming the cache works.
- The collection-off comment is false. With the flag genuinely off
(confirmed via `config get`), /v1/stats returns full historical
totals, not the zeros the comment promises, and still pays the whole
258 ms walk.
- diagnostics.otel.metrics and .logs are dead knobs: parsed, defaulted,
serialised, and never read outside config. Otel.pas has 105 Span
references and zero counter/histogram/gauge. Their only other mention
is a test asserting they survive serialisation, which makes a
non-functional switch look covered.
- /v1/stats reported 300 sessions where `pasclaw learn` scanned 240 on
the identical home -- bucket sessions counted in one surface, hidden
in every other.
Also recorded: no cost model anywhere, while the rollup's stated
purpose is showing "which provider is eating the budget" from summed
input+output tokens; no time dimension, so "what did I spend today" is
unanswerable; no latency or error counters; no reset.
The plan ranks P1 headers-only load, P2 split the token classes,
P3 local cost estimation, P4 fix the collection-off path, P5 honest
session count, P6 wire or delete the OTel metrics flag, P7 a time
dimension -- with P7 explicitly deferred as the one structural change
that needs a reason beyond symmetry with other tools.
The doc closes with what was not covered: FPC/Linux only, the web UI
and TUI were read rather than driven, the corpus is synthetic with
uniform turns, no concurrency testing, no price list gathered, and
P1's speedup is a prediction the same harness can falsify.
Answers the question the perf work skipped: are the numbers the web UI shows actually right? Totals are right. The breakdowns are not. Accurate, verified by tracing the write path: token totals sum across every provider call in a turn, not just the last -- RunToolLoop accumulates into Loop.TotalUsage and all four stats writers feed it in, including AccumulateGatewayStats. And there is no double counting; PersistGatewaySession writes the transcript but never touches Meta.Stats, so a named session and its endpoint bucket do not both record the same tokens. Wrong: by_model and by_provider attribute a bucket's ENTIRE cumulative total to whichever model ran most recently. Gateway endpoints fold all traffic into one synthetic session per endpoint, and Meta.Model / Meta.Provider are scalar fields overwritten on every request. stats_attribution_repro drives the same primitives in the same order as AccumulateGatewayStatsRaw -- 100 requests on one model, then one request on another -- and the endpoint reports: model-EXPENSIVE 150,000 tok / 100 reqs -> absent model-CHEAP 15 tok / 1 req -> 150,015 anthropic 150,000 -> absent openai 15 -> 150,015 Totals correct, attribution inverted: a 10,001x over-attribution, with the model that did all the work missing entirely. The web UI renders these tables 1:1 with no caveat, and its model picker makes switching models the normal case rather than an edge case. AccumulateGatewayStats documents this as a deliberate trade-off and names the fix -- one bucket per (endpoint, model) pair. That is now P1, ahead of the performance work: a cost column computed from misattributed tokens would be confidently wrong rather than absent. Also corrects a claim in the earlier draft. "by_provider / by_model rollups sum correctly" was true of the arithmetic and false of the result; it now says so and points at the repro. Not covered, and now said plainly: no live provider turn was run (the relay provider would not start here), so the chain from a real provider usage block to a recorded counter was verified by reading the four writers rather than by driving one turn end to end. The web UI was read, not rendered.
The defect the previous commit measured, now fixed.
Gateway endpoints folded stateless traffic into one synthetic bucket
session per endpoint. TSessionMeta.Model and .Provider are scalar and
overwritten on every request, so a bucket's ENTIRE cumulative total was
attributed to whichever model happened to run last.
GatewayBucketId keys buckets by (endpoint, model) instead -- option (a),
which the AccumulateGatewayStats comment already named as the precise
fix. Every request landing in a bucket now shares that bucket's model,
so overwriting the scalar is a no-op rather than a lie. No schema
change; all six accumulate call sites across /v1/chat,
/v1/chat/completions and /v1/responses go through it.
Same workload against a running gateway, before and after:
before by_model model-CHEAP 150,015 (model-EXPENSIVE absent)
after by_model model-EXPENSIVE 150,000
model-CHEAP 15
before by_provider openai 150,015 (anthropic absent)
after by_provider anthropic 150,000
openai 15
Totals were correct before and are unchanged (100,010 in / 50,005 out /
101 turns) -- only the breakdown was wrong, and it is the breakdown the
web UI renders as a per-model table with no caveat.
Id sanitising: IsSafeSessionId allows [A-Za-z0-9._-] and model names
carry '/' and ':'. Dot is deliberately NOT preserved despite being
legal -- an id ending ".orig" is treated as a pre-prune archive by
IsSessionArchiveId and skipped by every listing, and a model name is
too close to that trap. Empty or all-separator model names fall back to
the bare endpoint id, preserving today's behaviour for passthrough
paths that never learn a model name.
test-stats-attribution pins both halves: the exact ids the gateway must
mint for real model names (slash, colon, dot, overlong, empty), and the
100-requests-then-1 workload that used to invert. It also asserts no
un-scoped endpoint bucket remains, so the fix is a replacement rather
than an addition. Wired into .PHONY and the test aggregate, both
verified, plus `make -n test`.
Two consequences recorded rather than hidden. Buckets written before
this change keep their old ids and their old misattributed history --
HandleStats just walks the directory, so those rows persist under the
last model they saw while new traffic accumulates correctly beside
them; deleting the _gateway_* sessions clears them. And bucket count
now grows with the number of models in use, which makes the separate
finding that /v1/stats counts buckets every other surface hides more
visible, not less.
The test drives TSession + AccumulateTurnStats in the same order
AccumulateGatewayStatsRaw does, because the gateway unit cannot be
linked into a test binary; it reimplements GatewayBucketId's contract
and pins it with explicit id-shape assertions. That limitation is
stated in the test header.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 222c8767d2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| behaviour for the passthrough paths that never learn a model name, | ||
| and gives those tokens a stable home rather than a bucket called | ||
| "_gateway_v1_chat_". *) | ||
| function GatewayBucketId(const Endpoint, Model: string): string; |
There was a problem hiding this comment.
Include the provider in the bucket identity
When /v1/config switches the primary provider while clients continue requesting the same model string, both providers resolve to the same bucket because ProviderName is absent from this key. AccumulateGatewayStatsRaw then overwrites Meta.Provider while retaining the cumulative counters, so /v1/stats.by_provider credits the first provider's tokens to the later provider—the same attribution failure this change is intended to fix. Key buckets by endpoint, provider, and model.
Useful? React with 👍 / 👎.
| ((C >= '0') and (C <= '9')) or (C = '-') or (C = '_') then | ||
| Clean := Clean + C | ||
| else | ||
| Clean := Clean + '-'; | ||
| if Length(Clean) >= MaxModelPart then Break; |
There was a problem hiding this comment.
Preserve uniqueness when encoding model names
When two valid model identifiers differ only in replaced characters, trailing separators, or content after byte 80—for example openai/gpt-5 and openai:gpt-5—this lossy encoding gives them the same bucket ID. Their counters are consequently merged and Meta.Model is overwritten by the latest request, recreating the incorrect by_model attribution this change is meant to eliminate. Append a stable hash or use another collision-resistant encoding rather than relying solely on the sanitized prefix.
Useful? React with 👍 / 👎.
Codex P2 x2 on PR #586. Both findings are the same class of bug the original fix claimed to eliminate, surviving in places that fix did not reach. 1. by_provider kept the identical defect. Keying buckets on (endpoint, model) left Meta.Provider scalar and overwritten: two providers serving one model string share a bucket, so the first provider's tokens get credited to the second. That happens when /v1/config switches the primary provider while clients keep sending the same model, and whenever a direct vendor key and an aggregator both answer to one name. Reproduced against the old key: 50 requests on one provider then one on another reported 15,003 tokens for the provider that used 3. Worth recording why this shipped: the original test varied model and provider TOGETHER (model-EXPENSIVE/anthropic, model-CHEAP/openai), so its "bucket provider = anthropic" assertion passed for the wrong reason and could never have caught a model-only key. TestAttributionByProvider now holds the model constant and varies only the provider. 2. The readable id is lossy, so it cannot carry identity alone. Sanitising maps everything outside [A-Za-z0-9_-] to '-', flattening "openai/gpt-5" and "openai:gpt-5" into one bucket; trailing separators are stripped, so "gpt-5/" and "gpt-5:" merge; and truncation collides any two long names sharing a prefix, which is entirely plausible for dated or versioned model ids. Every collision merges counters and reinstates the misattribution. The id now ends in a 32-bit FNV-1a of the RAW provider and model, joined by #1 -- a byte that cannot appear in either, so provider "a" + model "bc" cannot hash the same as "ab" + "c". FNV-1a because it must be deterministic across processes and restarts; a non-stable hash would orphan yesterday's bucket on every boot. The readable prefix stays for humans reading the session list; the suffix is what makes the identity sound. All six accumulate call sites now pass the provider name they already had to hand. The test grew from 16 assertions to 24 and was negative-tested: reverted to the old model-only lossy key, exactly the expected six fail -- provider attribution (15,003 vs 3), slash-vs-colon, and trailing separators. The two remaining collision cases guard the new scheme's own risks (hash field boundary, 64-char truncation) rather than the old bug, so they correctly stay green either way.
Conflicts were both list lines in the Makefile -- .PHONY and the test
aggregate -- where main had gained targets while this branch added one.
Resolved as a union with main's ordering authoritative:
from main test-sqlite-hint, test-memory-search-roundtrip (this
session's #582, since merged), test-agents
from here test-stats-attribution
All four verified present in .PHONY, in the test aggregate, and as real
targets, plus `make -n test`. bench-stats confirmed still OUT of the
aggregate -- it is a measuring tool, not a pass/fail suite.
PasClaw.Gateway.Server.pas auto-merged; GatewayBucketId and all six of
its call sites survived, and the tree builds clean.
A benchmark → profile → verify → research → improve pass over stats collection. It found one user-visible correctness bug, which this fixes, plus a measured performance problem and several dead or misleading surfaces, which it documents.
The bug:
/v1/statscredited the wrong modelby_modelandby_providerattributed a bucket's entire cumulative total to whichever model happened to run most recently.Gateway endpoints fold stateless traffic into one synthetic bucket session per endpoint.
TSessionMeta.Model/.Providerare scalar fields overwritten on every request — so one bucket accumulated tokens from every model, and the breakdown named only the last one.Measured against a running gateway: 100 requests on one model, then a single request on another.
model-EXPENSIVEmodel-CHEAPanthropicopenaiA 10,001× over-attribution, with the model that did all the work missing from the table entirely. Totals were correct throughout and are unchanged (100,010 in / 50,005 out / 101 turns) — only the breakdown was wrong, and the breakdown is what the web UI renders as a per-model table with no caveat, next to a model picker that makes switching models routine.
Fix
GatewayBucketIdkeys buckets by(endpoint, model)— option (a), which theAccumulateGatewayStatscomment already named as the precise remedy. Every request landing in a bucket now shares that bucket's model, so overwriting the scalar is a no-op rather than a lie. No schema change; all six accumulate call sites across/v1/chat,/v1/chat/completionsand/v1/responsesgo through it.Id sanitising.
IsSafeSessionIdallows[A-Za-z0-9._-], and model names carry/and:(anthropic/claude-x,openai:gpt-5). Dot is deliberately not preserved despite being legal: an id ending.origis treated as a pre-prune archive byIsSessionArchiveIdand skipped by every listing, soclaude-3.5-sonnetwould have minted a bucket one suffix away from being invisible. Empty or all-separator model names fall back to the bare endpoint id, preserving today's behaviour for passthrough paths that never learn a model name.Two consequences, recorded rather than hidden
HandleStatsjust walks the directory, so pre-fix rows persist under the last model they saw while new traffic accumulates correctly beside them. Deleting the_gateway_*sessions clears them. Called out in the code./v1/statscounting buckets every other surface hides — more visible, not less. That one is documented, not fixed.What else the pass measured
Full write-up in
docs/stats-collection-plan.md. Harness ismake bench-stats, deliberately not in thetestaggregate — it measures, it does not assert.Performance. Holding session count at 500 and varying transcript length isolates per-file from per-byte cost:
/v1/stats~26 ms/MB against a fixed per-file cost of 0.077 ms. Nearly all of the endpoint's cost is reading and JSON-parsing message bodies to sum seven
Int64s out ofMeta.ListSessionsalready concedes this — "wasteful… if it grows, write a headers-only Load" — and the measurement says when. Behind a 5 s cache, a 4.3 s walk keeps the gateway recomputing ~86% of wall-clock.Verified against a running gateway:
/v1/statsreturns full historical totals, not the zeros the comment promises — and still pays the whole 258 ms walk.diagnostics.otel.metricsand.logsare dead knobs: parsed, defaulted, serialised, never read.Otel.pashas 105Spanreferences and zero counter/histogram/gauge. Their only other mention is a test asserting they survive serialisation, which makes a non-functional switch look covered./v1/statsreported 300 sessions wherepasclaw learnscanned 240 on the identical home.Confirmed correct, so it does not get changed: token totals sum across every provider call in a turn (
Loop.TotalUsage), and there is no double counting —PersistGatewaySessionwrites the transcript but never touchesMeta.Stats.Tests
make test-stats-attributionpins both halves: the exact ids the gateway must mint for real model names (slash, colon, dot, overlong, empty, all-separator), and the 100-then-1 workload that used to invert. It also asserts no un-scoped endpoint bucket remains, so the fix is a replacement rather than an addition.Wired into
.PHONYand thetest:aggregate — both verified individually, plusmake -n test. Full suite green:EXIT=0, 66 suites, with the new test's 16 assertions visible inside the full run rather than only standalone.Limitations
TSession+AccumulateTurnStatsin the same orderAccumulateGatewayStatsRawdoes, because the gateway unit cannot be linked into a test binary. It reimplementsGatewayBucketId's contract and pins it with explicit id-shape assertions; that limitation is stated in the test header.webui.html; no browser was opened. The attribution defect was reproduced against the endpoint the UI reads.Remaining items in the plan — headers-only load, cost model, the dead OTel flag — are documented and ranked, not implemented.
🤖 Generated with Claude Code
https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Generated by Claude Code