Skip to content

feat(ai): Hash the prompt prefix to tell cache expiry from prefix changes - #8440

Open
sentry-junior[bot] wants to merge 7 commits into
masterfrom
feat/gen-ai-prefix-hashes
Open

sentry-junior[bot] wants to merge 7 commits into
masterfrom
feat/gen-ai-prefix-hashes

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Description

Why: LLM apps pay a cache-write premium every time the provider's prompt cache misses. A miss has one of two causes: the cache expired because the gap between calls outlived the TTL, which cache warming or a longer TTL fixes, or the prompt prefix (tools, system prompt or history) changed, which a code change fixes. Today Sentry can't show the hit rate or tell these causes apart; together, the PRs below let Sentry show the hit rate, alert on drops, price cache tokens correctly, name the cause of each miss, attribute it to a call site, and rank where warming would save money.

This PR is the "which cause" piece for the Python SDK: the Anthropic and OpenAI (Chat Completions and Responses) integrations now set the hashes from getsentry/sentry-conventions#844. If every hash matches the previous call, the cache expired. If one changed, the prefix changed. This depends on getsentry/sentry-conventions#844 and shouldn't merge before it.

What:

  • gen_ai.tool.definitions.hash and gen_ai.system_instructions.hash cover the stable start of the request.
  • gen_ai.input.messages.hash covers the input messages, and gen_ai.input.messages.prefix_hash the messages before the model's latest turn. If a call's prefix hash equals the previous call's messages hash, the app only appended to the history.

Decisions worth a look:

  • All hashes come from the raw request kwargs, before normalization or truncation, and also when data_collection.gen_ai.inputs is off. That's the main reason this has to happen in the SDK. The convention marks them apply_scrubbing: never.
  • They are skipped for NoOpSpan, so unsampled calls pay nothing.
  • Tools and system instructions are hashed as json.dumps(value, separators=(",", ":"), ensure_ascii=False) of the request value, with cache_control kept. When a Responses request sets both instructions and leading system/developer input messages, the system hash covers both.
  • The message hashes leave out the leading system/developer messages and every cache_control member, because apps move that breakpoint to the newest message on each call. Response objects that the app appends (pydantic models) are hashed via model_dump(mode="json", exclude_unset=True).
  • Both message hashes come from one serialization pass: the SHA-256 state is copied at the prefix boundary, so the cost is linear in the history size.
  • In the Responses API, the model's turn also includes reasoning and *_call items. With previous_response_id or conversation, the input holds only new items, so no message hashes are set.
  • Only list/tuple tools and messages are hashed, so a caller's generator is never consumed. Values that can't be serialized to JSON are skipped.

Other gen_ai integrations (Google GenAI, LiteLLM, LangChain, ...) can follow once the convention is settled.

Issues

Part of:

via @BYK.

--

View Session [Sentry]

…ions.hash

Hash the tools and system instructions of Anthropic and OpenAI requests, so a reader can tell a changed prompt prefix apart from an expired provider cache. The hashes are set even when inputs are not recorded.

Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Dec 2, 2026
@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 29d14d4.

Main concerns: data sent to Sentry, reach, host performance.

This label is a hint for reviewers, not an approval.

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Coverage Results 📊

✅ 60145 passed | ⏭️ 3149 skipped | Total: 63294 | Pass Rate: 95.02% | Execution Time: 164m 15s

📊 Comparison with Base Branch

Metric Change
Total Tests 📈 +172
Passed Tests 📈 +143
Failed Tests 📉 -1
Skipped Tests 📈 +30

All tests are passing successfully.

✅ Patch coverage is 92.63% (88 of 95 changed executable lines covered; target 80%).
Project statement coverage is 90.27% (up 0.02 percentage points from base (d860464) to head (29d14d4)).

Changed files with executable lines (4)
File Patch coverage Changed executable lines
sentry_sdk/ai/utils.py 91.14% 72/79 covered; missed: 510, 511, 539, 553, 592, 593, 618; partial branches: 538, 552, 617, 623, 630
sentry_sdk/consts.py 100.00% 8/8 covered
sentry_sdk/integrations/anthropic.py 100.00% 1/1 covered
sentry_sdk/integrations/openai.py 100.00% 7/7 covered
Coverage diff
@@            Coverage Diff             @@
##        master     #8440       +/-##
==========================================
+ Coverage    90.25%    90.27%    +0.02%
==========================================
  Files          201       201         —
  Tracked lines     22191     22285       +94
  Branches      7776      7818       +42
==========================================
+ Hits         20028     20117       +89
- Misses        2163      2168        +5
- Partials      1289      1292        +3

Generated by Coverage Action

@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 2, 2026
@sentry-junior
sentry-junior Bot requested a review from BYK December 2, 2026 15:49
@BYK
BYK marked this pull request as ready for review December 2, 2026 15:57
@BYK
BYK requested a review from a team as a code owner December 2, 2026 15:57
@github-actions github-actions Bot removed the risk: medium PR risk score: medium label Dec 2, 2026
…t have none

Hash list items one by one with a shared JSON encoder, and copy an item without cache_control only when its JSON has that key. The hashes stay the same.

Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 2, 2026
Hash the JSON in insertion order and keep cache_control, instead of a canonical form. A key reorder or a moved cache_control breakpoint now changes the hash, because the provider sees different bytes. The expected values are now per-SDK vectors.

Co-Authored-By: Burak Yigit Kaya <126780+BYK@users.noreply.github.com>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 2, 2026
The prefix hash covers the input messages before the model's latest turn, so it equals the full messages hash of the previous call when the app only appended to the history. Both hashes leave out leading system messages and cache_control, and are computed in one serialization pass.

Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
@github-actions github-actions Bot removed the risk: medium PR risk score: medium label Dec 3, 2026
@sentry-junior sentry-junior Bot changed the title feat(ai): Set gen_ai.tool.definitions.hash and gen_ai.system_instructions.hash feat(ai): Set gen_ai request and input message hashes Dec 3, 2026
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
Comment thread sentry_sdk/integrations/openai.py Resolved
The Responses API sends both, so a change to either must change gen_ai.system_instructions.hash. The message hashes leave the leading system messages out, so without this a change to them changed no hash.
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Dec 3, 2026
sentry-junior Bot added a commit to getsentry/sentry-javascript that referenced this pull request Dec 3, 2026
…ssages

The OpenAI Responses API sends both, so a change to either must change gen_ai.system_instructions.hash. Matches getsentry/sentry-python#8440.
@sentry-junior sentry-junior Bot changed the title feat(ai): Set gen_ai request and input message hashes feat(ai): Hash the prompt prefix to tell cache expiry from prefix changes Dec 5, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant