Skip to content

fix(cache): stabilize compression session feedback - #663

Merged
SantiagoDePolonia merged 3 commits into
mainfrom
fix/compression-cache-feedback
Aug 8, 2026
Merged

fix(cache): stabilize compression session feedback#663
SantiagoDePolonia merged 3 commits into
mainfrom
fix/compression-cache-feedback

Conversation

@SantiagoDePolonia

@SantiagoDePolonia SantiagoDePolonia commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Description

  • canonicalize auto-detected session anchors so JSON whitespace, object-key order, and equivalent string escapes do not split one conversation into multiple sessions
  • add optional, content-free provider response feedback for request rewriters
  • report resolved model/provider plus input, cache-read, and cache-write token counts for normal and streaming responses
  • let observers decline feedback per request so normal traffic keeps the existing streaming fast path
  • request streaming usage only when an interested observer is attached
  • isolate observer panics from successful provider responses

This supplies the cache-domain and provider-cache evidence consumed by the companion GoModel Pro compression change.

Verification

  • go test ./...
  • go test -race ./internal/server ./internal/session
  • make lint
  • full pre-commit suite including make test-race, make fix-check, hot-path guards, and lint

AI Generated (optional)

Implemented and verified with Codex.

Summary by CodeRabbit

  • New Features

    • Added optional response feedback for successful chat and Responses API requests.
    • Feedback can include request and session identifiers, endpoint, model, provider, token usage, and cache usage.
    • Added per-request controls for selective feedback.
    • Streaming responses report usage information without retaining response content.
  • Improvements

    • Automatic session detection now treats equivalent JSON formatting consistently while preserving meaningful ordering and value differences.
    • Unknown usage data is reported when unavailable.
    • Feedback filtering errors no longer interrupt request processing.

@SantiagoDePolonia

Copy link
Copy Markdown
Contributor Author

Companion GoModel Pro epoch/compression change: https://github.com/ENTERPILOT/GoModel-pro/pull/16

@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5ac0b73c-a69f-43a5-809a-b595560faaa1

📥 Commits

Reviewing files that changed from the base of the PR and between a70bca4 and d77f441.

📒 Files selected for processing (1)
  • internal/server/request_rewrite.go
💤 Files with no reviewable changes (1)
  • internal/server/request_rewrite.go

📝 Walkthrough

Walkthrough

The PR adds optional response-feedback observers and filters, integrates feedback collection into chat and Responses API handlers, and canonicalizes JSON segments used for automatic session identifiers.

Changes

Response feedback

Layer / File(s) Summary
Feedback contract and rewrite registration
ext/ext.go, internal/server/request_rewrite.go, internal/server/request_rewrite_test.go
The extension API defines response observers and per-request filters. Request rewriting registers eligible observers and isolates filter panics.
Feedback collection and usage parsing
internal/server/response_feedback.go, internal/server/response_feedback_test.go
The server extracts token and cache usage from completed responses and streaming events, then sends normalized notifications while isolating observer panics.
Chat and Responses API integration
internal/server/translated_inference_service.go
The handlers enable usage reporting when observers exist and notify observers for successful streaming and non-streaming responses.

Session anchor canonicalization

Layer / File(s) Summary
Canonical session anchor generation
internal/session/detect.go, internal/session/detect_test.go
Automatic session detection canonicalizes valid JSON before hashing, rejects multiple values, and preserves array order and message-value differences.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RequestRewriter
  participant TranslatedInferenceService
  participant Provider
  participant ResponseFeedbackObserver
  RequestRewriter->>TranslatedInferenceService: register eligible observers
  TranslatedInferenceService->>Provider: request with usage reporting enabled
  Provider-->>TranslatedInferenceService: completed or streaming response
  TranslatedInferenceService->>ResponseFeedbackObserver: notify response metadata and usage
Loading

Possibly related PRs

Poem

A rabbit watches each response flow,
While tokens and cache values show.
Streams close, and observers hear,
Canonical sessions become clear.
Rewritten requests leave a trace.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the cache-related session feedback stabilization, which is a central part of the changes.
Description check ✅ Passed The description explains the changes, rationale, verification steps, and optional AI-generated context using the repository template.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/compression-cache-feedback

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🤖 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 `@ext/ext.go`:
- Around line 84-116: Add user-facing extension documentation for
ResponseFeedbackObserver and ResponseFeedbackFilter alongside the existing
extension API contract. Document callback timing after successful rewritten
requests, the meaning of usageObserved, the requirement that observers be
concurrency-safe and return promptly, and that WantsResponseFeedback controls
per-request registration while observers without the filter receive all
successful responses.

In `@internal/server/response_feedback.go`:
- Around line 64-67: Update the non-nil resp.Usage branch in the response
feedback handling to set usage.observed = true after cacheUsageFromCore
processes the usage object, preserving confirmed zero values. Add a regression
test covering a zero-valued Responses API usage object and verify it remains
observed.

In `@internal/session/detect_test.go`:
- Around line 199-228: Add direct unit tests for canonicalSegment covering
malformed JSON and concatenated JSON values, and assert that each returns the
exact original raw segment unchanged. Keep the existing canonicalization tests
intact and target the raw fallback behavior specifically, including both
decode-error and trailing-value cases.
🪄 Autofix

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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: fe2b0761-909f-42df-bb33-dd554fbbe51f

📥 Commits

Reviewing files that changed from the base of the PR and between 8f5bb4a and 56c4b3a.

📒 Files selected for processing (8)
  • ext/ext.go
  • internal/server/request_rewrite.go
  • internal/server/request_rewrite_test.go
  • internal/server/response_feedback.go
  • internal/server/response_feedback_test.go
  • internal/server/translated_inference_service.go
  • internal/session/detect.go
  • internal/session/detect_test.go

Comment thread ext/ext.go
Comment thread internal/server/response_feedback.go
Comment thread internal/session/detect_test.go
Comment thread internal/server/response_feedback.go Fixed
@codecov-commenter

codecov-commenter commented Aug 8, 2026

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 76.19048% with 50 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/server/response_feedback.go 76.98% 19 Missing and 10 partials ⚠️
internal/server/translated_inference_service.go 51.35% 15 Missing and 3 partials ⚠️
internal/session/detect.go 89.65% 2 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Aug 8, 2026

Copy link
Copy Markdown

Confidence Score: 4/5

Not safe to merge until optional response-feedback filters can fail without aborting inference requests.

The failure was reproduced through the real server path with an otherwise identical successful control request, directly demonstrating that the filter panic prevents provider dispatch.

Files Needing Attention: internal/server/request_rewrite.go needs local panic isolation around ResponseFeedbackFilter.WantsResponseFeedback; a regression test should exercise the server request path.

T-Rex T-Rex Logs

What T-Rex did

  • T-Rex produced a proof for a posted P1 finding and linked it to the corresponding review comment.
  • A second P1 finding was posted, with a review comment referenced as supporting evidence.
  • The focused Go repro test source was used to exercise the middleware path, installing an observer/rewriter and driving the actual inference request.
  • The normal control path completed successfully, returning HTTP 200 and invoking the provider during the repro test run.
  • The panicking response-feedback filter aborted the inference request, caused an HTTP 500 in Echo's recovery, and prevented provider invocation.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (1)

  1. General comment

    P1 Response-feedback filter panic aborts supported inference requests

    • Bug
      • RequestRewriteMiddleware calls an extension's WantsResponseFeedback without a local recovery boundary. The focused real-server repro sent POST /v1/chat/completions through Server.ServeHTTP; a panicking filter yielded HTTP 500 and the provider was not invoked. This differs from ObserveResponse, which is individually recovered in internal/server/response_feedback.go:87-94.
    • Cause
      • At internal/server/request_rewrite.go:59, filter.WantsResponseFeedback(in, res) executes directly. Its panic propagates to Echo's server-wide recovery middleware rather than being isolated as optional response-observer behavior.
    • Fix
      • Wrap the WantsResponseFeedback invocation in a narrow defer recover boundary. Treat a recovered panic as declining feedback (and optionally log the extension name/panic), so the inference request proceeds. Add a regression test retaining this repro's request path.

    T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "fix(cache): stabilize compression sessio..." | Re-trigger Greptile

Comment thread internal/server/request_rewrite.go Outdated

@coderabbitai coderabbitai Bot 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.

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 `@internal/server/request_rewrite.go`:
- Around line 107-110: Update the panic recovery logging in the request rewrite
flow to remove the recovered value from the slog.Warn attributes, retaining only
the rewriter name or a non-sensitive panic type. Ensure data originating from
ext.Input.Body or configured credentials cannot be emitted by this log.
🪄 Autofix

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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 00ed9f4c-e1ef-499d-a1b9-94e4565da2e1

📥 Commits

Reviewing files that changed from the base of the PR and between 56c4b3a and a70bca4.

📒 Files selected for processing (6)
  • ext/ext.go
  • internal/server/request_rewrite.go
  • internal/server/request_rewrite_test.go
  • internal/server/response_feedback.go
  • internal/server/response_feedback_test.go
  • internal/session/detect_test.go

Comment thread internal/server/request_rewrite.go
@SantiagoDePolonia

Copy link
Copy Markdown
Contributor Author

Addressed all review and CI findings in a70bca4e and d77f441a:

  • isolated WantsResponseFeedback panics so optional filters cannot abort inference, with real server-path coverage
  • removed recovered panic values from logs to prevent extension-controlled data leakage
  • preserved confirmed zero usage for Responses API feedback
  • replaced unsafe integer conversions with architecture-bounded parsing; CodeQL alert feat: add guardrails system with system prompt injection/override/decorator #64 is now fixed
  • added exact raw-fallback tests for malformed and concatenated JSON
  • expanded the public feedback extension contract documentation

The branch already contains the latest main (v0.1.71 / 8f5bb4a4). The full CI matrix, CodeQL, CodeRabbit, lint, race tests, integration, E2E, contract, build, performance, vulnerability, dashboard, and docs checks are green.

@SantiagoDePolonia
SantiagoDePolonia merged commit aefa498 into main Aug 8, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants