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. 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 https://docs.python.org/3/reference/datamodel.html object. hash : 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 https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics 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 : python 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 https://docs.python.org/3/using/cmdline.html envvar-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 https://docs.python.org/3/library/json.html json.JSONEncoder , 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 https://uvicorn.dev/deployment/ with --workers uses spawn instead of pre-fork, and spawn starts a fresh Python interpreter https://docs.python.org/3/library/multiprocessing.html contexts-and-start-methods . 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 https://gunicorn.org/design/ uses a pre-fork model. A forked child is effectively identical to its parent https://docs.python.org/3/library/multiprocessing.html contexts-and-start-methods , 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 https://docs.python.org/3/using/cmdline.html cmdoption-R 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: python assistant/prompt.py 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: python assistant/prompt.py, continued 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: python assistant/support.py 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 https://docs.pytest.org/en/stable/ and the standard library are enough: python tests/test prefix is stable.py 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: php tests/test prefix is stable.py, continued 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: tests/test prefix is stable.py, continued 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: python 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 https://docs.python.org/3/using/cmdline.html cmdoption-E , 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 https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics , which left beta on the Claude API on September 23, 2026 https://platform.claude.com/docs/en/release-notes/overview and reached the Python SDK's regular messages API in 1.9.0 https://github.com/anthropics/anthropic-sdk-python/blob/main/CHANGELOG.md . You send a diagnostics object with the id of an earlier response, and the API reports the first place where the two requests diverge. python adapters/claude.py 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: python adapters/claude.py, continued 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 https://docs.python.org/3/library/json.html , so it hands the SDK the order the core chose. The cached prefix runs tools, then system, then messages https://platform.claude.com/docs/en/build-with-claude/prompt-caching , so the one breakpoint on the system block covers both halves of Prefix . Two of the documented reasons https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics cache-miss-reason-types 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 or required 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 https://www.amazon.com/dp/B0HQWDH23Q 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 https://github.com/gabrielanhaia/hexagonal-python-examples .