Skip to content

feat(attributes): Add gen_ai prompt prefix hashes to tell cache expiry from prefix changes - #844

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

sentry-junior[bot] wants to merge 6 commits into
mainfrom
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: it defines a hash for each part of the cached prefix. If every hash matches the previous call, the cache expired. If one changed, the prefix changed, and the hash says which part.

What: Providers cache the start of a request: tools, then system instructions, then the conversation history. The hashes:

  • gen_ai.tool.definitions.hash: the tools request parameter.
  • gen_ai.system_instructions.hash: the system instructions (system, instructions, and the leading system/developer messages).
  • gen_ai.input.messages.hash: the input messages, without the leading system messages and cache_control.
  • gen_ai.input.messages.prefix_hash: the same hash over the messages before the model's latest turn.

How to read them against the previous call in the conversation:

  • Tool or system hash changed: the app changed that part of the prompt.
  • This call's prefix_hash equals the previous call's gen_ai.input.messages.hash: the app only appended to the history. A single hash of the whole request can't show this, because every call appends messages.
  • Everything matches and cache reads still dropped: the cache expired.

The SDK computes the hashes from the request as sent, so they work when input recording is off. Comparing stored raw values doesn't work, because Relay scrubs and trims them. All four attributes use apply_scrubbing: never: scrubbing a hash breaks the comparison it exists for, and the hashes don't follow send_default_pii / recordInputs.

Part of:

via @BYK.

--

View Session [Sentry]

…instructions.hash

Hashes of the stable start of a gen_ai request, so a reader can tell a changed prompt prefix apart from an expired provider cache.

Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
@vercel

vercel Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
sentry-conventions Ready Ready Preview Dec 3, 2026 11:02pm UTC

Request Review

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Semver Impact of This PR

🟡 Minor (new features)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


New Features ✨

Attributes

  • Add gen_ai prompt prefix hashes to tell cache expiry from prefix changes by BYK with sentry-junior in #844
  • Add deprecated server.socket.address attribute by srothh in #840
  • Add deprecated messaging.message.system by srothh in #841
  • Add missing log severity attributes by srothh in #831
  • Add WebSocket span name convention by chargome with claude in #836

Internal Changes 🔧

  • (attributes) Add descriptions for attribute namespaces by Lms24 in #755
  • (deps-dev) Bump tar from 7.5.19 to 8.0.2 by dependabot in #845

🤖 This preview updates automatically when you update the PR.

@BYK
BYK self-requested a review December 2, 2026 15:54
@BYK
BYK marked this pull request as ready for review December 2, 2026 15:55
@alexander-alderman-webb

Copy link
Copy Markdown
Contributor

Can we just compare the raw values of gen_ai.tool.definitions and gen_ai.system.instructions and only add this attribute to conventions when there's a use-case where someone disables GenAI data collection client side?

@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@alexander-alderman-webb When inputs are recorded, comparing the raw gen_ai.tool.definitions and gen_ai.system_instructions values does answer the same question. The hash attributes differ in three ways:

  • Input capture off. The raw values aren't sent at all then. The SDKs set the hashes either way, so this is the one case the raw values can't cover. Whether sending the hash with input capture off is acceptable is the open PII question in the description.
  • Query cost. Grouping or comparing on a 16-char string is cheap. Tool definitions and system prompts are often several KB per span, on every gen_ai span.
  • What gets compared. The recorded values are the SDK's normalized form, not the request as sent. The hash input is the raw request parameter with cache_control dropped, because frameworks move cache breakpoints between calls without changing the content. A raw-value comparison would need the same canonicalization on the query side.

If most users keep input capture on, the raw values cover most of the use case today, and deferring this until someone needs it with capture off is a fair call. That's a scope decision for you and @BYK. The SDK PRs (getsentry/sentry-python#8440, getsentry/sentry-javascript#27089) depend on this one, so they'd wait with it.

@alexander-alderman-webb

Copy link
Copy Markdown
Contributor

Hashing client-side also has costs. Is there a concrete reason we expect the comparisons to be too expensive?

@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@alexander-alderman-webb No, I don't have a measurement for that. The query-cost point was an expectation, based on tools and system prompts often being several KB per span, not something I profiled. It shouldn't carry the decision.

On the client side, the cost is one canonical JSON serialization plus one SHA-256 of the tools and system instructions per call. It's skipped for unsampled spans. Python uses hashlib and Node uses node:crypto. I haven't benchmarked that either.

The concrete reason for the attributes is the input-capture-off case. Without it, comparing the raw values is a reasonable alternative.

@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@alexander-alderman-webb One more reason I left out: with input capture on, the stored raw values still aren't reliable to compare, because Relay changes them before storage.

  • PII scrubbing: gen_ai.system_instructions and gen_ai.tool.definitions are in Relay's replace-only PII selector, so matches are replaced in place (relay-pii/src/convert.rs#L71-L113). Two identical requests can be stored differently, for example when only one of them gets a match.
  • Size trimming: when the project config sets a span size limit, Relay trims the span before EAP storage, and long strings get cut to the remaining budget (relay-server/src/processing/spans/process.rs#L365-L379). So the stored value depends on what else is on the span, and two different long prompts can trim to the same value.

The SDK computes the hash from the request before either step, so it doesn't have these problems.

@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@alexander-alderman-webb Following up on the client-side cost: here are the measurements on the code paths in getsentry/sentry-python#8440 and getsentry/sentry-javascript#27089.

The payload is tools plus system instructions, about 25% system prompt and the rest JSON-schema tools, with one cache_control member. Times are per call for both hashes together: the best of 7 runs on a 4 vCPU Xeon at 2.9 GHz, with Python 3.14 and Node 24. These are local numbers, not production numbers.

Size Python: canonical JSON Python: hashlib Node: canonical JSON Node: node:crypto Edge: plain-JS SHA-256
2.5 KB (4 tools) 45 µs 3 µs 25 µs 4 µs 30 µs
20 KB (31 tools) 317 µs 16 µs 188 µs 17 µs 196 µs
100 KB (155 tools) 1561 µs 72 µs 963 µs 78 µs 947 µs

The Edge path runs the same canonical JSON as Node; only the hash differs.

  • The canonical JSON dominates. It is about 95% of the cost in Python and 90% in Node, so a faster hash such as xxhash or murmur would save at most 5–10%. Neither is in the Python or JS standard library, so that would also mean a new Python dependency and a new JS implementation.
  • Python: about half of the JSON time is the copy that removes cache_control. The rest is json.dumps.
  • JS: the canonical JSON takes about 6× as long as a plain JSON.stringify of the same values, because it sorts keys in JS. The plain-JS SHA-256, used only on Vercel Edge and @sentry/cloudflare/request, costs about as much as the JSON again.

For typical 2–20 KB prefixes, this is 0.03–0.33 ms of CPU per sampled call, compared with LLM calls that take hundreds of milliseconds or more. At 100 KB it is 1–1.6 ms.

I didn't add memoization by object identity. Python lists and dicts can't be weakly referenced, so the cache would need id(), which can match a new object after the old one is freed. Frameworks also often change the same tools list in place, which would make a cached hash wrong. If the 100 KB case matters, the cheaper options are to skip the cache_control copy in Python when no cache_control key is present, or to add a fast path in JS that uses JSON.stringify when no integer-like keys are present.

@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@alexander-alderman-webb Both SDK PRs now take a faster path for the canonical JSON, and the hashes are unchanged. Same setup as before: times are per call for tools plus system together, measured locally, not in production.

Size Python before Python now (no cache_control / with) Node JSON before Node JSON now node:crypto Edge plain-JS SHA-256
2.5 KB 48 µs 32 / 45 µs 24 µs 17 µs 4 µs 30 µs
20 KB 331 µs 231 / 244 µs 187 µs 122 µs 17 µs 194 µs
100 KB 1650 µs 1138 / 1155 µs 925 µs 587 µs 78 µs 934 µs

The Python columns include hashlib, which is 3–72 µs of each total.

The cross-language test vectors pass unchanged. New tests run the fast and slow paths on the same inputs, including cache_control, integer-like keys and toJSON. The canonical JSON is still most of the cost, so a different hash wouldn't change much.

@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

One more variant I measured: skip building the canonical JSON string and do it in one pass. This walks the value with sorted keys and without cache_control, and feeds the output into an incremental SHA-256 (hashlib.sha256().update, crypto.createHash().update), buffered and flushed every 64 KB. Its hashes are identical to the current ones. Same setup as before: per call, tools plus system together, measured locally.

Size Python now Python one-pass Node now (node:crypto) Node one-pass
2.5 KB 32 µs 74 µs 23 µs 32 µs
20 KB 232 µs 551 µs 143 µs 229 µs
100 KB 1143 µs 2705 µs 720 µs 1300 µs

The one-pass walk is slower in both: about 2.3× in Python, where a Python walker replaces the C json.dumps, and 1.4–1.8× in Node, where a JS walker replaces native JSON.stringify. Building the string is cheaper than walking the value in the language itself, so both SDK PRs keep the current fast paths. The plain-JS SHA-256 only hashes a whole string, so I didn't test it in one-pass form.

…nds them

Drop the canonical form. The hash input is the JSON as sent, in insertion order and with cache_control kept, so the examples change.

Co-Authored-By: Burak Yigit Kaya <126780+BYK@users.noreply.github.com>
@sentry-junior

sentry-junior Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

The hash input is now the JSON as the provider client sends it, with no canonical form: insertion order, cache_control kept. The attribute definitions say what that means: a key reorder or a moved breakpoint in the tools or system instructions changes the hash, and values compare only within one SDK and provider. New numbers, measured locally in the same setup as before, per call for tools plus system:

Size Python (json.dumps + hashlib) Node (JSON.stringify + node:crypto) Edge (JSON.stringify + plain-JS SHA-256)
2.5 KB 22 µs (was 32) 8 µs (was 21) 35 µs
20 KB 133 µs (was 232) 47 µs (was 139) 227 µs
100 KB 633 µs (was 1143) 234 µs (was 665) 1124 µs

In Node, the hash is now about a third of the cost. On Edge, the plain-JS SHA-256 is most of it.

"is_in_otel": false,
"visibility": "public",
"examples": ["776e84186ddaa3b9", "474a1bd4591d8c2d"],
"additional_context": [

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not look useful.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you say which part? Is it the example values here, which are just the hashes of the strings in the description, or the attribute itself? If it's the attribute: its job is to tell a changed system prompt apart from an expired provider cache when cache reads drop. That works even when input recording is off, and when Relay has scrubbed or trimmed gen_ai.system_instructions. If that use case isn't worth an attribute, that's a call for you and @BYK, and I'll leave it as is until you decide.

Comment on lines +11 to +19
"additional_context": [
"Providers such as Anthropic and OpenAI cache the start of a request, which begins with the tool definitions. When this value differs from the previous call, the tool definitions changed and the provider could not reuse its cache for them.",
"The hash input is the tools request parameter in the provider's own format, as the caller passed it, before any SDK normalization or truncation. Examples are `tools` for the Anthropic Messages API and for the OpenAI Chat Completions and Responses APIs. It is not the value of `gen_ai.tool.definitions`.",
"Serialize the input as JSON the way the provider client sends it: object keys in insertion order, array order kept, `cache_control` members kept, no whitespace between tokens, and non-ASCII characters not escaped. A change to the key order changes the value. This is intended, because the provider receives different bytes. A `cache_control` breakpoint that moves within the tool definitions also changes the value. This is rare, because frameworks usually move breakpoints in the messages, which are not part of the input.",
"The value is the first 16 lowercase hexadecimal characters (64 bits) of the SHA-256 digest of the UTF-8 bytes of that JSON. The example is the hash of `[{\"name\":\"get_weather\",\"description\":\"Get the weather for a location\",\"input_schema\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\"}},\"required\":[\"location\"]}}]`.",
"SDKs set this attribute whether or not they record `gen_ai.tool.definitions` or other request content. Omit it when the request has no tools or an empty list of tools, or when the SDK cannot serialize them.",
"Compare values only between spans from the same SDK with the same `gen_ai.provider.name`. SDKs in different languages can serialize the same value differently, for example key order or floating-point numbers.",
"Use it with `gen_ai.system_instructions.hash` and `gen_ai.request.model`. When all three match the previous call and cache reads still drop, the provider cache likely expired. Other changes that invalidate a provider cache, such as a different `tool_choice`, thinking settings, or images in the messages, do not change this value."
],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not look useful either.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question here: is it this guidance (compare only within one SDK and provider, use it with the model and the system hash), or the tools hash as a whole? If it's the guidance, I can cut it down to the hash input and the value format.

@cleptric cleptric left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general, we try to add conventions with clear intent and it is not clear to me what these will be used for based of the word soup junior dumped in here.

Lead with what the hashes are for, and keep only the value format and the comparison rule.
@sentry-junior

sentry-junior Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Fair. I cut the descriptions down in 01eb537 and rewrote the PR description to lead with the intent: when cached input tokens drop, these two hashes show whether the app changed its tools or system prompt, or whether the provider cache just expired. Each attribute now says what it's for, how the value is computed, and what to compare it with. If the intent itself doesn't justify new attributes, that's for you and @BYK to settle.

@sentry-junior
sentry-junior Bot requested a review from cleptric December 3, 2026 15:34
Scrubbing a hash would break the comparison it exists for, and the hashes are not tied to input recording.

Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
Most cached input tokens in an agent loop are the conversation history. Comparing the prefix hash of a call with the full hash of the previous call shows whether the app only appended to the history or rewrote it.

Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>
@sentry-junior sentry-junior Bot changed the title feat(attributes): Add gen_ai.tool.definitions.hash and gen_ai.system_instructions.hash feat(attributes): Add gen_ai request and input message hashes Dec 3, 2026

This branch was successfully deployed

1 active deployment
Preview — 6f640d21 Deployed Dec 3, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants