{"slug": "a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart", "title": "A Python set in Your Tool List Can Break Prompt Caching on Every Restart", "summary": "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.", "body_md": "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.\n\nOne candidate cause is two characters of Python: the `{` and `}` around your tool names. You wrote a set.\n\nPython'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.\n\nSave this as `leaky.py`:\n\n``` python\nimport hashlib\nimport json\n\nTOOL_NAMES = {\n    \"search_docs\", \"open_ticket\", \"close_ticket\",\n    \"refund_order\", \"lookup_user\", \"escalate\",\n}\n\ntools = [\n    {\n        \"name\": name,\n        \"description\": f\"Run {name}.\",\n        \"input_schema\": {\"type\": \"object\", \"properties\": {}},\n    }\n    for name in TOOL_NAMES\n]\n\npayload = json.dumps(tools, sort_keys=True)\nprint(hashlib.sha256(payload.encode()).hexdigest()[:12])\n```\n\nRun 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:\n\n```\nfor seed in 1 2 3 4 5; do\n  PYTHONHASHSEED=$seed python3 leaky.py\ndone\n```\n\nCompare 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.\n\nLook 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.\n\nThere 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.\n\nFor `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.\n\n[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.\n\n[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.\n\nYou 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.\n\n*Same code, same tools, two processes. A set lets each one pick its own order.*\n\nIt'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.\n\nHere is a core module that imports no SDK, reads no clock and reads no environment:\n\n``` python\n# assistant/prompt.py\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import date\nfrom typing import Any\n\n@dataclass(frozen=True, slots=True)\nclass Tool:\n    name: str\n    description: \"str\"\n    schema: dict[str, Any]\n\n@dataclass(frozen=True, slots=True)\nclass Prefix:\n    system: str\n    tools_json: str\n\n    def sha256(self) -> str:\n        pair = json.dumps([self.system, self.tools_json])\n        return hashlib.sha256(pair.encode()).hexdigest()\n```\n\nTwo functions finish the module, one for each side of the cache breakpoint:\n\n``` python\n# assistant/prompt.py, continued\ndef build_prefix(\n    instructions: str, tools: tuple[Tool, ...]\n) -> Prefix:\n    wire = [\n        {\n            \"name\": tool.name,\n            \"description\": tool.description,\n            \"input_schema\": tool.schema,\n        }\n        for tool in tools\n    ]\n    return Prefix(\n        system=instructions,\n        tools_json=json.dumps(wire, sort_keys=True),\n    )\n\ndef user_message(\n    question: str, today: date, request_id: str\n) -> str:\n    return (\n        f\"Date: {today.isoformat()}\\n\"\n        f\"Request: {request_id}\\n\\n\"\n        f\"{question}\"\n    )\n```\n\nThe 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.\n\nTwo 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.\n\nComposition lives in its own module, because that is where the set usually hides:\n\n``` python\n# assistant/support.py\nfrom assistant.prompt import Prefix, Tool, build_prefix\n\nINSTRUCTIONS = \"You answer customer support questions.\"\nTOPICS = (\"billing\", \"shipping\", \"returns\")\n\nTOOLS = (\n    Tool(\n        name=\"search_docs\",\n        description=\"Search the help center.\",\n        schema={\n            \"type\": \"object\",\n            \"properties\": {\n                \"topic\": {\n                    \"type\": \"string\",\n                    \"enum\": list(TOPICS),\n                },\n                \"query\": {\"type\": \"string\"},\n            },\n            \"required\": [\"topic\", \"query\"],\n        },\n    ),\n)\n\ndef support_prefix() -> Prefix:\n    return build_prefix(INSTRUCTIONS, TOOLS)\n```\n\n`list(TOPICS)` is safe while `TOPICS` is a tuple. Change the parentheses to braces and no type checker will complain about that line.\n\nThe 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:\n\n``` python\n# tests/test_prefix_is_stable.py\nimport os\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nfrom assistant.support import support_prefix\n\nROOT = Path(__file__).resolve().parents[1]\nDIGEST = Path(__file__).with_name(\"prefix.sha256\")\n\nREAL = \"\"\"\nfrom assistant.support import support_prefix\nprint(support_prefix().sha256())\n\"\"\"\n\nCONTROL = \"\"\"\nprint(list({\n    \"search_docs\", \"open_ticket\", \"close_ticket\",\n    \"refund_order\", \"lookup_user\", \"escalate\",\n}))\n\"\"\"\n```\n\nThe harness runs a snippet under eight seeds and counts the different outputs:\n\n``` php\n# tests/test_prefix_is_stable.py, continued\ndef distinct_outputs(code: str) -> int:\n    seen = set()\n    for seed in range(8):\n        done = subprocess.run(\n            [sys.executable, \"-c\", code],\n            cwd=ROOT,\n            env={**os.environ, \"PYTHONHASHSEED\": str(seed)},\n            capture_output=True,\n            text=True,\n            check=True,\n        )\n        seen.add(done.stdout)\n    return len(seen)\n```\n\nTwo of the three tests use it:\n\n```\n# tests/test_prefix_is_stable.py, continued\ndef test_prefix_is_the_same_in_every_process():\n    assert distinct_outputs(REAL) == 1\n\ndef test_the_harness_notices_a_set():\n    assert distinct_outputs(CONTROL) > 1\n\ndef test_prefix_matches_the_reviewed_digest():\n    expected = DIGEST.read_text().strip()\n    assert support_prefix().sha256() == expected\n```\n\nCreate the digest file once, from the project root, then commit it:\n\n``` python\npython3 -c \"from assistant.support import support_prefix; \\\nprint(support_prefix().sha256())\" > tests/prefix.sha256\npython3 -m pytest\n```\n\nEach 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.\n\nThe 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.\n\nA 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.\n\n*The prefix is settled inside the core, before the adapter sees it.*\n\nThe 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.\n\n``` python\n# adapters/claude.py\nimport json\nimport logging\nfrom dataclasses import dataclass\n\nfrom anthropic import Anthropic\n\nfrom assistant.prompt import Prefix\n\nlog = logging.getLogger(__name__)\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n    id: str\n    text: str\n```\n\nThe call opts in to diagnostics and logs the reason:\n\n``` python\n# adapters/claude.py, continued\nclass ClaudeModel:\n    def __init__(self, client: Anthropic, model: str) -> None:\n        self._client = client\n        self._model = model\n\n    def ask(\n        self, prefix: Prefix, user: str, previous_id: str | None\n    ) -> Reply:\n        message = self._client.messages.create(\n            model=self._model,\n            max_tokens=1024,\n            tools=json.loads(prefix.tools_json),\n            system=[{\n                \"type\": \"text\",\n                \"text\": prefix.system,\n                \"cache_control\": {\"type\": \"ephemeral\"},\n            }],\n            messages=[{\"role\": \"user\", \"content\": user}],\n            diagnostics={\"previous_message_id\": previous_id},\n        )\n        found = message.diagnostics\n        reason = found.cache_miss_reason if found else None\n        if reason is not None:\n            log.warning(\n                \"cache diagnostics: %s prefix=%s read=%s\",\n                reason.type,\n                prefix.sha256()[:12],\n                message.usage.cache_read_input_tokens,\n            )\n        text = \"\".join(\n            block.text\n            for block in message.content\n            if block.type == \"text\"\n        )\n        return Reply(id=message.id, text=text)\n```\n\n`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.\n\nThe 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`.\n\nTwo 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:\n\n| Reason | What the docs say differs | Where to look in your core | \n|---|---|---|\n| `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 | \n| `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 | \n\nStore `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.\n\nThe documented limits:\n\n`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.\nI 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.\n\nStart 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.\n\nThe 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).", "url": "https://wpnews.pro/news/a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart", "canonical_source": "https://dev.to/gabrielanhaia/a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart-49n2", "published_at": "2026-12-06 04:00:55+00:00", "updated_at": "2026-12-06 04:14:32.070793+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools", "developer-tools"], "entities": ["Claude", "Python", "Uvicorn", "Gunicorn", "PYTHONHASHSEED"], "also_reported_by": [], "takeaway": "Iterating a Python set of tool names produces a different order in each process because str hashes are salted, so sort the set before serializing the tool list or the prompt prefix changes and Claude's cache_read_input_tokens drops to zero.", "recommendation": {"advice": "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.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart", "markdown": "https://wpnews.pro/news/a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart.md", "text": "https://wpnews.pro/news/a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart.txt", "jsonld": "https://wpnews.pro/news/a-python-set-in-your-tool-list-can-break-prompt-caching-on-every-restart.jsonld"}}