- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
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.
Reproduce it without an API key
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.
Which processes disagree depends on how they start
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.
Make the prefix an output of the core
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:
# 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:
# 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:
# 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.
Test it in several processes
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:
# 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:
# 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:
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.
Let the adapter ask Claude what changed
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.
# 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:
# 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, 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 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:
- Only the earliest divergence is reported, so fix it and look again.
-
diagnostics: nullmeans 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, the requests match and the entry had expired or the prompt was too short. -
cache_miss_reason: nullmeans the comparison was still running. Check the next turn. -
previous_message_not_foundis not evidence that your request changed, andunavailablemeans no comparison was produced either. The adapter logs both, so filter them out before you alert. - Fingerprints expire after a short period and only compare inside one workspace. A check across a slow deploy may find nothing.
- The docs list the feature for the Claude API and Claude Models on Google Cloud (Anthropic managed) only.
- Sending
diagnosticsmakes the API keep a short-lived fingerprint of the request: hashes and token-count estimates, not the prompt text. The feature is not HIPAA eligible, and a HIPAA-enabled organization gets a400if it sends the object, so leave it out there. - The toy prompt here is probably too short to cache: the minimum is 512 tokens on the newest models and higher on older ones.
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.
If this was useful
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.
