Skip to content

fix(openai): preserve image token usage - #117226

Merged
steipete merged 2 commits into
mainfrom
codex/qa400-openai-image-usage-owner
Oct 21, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/qa400-openai-image-usage-owner

Conversation

@steipete

@steipete steipete commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes direct OpenAI image generation and editing silently discarding provider-reported token usage.

User Impact

Image results retain input, output, and total token counts plus documented text/image breakdowns, including zeroes. Existing normalized-size metadata remains available. Responses without usage behave as before.

Why This Change Was Made

On main (9d33fbb66fbf5852e119d69c6ea2fdbc58240342), extensions/openai/image-generation-response.ts:66 returns only decoded images and drops the response's usage. The private response reader now projects the documented counters and returns them beside the images; its existing caller merges usage with size metadata.

Only nonnegative safe integer counters are retained. The fields match the installed OpenAI SDK's ImagesResponse.Usage contract. Unknown fields and malformed counters are omitted. The separate Codex Responses transport keeps its existing contract: the previous review's request to redesign that unrelated metadata path is outside this direct Images API repair.

Production: +39/-6 (net +33); tests: +87/-0 (net +87); docs: +3. The private reader remains the response owner; no new SDK surface, configuration, or transport policy was added.

Evidence

  • RED on unchanged main: all three focused usage cases failed because usage was absent, covering generation, multipart editing, and valid counters mixed with malformed/unknown fields. The final focused file uses native Response bodies and the real bounded JSON reader. Wrapper wall time: 173.92 seconds; Vitest: 131.59 seconds, 93% transformation.
  • GREEN: node scripts/run-vitest.mjs extensions/openai/image-generation-provider.usage.test.ts --maxWorkers=1 — 3/3 passed. Wrapper wall time: 62.94 seconds; Vitest: 45.55 seconds, 87% transformation. The cases took 1.08, 0.50, and 0.53 seconds.
  • The same production change also passed 65 provider and URL-response tests before relocating the new regressions: wrapper 140.33 seconds, Vitest 112.35 seconds. Existing coverage checks no-usage responses, Codex transport behavior, and inline/URL image decoding. The large provider test file remains unchanged to respect its existing line budget.
  • Targeted oxlint with config/tsconfig/oxlint.json, oxfmt, whitespace, and the line-cap ratchet passed. A nearby single-use size alias was inlined to keep the existing provider file at its baseline size.
  • Fresh independent Codex autoreview of the production change is clean through P2. The subsequent test-mock repair is also independently clean through P2 (confidence 0.94).
  • Initial CI run 39565176272 caught a new test auth mock that replaced SDK exports. The mock now preserves real exports and overrides only key resolution. The mock-export ratchet passes, and the three usage regressions pass again (273.53 seconds including worker preparation; Vitest 189.46 seconds, 94% transformation).
  • No live OpenAI calls were made, as requested for this repair lane. Tests run the production provider and response decoder with fixed HTTP/response fixtures; PR CI supplies broad proof.

Exact-head CI: run 39569159841 is green for 3474b172513af294f666bfaac2c8b8896cb7f7cc; the watcher excludes 21 superseded checks from older runs. Fresh ClawSweeper review at 2026-10-21T08:32:06Z (workflow 39569298874) found no actionable issues. The PR is ready and mergeable.

@steipete
steipete marked this pull request as ready for review August 1, 2026 05:23
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 1, 2026
@clawsweeper

clawsweeper Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Preserves documented token usage from direct OpenAI image generation and editing responses alongside existing size metadata.

Example: A gpt-image-1 generation returns input_tokens=0, output_tokens=92, and total_tokens=92.

  • Before: The image result discards all three counters.
  • After: Result metadata retains all three counters, including zero, and any size-normalization metadata.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch has no identified defects and useful provider-boundary regressions; behavioral evidence remains fixture-based.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers generation, multipart editing, zero preservation, and malformed counters through production provider code with fixed response fixtures, without live OpenAI calls.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Direct image generation and editing discard provider-reported token counts needed for usage accounting.
Reason: The maintainer-authored direction addresses a verified response-boundary defect without adding configuration, public APIs, or unrelated behavior.

Merge readiness

✅ Ready for maintainer review

This maintainer-authored PR fixes usage loss still present on main; no actionable correctness or security findings remain.

Priority: P2
Reviewed head: 3474b172513af294f666bfaac2c8b8896cb7f7cc

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No shipped CLI or Gateway execution showing retained usage was supplied; the reported red/green cases exercise the real provider and decoder with mocked HTTP boundaries.
Agent review details

How this fits together

The OpenAI plugin sends generation or multipart editing requests, decodes bounded provider responses, and returns image assets and metadata through the shared image-generation runtime.

flowchart LR
  A[Image request] --> B[OpenAI provider]
  B --> C[Direct Images API]
  C --> D[Bounded response reader]
  D --> E[Images and projected usage]
  E --> F[Shared runtime result]
Loading

Technical review

Best possible solution:

Keep usage projection in the existing private response reader and merge it with size metadata through the existing caller.

Do we have a high-confidence way to reproduce the issue?

Current-main source conclusively drops response usage; the PR reports three regression cases failing before the repair and passing afterward, but no code was executed during this read-only review.

Is this the best way to solve the issue?

This is a focused repair at the existing response owner; preserving the separate Codex Responses contract avoids an unrelated transport redesign.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 5b5c65e1be73.

Provenance checked

  • Private Images API response reader keeps the original intent (16143aa: fix(openai): accept URL images from compatible providers #170278 introduced bounded URL-image normalization while preserving existing request, download, and credential policies.)
  • Size normalization and result metadata keeps the original intent (6175309: Normalize unsupported legacy image sizes and expose requested and normalized dimensions; the repair retains these fields and changes no size decision.)
  • Direct request construction keeps the original intent (1690803: refactor(media): deslop media #156406 consolidated JSON and multipart preparation without intended behavior changes; inlining the size alias preserves that construction.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 16143aa adds extensions/openai/image-generation-response.ts:7 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 16143aab69b0; files: extensions/openai/image-generation-response.ts)
  • Vincent Koc: Raw commit 0ad2dbd adds extensions/openai/image-generation-provider.ts:111 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0ad2dbd30754; files: extensions/openai/image-generation-provider.ts)

PR surface

Source +33, Tests +87, Docs +3. Total +123 across 4 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 39 6 +33
Tests 1 87 0 +87
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 129 6 +123

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +39/-6; tests +87/-0 Growth implements bounded documented-field projection and covers generation, multipart editing, and malformed counters without adding another owner.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Provider-reported usage is silently discarded, limiting cost accounting while image generation itself continues to work.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-01T11:00:54.425Z sha 92fcf8a :: needs maintainer review before merge. :: none
  • reviewed 2026-08-01T11:05:14.406Z sha 92fcf8a :: needs maintainer review before merge. :: none
  • reviewed 2026-08-02T07:49:26.309Z sha 92fcf8a :: needs maintainer review before merge. :: none
  • reviewed 2026-08-03T08:42:46.966Z sha 92fcf8a :: needs maintainer review before merge. :: none
  • reviewed 2026-08-03T21:25:59.662Z sha 92fcf8a :: found issues before merge. :: [P1] Normalize Codex image usage before returning shared metadata
  • reviewed 2026-08-05T05:06:44.387Z sha 92fcf8a :: found issues before merge. :: [P1] Unify the image metadata boundary across transports
  • reviewed 2026-08-06T09:07:39.603Z sha 92fcf8a :: found issues before merge. :: [P1] Unify the image metadata boundary across transports
  • reviewed 2026-10-21T08:05:09.249Z sha b0bba87 :: needs maintainer review before merge. :: none

Reviewed October 21, 2026, 4:32 AM ET / 08:32 UTC (Revision 10).

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read this as a contract change rather than a metadata addition, since resolveOpenAIImageUsage is what now defines what metadata.usage is allowed to contain.

What I checked and found sound:

  • The whitelist is genuinely a whitelist, not a sanitizer. projectTokenCounts builds the result from a fixed field list and flatMaps away anything asSafeIntegerInRange rejects, so an unknown provider field cannot survive by being well-formed. That is the right shape for a field fed by provider JSON, and the 4 KiB unbounded_provider_metadata case in the new test pins it.
  • Zero is preserved rather than treated as absent. min: 0 plus the Object.keys(...).length > 0 checks mean an all-zero usage block still emits, instead of collapsing to undefined through a truthiness test. The merges zero-valued image usage with existing normalized-size metadata case is load-bearing for that, and it is easy to regress later.
  • The metadata merge does not clobber size resolution. Spreading sizeResolution.metadata first and gating on Object.keys(metadata).length > 0 keeps the previous { requestedSize, normalizedSize } behavior intact when usage is absent, so the ...(sizeResolution.metadata ? ... : {}) → ...(Object.keys(metadata).length > 0 ? ... : {}) swap is behavior-preserving in both directions.

One gap, in the inline comment: the Codex Responses transport in this same file returns completedResponse.usage and completedResponse.tool_usage verbatim (:706-707, both typed unknown at :521-522) and surfaces them through :892, so the bound this PR establishes applies to one of the provider's two transports. I ran the branch's own two tests together to confirm the split is real and not a fixture artifact.

I deliberately did not claim a live leak — I searched for a downstream reader of metadata.usage under src/ and found none outside tests, so the concern is contract consistency, not a demonstrated user-facing effect. Worth a line in the body either way, so the next person does not have to re-derive which transport the guarantee covers.

);
}

const usage = resolveOpenAIImageUsage(data);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This provider has a second transport that also emits usage into metadata, and it is not routed through resolveOpenAIImageUsage.

generateOpenAICodexImage returns the provider objects verbatim (line numbers are this head, 92fcf8a):

// extensions/openai/image-generation-provider.ts:702-708
return {
  images,
  model: params.model,
  metadata: {
    usage: completedResponse.usage,      // :521  usage?: unknown
    toolUsage: completedResponse.tool_usage,  // :522  tool_usage?: unknown
  },
};

and that object is surfaced to the caller through the aggregate at :892 — responses: results.map((result) => result.metadata).filter(Boolean).

Nothing narrows it on the way out: both fields are typed unknown at :521-522, so after this PR the same provider reports metadata.usage under two different contracts depending on which transport served the request:

input direct path (this PR) Codex Responses path
input_tokens: -1 dropped (asSafeIntegerInRange, min: 0) preserved
output_tokens: 1.5 dropped preserved
total_tokens: Number.MAX_SAFE_INTEGER + 1 dropped preserved
unknown provider field (e.g. a 4 KiB string) dropped (whitelist) preserved
cached_tokens / cache_write_tokens dropped (detailFields is ["text_tokens", "image_tokens"], :148) preserved
tool_usage no equivalent preserved verbatim as toolUsage

The branch's own test suite states both halves of that split, and I ran them together on this head to be sure they coexist rather than one superseding the other — drops unsafe counts and unknown provider fields from image-usage metadata and falls back to Codex OAuth image generation through Responses streaming, 2 passed. The second one's expectation is the passthrough, spelled out:

expect(result.metadata).toEqual({
  responses: [
    {
      usage: { input_tokens: 10, output_tokens: 20, total_tokens: 30 },
      toolUsage: { image_gen: { total_tokens: 30 } },
    },
  ],
  ...
});

Scope, honestly: I looked for a consumer that reads metadata.usage and normalizes or renders it, and found none under src/ outside tests. So this is not a demonstrated leak into a user-visible surface — the claim is narrower: the invariant this PR introduces ("image usage metadata is bounded and whitelisted") currently holds for one of the provider's two transports, and the type system does not stop the other from carrying arbitrary provider payloads under the same key name.

Reusing resolveOpenAIImageUsage(completedResponse) at :706 would close it in one line; tool_usage would need a decision of its own since it has no counterpart in the direct path.

@Yigtwxx

Yigtwxx commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Following up on my earlier review with the one thing the automated pass explicitly could not reach: "the exact OpenAI SDK and Azure response-field contract was not independently available in this checkout." I have both in a local checkout, so here are the addresses rather than a description.

The whitelist is exactly the SDK contract — not a subset, not a superset.

Installed [email protected], node_modules/openai/resources/images.d.ts:

address declaration
:344 usage?: ImagesResponse.Usage — optional, documented "For gpt-image-1 only"
:354, :362, :366 input_tokens: number, output_tokens: number, total_tokens: number
:358 input_tokens_details: Usage.InputTokensDetails (required)
:370 output_tokens_details?: Usage.OutputTokensDetails (optional)
:376 InputTokensDetails — image_tokens: number, text_tokens: number, and nothing else
:389 OutputTokensDetails — image_tokens: number, text_tokens: number, and nothing else

resolveOpenAIImageUsage projects ["input_tokens", "output_tokens", "total_tokens"] at the top level and ["text_tokens", "image_tokens"] inside both detail objects. That is a field-for-field match with the declaration above: every declared numeric scalar is carried, and no undeclared name is.

Two details worth recording so nobody re-derives them:

  • The PR treats input_tokens_details as optional (if (!details) continue) although the SDK declares it required. That is the safe direction — a provider omitting it yields a missing key rather than a throw — and it is what makes the same projection reusable for Azure below.
  • The new test feeds cached_tokens: 7 and cache_write_tokens: 0 into input_tokens_details. Neither is declared at :376, so those are not dropped documented fields — the case is exercising rejection of undeclared names, which is the property that matters for a field fed from provider JSON. Worth keeping exactly as written.

On Azure: the contract question is settled by construction, not by knowing Azure's field list.

Azure is served by this same file, and isAzure never reaches the response. On current main (extensions/openai/image-generation-provider.ts) it branches only:

  • :1004-1006 the URL (buildAzureImageUrl → /openai/deployments/{model}/images/{action}?api-version=...)
  • :985-987 the auth header (api-key vs Authorization)
  • :997 the timeout default, :1001 native size limits, :1010/:1051 whether model goes in the body

Both providers then converge on a single readProviderJsonResponse at :1073 and a single metadata return at :1101 — the exact line this PR replaces. So Azure gets the same projection, and because that projection is a whitelist rather than a sanitizer, an Azure-only extra field is dropped without anyone having to enumerate Azure's response first.

That inverts the open question usefully: the residual Azure risk is not leakage, it is under-reporting — a field Azure documents but OpenAI does not would be silently discarded. I want to be explicit that I did not verify Azure's live response; I have no Azure OpenAI deployment, and I am not going to assert a wire shape I did not observe. What I can state is that no Azure field can widen metadata.usage beyond the six names above.

This does not touch the two remaining risk items — the behind-main merge result and the maintainer label — which stay owner-side.

@Yigtwxx

Yigtwxx commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

One more owner-side item, with the mechanism rather than a description: the red openclaw/ci-gate on 92fcf8a is neither a test failure nor a stale badge. No CI lane has ever executed on this head.

What actually ran. The CI workflow was triggered exactly twice on this SHA, one second apart:

run created jobs
30685748310 05:23:47Z 24 cancelled + 1 failure
30685748954 05:23:48Z 25 skipped

The job outcomes identify which event produced which run without having to guess. Run …8310's jobs started and were then cancelled, so its payload carried draft: false — that is the ready_for_review run, the one that would have tested. Run …8954 skipped all 25 jobs, which is what .github/workflows/ci.yml:69 and :802 do when github.event.pull_request.draft is true — that is the opened run.

Why the later run won. This PR was opened at 05:23:42Z and marked ready at 05:23:44Z, two seconds apart. Both events are triggers (ci.yml:47), and the concurrency group is keyed on the PR number, not the SHA or the event (ci.yml:55), with cancel-in-progress enabled for pull_request (ci.yml:58). The two runs therefore collide, and the draft run arrived second: it cancelled the run that was going to test, then declined to test anything itself.

ci-gate (job 91331049849) is inside the cancelled run and failed at Verify selected CI lanes after two seconds — 05:23:51Z to 05:23:53Z. That duration is the tell: it is reporting lanes that never produced a result, not lanes that produced a bad one.

Control. On c65f4d1a78f — a head that was not flipped out of draft — CI appears once and runs to completion. The lanes work; the two-second draft window is what removed them here.

This looks like a repo-level race rather than anything about this change: any PR opened as a draft and marked ready within the same few seconds can land in the same state, with a red gate and no test signal. Happy to file that separately if it is worth bounding on its own terms.

The fix here is a re-run or any new push, both of which are yours — I cannot trigger either from outside. Nothing in this note bears on the diff itself; the SDK-contract check in my previous comment stands unchanged.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. proof: sufficient ClawSweeper judged the real behavior proof convincing. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 3, 2026
@fuller-stack-dev fuller-stack-dev self-assigned this Sep 15, 2026
Keep documented image usage counters in the private response decoder and return them beside normalized size metadata. Preserve zero counts and omit malformed or unsupported fields.
@steipete
steipete force-pushed the codex/qa400-openai-image-usage-owner branch from 92fcf8a to b0bba87 Compare October 21, 2026 07:53
@steipete steipete changed the title fix(openai): preserve authoritative image token usage fix(openai): preserve image token usage Oct 21, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Oct 21, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Oct 21, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 21, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 21, 2026
@steipete
steipete merged commit a513fa8 into main Oct 21, 2026
120 of 122 checks passed
@steipete
steipete deleted the codex/qa400-openai-image-usage-owner branch October 21, 2026 16:18
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
* fix(openai): preserve image token usage

Keep documented image usage counters in the private response decoder and return them beside normalized size metadata. Preserve zero counts and omit malformed or unsupported fields.

* test(openai): preserve auth module exports in usage fixtures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: openai maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants