Repository navigation
fix(openai): preserve image token usage - #117226
Conversation
|
Codex review: needs maintainer review before merge. What this changesPreserves 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +33, Tests +87, Docs +3. Total +123 across 4 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (9 earlier review cycles; latest 8 shown)
Reviewed October 21, 2026, 4:32 AM ET / 08:32 UTC (Revision 10). |
Yigtwxx
left a comment
There was a problem hiding this comment.
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.
projectTokenCountsbuilds the result from a fixed field list andflatMaps away anythingasSafeIntegerInRangerejects, 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 KiBunbounded_provider_metadatacase in the new test pins it. - Zero is preserved rather than treated as absent.
min: 0plus theObject.keys(...).length > 0checks mean an all-zero usage block still emits, instead of collapsing toundefinedthrough a truthiness test. Themerges zero-valued image usage with existing normalized-size metadatacase is load-bearing for that, and it is easy to regress later. - The metadata merge does not clobber size resolution. Spreading
sizeResolution.metadatafirst and gating onObject.keys(metadata).length > 0keeps 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); |
There was a problem hiding this comment.
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.
|
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
Two details worth recording so nobody re-derives them:
On Azure: the contract question is settled by construction, not by knowing Azure's field list. Azure is served by this same file, and
Both providers then converge on a single 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 This does not touch the two remaining risk items — the behind-main merge result and the |
|
One more owner-side item, with the mechanism rather than a description: the red What actually ran. The
The job outcomes identify which event produced which run without having to guess. 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 (
Control. On 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. |
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.
92fcf8a to
b0bba87
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
* 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
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:66returns 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.Usagecontract. 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
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.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.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.