Repository navigation
fix(openai): canonical Chat cache-hit and billing accounting - #117043
Conversation
|
Codex review: needs real behavior proof before merge. Reviewed July 31, 2026, 5:58 PM ET / 21:58 UTC. ClawSweeper reviewWhat this changesThe PR moves OpenAI Chat Completions usage and cost parsing into a shared helper so package and managed transports both account for compatible prompt-cache hits, cache writes, provider-billed costs, and their intentional reasoning-token differences. Merge readiness⛔ Blocked until real behavior proof is added - 5 items remain This PR addresses a real managed-transport accounting gap: current main recognizes compatible cache-hit tokens in the package path but not the managed path. The shared parser preserves the prior package/managed reasoning-token distinction and adds focused parity coverage, so no code defect was found in the branch; however, the protected Priority: P2 Review scores
Verification
How this fits togetherOpenAI-compatible streaming transports receive usage data in completion chunks and normalize it into OpenClaw token and cost records. Those records are consumed by the managed transport and the package provider to report model-run billing consistently. flowchart LR
Provider[OpenAI-compatible SSE stream] --> Usage[Completion usage chunk]
Usage --> Parser[Shared usage and cost parser]
Pricing[Model pricing] --> Parser
Parser --> Package[Package provider result]
Parser --> Managed[Managed transport result]
Package --> Accounting[Operator-visible usage and cost]
Managed --> Accounting
Before merge
Agent review detailsSecurityNone. PR surfaceSource -34, Tests +194. Total +160 across 4 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep one canonical parser for the shared cache and billing invariant, retain the package-only omission of reasoning telemetry, refresh the merge result against current main, and attach redacted terminal or linked SDK output showing corrected managed cache-hit buckets and cost. Do we have a high-confidence way to reproduce the issue? Yes, from current source: send a managed Chat Completions SSE usage chunk with Is this the best way to solve the issue? Yes: extracting the duplicated usage accounting into the existing shared OpenAI transport owner is the most maintainable repair because it removes the drift that caused the managed fallback to be omitted while preserving each caller’s established output contract. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 3dce01fa201a. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
|
Merged via squash.
|
…odels-20260729 * origin/main: fix(tui): canonical terminal outcomes, cancellation, and error privacy (#117044) fix(cron): avoid phantom message tool guidance (#116908) fix(test): avoid macOS release gate deadlocks (#116972) fix(openai): canonical Chat cache-hit and billing accounting (#117043) fix(memory-wiki): salvage human Notes before pruning imported source pages (#102294) fix(memory): suggest reindex, not --fix, for a missing qmd index (#116958) chore(msteams): add private Gateway QA adapter fix(ui): make session controls and failures accessible (#117019) docs: fix tilde paths in CLI output examples (#114595) fix(plugins): canonical discovery diagnostics and deterministic lifecycles (#117025) fix(ui): honor Gateway readiness abort and subscription ownership (#117048) fix(updater): harden launchd replacement timing (#117030) fix(gateway): preserve static asset HEAD representation metadata (#117049) fix(gateway): abort embeddings when clients disconnect (#116146) fix(googlechat): retain fallback thread continuity (#117053)
…w#117043) * fix(ai): preserve cached usage in managed chat completions * test(ai): use canonical managed chat reasoning option --------- Co-authored-by: Peter Steinberger <[email protected]>
What Problem This Solves
Managed OpenAI-compatible Chat Completions ignored the existing
prompt_cache_hit_tokenscompatibility field, while the package-owned sibling already honored it. For a response with 100 prompt tokens, 25 cached tokens, and 20 completion tokens, current main reported 100 uncached tokens and cost 0.00014 in the managed path instead of 75 uncached tokens, 25 cached tokens, and cost 0.00012125.This PR extracts the existing usage invariant into one private shared owner used by both producers. It preserves cache writes, provider-billed costs including zero, nested choice usage, exact managed reasoning telemetry, and the package producer's intentionally different shipped reasoning-telemetry shape.
Inspectable Real-Behavior Proof: Installed SDK + Real HTTP/SSE
I reproduced both versions against a real localhost HTTP server using the installed
[email protected]SDK's real Chat Completions SSE parser, not a mocked SDK or direct invocation of the accounting helper. Each run issued two real HTTP requests to the same loopback SSE server: one package producer and one managed producer.The server returned the identical provider-compatible chunk to each request:
{ "id": "chatcmpl-redacted-proof", "object": "chat.completion.chunk", "model": "gpt-5.5", "choices": [ { "index": 0, "delta": { "role": "assistant", "content": "Billing verified." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 100, "prompt_cache_hit_tokens": 25, "completion_tokens": 20, "total_tokens": 120 } }Before: current-main
21fba83254a800843e26e1003dbc0e245ad97b27:{ "sdk": "[email protected]", "transport": "real localhost HTTP + installed SDK SSE parser", "requests": 2, "package": { "stopReason": "stop", "input": 75, "output": 20, "cacheRead": 25, "cacheWrite": 0, "totalTokens": 120, "costTotal": 0.00012124999999999999 }, "managed": { "stopReason": "stop", "input": 100, "output": 20, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 120, "costTotal": 0.00014 } }After: exact proposed immutable
b347f0783def5d1fddc82f7c45d3daaa0fb3bb0d:{ "sdk": "[email protected]", "transport": "real localhost HTTP + installed SDK SSE parser", "requests": 2, "package": { "stopReason": "stop", "input": 75, "output": 20, "cacheRead": 25, "cacheWrite": 0, "totalTokens": 120, "costTotal": 0.00012124999999999999 }, "managed": { "stopReason": "stop", "input": 75, "output": 20, "cacheRead": 25, "cacheWrite": 0, "totalTokens": 120, "costTotal": 0.00012124999999999999 } }The printed
0.00012124999999999999is the ordinary IEEE-754 representation of the expected 0.00012125. The repro used a disposable loopback listener and the literalredacted-proof-token; no production endpoint, credentials, user identifiers, or private data were involved.Actual command, run once in clean current main and once in the exact proposed checkout:
node --import ./node_modules/tsx/dist/loader.mjs \ /private/tmp/openclaw-wave3-cache-sdk-live-proof.mts "$(pwd)"The repro calls the actual production entry points
streamOpenAICompletionsandcreateOpenAICompletionsTransportStreamFn, with the existing transport host directed to the temporary localhost server. The corrected owner ispackages/ai/src/transports/openai-transport-shared.ts; the package and managed callers arepackages/ai/src/providers/openai-completions.tsandpackages/ai/src/transports/openai-completions-transport.ts.Why This Is the Owner-Boundary Fix
packages/ai/src/providers/openai-completions-usage-parity.test.ts, which is an in-memory provider-stream regression test. The word “cache” describes provider-reported token accounting; no persistent cache schema or storage is introduced or changed.Exact-Head Verification
b347f0783def5d1fddc82f7c45d3daaa0fb3bb0d; frozen feature baseline:36b80ada3ceae2de21b3d8710b883d778e4c4578.SimpleStreamOptions.reasoningfield. All three production blobs remain byte-for-byte identical to the originally reviewed implementation.pnpm tsgo:testpassed all three core, plugin, and root test-type projects on the exact head: Blacksmith exact-head type proof.check-test-typesrerun passed on the exact head: hosted test-type job.openclaw/ci-gatealso passed: hosted aggregate CI gate.--max-priority P3automated review: zero P0/P1/P2/P3 findings, confidence 0.94. Two fresh independent exact-head strict blind reviews were clean, confidence 0.995 and 0.99.packages/ai/test/fixtures/provider-transport-parity/openai-success.snap.txt, blobe2a1b1100acdf7c5f24c5c7cadd60e924c29b2ab; the corresponding OpenAI error and Anthropic success/error snapshots are also byte-identical.Current-Main Merge Review
Both automated-review rank-up moves were addressed:
origin/mainwasae27d79364476b426f86b59add76af69d0347c4e; its exact merge base with the proposed head is36b80ada3ceae2de21b3d8710b883d778e4c4578.git merge-tree --write-tree origin/main b347f0783def5d1fddc82f7c45d3daaa0fb3bb0dsucceeded without conflicts and produced merge tree3ab4e595d17aa01f51aa24714f6699abe74022a5. The published head was intentionally not rebased after its exact-head hosted gates passed; this clean current-main merge-result inspection preserves the already-proven immutable candidate.The maintainer-labeled PR remains an explicit maintainer landing decision; no autonomous bot merge, owner/config change, or compatibility waiver is requested.