open-code-review icon indicating copy to clipboard operation
open-code-review copied to clipboard

feat(llm): task-scoped session affinity for prompt caching

Open cometkim opened this issue 4 months ago • 5 comments

Description

Adds provider-side session affinity for prompt caching (#229) via a {ocr_session_key} template variable. Writing the placeholder is the opt-in — OCR never invents a parameter or header name, and sends nothing session-related unless configured.

OCR derives a prompt-cache affinity key for every LLM conversation, scoped to the review session and the task within it:

<session-id>-<task-type>-<scope-hash>

Prompt caches match on prefixes, and OCR's task types (plan, per-file main tool-loop, compression, dedup, filter, relocation) use unrelated prompts — while each file's main tool-loop re-sends a growing conversation prefix every round, which is where cache hits actually come from. Scoping the key per task conversation keeps each conversation on a consistent cache node instead of pinning a whole run to one hot key (e.g. OpenAI reroutes a prompt_cache_key once it exceeds ~15 req/min). The session-ID prefix keeps provider-side cache logs correlatable with ocr session records.

This PR:

  • adds llm.SessionTaskKey and context helpers (ContextWithSessionKey / SessionKeyFromContext); review/scan runs bind the real session's ID as a base key at Run, and each task conversation refines it where it starts (llmloop.RunPerFile, plan, review filter, compression, dedup, project summary, relocation) — using the same (session, task type, path) triple those sites already record into session history

  • expands the {ocr_session_key} template variable per request in extra_headers values and (recursively) extra_body values, so any provider's convention can be expressed with existing config fields — no new config surface:

    # OpenAI: prompt_cache_key request body field
    ocr config set providers.openai.extra_body '{"prompt_cache_key": "{ocr_session_key}"}'
    
    # Header-routed gateways (Cloudflare, Fireworks, Mistral, ...)
    ocr config set custom_providers.my-gateway.extra_headers "x-session-affinity={ocr_session_key}"
    
  • moves extra_headers/extra_body application from client construction to per-request SDK options so the template variable can expand to the key each request's context carries; session-less callers (ocr llm test) fall back to a per-client generated key

  • requests without the placeholder are byte-for-byte unchanged — no behavior change for existing configurations, and nothing is sent to gateways that reject unknown fields

Type of Change

  • [ ] Bug fix (non-breaking change that fixes an issue)
  • [x] New feature (non-breaking change that adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to change)
  • [ ] Refactoring (no functional changes)
  • [ ] Documentation update
  • [ ] CI / Build / Tooling

How Has This Been Tested?

  • [x] make test passes locally
  • [x] Manual testing (describe below)

Also verified with:

  • go test ./...
  • go vet ./...

New tests cover:

  • no injection without the placeholder: requests carry no session-related fields unless explicitly configured
  • llmloop: every round of RunPerFile reaches the client with the same task-scoped key (TestRunPerFile_TagsRequestsWithTaskSessionKey)
  • clients: context key takes precedence over the client fallback for both protocols; {ocr_session_key} expansion in headers and nested body values (including the OpenAI prompt_cache_key recipe via extra_body)
  • resolver: the raw {ocr_session_key} placeholder survives endpoint resolution untouched
  • SessionTaskKey: deterministic, distinct per task type and scope, header-safe for non-ASCII paths

Context propagation was verified end-to-end: the async comment worker pool and background compression use context.WithoutCancel, which preserves context values.

Checklist

  • [x] My code follows the project's coding style (go fmt, go vet)
  • [x] I have performed a self-review of my code
  • [x] I have added tests that prove my fix is effective or my feature works
  • [x] New and existing unit tests pass locally with my changes
  • [x] I have updated the documentation accordingly (if applicable)
  • [x] I have signed the CLA

Related Issues

Closes #229

🤖 Generated with Claude Code

cometkim avatar Jul 09 '26 07:07 cometkim

Overall this direction looks good to me.

One thing I’d like to see is an explicit opt-out. Right now the built-in openai provider always sends prompt_cache_key. That’s fine for the real OpenAI API, but if someone points providers.openai.url at an OpenAI-compatible gateway that rejects unknown body fields, this could break the main LLM path. The workaround is to switch to custom_providers, but that’s not very obvious.

Should we add a config flag to disable this for a provider, e.g. providers.<name>.session_affinity = false or similar?

FYI @lizhengfeng101

MuoDoo avatar Jul 09 '26 11:07 MuoDoo

@MuoDoo @lizhengfeng101 I'd like to ask for your opinions to finalize the changes.

  • Since this is a breaking change, would it be a good idea to even introduce it as an opt-in feature?
  • And would it be better to use a provider-oriented term like prompt_cache?

cometkim avatar Jul 09 '26 13:07 cometkim

Made the feature to opt in via the llm.session_affinity config flag.

However, this only enables automatic configuration for OpenAI-compatible APIs. If this is too complex, we can guide users to configure it manually via extra body/headers instead of using the extra flag.

It should be an opt-in feature either way.

cometkim avatar Jul 13 '26 07:07 cometkim

Simplified the configuration interface to use only the {ocr_session_key} template variable.

Users can opt in prompt-caching with extra_body or extra_headers. No extra config or env is needed for this.

cometkim avatar Jul 13 '26 07:07 cometkim

@MuoDoo Done rebasing. Since this is now an explicit opt-in via extra body or headers, I think it is safe even without other flags.

cometkim avatar Jul 15 '26 05:07 cometkim