cd /news/large-language-models/a-python-set-in-your-tool-list-can-b… · home › topics › large-language-models › article
[ARTICLE · art-182703] src=dev.to ↗ pub= topic=large-language-models verified=true sentiment=· neutral

A Python set in Your Tool List Can Break Prompt Caching on Every Restart

A developer demonstrated that building a Claude tool list from a Python set can silently break prompt caching, because string hashing is salted per process and set iteration order varies between interpreter runs. Running a script under different PYTHONHASHSEED values produced different SHA-256 digests of the serialized tools payload, meaning each new worker or restart can send a byte-different prompt prefix that misses the cache. The fix is to sort the set before converting it to a list, since json.dumps' sort_keys option does not reorder arrays.

recommendation

Sort any set-derived list before it enters a prompt prefix, and test across multiple PYTHONHASHSEED values, since two calls in one process share a seed and hide the bug.

more in playbook: Controlling LLM cost
by read10 min views5 publishedDec 6, 2026

A minute before the restart, the prefix was coming out of the cache. The worker comes back up with the same prompt, model and tools, and its first request reports cache_read_input_tokens at zero.

One candidate cause is two characters of Python: the { and } around your tool names. You wrote a set.

Python's reference says the hashes of str and bytes values are salted with an unpredictable random value: constant inside one process, unpredictable between runs. The same note adds that changing hash values affects the iteration order of sets, and that Python has never guaranteed that order. Claude's prompt cache needs the start of the prompt to be byte-for-byte identical to a recent request. If a set decides the order of anything in the prompt, each new process can send different bytes.

Save this as leaky.py:

import hashlib
import json

TOOL_NAMES = {
    "search_docs", "open_ticket", "close_ticket",
    "refund_order", "lookup_user", "escalate",
}

tools = [
    {
        "name": name,
        "description": f"Run {name}.",
        "input_schema": {"type": "object", "properties": {}},
    }
    for name in TOOL_NAMES
]

payload = json.dumps(tools, sort_keys=True)
print(hashlib.sha256(payload.encode()).hexdigest()[:12])

Run it under a few hash seeds. PYTHONHASHSEED set to an integer fixes the seed, so each line stands in for one process your deploy might start:

for seed in 1 2 3 4 5; do
  PYTHONHASHSEED=$seed python3 leaky.py
done

Compare the digests. Where two of them differ, the only thing that moved is the order of the tools. Now run it twice under one seed: same digest. A unit test that calls the builder twice in one process can't see the bug either, because both calls share one seed.

Look at sort_keys=True in that script. It sorts the keys of JSON objects. A list of tools is an array, and sort_keys leaves arrays alone. The same goes for an enum or required array inside a schema, if somebody built it with list(ALLOWED_TOPICS) from a set.

There is also a nasty route into this bug. json.dumps has no encoding for sets, so passing one raises TypeError. The obvious quick fix is list(the_set) or default=list. The error goes away, and the random order goes out on the wire.

For leaky.py, the repair is one line: for name in sorted(TOOL_NAMES). If you need the set elsewhere for membership checks, keep it, and sort it at the point where it becomes a list.

Uvicorn with --workers uses spawn instead of pre-fork, and spawn starts a fresh Python interpreter. Unless you set the seed, each worker draws its own. Workers on one machine can then build different prefixes, and each variant is its own cache entry.

Gunicorn uses a pre-fork model. A forked child is effectively identical to its parent, so its workers should inherit one seed and agree with each other. Then you restart the parent, and the whole group moves to a new order at once. Separate containers are separate interpreters, so replicas can disagree under either server.

You could export PYTHONHASHSEED=0 everywhere and watch the symptom go. The docs do list a cluster of processes sharing hash values as a use for the variable. But the same page says 0 disables hash randomization, which exists as protection against a denial-of-service attack on dict construction. It also leaves the prompt depending on an order the language never promised. A new Python build may change it again.

Same code, same tools, two processes. A set lets each one pick its own order.

It's easy to let the code that calls the LLM assemble the prompt on its way out. That puts the prompt on the wrong side of the boundary, where looking at it means mocking an SDK. Treat it as a return value of your own code and it becomes as testable as an invoice total.

Here is a core module that imports no SDK, reads no clock and reads no environment:

import hashlib
import json
from dataclasses import dataclass
from datetime import date
from typing import Any

@dataclass(frozen=True, slots=True)
class Tool:
    name: str
    description: "str"
    schema: dict[str, Any]

@dataclass(frozen=True, slots=True)
class Prefix:
    system: str
    tools_json: str

    def sha256(self) -> str:
        pair = json.dumps([self.system, self.tools_json])
        return hashlib.sha256(pair.encode()).hexdigest()

Two functions finish the module, one for each side of the cache breakpoint:

def build_prefix(
    instructions: str, tools: tuple[Tool, ...]
) -> Prefix:
    wire = [
        {
            "name": tool.name,
            "description": tool.description,
            "input_schema": tool.schema,
        }
        for tool in tools
    ]
    return Prefix(
        system=instructions,
        tools_json=json.dumps(wire, sort_keys=True),
    )

def user_message(
    question: str, today: date, request_id: str
) -> str:
    return (
        f"Date: {today.isoformat()}\n"
        f"Request: {request_id}\n\n"
        f"{question}"
    )

The date and the request id are arguments, and the only function that accepts them builds the user message. build_prefix has no parameter to put them in. Tools arrive as a tuple, so whoever composes the app writes the order down once, in source, where a reviewer can see it.

Two accidents fail loudly here. A Tool holds a dict, so it is unhashable, and {Tool(...), Tool(...)} raises TypeError. And json.dumps has no default=, so a set left inside a schema raises too. Don't add a default= to silence it.

Composition lives in its own module, because that is where the set usually hides:

from assistant.prompt import Prefix, Tool, build_prefix

INSTRUCTIONS = "You answer customer support questions."
TOPICS = ("billing", "shipping", "returns")

TOOLS = (
    Tool(
        name="search_docs",
        description="Search the help center.",
        schema={
            "type": "object",
            "properties": {
                "topic": {
                    "type": "string",
                    "enum": list(TOPICS),
                },
                "query": {"type": "string"},
            },
            "required": ["topic", "query"],
        },
    ),
)

def support_prefix() -> Prefix:
    return build_prefix(INSTRUCTIONS, TOOLS)

list(TOPICS) is safe while TOPICS is a tuple. Change the parentheses to braces and no type checker will complain about that line.

The seed is fixed when the interpreter starts, so a test that catches those braces has to start interpreters. pytest and the standard library are enough:

import os
import subprocess
import sys
from pathlib import Path

from assistant.support import support_prefix

ROOT = Path(__file__).resolve().parents[1]
DIGEST = Path(__file__).with_name("prefix.sha256")

REAL = """
from assistant.support import support_prefix
print(support_prefix().sha256())
"""

CONTROL = """
print(list({
    "search_docs", "open_ticket", "close_ticket",
    "refund_order", "lookup_user", "escalate",
}))
"""

The harness runs a snippet under eight seeds and counts the different outputs:

def distinct_outputs(code: str) -> int:
    seen = set()
    for seed in range(8):
        done = subprocess.run(
            [sys.executable, "-c", code],
            cwd=ROOT,
            env={**os.environ, "PYTHONHASHSEED": str(seed)},
            capture_output=True,
            text=True,
            check=True,
        )
        seen.add(done.stdout)
    return len(seen)

Two of the three tests use it:

def test_prefix_is_the_same_in_every_process():
    assert distinct_outputs(REAL) == 1

def test_the_harness_notices_a_set():
    assert distinct_outputs(CONTROL) > 1

def test_prefix_matches_the_reviewed_digest():
    expected = DIGEST.read_text().strip()
    assert support_prefix().sha256() == expected

Create the digest file once, from the project root, then commit it:

python3 -c "from assistant.support import support_prefix; \
print(support_prefix().sha256())" > tests/prefix.sha256
python3 -m pytest

Each test covers a different hole. The first compares SHA-256 digests across eight seeds and never opens a network connection. The second is the control: it runs a plain set through the same harness, so if a refactor gives all eight children the same seed, you find out. Leave -E and -I off the child command. Both make Python ignore every PYTHON* variable, and your eight chosen seeds would turn into eight random ones.

The third exists because the first has a blind spot. Eight subprocesses started in the same second all agree on today's date, so f"Today is {date.today()}" in the instructions passes the seed test. Against a committed digest it fails tomorrow morning. A prompt edit now also shows up in the pull request as a changed digest, which is a fair warning that the first request after deploy should write a new cache entry.

A set of two names has only two possible orders, so several seeds can agree by chance. A pass is strong evidence for a long tool list and weaker evidence for a short one. The seeds are fixed on purpose: random ones can go green and red on the same commit.

The prefix is settled inside the core, before the adapter sees it.

The digest covers what your core returns. Everything past it, meaning the adapter, the SDK and any gateway, can still alter the request. For that stretch there is cache diagnostics, which left beta on the Claude API on September 23, 2026 and reached the Python SDK's regular messages API in 1.9.0. You send a diagnostics object with the id of an earlier response, and the API reports the first place where the two requests diverge.

import json
import logging
from dataclasses import dataclass

from anthropic import Anthropic

from assistant.prompt import Prefix

log = logging.getLogger(__name__)

@dataclass(frozen=True, slots=True)
class Reply:
    id: str
    text: str

The call opts in to diagnostics and logs the reason:

class ClaudeModel:
    def __init__(self, client: Anthropic, model: str) -> None:
        self._client = client
        self._model = model

    def ask(
        self, prefix: Prefix, user: str, previous_id: str | None
    ) -> Reply:
        message = self._client.messages.create(
            model=self._model,
            max_tokens=1024,
            tools=json.loads(prefix.tools_json),
            system=[{
                "type": "text",
                "text": prefix.system,
                "cache_control": {"type": "ephemeral"},
            }],
            messages=[{"role": "user", "content": user}],
            diagnostics={"previous_message_id": previous_id},
        )
        found = message.diagnostics
        reason = found.cache_miss_reason if found else None
        if reason is not None:
            log.warning(
                "cache diagnostics: %s prefix=%s read=%s",
                reason.type,
                prefix.sha256()[:12],
                message.usage.cache_read_input_tokens,
            )
        text = "".join(
            block.text
            for block in message.content
            if block.type == "text"
        )
        return Reply(id=message.id, text=text)

ask returns text only. A real adapter also handles tool_use blocks; that loop is left out here because it doesn't touch the prefix.

The adapter makes no ordering decisions. json.loads preserves input order, so it hands the SDK the order the core chose. The cached prefix runs tools, then system, then messages, so the one breakpoint on the system block covers both halves of Prefix.

Two of the documented reasons cover the bugs in this post:

Reason What the docs say differs Where to look in your core
tools_changed Tools added, removed or reordered, or a schema serialized non-deterministically A set behind the tool list, or behind an enum orrequired array
system_changed Usually a timestamp, request id or other per-request value in the system prompt A clock read in the instructions, or a set joined into the text

Store previous_id outside the process. If each worker remembers its own last id in memory, you only ever compare a process with itself, where the hash seed is constant. Keep the id in shared storage, next to the conversation, so a request served by worker B can be compared with the one worker A sent.

The documented limits:

diagnostics: null means nothing diverged before the last breakpoint, or there was nothing to compare (a first turn, say). If you passed a real id and cache reads are still low or zero, cache_miss_reason: null means the comparison was still running. Check the next turn.previous_message_not_found unavailable means no comparison was produced either. The adapter logs both, so filter them out before you alert.diagnostics makes the API 400 if it sends the object, so leave it out there. I haven't run this adapter against the live API. The request and response shapes come from Anthropic's docs and the SDK source, so make one real call before you build an alert on it.

Start with the cheap half. Search your prompt code for set(, frozenset(, set literals and set comprehensions, add the subprocess test, and see whether the digests agree. If they don't, you found the bug without sending a single token.

The fix here is a boundary: the core decides the prompt and can be tested offline, and the adapter only delivers it. Hexagonal Architecture in Python is about drawing that kind of line in ordinary applications. It builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered, vertical slice) and then measures them. It isn't an AI book, but the habit of testing the important part with the outside world unplugged is the same one. Every listing runs from the free companion repo.

── more in #large-language-models 4 stories · sorted by recency
── more on @claude 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/a-python-set-in-your…] indexed:0 read:10min 2026-12-06 · —