Franklin icon indicating copy to clipboard operation
Franklin copied to clipboard

Anthropic prompt caching emits 5 cache_control breakpoints (max 4) → HTTP 400 on multi-turn tool sessions

Open Zambala108 opened this issue 6 months ago • 0 comments

Anthropic prompt caching emits 5 cache_control breakpoints (max is 4) → HTTP 400 on multi-turn tool sessions

Summary

applyAnthropicPromptCaching() places up to 5 cache_control breakpoints on the request, but Anthropic allows a maximum of 4 (counted across system + tools + messages combined). Any conversation that has a system prompt, registered tools, and at least 3 non-system messages — i.e. essentially every normal multi-turn tool session — gets rejected:

HTTP 400: A maximum of 4 blocks with cache_control may be provided. Found 5.

The first turn or two succeed; once history reaches 3 messages it fails on every subsequent request. Retrying replays the same history, so the count stays at 5 and the session is hard-stuck (not transient).

Environment

  • Package: @blockrun/franklin
  • Version: 3.23.0
  • Location: applyAnthropicPromptCaching() in agent/llm.js (compiled; source likely src/agent/llm.ts)
  • Models affected: all Anthropic models (observed on anthropic/claude-opus-4.8)
  • Severity: High — breaks multi-turn tool use on Anthropic; unrecoverable via retry

Steps to reproduce

  1. Start a session on an Anthropic model with a non-empty system prompt and at least one registered tool.
  2. Exchange a few turns so the model calls a tool and the non-system message count reaches ≥ 3.
  3. The next request fails with HTTP 400 ... A maximum of 4 blocks with cache_control may be provided. Found 5.

Observed session output

Captured terminal output (the model produces one assistant turn, then every following request 400s; pressing "continue" replays the same history and fails identically):

Auto → anthropic/claude-opus-4.8
我先看看 Surf 有哪些事件/新闻类的数据端点,确认能拿到的字段和最早时间。
[COMPLEX] claude-opus-4.8 · 2 in / 98 out · $0.0025

Request failed
• Type: Unknown
• Message: HTTP 400: A maximum of 4 blocks with cache_control may be provided. Found 5.
[COMPLEX] claude-opus-4.8 · 2 in / 98 out · $0.0025

❯ 继续
Request failed
• Type: Unknown
• Message: HTTP 400: A maximum of 4 blocks with cache_control may be provided. Found 5.

Expected vs. actual

  • Expected: the request carries at most 4 cache_control breakpoints and is accepted.
  • Actual: it carries 5 and Anthropic returns HTTP 400.

Root cause

The function spends one breakpoint on system, one on the last tool, and three on the last three messages — 5 total:

Placement Breakpoints
system prompt 1
last tool definition 1
last 3 messages (rolling window) 3
Total 5 ❌ (limit is 4)
function applyAnthropicPromptCaching(payload, request) {
    const out = { ...payload };
    const cacheMarker = { type: 'ephemeral' };
    // 1. system → 1 breakpoint
    if (typeof request.system === 'string' && request.system.length > 0) {
        out['system'] = [
            { type: 'text', text: request.system, cache_control: cacheMarker },
        ];
    }
    // 2. tools → 1 breakpoint on the last tool
    if (request.tools && request.tools.length > 0) {
        const toolsCopy = request.tools.map(t => ({ ...t }));
        toolsCopy[toolsCopy.length - 1]['cache_control'] = cacheMarker;
        out['tools'] = toolsCopy;
    }
    // 3. messages → up to 3 breakpoints
    if (request.messages && request.messages.length > 0) {
        const messagesCopy = request.messages.map(m => ({ ...m }));
        const start = Math.max(0, messagesCopy.length - 3); // fixed 3, ignores budget already spent on system/tools
        for (let idx = start; idx < messagesCopy.length; idx++) {
            // ...marks one cache_control on each message from `start` to the end...
        }
        out['messages'] = messagesCopy;
    }
    return out;
}

The function's own docstring miscounts the budget:

Places 4 cache_control breakpoints (Anthropic's max): 1. System prompt; 2-4. Last 3 non-system messages. Also caches the last tool definition.

system(1) + last 3 messages(3) is indeed 4, but the last-tool breakpoint was not counted, making the real total 5. (The referenced system_and_3 pattern is system + last 3 = 4 exactly; adding tool caching on top pushes it over.)

Why the first turn works

Early on, messages.length < 3, so the rolling window only marks 1–2 messages and the total stays ≤ 4. Once history reaches 3 messages the window fills to 3 and the total becomes 5.

Proposed fix

Budget the breakpoints to a hard total of 4: spend system and the last tool first, then give the rolling message window only the remaining budget. This keeps behavior identical in every case except the previously-overflowing one (system + tool + ≥3 messages), where the message window shrinks from 3 to 2.

 function applyAnthropicPromptCaching(payload, request) {
     const out = { ...payload };
     const cacheMarker = { type: 'ephemeral' };
+    // Anthropic allows at most 4 cache_control breakpoints per request,
+    // counted across system + tools + messages combined. Spend system (1)
+    // and the last tool (1) first, then give the message window the rest.
+    const MAX_BREAKPOINTS = 4;
+    let used = 0;
     if (typeof request.system === 'string' && request.system.length > 0) {
         out['system'] = [
             { type: 'text', text: request.system, cache_control: cacheMarker },
         ];
+        used++;
     }
     if (request.tools && request.tools.length > 0) {
         const toolsCopy = request.tools.map(t => ({ ...t }));
         toolsCopy[toolsCopy.length - 1]['cache_control'] = cacheMarker;
         out['tools'] = toolsCopy;
+        used++;
     }
     if (request.messages && request.messages.length > 0) {
         const messagesCopy = request.messages.map(m => ({ ...m }));
-        const start = Math.max(0, messagesCopy.length - 3);
+        // Never exceed the remaining budget (nor the original window of 3).
+        const windowSize = Math.min(3, Math.max(0, MAX_BREAKPOINTS - used));
+        const start = Math.max(0, messagesCopy.length - windowSize);
         for (let idx = start; idx < messagesCopy.length; idx++) {
             /* ...unchanged... */
         }
         out['messages'] = messagesCopy;
     }
     return out;
 }

Please also update the "Places 4 cache_control breakpoints" docstring so the count includes the tool breakpoint.

Breakpoint counts after the fix

Scenario Before After
system + tool + 5 messages 5 ❌ 4 ✅
system + tool + 3 messages 5 ❌ 4 ✅
system + 3 messages (no tools) 4 4 ✅
tool + 3 messages (no system) 4 4 ✅
10 messages only 3 3 ✅
early turn: system + tool + 1 message 3 3 ✅

Suggested regression test

Add a unit test for applyAnthropicPromptCaching that builds a request with a system prompt, ≥1 tool, and ≥3 messages, then asserts the total number of blocks carrying cache_control (the system block + the marked tool + each marked message block) is ≤ 4. This worst-case path is currently uncovered.

Zambala108 avatar Jun 01 '26 00:06 Zambala108