Skip to content

fix(openai): canonical Chat cache-hit and billing accounting - #117043

Merged
steipete merged 2 commits into
mainfrom
codex/wave3-openai-chat-usage-owner
Jul 31, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/wave3-openai-chat-usage-owner

Conversation

@steipete

@steipete steipete commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Managed OpenAI-compatible Chat Completions ignored the existing prompt_cache_hit_tokens compatibility 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.00012124999999999999 is the ordinary IEEE-754 representation of the expected 0.00012125. The repro used a disposable loopback listener and the literal redacted-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 streamOpenAICompletions and createOpenAICompletionsTransportStreamFn, with the existing transport host directed to the temporary localhost server. The corrected owner is packages/ai/src/transports/openai-transport-shared.ts; the package and managed callers are packages/ai/src/providers/openai-completions.ts and packages/ai/src/transports/openai-completions-transport.ts.

Why This Is the Owner-Boundary Fix

  • One canonical private parser now owns cache-hit fallback, disjoint prompt buckets, calculated cost, and provider-reported cost.
  • The package and managed producers invoke that same owner while explicitly preserving their existing difference in exposed reasoning-token telemetry.
  • Production source changes: 48 lines added / 82 removed; net −34.
  • No authentication, security, configuration, public Plugin SDK, gateway protocol, dependency, persisted-state, cache-storage, SQLite, schema, migration, or user-data changes.
  • The scanner's reported “persistent cache schema” points to 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

  • Proposed head: b347f0783def5d1fddc82f7c45d3daaa0fb3bb0d; frozen feature baseline: 36b80ada3ceae2de21b3d8710b883d778e4c4578.
  • The sole follow-up commit corrects only the managed test fixture's canonical SimpleStreamOptions.reasoning field. All three production blobs remain byte-for-byte identical to the originally reviewed implementation.
  • Full hosted-equivalent pnpm tsgo:test passed all three core, plugin, and root test-type projects on the exact head: Blacksmith exact-head type proof.
  • Four complete owner and sibling suites passed 125/125 on the exact head: Blacksmith exact-head owner proof.
  • The actual hosted PR check-test-types rerun passed on the exact head: hosted test-type job.
  • The actual hosted aggregate openclaw/ci-gate also passed: hosted aggregate CI gate.
  • Full-branch Sol/high --max-priority P3 automated 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.
  • The protected provider parity snapshots are unchanged, including packages/ai/test/fixtures/provider-transport-parity/openai-success.snap.txt, blob e2a1b1100acdf7c5f24c5c7cadd60e924c29b2ab; the corresponding OpenAI error and Anthropic success/error snapshots are also byte-identical.
  • Direct dependency contracts were inspected in the installed SDK's completion usage definitions; sibling Codex token accounting and its cache-write/reasoning regression were also checked.

Current-Main Merge Review

Both automated-review rank-up moves were addressed:

  1. Inspectable after-fix runtime proof: the complete real-HTTP, installed-SDK managed before/after terminal captures and the unchanged package sibling are included above.
  2. Refresh against current main: latest fetched origin/main was ae27d79364476b426f86b59add76af69d0347c4e; its exact merge base with the proposed head is 36b80ada3ceae2de21b3d8710b883d778e4c4578. git merge-tree --write-tree origin/main b347f0783def5d1fddc82f7c45d3daaa0fb3bb0d succeeded without conflicts and produced merge tree 3ab4e595d17aa01f51aa24714f6699abe74022a5. 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.

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Jul 31, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 31, 2026
@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 31, 2026, 5:58 PM ET / 21:58 UTC.

ClawSweeper review

What this changes

The 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 maintainer label, behind-main status, and absence of inspectable after-fix runtime evidence mean it should remain open for maintainer review.

Priority: P2
Reviewed head: b347f0783def5d1fddc82f7c45d3daaa0fb3bb0d

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The source refactor and parity test look coherent, but absent inspectable real-behavior proof remains a merge gate.
Proof confidence 🧂 unranked krab (1/6) Needs real behavior proof before merge: The body describes direct SDK results but supplies no inspectable after-fix terminal capture, redacted runtime log, live output, or linked artifact for the managed cache-hit behavior; add one before merge and redact private endpoints, keys, and identifiers. Updating the PR body should trigger a fresh ClawSweeper review; otherwise a maintainer can request one. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The body describes direct SDK results but supplies no inspectable after-fix terminal capture, redacted runtime log, live output, or linked artifact for the managed cache-hit behavior; add one before merge and redact private endpoints, keys, and identifiers. Updating the PR body should trigger a fresh ClawSweeper review; otherwise a maintainer can request one. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main defect boundary: The package provider recognizes prompt_cache_hit_tokens as a cache-read fallback, whereas the managed transport only reads prompt_tokens_details.cached_tokens; the same compatible usage chunk therefore receives different accounting on current main.
Shared owner preserves both output contracts: The PR centralizes cache read/write, cost calculation, provider-billed cost, and optional reasoning telemetry; package callers explicitly disable reasoning telemetry while managed callers retain it.
Focused parity coverage: The new test drives identical SSE usage scenarios through both paths, including compatible cache-hit fallback, cache writes, zero provider cost, nested choice usage, and the intentionally different reasoning-token field.
Findings None None.
Security None None.

How this fits together

OpenAI-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
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The body describes direct SDK results but supplies no inspectable after-fix terminal capture, redacted runtime log, live output, or linked artifact for the managed cache-hit behavior; add one before merge and redact private endpoints, keys, and identifiers. Updating the PR body should trigger a fresh ClawSweeper review; otherwise a maintainer can request one. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - Merging changes a compatibility-sensitive accounting path that intentionally has different package and managed reasoning-token output contracts; the final merged result should be refreshed against current main and checked for both contracts.
  • Resolve merge risk (P1) - The branch has no inspectable after-fix runtime artifact despite the claimed SDK audit, so the managed compatible cache-hit behavior is not yet independently reviewable.
  • Resolve merge risk (P1) - The protected maintainer label requires explicit maintainer handling even though the static patch review found no defect.
  • Complete next step (P2) - The protected maintainer label, compatibility-sensitive accounting boundary, and missing inspectable runtime proof require maintainer review rather than an automated repair lane.
Agent review details

Security

None.

PR surface

Source -34, Tests +194. Total +160 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 48 82 -34
Tests 1 194 0 +194
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 242 82 +160

Review metrics

None.

Stored data model

Persistent data-model change detected: persistent cache schema: packages/ai/src/providers/openai-completions-usage-parity.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh and prove the exact head (recommended)
    Refresh the proposed merge result against current main and attach redacted terminal output or a linked artifact that shows corrected managed cache-hit accounting before merge.
  2. Accept the stated SDK audit
    A maintainer may accept the body’s described SDK evidence after independently checking that the final merge result preserves the package and managed output contracts.
  3. Pause pending evidence
    Pause this PR if the claimed SDK run cannot be made inspectable, because the behavior change is billing-sensitive and the existing test is mock-transport coverage.

Technical review

Best 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 prompt_cache_hit_tokens but no prompt_tokens_details.cached_tokens; current main counts all prompt tokens as uncached while the package path subtracts the cache hit. This read-only review did not execute the scenario.

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.

Labels

Label justifications:

  • P2: The PR corrects bounded but user-visible OpenAI-compatible token and estimated-cost accounting.
  • merge-risk: 🚨 compatibility: The refactor changes the common accounting path while preserving intentionally different package and managed reasoning-token output shapes.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The body describes direct SDK results but supplies no inspectable after-fix terminal capture, redacted runtime log, live output, or linked artifact for the managed cache-hit behavior; add one before merge and redact private endpoints, keys, and identifiers. Updating the PR body should trigger a fresh ClawSweeper review; otherwise a maintainer can request one. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current-main defect boundary: The package provider recognizes prompt_cache_hit_tokens as a cache-read fallback, whereas the managed transport only reads prompt_tokens_details.cached_tokens; the same compatible usage chunk therefore receives different accounting on current main. (packages/ai/src/providers/openai-completions.ts:1098, 3dce01fa201a)
  • Shared owner preserves both output contracts: The PR centralizes cache read/write, cost calculation, provider-billed cost, and optional reasoning telemetry; package callers explicitly disable reasoning telemetry while managed callers retain it. (packages/ai/src/transports/openai-transport-shared.ts:67, b347f0783def)
  • Focused parity coverage: The new test drives identical SSE usage scenarios through both paths, including compatible cache-hit fallback, cache writes, zero provider cost, nested choice usage, and the intentionally different reasoning-token field. (packages/ai/src/providers/openai-completions-usage-parity.test.ts:167, b347f0783def)
  • Existing accounting invariant: Both prior parsers already normalize prompt buckets as disjoint input, cache-read, and cache-write values before applying model pricing and provider-reported cost; the branch removes duplicated implementations rather than changing that invariant. (packages/ai/src/transports/openai-completions-transport.ts:1944, 3dce01fa201a)
  • Feature-history ownership: Recent history for both central OpenAI Chat Completions files identifies Peter Steinberger as the latest area contributor, including the current-main Chat completion terminal handling work and this PR's two commits. (packages/ai/src/providers/openai-completions.ts:405, 4a8ce9c3365b)
  • Proof gate remains unmet: The PR body describes direct SDK outcomes but does not link or embed inspectable terminal output, logs, live output, or an artifact demonstrating the after-fix managed cache-hit result. The latest prior ClawSweeper review requested that exact evidence. (b347f0783def)

Likely related people:

  • steipete: Recent main history and both commits on this branch cover the OpenAI Chat Completions provider and managed transport paths. (role: recent area contributor; confidence: high; commits: 4a8ce9c3365b, b22beecab1a2, b347f0783def; files: packages/ai/src/providers/openai-completions.ts, packages/ai/src/transports/openai-completions-transport.ts, packages/ai/src/transports/openai-transport-shared.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach redacted terminal output or a linked artifact showing a managed SSE cache-hit result with corrected buckets and cost.
  • Refresh the exact merge result against current main before the maintainer landing review.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-07-31T21:21:00.309Z sha b22beec :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-31T21:38:58.712Z sha b22beec :: needs real behavior proof before merge. :: none

@steipete
steipete marked this pull request as ready for review July 31, 2026 21:33
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 31, 2026
@steipete
steipete merged commit ed84162 into main Jul 31, 2026
114 of 116 checks passed
@steipete
steipete deleted the codex/wave3-openai-chat-usage-owner branch July 31, 2026 22:19
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 31, 2026
…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)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 1, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant