gateway: a relayed Claude run keeps its cache as long as the request's own marks ask (Linka)
v0.1.3247 (dbc74414b) gave a bridge run the prompt-cache TTL of the user's pick, but read it only on the machine the relay runs on: its env, settings.json's env, then promptCacheTtl. A Docker magpie has none of them, so it fell back to 1h while the Mac it serves was set to 5m. The Mac's pick reaches the remote only as the cache marks its Claude Code puts on the request. A new run's TTL is now picked by runTTLFor: 1. FORCE_PROMPT_CACHING_5M on this computer: 5m, as Claude Code does. 2. The request's own marks: the longest TTL on its tools, system, messages or the request itself (askedCacheTTL, Request.askedTTL). 3. claudeRunTTL: this computer's CLAUDE_CODE_PROMPT_CACHE_TTL or promptCacheTtl. 4. 1h, only for a request with no marks (Chat, Responses clients). The run started from a saved transcript (replaySession) follows it too. Warmup and usage runs have no request and keep claudeRunTTL (cleanClaudeEnv). Linka's FORCE_PROMPT_CACHING_5M=1 workaround keeps working. Docs: claude-subscription-bridge.md. Tests: four new cases in TestClaudeRunKeepsTheUsersCacheTTL (the child's env and the first message's marks): client 5m with nothing set here; client 5m over this computer's 1h; client 1h over its 5m; forced 5m over client 1h. New TestAskedCacheTTL with bodies shaped like Claude Code's (billing line, marked system blocks, the last message marked). Run on mote: go vet ./internal/gateway for darwin, linux and windows; gofmt clean; go test -count=1 -timeout 45m ./internal/gateway: ok (958.9s), at base578053d6a. Broken by hand: startRun back on claudeRunTTL(os.Environ()), three of the four new cases red (client 5m, 5m over 1h, 1h over 5m); the forced case passes on the old code too, as it should. Not tried: a real request through a real Docker magpie. Linka's other ask, a settings UI for the remote's built-in Claude Code and the Agents page not detecting it, is not addressed here. Reported-by: Linka
This commit is contained in:
@@ -704,6 +704,19 @@ lifetime it started with (`cachePrefix.ttl`; one saved before it was kept
|
||||
is an hour's). Until 11-07 every run was given 1h whatever the pick
|
||||
(linkaww). `TestClaudeRunKeepsTheUsersCacheTTL`.
|
||||
|
||||
A new run (and one started from a transcript, `replaySession`) picks its
|
||||
lifetime with `runTTLFor`: `FORCE_PROMPT_CACHING_5M` on this computer
|
||||
gives 5m, as Claude Code does; else the request's own marks decide, the
|
||||
longest TTL marked on its tools, system, messages or the request itself
|
||||
(`askedCacheTTL`, `Request.askedTTL`); else `claudeRunTTL` as above. A
|
||||
client's Claude Code marks as its own user picked, 5m unless asked for an
|
||||
hour, so a remote magpie (Docker, another machine) follows the client's
|
||||
pick, not its own settings, which the client's never reach. Chat and
|
||||
Responses requests carry no marks and keep `claudeRunTTL`; warmup and
|
||||
usage runs have no request and keep it too (`cleanClaudeEnv`). Up to
|
||||
v0.1.3255, a remote relay wrote an hour's cache for a Mac set to 5m
|
||||
(Linka). `TestAskedCacheTTL`.
|
||||
|
||||
## Client-placed cache marks (#1717)
|
||||
|
||||
A client can send `X-Magpie-Cache-Marks: client` on a `/v1/messages`
|
||||
|
||||
@@ -156,6 +156,9 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
|
||||
}
|
||||
r := &Request{Model: a.Model, System: stringOrText(a.System), MaxTokens: a.MaxTokens,
|
||||
Temp: a.Temperature, TopP: a.TopP, Stop: a.StopSequences, Stream: a.Stream, Fast: a.Speed == "fast"}
|
||||
if !facts {
|
||||
r.askedTTL = askedCacheTTL(&a)
|
||||
}
|
||||
if clientMarks {
|
||||
var err error
|
||||
r.clientCache, err = readClientCache(a)
|
||||
|
||||
@@ -103,6 +103,62 @@ func cacheTTL(cc map[string]string) string {
|
||||
return cc["ttl"]
|
||||
}
|
||||
|
||||
// askedCacheTTL is the longest TTL a Messages request's own cache marks
|
||||
// ask for, on its tools, its system, its messages or the request itself,
|
||||
// "" for one that marks nothing. A Claude bridge run started for it keeps
|
||||
// its cache that long (runTTLFor): the client's Claude Code marks as its
|
||||
// user picked, an hour only when asked (Linka, a Docker magpie's relay
|
||||
// writing an hour's cache for a Mac set to 5m).
|
||||
func askedCacheTTL(a *aRequest) string {
|
||||
ttl := ""
|
||||
take := func(raw json.RawMessage) {
|
||||
if len(raw) == 0 || ttl == "1h" {
|
||||
return
|
||||
}
|
||||
var cc map[string]string
|
||||
if json.Unmarshal(raw, &cc) != nil {
|
||||
return
|
||||
}
|
||||
switch t := cacheTTL(cc); t {
|
||||
case "5m", "1h":
|
||||
if ttl == "" || t == "1h" {
|
||||
ttl = t
|
||||
}
|
||||
}
|
||||
}
|
||||
take(a.CacheControl)
|
||||
for _, t := range a.Tools {
|
||||
take(t.CacheControl)
|
||||
}
|
||||
if bytes.Contains(a.System, cacheControlField) {
|
||||
var system []struct {
|
||||
CacheControl json.RawMessage `json:"cache_control"`
|
||||
}
|
||||
if json.Unmarshal(a.System, &system) == nil {
|
||||
for _, b := range system {
|
||||
take(b.CacheControl)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range a.Messages {
|
||||
if ttl == "1h" {
|
||||
break
|
||||
}
|
||||
if !bytes.Contains(m.Content, cacheControlField) {
|
||||
continue
|
||||
}
|
||||
var blocks []struct {
|
||||
CacheControl json.RawMessage `json:"cache_control"`
|
||||
}
|
||||
if json.Unmarshal(m.Content, &blocks) == nil {
|
||||
for _, b := range blocks {
|
||||
take(b.CacheControl)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ttl
|
||||
}
|
||||
|
||||
func renderedCacheBlock(b aBlock) bool {
|
||||
switch b.Type {
|
||||
case "text":
|
||||
|
||||
@@ -51,9 +51,16 @@ func TestClaudeInstructionsCachedApart(t *testing.T) {
|
||||
// requests wrote an hour's cache.
|
||||
func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, settings, env, force, want string
|
||||
name, settings, env, force, marks, want string
|
||||
}{
|
||||
{name: "nothing picked", want: "1h"},
|
||||
// the client's own marks: its Claude Code marks as its user
|
||||
// picked, five minutes by default (Linka: a Docker magpie's
|
||||
// relay wrote an hour's cache for a Mac set to 5m)
|
||||
{name: "client marks 5m", marks: `{"type":"ephemeral"}`, want: "5m"},
|
||||
{name: "client marks 5m over this computer's 1h", marks: `{"type":"ephemeral","ttl":"5m"}`, settings: `{"promptCacheTtl":"1h"}`, want: "5m"},
|
||||
{name: "client marks 1h over this computer's 5m", marks: `{"type":"ephemeral","ttl":"1h"}`, settings: `{"promptCacheTtl":"5m"}`, want: "1h"},
|
||||
{name: "forced 5m over client marks 1h", marks: `{"type":"ephemeral","ttl":"1h"}`, force: "1", want: "5m"},
|
||||
{name: "agents page 5m", settings: `{"promptCacheTtl":"5m"}`, want: "5m"},
|
||||
{name: "agents page 1h", settings: `{"promptCacheTtl":"1h"}`, want: "1h"},
|
||||
{name: "settings env", settings: `{"env":{"CLAUDE_CODE_PROMPT_CACHE_TTL":"5m"},"promptCacheTtl":"1h"}`, want: "5m"},
|
||||
@@ -76,6 +83,9 @@ func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) {
|
||||
if c.force != "" {
|
||||
t.Setenv("FORCE_PROMPT_CACHING_5M", c.force)
|
||||
}
|
||||
if c.marks != "" {
|
||||
h.extra = `"cache_control":` + c.marks + `,`
|
||||
}
|
||||
h.ask("rules", "hello", "next")
|
||||
runs := h.runs()
|
||||
if len(runs) != 1 {
|
||||
@@ -101,6 +111,28 @@ func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The TTL a Messages request asks for is its longest mark's, wherever it
|
||||
// is: Claude Code marks its system blocks and its last message (Linka).
|
||||
func TestAskedCacheTTL(t *testing.T) {
|
||||
for _, c := range []struct{ body, want string }{
|
||||
{`{"model":"m","messages":[{"role":"user","content":"hi"}]}`, ""},
|
||||
{`{"model":"m","system":"rules","messages":[{"role":"user","content":"cache_control"}]}`, ""},
|
||||
{`{"model":"m","system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.319"},{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral"}}]}]}`, "5m"},
|
||||
{`{"model":"m","system":[{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, "1h"},
|
||||
{`{"model":"m","tools":[{"name":"read","input_schema":{},"cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral"}}]}]}`, "1h"},
|
||||
{`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, "1h"},
|
||||
{`{"model":"m","cache_control":{"type":"ephemeral"},"messages":[{"role":"user","content":"hi"}]}`, "5m"},
|
||||
} {
|
||||
req, err := parseAnthropic([]byte(c.body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.askedTTL != c.want {
|
||||
t.Errorf("%s: %q, want %q", c.body, req.askedTTL, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code's system prompt begins with a billing line whose hash follows
|
||||
// the request's first user message. Its auto mode classifier sends the same
|
||||
// policy with another transcript each time: with the line kept, no check's
|
||||
|
||||
@@ -97,8 +97,8 @@ func replaySession(dirs []string, work, model string, req *Request) *savedSessio
|
||||
}
|
||||
log.Printf("claude: a new Claude Code goes on with the conversation from a transcript of it (%d messages, %d images), typed the last turn's %d", split, countImages(req.Messages[:split]), len(req.Messages)-split)
|
||||
// its first message has no marks: the run keeps its cache as the user
|
||||
// picked (claudeRunTTL)
|
||||
return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true, appended: req.appendPrompt, cachePrefix: cachePrefix{ttl: claudeRunTTL(os.Environ())}}
|
||||
// picked (runTTLFor)
|
||||
return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true, appended: req.appendPrompt, cachePrefix: cachePrefix{ttl: runTTLFor(req, os.Environ())}}
|
||||
}
|
||||
|
||||
// replyWords is what a reply says, its thinking left out.
|
||||
|
||||
@@ -1167,7 +1167,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
prefix = from.cachePrefix
|
||||
prompt = renderClaudeTurn(req.Messages[len(req.Messages)-len(from.since):], req.Tools)
|
||||
} else {
|
||||
req.cacheTTL = claudeRunTTL(os.Environ())
|
||||
req.cacheTTL = runTTLFor(req, os.Environ())
|
||||
prompt, err = renderClaudePrompt(req)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
@@ -3499,6 +3499,22 @@ func inClaudeDir(env []string, configDir string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func forced(v string) bool { return v != "" && v != "0" && v != "false" }
|
||||
|
||||
// claudeForced5m: FORCE_PROMPT_CACHING_5M is set, in env or in Claude
|
||||
// Code's settings.json's env, as claudeRunTTL reads it.
|
||||
func claudeForced5m(env []string) bool {
|
||||
if v, _ := edit.GetJSON(filepath.Join(claudeConfigDir(), "settings.json"), "env.FORCE_PROMPT_CACHING_5M"); v != "" {
|
||||
return forced(v)
|
||||
}
|
||||
for _, e := range env {
|
||||
if v, ok := strings.CutPrefix(e, "FORCE_PROMPT_CACHING_5M="); ok {
|
||||
return forced(v)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// claudeRunTTL is how long the prompt cache of a bridge's Claude Code run
|
||||
// is kept, "5m" or "1h": the user's own pick for Claude Code's main
|
||||
// conversation, as Claude Code resolves it (FORCE_PROMPT_CACHING_5M, then
|
||||
@@ -3521,7 +3537,7 @@ func claudeRunTTL(env []string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if v := envOf("FORCE_PROMPT_CACHING_5M"); v != "" && v != "0" && v != "false" {
|
||||
if forced(envOf("FORCE_PROMPT_CACHING_5M")) {
|
||||
return "5m"
|
||||
}
|
||||
if v := envOf("CLAUDE_CODE_PROMPT_CACHE_TTL"); v == "5m" || v == "1h" {
|
||||
@@ -3533,6 +3549,23 @@ func claudeRunTTL(env []string) string {
|
||||
return "1h"
|
||||
}
|
||||
|
||||
// runTTLFor is how long a bridge run started for req keeps its prompt
|
||||
// cache: five minutes when FORCE_PROMPT_CACHING_5M says so, as Claude Code
|
||||
// itself would; else what the request's own marks ask for, its client's
|
||||
// Claude Code marking as that computer's user picked, five minutes by
|
||||
// default (a remote magpie's relay was given the hour of its own setting,
|
||||
// never the Mac's, Linka); else, for a request with no marks, this
|
||||
// computer's pick or an hour (claudeRunTTL).
|
||||
func runTTLFor(req *Request, env []string) string {
|
||||
if claudeForced5m(env) {
|
||||
return "5m"
|
||||
}
|
||||
if req != nil && req.askedTTL != "" {
|
||||
return req.askedTTL
|
||||
}
|
||||
return claudeRunTTL(env)
|
||||
}
|
||||
|
||||
func cleanClaudeEnv(env []string) []string {
|
||||
return cleanClaudeEnvTTL(env, claudeRunTTL(env))
|
||||
}
|
||||
|
||||
@@ -179,6 +179,9 @@ type Request struct {
|
||||
// keeps its prompt cache (claudeRunTTL), which the marks magpie adds
|
||||
// follow (runMark); "" is an hour
|
||||
cacheTTL string
|
||||
// askedTTL is the longest TTL the request's own cache marks ask for
|
||||
// (askedCacheTTL), "" for one that marks nothing or came in another API
|
||||
askedTTL string
|
||||
// leanPrompt has the Claude bridge give the caller's instructions as
|
||||
// the run's system prompt, in place of Claude Code's (ClaudeLeanPrompt).
|
||||
leanPrompt bool
|
||||
|
||||
Reference in New Issue
Block a user