Skip to content

fix(compact): report upstream usage for native compact turns - #945

Draft
DevMello wants to merge 2 commits into
lidge-jun:devfrom
DevMello:fix/compact-native-usage
Draft

fix(compact): report upstream usage for native compact turns#945
DevMello wants to merge 2 commits into
lidge-jun:devfrom
DevMello:fix/compact-native-usage

Conversation

@DevMello

@DevMello DevMello commented Aug 3, 2026

Copy link
Copy Markdown

Summary

Native /v1/responses/compact turns buffer the upstream JSON and return it without reading the body, so every native compaction lands in /api/usage as unreported even though the response carries a full usage object. Compact turns are among the largest requests an account makes, so the undercount is biggest exactly where usage matters. The routed branch already reports through handleResponses. The native branch now inspects a clone of the buffered body with the existing inspectResponseLogJson helper, filling usage, resolved model, and service tier in the request log. The client body is unchanged and synthetic error responses are not inspected.

Verification

  • New test in tests/responses-compaction-routing.test.ts: a native compact turn fills the request log usage from the upstream body and the client still receives the body intact.
  • bun run test, typecheck, lint:gui, privacy:scan.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Summary by CodeRabbit

  • Bug Fixes

    • Native compact responses now preserve the upstream response body while correctly recording usage and response metadata in request logs.
    • Synthetic buffering errors are excluded from metadata inspection.
    • Non-JSON response bodies no longer report usage incorrectly.
  • Tests

    • Added regression coverage to verify response delivery and usage tracking for compact responses.

@github-actions github-actions Bot added the bug Something isn't working label Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The native compact-response path now parses successful buffered upstream JSON and applies usage and response metadata to the request log. Synthetic buffering errors are excluded. A regression test verifies payload preservation, token usage recording, and usage-debug field handling.

Changes

Native compact usage reporting

Layer / File(s) Summary
Buffered response inspection and regression coverage
src/server/responses/compact.ts, tests/responses-compaction-routing.test.ts
The compact path uses applyResponseLogMetadata for successful buffered JSON responses. It ignores parsing failures and synthetic buffering errors. The regression test verifies the intact client payload, recorded token usage, and excluded usage-debug body fields.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: wibias, ingwannu, lidge-jun

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: reporting upstream usage for native compact responses.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2ae3b5fc8d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/responses/compact.ts Outdated
// Lift usage and response metadata from the buffered upstream JSON into the
// request log; the routed branch gets the same through handleResponses. The
// synthetic buffer errors are not upstream bodies and stay uninspected.
if (buffered.ok) inspectResponseLogJson(logCtx, await buffered.clone().text());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid persisting compact bodies in usage debug

When usage debugging is enabled, inspectResponseLogJson also copies the first 2 KiB of the body into usageDebugBodySample, which is later written to ~/.opencodex/usage-debug.jsonl. Native compact responses are replacement history derived from the conversation being compacted, so this new call can persist private conversation content just to extract token usage; parse the buffered JSON for usage/metadata without invoking the debug body sampler.

AGENTS.md reference: AGENTS.md:L214-L215

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/responses-compaction-routing.test.ts`:
- Around line 188-192: Update the response assertion in this test to validate
the complete upstream payload, not only body.usage. Assert that body also
preserves the expected id, status, and output fields while retaining the
existing usage and logCtx.usage checks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7739ee1a-3d74-4c37-a3ae-932f1a61abb4

📥 Commits

Reviewing files that changed from the base of the PR and between 6a7351b and 2ae3b5f.

📒 Files selected for processing (2)
  • src/server/responses/compact.ts
  • tests/responses-compaction-routing.test.ts

Comment on lines +188 to +192
expect(response.status).toBe(200);
const body = await response.json() as { usage?: Record<string, unknown> };
expect(body.usage).toMatchObject({ input_tokens: 10, output_tokens: 5, total_tokens: 15 });
expect(logCtx.usage).toMatchObject({ inputTokens: 10, outputTokens: 5, totalTokens: 15 });
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the complete upstream payload.

Lines 189-190 check only body.usage. A regression that removes id, status, or output would still pass, although this PR must preserve the complete upstream body.

Proposed assertion
-    const body = await response.json() as { usage?: Record<string, unknown> };
-    expect(body.usage).toMatchObject({ input_tokens: 10, output_tokens: 5, total_tokens: 15 });
+    const body = await response.json();
+    expect(body).toEqual(completedPayload("native summary"));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/responses-compaction-routing.test.ts` around lines 188 - 192, Update
the response assertion in this test to validate the complete upstream payload,
not only body.usage. Assert that body also preserves the expected id, status,
and output fields while retaining the existing usage and logCtx.usage checks.

@lidge-jun

Copy link
Copy Markdown
Owner

Carried onto the review stack as #953 (stack 3/3), unmodified.

Your commits were taken with git cherry-pick -x, so they keep your authorship — git log --format='%an' on the stack branch shows you, not me. No content was changed; the diff on the stack is byte-identical to what you wrote here, and it applied to dev with no conflict resolution.

Verified on the stack: bun x tsc --noEmit exit 0, and the full suite at 7691 pass / 8 skip / 0 fail across 507 files.

This PR stays open until #953 lands. If a maintainer prefers to take yours directly instead, that path is unaffected — the stack commits get dropped and this one merges. Once #953 merges I'll close this as carried, with the credit already in the commit history rather than in a comment.

Stack: #951 (plan, base dev) → #952 (#908 long-context pricing) → #953 (this carry). Review bottom-up.

Thanks for the fix.

The native branch buffers the upstream compact JSON and returns it
without inspecting the body, so the request log row lands with no
usage. Lift usage and response metadata from the buffered body the
same way the routed branch gets it through handleResponses.
@DevMello
DevMello force-pushed the fix/compact-native-usage branch from c1dbe0a to 8192ea4 Compare August 3, 2026 21:57
@DevMello
DevMello marked this pull request as ready for review August 3, 2026 22:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/responses-compaction-routing.test.ts`:
- Around line 170-206: Extend the “buffered upstream body” test around
handleResponsesCompact to return response data whose model and service_tier
differ from the initial route metadata, then assert logCtx.resolvedModel and
logCtx.responseServiceTier are populated from that response. Add a focused
non-OK or synthetic buffering case that exercises the buffered.ok exclusion and
verifies existing request-log metadata remains unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: cdea9032-d8c1-41ce-af15-de6b01ccaa10

📥 Commits

Reviewing files that changed from the base of the PR and between 2ae3b5f and 8192ea4.

📒 Files selected for processing (2)
  • src/server/responses/compact.ts
  • tests/responses-compaction-routing.test.ts

Comment on lines +170 to +206
describe("native compact usage reporting", () => {
test("the buffered upstream body fills the request log usage and stays intact for the client", async () => {
const config = {
defaultProvider: "openai-apikey",
providers: {
"openai-apikey": {
adapter: "openai-responses",
baseUrl: "https://api.openai.com/v1",
authMode: "key",
apiKey: "sk-test",
},
},
} as unknown as OcxConfig;
globalThis.fetch = (async () => jsonResponse(completedPayload("native summary"))) as typeof fetch;
const logCtx: RequestLogContext = { model: "", provider: "" };
const previousUsageDebug = process.env.OPENCODEX_USAGE_DEBUG;
process.env.OPENCODEX_USAGE_DEBUG = "1";
let response: Response;
try {
response = await handleResponsesCompact(
compactionRequest(baseCompactionBody({ model: "openai-apikey/gpt-5.5" })),
config,
logCtx,
);
} finally {
if (previousUsageDebug === undefined) delete process.env.OPENCODEX_USAGE_DEBUG;
else process.env.OPENCODEX_USAGE_DEBUG = previousUsageDebug;
}
expect(response.status).toBe(200);
expect(await response.json()).toEqual(completedPayload("native summary"));
expect(logCtx.usage).toMatchObject({ inputTokens: 10, outputTokens: 5, totalTokens: 15 });
// The compact body is replacement history; even with usage debug on it must
// never be sampled into the debug log.
expect(logCtx.usageDebugBodyKind).toBeUndefined();
expect(logCtx.usageDebugBodySample).toBeUndefined();
});
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the remaining response-log branches.

This test checks usage and complete body preservation only. It does not exercise model or service_tier extraction in src/server/request-log.ts, Lines 489-504. It also does not verify the buffered.ok exclusion at src/server/responses/compact.ts, Line 513.

Add assertions for logCtx.resolvedModel and logCtx.responseServiceTier using response values that differ from the initial route metadata. Add a non-OK or synthetic buffering case and assert that existing request-log metadata remains unchanged.

As per path instructions, source behavior changes require focused regression coverage in tests/; cover these new branches here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/responses-compaction-routing.test.ts` around lines 170 - 206, Extend
the “buffered upstream body” test around handleResponsesCompact to return
response data whose model and service_tier differ from the initial route
metadata, then assert logCtx.resolvedModel and logCtx.responseServiceTier are
populated from that response. Add a focused non-OK or synthetic buffering case
that exercises the buffered.ok exclusion and verifies existing request-log
metadata remains unchanged.

Source: Path instructions

@Wibias
Wibias marked this pull request as draft August 3, 2026 22:34
@Wibias

Wibias commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Leave it as draft. Thanks. It doesnt need any more changes as you can see in juns comment on which you didn't respond to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants