Skip to content

feat(provider): ask for the prompt cache through the protocol, not the vendor (ADR 0346) - #1573

Merged
aponcedeleonch merged 6 commits into
mainfrom
feat/openrouter-anthropic-prompt-caching
Sep 18, 2026
Merged

aponcedeleonch merged 6 commits into
mainfrom
feat/openrouter-anthropic-prompt-caching

Conversation

@aponcedeleonch

@aponcedeleonch aponcedeleonch commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements the acceptance plan in #1572 (the PR below this one in the stack).

Mecatl now asks for a prompt cache through the Responses protocol, emitting one
prompt_cache_breakpoint on an input_text block of every request, governed only by
--no-prompt-cache. No vendor is consulted, so an upstream that caches only when asked is
covered on any endpoint, including ones composition cannot classify. OpenRouter's root
cache_control is retired.

This fixes the reported case directly. toolhive + anthropic/claude-opus-4.8 now carries a
breakpoint, the gateway forwards it, and OpenRouter translates it for Anthropic. No new
provider selected, no operator config, no id translation.

Development stage

  • Plan / Interface
  • Implementation — based on a Plan / Interface PR (merged)
  • Combined
  • Spike / Routine

Contract linkage

Interface conformance

Matches the approved contract.

Issue relationship

Closes #1558

Type of change

  • Behavioral/interface plan
  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation/process
  • Other (describe):

Test plan

Baseline checks

  • Acceptance-plan checker — plan changes live in plan: ask for the prompt cache through the protocol, not the vendor (ADR 0346) #1572
  • Linting (task lint) — 0 issues, root + all provider modules
  • Offline test suite (task test) — green except one pre-existing failure, see below
  • Offline demo (go run ./cmd/mecademo)
  • Markdown changed: docs generation/link checks (task docs)
  • User docs changed: site build (task site:build) — 83 documents
  • Guarded engine API affected: compatibility check (task api:check)
  • Intentional engine API change — none; the provider/openai additions are outside the engine gate
  • Landed plan: strict acceptance trace — plan is not landed
  • Final implementation review: /panel-review — not yet run

TestMecak8sHelmChart_DeployCheckProductionFixtureRuntimeAndSpread fails, and fails
identically on the clean baseline
— verified by stashing, not assumed.

Changes

File Change
provider/openai/breakpoint.go New. Placement, the canonical-OpenAI carve-out, the marker stamp
provider/openai/request.go Breakpoint index threaded into buildInput; root cache_control retired
provider/openai/cache.go, openai.go WithPromptCacheBreakpoints, WithCacheKeySalt
internal/app/registry.go Arms breakpoints per entry; openrouter-anthropic; sibling map narrowed to the OpenRouter pair
internal/app/openrouteranthropic.go Base derivation, promptCachedFor, posture line
user-docs/features/choose-models.md Both gateway surfaces cache; corrected the no-cache marker's meaning

User-facing change

A model that caches only when asked now caches on any Responses endpoint, including the
ToolHive gateway and a custom OpenAI-compatible endpoint, with no configuration. Roughly 10x
cheaper input on long sessions with such a model. openrouter-anthropic appears as a second
provider id and adds four breakpoints plus --anthropic-cache-ttl where you want more than
the floor.

Special notes for reviewers

I got this wrong once, and the guard is in the diff. My first revision gated the breakpoint
on cacheDialect. Composition resolves every unrecognised endpoint — the ToolHive gateway
included — to CacheDialectNone, which is precisely where an explicit-ask upstream has no
other way to ask. It would have passed every dialect-bearing test and delivered nothing to the
only case that mattered. TestADR_0346_BreakpointNotGatedOnDialect exists so it cannot come
back.

A serialization trap worth knowing. PromptCacheBreakpoint is omitzero and its struct
holds only a constant, so a zero-value literal marshals to nothing and the marker silently
vanishes. Mode must be set explicitly; the SDK's own call sites do the same.

The no-cache picker marker is now close to vestigial, and I did not rip it out
unilaterally. You chose "mark the non-caching row" when non-caching rows existed. After this
change mecatl asks for caching everywhere, so prompt_cached is true unless
--no-prompt-cache is set, and the marker only fires then. Whether an upstream honours the
ask is not statically knowable, so the signal must not claim it. Worth deciding whether to keep
the field, and I would rather you decide than discover it.

The ToolHive sibling redirect is gone, on measured evidence rather than reasoning: that
gateway exposes one Claude Opus 4.8 as anthropic/claude-opus-4.8, claude-opus-4-8 and
us.anthropic.claude-opus-4-8 depending on the downstream, so switching provider while
carrying the id verbatim cannot resolve. The breakpoint covers that case with no translation.

Still not covered by a test: AC1.7's end-to-end non-zero CacheReadTokens through a
dialect-less endpoint, and AC2.3's TTL stamping. Both are the plan's headline behaviours and
inherited from already-tested code rather than newly proven. I would not call this done without
AC1.7.

🤖 Generated with Claude Code

@aponcedeleonch
aponcedeleonch marked this pull request as ready for review September 15, 2026 16:08
@aponcedeleonch
aponcedeleonch force-pushed the feat/openrouter-anthropic-prompt-caching branch from 5b3fa82 to 9fc029b Compare September 16, 2026 15:54
@aponcedeleonch aponcedeleonch changed the title feat(provider): route Claude prompt caching through native Messages (ADR 0343) feat(provider): ask for the prompt cache through the protocol, not the vendor (ADR 0343) Sep 16, 2026
@aponcedeleonch
aponcedeleonch force-pushed the feat/openrouter-anthropic-prompt-caching branch from 9fc029b to ffbd50f Compare September 16, 2026 16:09
Base automatically changed from plan/unified-prompt-cache-dialect to main September 17, 2026 11:44
@aponcedeleonch
aponcedeleonch force-pushed the feat/openrouter-anthropic-prompt-caching branch from d982282 to 35f35dd Compare September 17, 2026 11:44
@aponcedeleonch aponcedeleonch changed the title feat(provider): ask for the prompt cache through the protocol, not the vendor (ADR 0343) feat(provider): ask for the prompt cache through the protocol, not the vendor (ADR 0346) Sep 17, 2026

@jhrozek jhrozek 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.

Panel review (Spec/Standards/Test-adequacy/Domain, diffed against origin/main) plus verification of an independently-supplied review-openai.md report. Findings below are the subset confirmed by direct code reading; several other claims in that second report (breakpoints defaulting off in composition, the image-only-message case, the seenAssistant gate "conflicting" with AC1.3, AC2.1/2.2/2.4 coverage, the salted-anchor correlation claim) were checked and are false or overstated, so they're omitted here.

Comment thread internal/app/registry.go Resolved
Comment thread internal/app/openrouteranthropic.go Resolved
Comment thread internal/app/openrouteranthropic.go Resolved
Comment thread internal/app/registry.go Resolved
Comment thread provider/openai/breakpoint.go Resolved
Comment thread provider/openai/cache.go Resolved
Comment thread user-docs/features/choose-models.md Resolved
Comment thread internal/app/promptcachesalt.go Resolved
aponcedeleonch added a commit that referenced this pull request Sep 17, 2026
…er protocol

Addresses the two blockers from the PR #1573 review, plus the two
composition-layer reuse findings that live in the same files.

Blocker 1: every Anthropic-protocol entry now gets a redirect-refusing HTTP
client. anthropic-sdk-go ships no cross-origin guard of its own (unlike
openai-go, whose guard makes the equivalent openai-path client a second layer),
so composition was the only layer that could refuse and it was not refusing.
Go's default client strips Authorization cross-origin but NOT x-api-key, which
is the header this protocol authenticates with, and never strips the body on a
307 re-send. Every one of these entries derives its base from
operator-overridable config, so the fix is in newAnthropicEntryFor rather than
at the openrouter-anthropic call site: it closes the same gap on the plain
anthropic entry and a future caller cannot forget it. It is prepended before
extra, so the gateway entries' own bearer-injecting clients still win.

TestADR_0346_AnthropicProtocolEntryRefusesRedirect drives both the shared
.provider and a remint. Its bare-adapter control asserts the unwired adapter
DOES follow, so the test cannot go vacuous if the SDK later grows a guard.
Removing the fix makes it report the leak concretely: X-Api-Key travelled to
the redirect target on both mints.

Blocker 2: prompt_cached was true for any registered provider, which was wrong
for Chat Completions. openaichat has no breakpoint mechanism (ADR 0346's fix is
a Responses field) and openaichatCacheDialectFor returns None for every
registered id, so opencode and every custom api_flavor:
openai-chat-completions definition send no cache ask at all. Reporting true
there recreated exactly the ADR 0100 failure the signal exists to expose: a
provider silently re-paying full input every turn, indistinguishable in the
picker from one that caches. promptCacheSource likewise claimed "responses
breakpoint" for an entry that does not speak Responses.

The anthropicProtocol bool becomes a three-value providerProtocol enum
mirroring permconfig's api_flavor vocabulary, because Chat Completions answers
this question differently from BOTH siblings and a second bool would encode an
impossible fourth state. Its zero value is the Responses arm, so every
hand-built providerEntry literal keeps today's behaviour.

The Chat Completions arm still reports true under the canonical-OpenAI dialect,
where the endpoint caches implicitly with nothing sent, so it must not be
simplified to "chat completions never caches" —
TestADR_0346_ChatCompletionsUnderCanonicalOpenAIDialectStillCaches pins that.

Also: openRouterAnthropicBaseURL now delegates to deriveGatewayBaseURL with an
empty segment rather than reimplementing its sanitisation, and the two
OpenRouter surfaces share one lister value. The existing derivation table
passes unchanged as the no-behaviour-change proof. The shared lister does not
dedupe the pair's two GETs per refresh pass; a cached fetch was considered and
declined, because it would add an outlives-a-call resource requiring an
ADR 0027 List 1 row to save one background request.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aponcedeleonch added a commit that referenced this pull request Sep 17, 2026
…for the salt

Addresses three non-blocking findings from the PR #1573 review.

retentionDenyPrefixes and breakpointSupportPrefixes held the same two values in
two literals. They are one documented event read from two sides: at GPT-5.6,
explicit breakpoints arrived AND prompt_cache_retention was deprecated. ADR 0346
decision 2 already claims this table is reused, so the code now matches the ADR
rather than the ADR being edited down to the code. explicitCacheModelPrefixes is
denied on by retentionFor and allowed on by supportsExplicitBreakpoint.

TestCacheSemanticsCutoverIsOneList asserts the two sides PER MODEL rather than
as two independent tables, because two separate lists would pass a test that
checked each side alone, and that is the divergence being prevented.

The CacheDialect type and CacheDialectOpenRouter comments still described the
request-root cache_control field this PR retired. They now state what each
dialect actually emits, and say that the ask for a cache moved to the separate
WithPromptCacheBreakpoints Option. TestCacheDialectOpenRouterSendsCacheControl-
NoRetention is renamed to SendsCacheKeyOnly: it was asserting the opposite of
its own name.

newPromptCacheKeySalt becomes crypto/rand.Text(), the stdlib's own constructor
for this. The hand-rolled read plus hex encode carried a documented fail-soft
branch for a crypto/rand read error, and since Go 1.24 that error cannot happen
(a failure is an unrecoverable crash, not a returned error), so the branch was
already dead and the comment promised a degradation the code could not perform.
The salt test drops its hex-length assertion for an entropy floor, since
rand.Text documents its length as subject to change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aponcedeleonch added a commit that referenced this pull request Sep 17, 2026
Two corrections to the prompt-cache section, one from the PR #1573 review and
one that this PR's own prompt_cached fix made necessary.

The page said --no-prompt-cache is the right setting for a deployment relying on
a zero-retention arrangement. It is not sufficient: provider/anthropic emits the
StablePrefix cache_control breakpoint unconditionally, explicitly outside
WithConversationCaching, so a Messages endpoint is still asked to retain the
system prefix. Such a deployment needs the flag AND a route that avoids the
Messages providers, which the page now names.

The no-cache marker paragraph said no row is marked with default settings. That
is no longer true: the marker fires for a Claude model whose provider cannot ask
for a cache, and reporting prompt_cached honestly for Chat Completions entries
makes that reachable without any flag. The paragraph now describes both ways to
see it and what to do about it, which also makes the marker a live cost signal
rather than the near-vestigial one the PR body asked about.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aponcedeleonch
aponcedeleonch force-pushed the feat/openrouter-anthropic-prompt-caching branch from 078270b to 58e7a55 Compare September 17, 2026 16:26
aponcedeleonch added a commit that referenced this pull request Sep 17, 2026
…er protocol

Addresses the two blockers from the PR #1573 review, plus the two
composition-layer reuse findings that live in the same files.

Blocker 1: every Anthropic-protocol entry now gets a redirect-refusing HTTP
client. anthropic-sdk-go ships no cross-origin guard of its own (unlike
openai-go, whose guard makes the equivalent openai-path client a second layer),
so composition was the only layer that could refuse and it was not refusing.
Go's default client strips Authorization cross-origin but NOT x-api-key, which
is the header this protocol authenticates with, and never strips the body on a
307 re-send. Every one of these entries derives its base from
operator-overridable config, so the fix is in newAnthropicEntryFor rather than
at the openrouter-anthropic call site: it closes the same gap on the plain
anthropic entry and a future caller cannot forget it. It is prepended before
extra, so the gateway entries' own bearer-injecting clients still win.

TestADR_0346_AnthropicProtocolEntryRefusesRedirect drives both the shared
.provider and a remint. Its bare-adapter control asserts the unwired adapter
DOES follow, so the test cannot go vacuous if the SDK later grows a guard.
Removing the fix makes it report the leak concretely: X-Api-Key travelled to
the redirect target on both mints.

Blocker 2: prompt_cached was true for any registered provider, which was wrong
for Chat Completions. openaichat has no breakpoint mechanism (ADR 0346's fix is
a Responses field) and openaichatCacheDialectFor returns None for every
registered id, so opencode and every custom api_flavor:
openai-chat-completions definition send no cache ask at all. Reporting true
there recreated exactly the ADR 0100 failure the signal exists to expose: a
provider silently re-paying full input every turn, indistinguishable in the
picker from one that caches. promptCacheSource likewise claimed "responses
breakpoint" for an entry that does not speak Responses.

The anthropicProtocol bool becomes a three-value providerProtocol enum
mirroring permconfig's api_flavor vocabulary, because Chat Completions answers
this question differently from BOTH siblings and a second bool would encode an
impossible fourth state. Its zero value is the Responses arm, so every
hand-built providerEntry literal keeps today's behaviour.

The Chat Completions arm still reports true under the canonical-OpenAI dialect,
where the endpoint caches implicitly with nothing sent, so it must not be
simplified to "chat completions never caches" —
TestADR_0346_ChatCompletionsUnderCanonicalOpenAIDialectStillCaches pins that.

Also: openRouterAnthropicBaseURL now delegates to deriveGatewayBaseURL with an
empty segment rather than reimplementing its sanitisation, and the two
OpenRouter surfaces share one lister value. The existing derivation table
passes unchanged as the no-behaviour-change proof. The shared lister does not
dedupe the pair's two GETs per refresh pass; a cached fetch was considered and
declined, because it would add an outlives-a-call resource requiring an
ADR 0027 List 1 row to save one background request.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aponcedeleonch added a commit that referenced this pull request Sep 17, 2026
…for the salt

Addresses three non-blocking findings from the PR #1573 review.

retentionDenyPrefixes and breakpointSupportPrefixes held the same two values in
two literals. They are one documented event read from two sides: at GPT-5.6,
explicit breakpoints arrived AND prompt_cache_retention was deprecated. ADR 0346
decision 2 already claims this table is reused, so the code now matches the ADR
rather than the ADR being edited down to the code. explicitCacheModelPrefixes is
denied on by retentionFor and allowed on by supportsExplicitBreakpoint.

TestCacheSemanticsCutoverIsOneList asserts the two sides PER MODEL rather than
as two independent tables, because two separate lists would pass a test that
checked each side alone, and that is the divergence being prevented.

The CacheDialect type and CacheDialectOpenRouter comments still described the
request-root cache_control field this PR retired. They now state what each
dialect actually emits, and say that the ask for a cache moved to the separate
WithPromptCacheBreakpoints Option. TestCacheDialectOpenRouterSendsCacheControl-
NoRetention is renamed to SendsCacheKeyOnly: it was asserting the opposite of
its own name.

newPromptCacheKeySalt becomes crypto/rand.Text(), the stdlib's own constructor
for this. The hand-rolled read plus hex encode carried a documented fail-soft
branch for a crypto/rand read error, and since Go 1.24 that error cannot happen
(a failure is an unrecoverable crash, not a returned error), so the branch was
already dead and the comment promised a degradation the code could not perform.
The salt test drops its hex-length assertion for an entropy floor, since
rand.Text documents its length as subject to change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aponcedeleonch added a commit that referenced this pull request Sep 17, 2026
Two corrections to the prompt-cache section, one from the PR #1573 review and
one that this PR's own prompt_cached fix made necessary.

The page said --no-prompt-cache is the right setting for a deployment relying on
a zero-retention arrangement. It is not sufficient: provider/anthropic emits the
StablePrefix cache_control breakpoint unconditionally, explicitly outside
WithConversationCaching, so a Messages endpoint is still asked to retain the
system prefix. Such a deployment needs the flag AND a route that avoids the
Messages providers, which the page now names.

The no-cache marker paragraph said no row is marked with default settings. That
is no longer true: the marker fires for a Claude model whose provider cannot ask
for a cache, and reporting prompt_cached honestly for Chat Completions entries
makes that reachable without any flag. The paragraph now describes both ways to
see it and what to do about it, which also makes the marker a live cost signal
rather than the near-vestigial one the PR body asked about.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
aponcedeleonch and others added 6 commits September 17, 2026 19:30
…e vendor

Implements the ADR 0346 acceptance plan.

Emits one prompt_cache_breakpoint on an input_text block of every Responses
request, governed only by --no-prompt-cache, and retires OpenRouter's root
cache_control. Explicit breakpoints are additive to implicit caching by
specification, so one marker is always legal: an implicit cacher gets both, an
explicit-ask upstream gets the ask, and an endpoint that does not implement the
field ignores it. No vendor is ever consulted, so a future provider with
Anthropic's semantics is covered with no code change.

The failure direction is what makes that affordable. The breakpoint is part of
the Responses protocol, so a wrong guess is an ignored field; root cache_control
was an OpenRouter extension, so a wrong guess was a 400 and therefore a hard
outage under llmresilience's non-retryable-4xx rule.

Also adds openrouter-anthropic (native Messages, four breakpoints plus a TTL
where the ids are shared), narrows the sibling default redirect to the OpenRouter
pair, salts prompt_cache_key per process, refuses redirects on generic
openai-compat entries, and reports the resolved cache posture once per build.

Two details worth knowing for review.

The breakpoint switch is deliberately SEPARATE from the cache dialect. Gating it
on the dialect reproduces the exact bug being fixed, because composition
resolves every unrecognised endpoint — the ToolHive gateway included — to
CacheDialectNone, which is precisely where an explicit-ask upstream has no other
way to ask. An earlier revision had that wrong;
TestADR_0346_BreakpointNotGatedOnDialect is the regression guard.

The marker param must set Mode explicitly. The field is omitzero and its struct
holds only a constant, so a zero-value literal marshals to nothing and the
marker silently vanishes.

The ToolHive sibling redirect is dropped on measured evidence: that gateway
exposes one Claude Opus 4.8 as anthropic/claude-opus-4.8, claude-opus-4-8 and
us.anthropic.claude-opus-4-8 depending on the downstream route, so a
provider-only switch cannot resolve. The breakpoint covers that case instead.

prompt_cached now reports whether mecatl ASKS for caching, since "this endpoint
emits nothing" no longer exists; whether an upstream honours the ask is not
statically knowable.

Relates to #1558

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The field's documentation described the world before decision 1. It said false
marks "an Anthropic model on an OpenAI-Responses endpoint whose dialect is
None" — the exact case this ADR eliminated by detaching the breakpoint from the
dialect. promptCachedFor now returns false only for PromptCacheDisabled or an
unregistered provider, and projectAll iterates reg.Available(), so false means
one thing: the server was started with --no-prompt-cache.

That matters beyond tidiness because prompt_cached is published contract
documentation. An SDK consumer implementing field 7 against the old comment
would render "this endpoint cannot cache" for a harness-wide switch. The
rewrite says what mecatl knows (it ASKED) and admits what it cannot know
(whether the upstream honoured it), and records the Anthropic-scoping
convention so a client does not mark every row under a global disable.

Comment-only: no wire change, no field renumbering. contracts/gen and
sdk/typescript are regenerated via buf, never hand-edited.

The same drift had reached three internal comments, fixed here rather than
left to rot next to the corrected one: client.ModelInfo.PromptCached,
modelCapSegments (which also now records WHY the marker is worth an in-screen
signal — a connect-mode mecatui never passed the flag, and the posture line
goes to the log file), and the openrouter test's claim that the canonical
Responses endpoint receives a root cache_control, which decision 3 retired.

The picker fixture is retargeted onto the reachable state. uncachedModels
previously built one non-caching toolhive row beside two caching ones, which
composition can no longer emit, since the flag behind false is harness-wide.
Every row now reports false, and a new assertion pins the scoping half that was
never covered: the SAME disabled posture leaves the gpt-5 row unmarked. Guarded
against vacuity — forcing modelLooksAnthropic true fails it on found=true
marked=true. markedRowsFor exists because the legend line contains "no-cache"
too, so a whole-view Contains cannot tell a marked row from its explanation.

Test doc comments cited AC2.5 and a nonexistent AC2.6; the plan files these
under AC3.4 and AC3.5. Test NAMES are left alone deliberately: the approved
acceptance plan cites them verbatim in its verify lines, so renaming would
break traceability in a PR that is not this one.

Relates to #1558

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…er protocol

Addresses the two blockers from the PR #1573 review, plus the two
composition-layer reuse findings that live in the same files.

Blocker 1: every Anthropic-protocol entry now gets a redirect-refusing HTTP
client. anthropic-sdk-go ships no cross-origin guard of its own (unlike
openai-go, whose guard makes the equivalent openai-path client a second layer),
so composition was the only layer that could refuse and it was not refusing.
Go's default client strips Authorization cross-origin but NOT x-api-key, which
is the header this protocol authenticates with, and never strips the body on a
307 re-send. Every one of these entries derives its base from
operator-overridable config, so the fix is in newAnthropicEntryFor rather than
at the openrouter-anthropic call site: it closes the same gap on the plain
anthropic entry and a future caller cannot forget it. It is prepended before
extra, so the gateway entries' own bearer-injecting clients still win.

TestADR_0346_AnthropicProtocolEntryRefusesRedirect drives both the shared
.provider and a remint. Its bare-adapter control asserts the unwired adapter
DOES follow, so the test cannot go vacuous if the SDK later grows a guard.
Removing the fix makes it report the leak concretely: X-Api-Key travelled to
the redirect target on both mints.

Blocker 2: prompt_cached was true for any registered provider, which was wrong
for Chat Completions. openaichat has no breakpoint mechanism (ADR 0346's fix is
a Responses field) and openaichatCacheDialectFor returns None for every
registered id, so opencode and every custom api_flavor:
openai-chat-completions definition send no cache ask at all. Reporting true
there recreated exactly the ADR 0100 failure the signal exists to expose: a
provider silently re-paying full input every turn, indistinguishable in the
picker from one that caches. promptCacheSource likewise claimed "responses
breakpoint" for an entry that does not speak Responses.

The anthropicProtocol bool becomes a three-value providerProtocol enum
mirroring permconfig's api_flavor vocabulary, because Chat Completions answers
this question differently from BOTH siblings and a second bool would encode an
impossible fourth state. Its zero value is the Responses arm, so every
hand-built providerEntry literal keeps today's behaviour.

The Chat Completions arm still reports true under the canonical-OpenAI dialect,
where the endpoint caches implicitly with nothing sent, so it must not be
simplified to "chat completions never caches" —
TestADR_0346_ChatCompletionsUnderCanonicalOpenAIDialectStillCaches pins that.

Also: openRouterAnthropicBaseURL now delegates to deriveGatewayBaseURL with an
empty segment rather than reimplementing its sanitisation, and the two
OpenRouter surfaces share one lister value. The existing derivation table
passes unchanged as the no-behaviour-change proof. The shared lister does not
dedupe the pair's two GETs per refresh pass; a cached fetch was considered and
declined, because it would add an outlives-a-call resource requiring an
ADR 0027 List 1 row to save one background request.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…for the salt

Addresses three non-blocking findings from the PR #1573 review.

retentionDenyPrefixes and breakpointSupportPrefixes held the same two values in
two literals. They are one documented event read from two sides: at GPT-5.6,
explicit breakpoints arrived AND prompt_cache_retention was deprecated. ADR 0346
decision 2 already claims this table is reused, so the code now matches the ADR
rather than the ADR being edited down to the code. explicitCacheModelPrefixes is
denied on by retentionFor and allowed on by supportsExplicitBreakpoint.

TestCacheSemanticsCutoverIsOneList asserts the two sides PER MODEL rather than
as two independent tables, because two separate lists would pass a test that
checked each side alone, and that is the divergence being prevented.

The CacheDialect type and CacheDialectOpenRouter comments still described the
request-root cache_control field this PR retired. They now state what each
dialect actually emits, and say that the ask for a cache moved to the separate
WithPromptCacheBreakpoints Option. TestCacheDialectOpenRouterSendsCacheControl-
NoRetention is renamed to SendsCacheKeyOnly: it was asserting the opposite of
its own name.

newPromptCacheKeySalt becomes crypto/rand.Text(), the stdlib's own constructor
for this. The hand-rolled read plus hex encode carried a documented fail-soft
branch for a crypto/rand read error, and since Go 1.24 that error cannot happen
(a failure is an unrecoverable crash, not a returned error), so the branch was
already dead and the comment promised a degradation the code could not perform.
The salt test drops its hex-length assertion for an entropy floor, since
rand.Text documents its length as subject to change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two corrections to the prompt-cache section, one from the PR #1573 review and
one that this PR's own prompt_cached fix made necessary.

The page said --no-prompt-cache is the right setting for a deployment relying on
a zero-retention arrangement. It is not sufficient: provider/anthropic emits the
StablePrefix cache_control breakpoint unconditionally, explicitly outside
WithConversationCaching, so a Messages endpoint is still asked to retain the
system prefix. Such a deployment needs the flag AND a route that avoids the
Messages providers, which the page now names.

The no-cache marker paragraph said no row is marked with default settings. That
is no longer true: the marker fires for a Claude model whose provider cannot ask
for a cache, and reporting prompt_cached honestly for Chat Completions entries
makes that reachable without any flag. The paragraph now describes both ways to
see it and what to do about it, which also makes the marker a live cost signal
rather than the near-vestigial one the PR body asked about.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
AC1.7 and AC2.3 were the two criteria the PR body self-flagged as unverified.
Both are offline and drive the REAL adapters (providerConstructor nil).

AC1.7 is the headline of ADR 0346 end to end. The endpoint is an
operator-overridden base URL, which resolves to CacheDialectNone: the exact
deployment shape the reported incident came from, and the case that previously
got no cache ask at all. Two turns on one session, because breakpointIndex
deliberately marks nothing before a prior assistant turn exists. It asserts turn
1 carries no breakpoint, turn 2 does, and turn 2's cached_tokens surfaces as
non-zero CacheReadTokens on EvResult — that last one is what makes it an e2e
rather than a marshalling test, since it walks the upstream's reported figure
through the adapter's usage mapping out to the client-visible event.

Restoring the pre-ADR-0346 dialect gate makes it fail on exactly the right
assertion ("turn 2 carried NO prompt_cache_breakpoint on a dialect-less
endpoint"), so it is a real regression guard for the bug and not just a
description of current behaviour.

AC2.3 covers the TTL, which is the concrete reason one OpenRouter credential
registers a second Messages-speaking provider at all: the Responses protocol
cannot express a cache lifetime. It drives a request with a layered system
prompt and a multi-turn conversation, because driveStream's single bare message
fires only the top-level marker and one marker cannot distinguish "stamped
uniformly" from "stamped once and missed the rest". That shape spreads three
markers across system[], messages[] and the request root. Both directions are
asserted: the flag set stamps the TTL on every marker, and the flag unset emits
no ttl key rather than hardcoding the API default.

The body walkers read decoded JSON rather than calling the adapters' own
helpers, so the wire assertions are not circular with their producers.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aponcedeleonch
aponcedeleonch force-pushed the feat/openrouter-anthropic-prompt-caching branch from 58e7a55 to 49c7cd8 Compare September 17, 2026 16:34

@jhrozek jhrozek 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.

All 8 findings from the earlier review (redirect protection on the new openrouter-anthropic entry, promptCachedFor's protocol-blind check, the reimplemented deriveGatewayBaseURL, the duplicate OpenRouter lister, the duplicated breakpoint-prefix list, stale doc comments, the --no-prompt-cache zero-retention doc claim, and the crypto/rand.Text() advisory) were addressed in 199e40c / c1a2c7e / 8bde313, verified directly against the current code, with the corresponding tests (TestADR_0346_*, TestCacheSemanticsCutoverIsOneList, TestCacheDialectOpenRouterSendsCacheKeyOnly) passing.

Also manually verified against a live OpenRouter key:

  • openrouter-anthropic registers and lists Anthropic-only models (27 vs 445 on plain openrouter).
  • prompt_cached: true is now reported correctly for Claude rows on both openrouter and openrouter-anthropic — the actual bug this PR fixes (#1558).
  • --no-prompt-cache correctly suppresses the marker and logs forced off by --no-prompt-cache for all four provider entries.

Approving.

@aponcedeleonch
aponcedeleonch merged commit 2eba2cc into main Sep 18, 2026
62 of 64 checks passed
@aponcedeleonch
aponcedeleonch deleted the feat/openrouter-anthropic-prompt-caching branch September 18, 2026 07:29
This was referenced Sep 21, 2026
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.

Prompt caching is silently off for Claude/Qwen on every OpenAI-Responses endpoint except canonical OpenRouter

2 participants