sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] harness-py: per-call ContextInjector reminders defeat implicit prompt caching (GPT-6 Luna on Bedrock)

Open Flolight opened this issue 1 month ago • 7 comments

Human Overview

On models whose provider caches implicitly by exact prompt prefix, with no explicit cachePoint (we observed it with us.openai.gpt-6-luna on Bedrock Converse), create_harness() gets almost no cache hits on multi-step tasks. The cause is the placement of the two built-in ContextInjector reminders (environment and todos): they are appended as a trailing block of the latest user message for one call only, so request N is never a prefix of request N+1. On Anthropic models this is harmless because the SDK places a cache point before the trailing block; on implicit-prefix caches it invalidates nearly everything after the system prompt.

Checks

  • [x] I have updated to the latest minor and patch version of Strands (strands-harness 0.1.2; strands-agents 1.57.1, latest is 1.57.2)
  • [x] I have checked the documentation and this is not expected behavior
  • [x] I have searched issues and there are no duplicates (related but distinct: #4176, #1140)

SDK Language

Python

Strands Version

strands-harness 0.1.2, strands-agents 1.57.1

Language Runtime Version

Python 3.12

Operating System

macOS (Apple silicon)

Installation Method

pip

Steps to Reproduce

  1. agent = create_harness(model="bedrock/us.openai.gpt-6-luna") (us-east-1), run any multi-step task with several tool calls, e.g. "fix the failing tests in this directory".
  2. Wrap botocore.client.BaseClient._make_api_call to log every Converse request, then compare consecutive requests.
  3. Sum cacheReadInputTokens against total input tokens from agent.event_loop_metrics.

Expected Behavior

As with a plain SDK Agent on the same model, each request is the previous request plus new content, so the implicit cache serves most of the input on later calls.

Actual Behavior

Every consecutive pair of requests diverges at 72-98% of the request length, at the position of the previous call's injected <system-reminder>. Measured over 3 runs per task (5 small coding/analysis tasks, 3 to 20 tool calls each), cache-read share of input:

Task Plain SDK Agent, CacheConfig(strategy="auto") create_harness() default Reminders moved (workaround below)
Fix 2 bugs until tests pass 69% 4% 92%
Rename a function across 7 files 72% 16% 91%
Analyse a 3.7 MB log file 47% 47% 87%

With the workaround, the harness's cost on these tasks fell 64-81% with the same pass rate. Moving only the environment block recovers about half; the todos reminder (trigger everyTurn) breaks the prefix from the first todo_write onward.

The same workaround makes no difference on us.anthropic.claude-sonnet-5-5, which already reads 87-93% from cache with the defaults.

Possible Solution

The comment in strands/injection/_message_injection.py notes that a trailing run "is the only placement a provider can keep out of its cached prefix", which holds for explicit-cache-point providers only. Options: make placement provider-aware (for implicit-prefix caches, fold per-session content such as environment into the system prompt once, and inject the todo list only when it changes), or expose a stable placement option on ContextInjector. A doc note on the harness caching page would help in the meantime.

Workaround we used, no patch:

from strands_harness import create_harness
from strands_harness.plugins.todos import Todos

class TodosNoReminder(Todos):
    def init_agent(self, agent):  # keep the todo_write tool, skip the per-call reminder
        pass

agent = create_harness(
    model="bedrock/us.openai.gpt-6-luna",
    builtin_plugins=[],
    plugins=[TodosNoReminder()],
    instructions="<environment>\nPlatform: ...\nDate: ...\nWorking directory: ...\n</environment>",
)

Happy to open a PR once you prefer an approach.

Related Issues

#4176 (cache-aware context manager), #1140 (caching for all models)

Flolight avatar Oct 05 '26 12:10 Flolight

I investigated this from the harness side and can confirm the mechanics: the environment and todos ContextInjectors re-render a trailing <system-reminder> block on every model call, so on implicit-prefix caches each request diverges from the previous one exactly at that position.

Before building a fix, I'd like to propose a concrete approach:

Make the harness injections cache-stable (harness-side only, no SDK changes):

  1. Environment block — fold the static part (platform, cwd, AGENTS.md, nearby links) into the system prompt once per session. Only the date changes per turn, so the prefix would bust at most once a day instead of every call. (I see the current docstring keeps the date out of the system prompt deliberately to protect the cached prefix on explicit-cache-point providers — for implicit-prefix providers the trailing block already busts everything after it, so the trade-off flips.)
  2. Todos reminder — inject only when the rendered list actually changes. Skipping identical re-injections preserves the prefix for free and is behavior-neutral for explicit-cache-point providers.

Both keep the first-call experience identical; they only remove redundant re-injection.

Does this direction sound right, or would you prefer the stable placement option on ContextInjector itself? Happy to implement whichever you prefer.

karmendra8386 avatar Oct 06 '26 18:10 karmendra8386

@strandly-the-agent can you test this? I think since we brought in model info, we switched to cache points for GPT 5.6+. This essentially helps all dynamic/temp context that is injected todos, memory, and so on.

These issues should be fixed, and I. think cache should be working properly. If so, we can close the issue.

mkmeral avatar Nov 18 '26 17:11 mkmeral

@mkmeral Tested on main (6e1d55b93, Python): not fully fixed, I wouldn't close yet. The cache points only apply on the Mantle/Responses route. The route in this issue, bedrock/us.openai.gpt-6-luna (Converse), still sends none, and with todos on it still reads almost nothing from cache.

Same task as the report (fix 2 bugs until tests pass), gpt-6-luna, us-east-1, cache-read share of input per run:

create_harness(...) Cache points sent Cache-read share
bedrock/…, defaults (environment only) 0 82%, 85%, 89%
bedrock/…, no reminders (control) 0 81%, 93%, 90%
bedrock/…, builtin_plugins=["environment", "todos"] 0 0%, 4%, 11%, 0%, 5%, 5%
bedrock-mantle/…, ["environment", "todos"] yes, one more each call 88%, 89%, 86%
  • Defaults are fine now, but because todos became opt-in (#5974), not because of cache points: the environment reminder breaks the prefix once per user turn, then every request is a pure append.
  • Any everyTurn injector on Converse-hosted GPT still breaks the prefix on every call (0 of 63 consecutive request pairs were a pure append). BedrockModel deliberately resolves openai.* to implicit caching (bedrock.py:142-143), and Converse rejects a cachePoint for this model outright, so there is no cache-point fix on that route.
  • Not tested: OpenAI direct (openai/…, same code path as Mantle) and the TS harness.

What's left is narrower than the original report: everyTurn reminders (todos) on Converse-hosted GPT. Routing bedrock/openai.gpt-* through Mantle in the harness would cover it; that call is yours.

Mechanism, per-call traces, probe output, script

Mechanism. ContextInjector now writes an injected block into history (#5977), and for models without temporary messages _render_injected_blocks sends only the latest user message's blocks and drops the earlier ones (strands/models/_model_proxy.py:195-200). So request N ends with the todo reminder and request N+1 no longer contains it at that position, which is the divergence the report describes. On Mantle the SDK puts a prompt_cache_breakpoint ahead of the reminder, so the cached prefix survives.

Per-call usage, one run each (kept = % of the previous request repeated verbatim from the start; Converse inputTokens excludes cached tokens, the Responses API includes them, and the shares above account for that):

bedrock/… + todos
  call  1 kept=None  todo=0 in=2 read=0 write=2517
  call  2 kept=97.6  todo=1 in=2 read=0 write=2662
  call  3 kept=98.4  todo=1 in=2 read=0 write=2891
  call  4 kept=98.5  todo=1 in=2 read=0 write=3426
  call  5 kept=98.7  todo=1 in=2 read=0 write=5072
  ...
  call 12 kept=99.4  todo=1 in=2 read=0 write=7503

bedrock/… defaults
  call  1 kept=None  env=1 in=2 read=0    write=2293
  call  2 kept=97.4  env=0 in=2 read=2207 write=731
  call  3 kept=100.0 env=0 in=2 read=2938 write=290
  call  4 kept=100.0 env=0 in=2 read=3228 write=830
  ...
  call  7 kept=100.0 env=0 in=2 read=4430 write=80

bedrock-mantle/… + todos
  call  1 kept=None  cp=1  in=5345 read=0    write=5214
  call  2 kept=97.5  cp=2  in=5464 read=5214 write=140
  call  3 kept=97.6  cp=3  in=5878 read=5354 write=414
  ...
  call 11 kept=98.7  cp=11 in=8620 read=8365 write=142

All 15 runs ended with the tests passing. One extra smoke run of the bedrock/… + todos arm before the batch read 57%: it kept re-reading one 4.2k-token prefix and never extended it. I can't explain that from prefix matching alone; Bedrock's implicit cache for GPT isn't documented at that level, so treat the shares as measured, not modelled.

Converse rejects cache points for this model:

boto3.client("bedrock-runtime", region_name="us-east-1").converse(
    modelId="us.openai.gpt-6-luna",
    messages=[{"role": "user", "content": [{"text": "Say hi."}, {"cachePoint": {"type": "default"}}]}],
)
# AccessDeniedException: You invoked an unsupported model or your request did not allow prompt caching.

Side observation. With the userTurn trigger the environment block (platform, date, cwd, AGENTS.md contents) is in the first request of a turn only; from the first tool result on, the model no longer receives it (env=0 above, both routes). That follows from #5977's "latest user message only" rule, so I assume it's intended; flagging it because it includes AGENTS.md.

Environment: strands-agents 1.65.1.dev50+g6e1d55b93, strands-harness 0.4.1.dev60+g6e1d55b93 (editable from main), Python 3.13, Linux. Fixture: a 2-module package with 2 planted bugs, 7 pytest tests, a 2-line AGENTS.md. Prompt: Fix the failing tests in this directory. plus Track your steps with todo_write. on the todos arms. Each run in a fresh copy of the fixture, as its own process.

Script (run from the fixture directory, python run_one.py <arm> out.json):

import copy, json, subprocess, sys

import botocore.client
from strands.models import BedrockModel
from strands.models.openai_responses import OpenAIResponsesModel
from strands_harness import create_harness

ARMS = {
    "converse-default": dict(model="bedrock/us.openai.gpt-6-luna"),
    "converse-todos": dict(model="bedrock/us.openai.gpt-6-luna", builtin_plugins=["environment", "todos"]),
    "converse-noreminders": dict(model="bedrock/us.openai.gpt-6-luna", builtin_plugins=[]),
    "mantle-todos": dict(model="bedrock-mantle/openai.gpt-6-luna", builtin_plugins=["environment", "todos"]),
}
PROMPT = "Fix the failing tests in this directory."
TODO_NUDGE = " Track your steps with todo_write."

arm, out_path = sys.argv[1], sys.argv[2]
requests, usages = [], []

_orig_api_call = botocore.client.BaseClient._make_api_call

def _logged_api_call(self, operation_name, api_params):
    if operation_name in ("Converse", "ConverseStream"):
        requests.append(copy.deepcopy({k: api_params.get(k) for k in ("toolConfig", "system", "messages")}))
    return _orig_api_call(self, operation_name, api_params)

botocore.client.BaseClient._make_api_call = _logged_api_call

_orig_format = OpenAIResponsesModel._format_request

def _logged_format(self, *args, **kwargs):
    request = _orig_format(self, *args, **kwargs)
    requests.append(copy.deepcopy({k: request.get(k) for k in ("tools", "instructions", "input")}))
    return request

OpenAIResponsesModel._format_request = _logged_format

def _log_usage(cls):
    orig = cls.stream

    async def stream(self, *args, **kwargs):
        async for event in orig(self, *args, **kwargs):
            if isinstance(event, dict) and "metadata" in event:
                usages.append(dict(event["metadata"].get("usage", {})))
            yield event

    cls.stream = stream

_log_usage(BedrockModel)
_log_usage(OpenAIResponsesModel)

config = ARMS[arm]
agent = create_harness(**config)
agent(PROMPT + (TODO_NUDGE if "todos" in config.get("builtin_plugins", []) else ""))
tests = subprocess.run([sys.executable, "-m", "pytest", "-q"], capture_output=True, text=True)

def diverge(a, b):
    n = min(len(a), len(b))
    return next((i for i in range(n) if a[i] != b[i]), n)

calls, previous = [], None
for index, request in enumerate(requests):
    text = json.dumps(request, default=str)
    calls.append({
        "call": index + 1,
        "main": bool(request.get("toolConfig") or request.get("tools")),  # False: memory-extraction side call
        "prev_request_kept_pct": None if previous is None else round(100 * diverge(previous, text) / len(previous), 1),
        "cache_points": text.count('"cachePoint"') + text.count("prompt_cache_breakpoint"),
        "has_environment_block": "<environment>" in text or "Working directory" in text,
        "has_todo_reminder": "Your current todo list" in text,
        "usage": usages[index] if index < len(usages) else {},
    })
    previous = text

json.dump({"arm": arm, "tests_pass": tests.returncode == 0, "calls": calls}, open(out_path, "w"), indent=1)

Share = cacheReadInputTokens / (inputTokens + cacheReadInputTokens + cacheWriteInputTokens) on Converse and cacheReadInputTokens / inputTokens on Mantle, over the calls with main=True.

Automated verification. A starting point, not a final determination.

strandly-the-agent avatar Nov 18 '26 18:11 strandly-the-agent

TL;DR: still reproduces with the default harness on bedrock/us.openai.gpt-6-luna (Converse, implicit caching), measured on main @ 6e1d55b93.

Three plain chat turns, session and memory off, one run per arm in separate processes. cacheRead tokens per turn:

Arm Turn 1 Turn 2 Turn 3
default harness (environment reminder on) 0 0 1730
builtin_plugins=[] (no reminder) 1730 2095 2141

With the reminder, the only read is the static tools + system prefix, and only from turn 3; the conversation is never read.

Filed from the same audit and related to this one:

  • #6339: the Responses adapters put per-call text before the tool output on the non-checkpoint path.
  • #6352: the reminder also carries the whole AGENTS.md, so that text is uncached on every turn.
  • A status note on #5802: GPT-5.6+ gets no breakpoints unless cache_config is passed.

strandly-the-agent avatar Nov 18 '26 21:11 strandly-the-agent

Following up on my investigation above (Oct 6) and today's retest: the Converse route is the remaining gap. The cache points cover Mantle/Responses, but on implicit-prefix caches the per-call reminder block still breaks the prefix, so request N is never a prefix of request N+1.

@jimbrub — happy to take the Converse-route fix if that's useful. I'd start from the reproduction and measurements in this thread and look at keeping consecutive requests prefix-stable on implicit caches without changing the Anthropic cachePoint behavior. If you're already mid-fix on this route, I'll stand down — just say so.

karmendra8386 avatar Nov 18 '26 22:11 karmendra8386

@strandly-the-agent once pr 6548 is ported to python, will this issue be ready to close?

jimbrub avatar Nov 25 '26 15:11 jimbrub

@jimbrub Not fully. The port takes this issue's worst case (an everyTurn reminder such as todos, on bedrock/us.openai.gpt-6-luna) from 0% cache reads to about 43%, against about 80% with no reminders.

I prototyped the port on Python main (d76bf8d08) by giving GPT-6 Luna the Nova placement rules that #6548 uses, then reran this issue's task live. Cache-read share of input per run:

create_harness(...) main port prototype
["environment", "todos"], tool-loop task 0%, 0%, 0% 41%, 45%, 43%
defaults (environment only), same task 71%, 72%, 76% 77%, 77%, 76%
defaults, 3 chat turns (tokens read per turn) 0 / 0 / 0 0 / 0 / ~2,250 of ~2,400
no reminders (control), same task 82%, 79%, 79% 86%, 82%
  • What the port fixes: the tools and system prompt are read on every call from the third on, and across user turns the conversation is read up to the previous user message.
  • What it can't fix: with an everyTurn reminder, nothing after the first user message is read inside a tool loop (a flat ~2.4k tokens per call). Converse rejects a cache point directly after a toolResult, so the reminder at the end of each tool-result message still breaks the prefix.

My suggestion: close after the port only if you accept that limit for everyTurn injectors on Converse and document it. Otherwise keep this open, narrowed to that case. The one lever left on Converse is keeping injected text in later requests, which #6221 is set up to benchmark. Mantle read 86 to 89% on the todos arm in my 11-18 run.

Per-call reads, request shapes, prototype patch, port notes, limits

Per-call cache reads, one run per arm

todos, main      reads 0 on all 12 calls                                   prompt 2461 -> 5559
todos, port      0 / 0 / 2380 / 2380 / 2380 / ... / 2380 (11 calls)        prompt 2468 -> 6601
defaults, main   0 / 0 / 2457 / 3630 / 4054 / 4256 / 4464                  prompt 2236 -> 5317
defaults, port   0 / 0 / 2448 / 3661 / 4092 / 4307 / 4467 / 4675           prompt 2237 -> 4923
no reminders     0 / 2156 / 2380 / 2927 / 4366 / 4518 / 4769 / 4981        prompt 2158 -> 5826
  • 25 runs are counted here: 3 per arm, except 2 for the prototype's no-reminders arm and 2 for a no-reminders chat control on main (0 / 2160 / 2242). Every task run ended with the tests passing.
  • With todos, 0 of 59 consecutive request pairs were a pure append (30 on main, 29 on the prototype). The port does not change what is sent, only where the points are.
  • One of the three prototype todos runs read 2,474 instead of ~2,380 from call 4 on. I can't tell from the token counts which boundary that is.

Request shapes the prototype sent

call 1   system:[text, CP]   user:[text, CP, reminder]
call 2+  system:[text, CP]   user:[text, CP]   ...   user:[toolResult..., reminder]
chat     system:[text, CP]   user:[text, CP]   user:[text, CP]   user:[text, CP, reminder]

These match what #6548 sends in TypeScript: no tools point, no TTL, and no point after a tool result. None was rejected.

Prototype patch

Two module functions in strands/models/bedrock.py, patched at run time, with nothing else changed:

import strands.models.bedrock as bedrock

def _gpt_cache_points(model_id: str) -> bool:
    return "openai.gpt-6-luna" in model_id.lower()

_limits, _info = bedrock._converse_limits_cache_points, bedrock._converse_cache_model_info
bedrock._converse_limits_cache_points = lambda model_id: _gpt_cache_points(model_id) or _limits(model_id)
bedrock._converse_cache_model_info = lambda model_id: (
    bedrock._CACHE_POINTS if _gpt_cache_points(model_id) else _info(model_id)
)

It has no fallback for a refused point, which the real port needs.

Method

  • Same script and share formula as my 11-18 comment, with two changes: session=False, memory=False on every arm, and a per-process nonce prepended to the system prompt and the first tool description, so no run reads another run's cache.
  • Fixture: a 2-module package with 2 planted bugs, 7 pytest tests and a 2-line AGENTS.md. Prompt: Fix the failing tests in this directory., plus Track your steps with todo_write. on the todos arm. Each run in a fresh copy, as its own process, us-east-1.
  • strands-agents 1.66.1.dev34+gd76bf8d08, strands-harness 0.5.1.dev33+gd76bf8d08, Python 3.13, Linux.

Notes for the port

  • The harness passes CacheConfig(strategy="auto", tools_ttl=True) to every Bedrock model (harness-py/src/strands_harness/models.py:230). Under the Nova rules that raises the this model accepts no tool-level cache point warning (bedrock.py:804), 5 to 6 times per task run in the prototype's logs.
  • Luna reads an explicit point only from the third call, where implicit caching without reminders reads on the second. I saw the same on raw Converse in the #6548 re-review, so it is a Bedrock behaviour and not the port's.

Limits

  • One model (us.openai.gpt-6-luna), one region, one small task with 7 to 12 calls per run. The flat read is a smaller share on longer loops: 30% by call 8 in the #6548 review, where tool results were about 1.2k tokens each.
  • The toolResult rejection and the Mantle figure come from my earlier runs (11-24 and 11-18), not from today.
  • The main column is lower than on 11-18 (defaults were 82 to 89% then) because reads now start one call later and each run is isolated by the nonce. Compare the columns with each other, not with the earlier dates.
  • A first batch of 19 runs without the nonce is discarded: main-arm runs read cache entries written by prototype runs with the same system prompt.
  • Usage: 308 Converse calls, about 1.2M prompt tokens across both batches. No AWS resources created.

strandly-the-agent avatar Nov 25 '26 16:11 strandly-the-agent