Skip to content

feat(guardrails): add only_scan_new_messages for per-session incremental scanning - #33278

Merged
yucheng-berri merged 11 commits into
litellm_internal_stagingfrom
litellm_guardrail_only_scan_new_messages
Jul 22, 2026
Merged

yucheng-berri merged 11 commits into
litellm_internal_stagingfrom
litellm_guardrail_only_scan_new_messages

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Captured live at commit 29ca44115e against a real Bedrock guardrail (ApplyGuardrail, real Anthropic model responses) through a local proxy with only_scan_new_messages: true. Two turns share one session via x-litellm-session-id, and --detailed_debug logs show the exact payload sent to Bedrock each turn.

Turn 1 (new session) sends the full initial context to Bedrock:

curl http://localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-1234" \
  -H "x-litellm-session-id: demo-live-1" -d '{"model":"claude-sonnet-4-5","messages":[
    {"role":"system","content":"You are a helpful geography assistant."},
    {"role":"user","content":"In one short sentence, what is the capital of France?"}]}'

# Bedrock AI request body: {'source': 'INPUT', 'content': [
#   {'text': {'text': 'You are a helpful geography assistant.'}},
#   {'text': {'text': 'In one short sentence, what is the capital of France?'}}]}

Turn 2 (same session, one assistant reply plus a new user question appended) sends only the newly appended messages, not the system prompt or the first question again:

curl http://localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-1234" \
  -H "x-litellm-session-id: demo-live-1" -d '{"model":"claude-sonnet-4-5","messages":[
    {"role":"system","content":"You are a helpful geography assistant."},
    {"role":"user","content":"In one short sentence, what is the capital of France?"},
    {"role":"assistant","content":"The capital of France is Paris."},
    {"role":"user","content":"And what is the capital of Germany?"}]}'

# Bedrock AI request body: {'source': 'INPUT', 'content': [
#   {'text': {'text': 'The capital of France is Paris.'}},
#   {'text': {'text': 'And what is the capital of Germany?'}}]}

Resending turn 2 unchanged makes no Bedrock call at all; the log shows Bedrock Guardrail: no new messages to scan for this session, skipping API call. The same behavior was confirmed on the Anthropic /v1/messages endpoint (the surface Claude Code uses), where turn 2 again sent only the two appended messages.

Claude Code note: this was validated end to end with the real Claude Code CLI pointed at the proxy. Claude Code sends x-claude-code-session-id, which the proxy's existing header extraction maps straight onto the session key, so two turns of one claude session (claude -p then claude -p --continue) share a session id with no extra config. Turn 1 sent Bedrock the full initial context (system reminders plus the first question); turn 2 sent only the two newly appended messages (the prior answer and the new question), leaving the system prompt unscanned the second time. When no session id is present the request falls back to a full scan, so behavior is safe either way.

Live Claude Code POC, recorded on commit 05dcf54efd (the commit that includes the masked-output fallback and the shared-cache resolution). Turn 1 (claude -p, answer Paris) scanned the full initial context; turn 2 (claude -p --continue, answer Berlin) sent Bedrock only the two newly appended segments (Paris and And Germany? One word.).

Live Claude Code incremental scan POC

Terminal transcript of both turns

Generic agent POC (not Claude Code), recorded on commit 05dcf54efd. A multi-turn agent built on the OpenAI SDK, pointed at the proxy, propagating a stable session id via extra_body={"litellm_session_id": ...}. Turn 1 scanned the full initial context (system prompt + first question); turns 2 and 3 each sent Bedrock only the two newly appended segments (prior answer + new question), never the whole growing conversation. This shows the feature works for any agent that carries a session id, not just Claude Code.

Generic agent incremental scan POC

Generic agent three-turn transcript

Type

🆕 New Feature

Changes

Adds one opt-in guardrail config flag, only_scan_new_messages, for per-session incremental scanning. The motivation is a customer running Bedrock Guardrails at high volume (long Claude Code sessions) who hits guardrail throttling; re-scanning the entire growing context on every request is the main source of pressure. When enabled, the guardrail only sends messages it has not already scanned earlier in the same session.

guardrails:
  - guardrail_name: bedrock-guard
    litellm_params:
      guardrail: bedrock
      mode: pre_call
      only_scan_new_messages: true   # default false

Mechanism lives in the shared CustomGuardrail layer as two helpers, wired into Bedrock's apply_guardrail (the path the proxy actually runs for Bedrock via the unified guardrail interface; the earlier async_pre_call_hook is no longer the live entrypoint):

# filter_new_texts_for_session(texts, request_data, cache) -> list | None
#   None  => full scan (feature off, no session id, masking on, or cache read failed)
#   list  => scan only this subset (may be empty => skip the provider call)
seen = cache.get(f"guardrail_scanned_texts:{guardrail_name}:{session_id}")
return [t for t in texts if sha256(t) not in seen]

# mark_texts_scanned(...) runs only after a non-blocked provider response,
# so a blocked segment is never recorded and a retry re-checks it

Design answers to the investigation questions:

Shared vs Bedrock-only: the helper is shared so other guardrails can adopt it, but only Bedrock is wired in this PR. No behavior changes for any other guardrail. Whether to roll it out beyond Bedrock needs guardrail-owner sign-off.

Session key: reuses the session id LiteLLM already derives (litellm_session_id, else metadata.session_id, else litellm_metadata.session_id). Proxy header extraction already recognizes x-litellm-session-id, x-litellm-trace-id, and any x-<vendor>-session-id. Claude Code sends x-claude-code-session-id, which the proxy maps onto the session key; this was confirmed live with the Claude Code CLI (see the proof note). When absent the request falls back to a full scan.

Not Claude Code specific: any agent opts in the same way, by propagating a stable session id across turns. An OpenAI-SDK agent passes extra_body={"litellm_session_id": "..."} (or metadata.session_id), an HTTP agent sets the x-litellm-session-id header or a litellm_session_id body field; nothing about the feature is tied to the Claude Code client. This was validated live with a generic multi-turn agent built on the OpenAI SDK (see the proof note) in addition to Claude Code.

System prompt and tools: the diff is computed over the exact text segments Bedrock's ApplyGuardrail receives, which is the granularity that determines the guardrail verdict (Bedrock evaluates content text, not roles). An unchanged system prompt is scanned once and skipped thereafter, and an edited earlier message changes its text and is re-scanned. Because the hash is content-only, two segments with identical text dedupe to one scan, which is safe for a stateless content guardrail. Open decision for a DRI: if stricter per-message identity is wanted (so a role change with identical text, or a repeated identical line, still re-scans), the hash should incorporate the serialized message rather than the flat text; that is a small change but needs guardrail-owner sign-off on the desired semantics.

Blocking vs masking: intended for blocking/detection guardrails only. This is enforced in two places. Up front, if mask_request_content or mask_response_content is set, it falls back to a full scan and does not write hash state. It also enforces at the response level, which matters for Bedrock because masking/anonymization is configured on the guardrail in the AWS console and is not visible from LiteLLM config: if the diff scan comes back with rewritten (ANONYMIZED) output, that masked copy cannot be reapplied to the context the fast path skipped, so the scan discards the diff result, falls back to a full-context scan (which applies the masking), and records no session state. Without this the fast path would drop the masked copy, send the raw text to the model, and stamp it scanned so it was never re-checked

Cache: hashes only, never content. Key is guardrail_scanned_texts:{guardrail_name}:{session_id}. Entries expire after 24h (GUARDRAIL_SCANNED_MESSAGES_CACHE_TTL_SECONDS). It uses the proxy's shared cache (proxy_logging_obj.internal_usage_cache.dual_cache), so when the deployment configures Redis the scanned-segment state is shared across proxy instances; off the proxy (e.g. unit tests) it falls back to a process-local DualCache where sharing does not apply. A cache read failure falls back to a full scan; a write failure logs and lets the request through so the next call re-scans

Known limitations for a DRI to weigh:

The read-merge-write of the hash set is not atomic, so two concurrent requests in the same session can each scan and then overwrite each other's set, causing a small amount of duplicate scanning (never a missed scan). For the MVP this is documented as acceptable best-effort; a Redis atomic set-add or lock would remove it if strictness is required.

A segment that passed is remembered as scanned for the full 24h TTL. If the guardrail policy is tightened in that window, previously passed content in an ongoing session is not re-evaluated until the entry expires or the content changes. Shortening or invalidating the TTL on a policy change is a product decision.

Scanning only the per-session diff means the guardrail sees each new segment against the policy but not against the earlier session context. An attack deliberately spread across turns, where each individual segment is benign but the accumulation is not, can evade a diff-only scan in a way a full-context scan would catch. This is inherent to incremental scanning and is the reason the feature is opt-in per guardrail and off by default. The planned mitigation is an optional lookback knob (for example only_scan_new_messages_lookback: N) that also re-includes the last N prior segments on each turn, trading some extra scanning for cross-turn coverage; it is deliberately out of scope for this v0 and left as a clean extension of filter_new_texts_for_session for a follow-up once a guardrail owner sets the default.

Tests in tests/test_litellm/integrations/test_custom_guardrail.py cover the shared helpers: feature off, missing session id (full scan, no state), masking fallback, cache read failure (full scan), first turn records hashes, follow-up dedupes previously scanned segments, empty diff, an edited earlier segment is re-scanned, a blocked scan does not persist hashes, and the fixed TTL is used on write. Tests in tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py exercise the live apply_guardrail path directly: first turn scans the full context, a follow-up scans only the diff, an identical resend makes no Bedrock call, a request with no session id scans the full context, a blocked turn is re-scanned on retry, a guardrail that returns masked/anonymized output falls back to a full-context scan and records no session state so the masked content is applied and an identical resend is scanned again, and a generic (non Claude Code) agent that carries metadata.session_id across a growing three-turn conversation scans only the newly appended segments on every turn after the first.

Live validation: flag interactions, /v1/messages, and tool handling

A follow-up pass ran this branch against a real Bedrock guardrail, capturing the exact ApplyGuardrail payload, hash persistence, and skip decisions per turn; 30 scenarios across both endpoints, each with the flag on and off

Confirmed working: the full /v1/messages sequence (first turn scans eligible context, later turns scan only appended segments, identical resends make zero Bedrock calls, an edited message re-scans alone, a new session re-scans in full); x-claude-code-session-id, x-litellm-session-id, and body litellm_session_id all map to one session key; blocked segments are never cached and re-scan on retry; skip_system_message_in_guardrail and skip_tool_message_in_guardrail compose correctly; masking flags fall back to exactly one full scan per turn with no state written; two replicas sharing Redis share scanned state (hashes only), and without Redis a fresh process safely re-scans

Two combinations misbehave and should be fixed or rejected at config time. experimental_use_latest_role_message_only is silently ignored because the incremental path runs before message selection, so content that flag excludes gets scanned and cached; fall back to the full path when it is set. A Bedrock guardrail that anonymizes content triggers the masked-output fallback on every turn forever, doubling ApplyGuardrail traffic; disable incremental for the instance after the first masked response

Pre-existing gaps, unchanged by this PR and follow-up ticket material: the /v1/messages input path never scans the top-level system field, tool_use arguments, or tool_result content (the same tool result is scanned via /v1/chat/completions), and tool_call arguments are not scanned on any path. One observation in the feature's favor: a string Bedrock blocks in isolation passed the baseline full-context batch, so the smaller incremental payloads actually detect better

Regression tests extending the two mapped test files cover the /v1/messages diff sequence, cross-session re-scan, masking single-scan, the anonymize fallback, and tool-text preservation, plus an xfail encoding the intended latest-role semantics; 17 pass, 1 xfail; added in 2cff58e. The scanned-messages cache TTL is now overridable via the GUARDRAIL_SCANNED_MESSAGES_CACHE_TTL_SECONDS env var (default 24h; 5fa8ff0), which narrows the policy-staleness window called out under known limitations

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/27b19ab26f3c4437a42d67917a5e5735
Requested by: @ishaan-berri

…tal scanning

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
@ghost ghost self-assigned this Jul 14, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Jul 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ yucheng-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.28713% with 29 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...y/guardrails/guardrail_hooks/bedrock_guardrails.py 46.29% 29 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an opt-in only_scan_new_messages flag to the Bedrock guardrail that enables per-session incremental scanning: on each turn after the first, only text segments whose SHA-256 hash has not already been recorded in the session cache are sent to Bedrock's ApplyGuardrail, addressing throttling pressure from long multi-turn sessions. The feature is off by default, falls back to full-scan when no session id is present or the cache is unavailable, and correctly gates out masking guardrails both at the LiteLLM config layer and by detecting server-side anonymized output in the Bedrock response.

  • The core incremental logic (filter_new_texts_for_session, mark_texts_scanned) lives on CustomGuardrail as a shared helper layer but is only wired into BedrockGuardrail.apply_guardrail; other guardrail types that set the flag silently get full scans with no warning.
  • The experimental_use_latest_role_message_only + only_scan_new_messages combination is a documented known gap (xfail test included) where the incremental path runs before message selection, causing the latest-role filter to be bypassed for cached segments; the PR description promises a config-time guard but none is implemented.
  • Test coverage is thorough (mocks only, no real network calls) across 30+ scenarios including cache failure, masked-output fallback, blocked non-persistence, multi-turn agents, and /v1/messages path.

Confidence Score: 4/5

Safe to merge for the common case; the two flag-interaction gaps both over-scan rather than under-scan, so guardrail coverage is never reduced.

The incremental scan logic is sound and the masking/blocking fallbacks are correctly wired. The two open issues are both in the direction of doing more work than intended (scanning content a flag should have excluded, or silently full-scanning on non-Bedrock guardrails) rather than skipping content that should be checked. No content is ever silently allowed through when it should be blocked.

litellm/integrations/custom_guardrail.py and litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py — the flag-interaction handling between only_scan_new_messages and experimental_use_latest_role_message_only, and the missing warning for non-Bedrock guardrails.

Important Files Changed

Filename Overview
litellm/constants.py Adds GUARDRAIL_SCANNED_MESSAGES_CACHE_TTL_SECONDS (default 24h, env-overridable) following existing pattern.
litellm/types/guardrails.py Adds Optional[bool] only_scan_new_messages field to BaseLitellmParams with a descriptive docstring; defaults to False.
litellm/integrations/custom_guardrail.py Adds only_scan_new_messages flag, filter_new_texts_for_session, and mark_texts_scanned helpers to CustomGuardrail; helpers are wired only in BedrockGuardrail so other guardrails silently ignore the flag.
litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py Adds _apply_incremental_request_scan, _bedrock_response_has_masked_output, and _incremental_scan_cache; wires incremental scan into apply_guardrail for input_type=request. Known gap: experimental_use_latest_role_message_only bypass is not guarded here.
litellm/proxy/guardrails/guardrail_initializers.py Passes only_scan_new_messages to BedrockGuardrail constructor; uses or False to coerce None from Optional[bool] to False.
tests/test_litellm/integrations/test_custom_guardrail.py Adds TestOnlyScanNewMessages with 13 unit tests covering feature-off, no session id, masking guard, cache failure, deduplication, edit rescan, blocked non-persistence, TTL, and multi-source session ids — all mocked, no real network calls.
tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py Adds TestBedrockOnlyScanNewMessages and TestBedrockIncrementalFlagInteractions; exercises apply_guardrail directly with patched make_bedrock_api_request; includes xfail for the documented experimental_use_latest_role_message_only gap.
tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py Adds TestAnthropicMessagesIncrementalScan verifying the /v1/messages path: first turn, diff turn, identical resend, edited history, and tool-use text preservation — all mocked.
tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py Adds TestIncrementalScanRespectsSkipFlags verifying skip_system_message_in_guardrail and skip_tool_message_in_guardrail compose correctly with incremental mode.

Reviews (5): Last reviewed commit: "test(guardrails): prove skip_system/skip..." | Re-trigger Greptile

…matting

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
@codspeed

codspeed Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_guardrail_only_scan_new_messages (79c1719) with litellm_internal_staging (2b2ae4c)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (1ea7db2) during the generation of this report, so 2b2ae4c was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

devin-ai-integration Bot and others added 3 commits July 14, 2026 23:03
…drail path

The initial wiring lived in BedrockGuardrail.async_pre_call_hook, but the proxy
routes Bedrock through the unified apply_guardrail interface, so the flag had no
effect live. Move incremental selection into apply_guardrail: filter the flat
texts list against per-session scanned hashes, skip the Bedrock call when nothing
is new, and mark hashes only after a successful (non-blocked) scan. Full-context
fallback is preserved when there is no session id, the cache is unavailable, or a
masking guardrail is configured.

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
…uards

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
@yucheng-berri

Copy link
Copy Markdown
Contributor

@greptileai review on latest head

…sks content, use shared cache

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
@yucheng-berri

Copy link
Copy Markdown
Contributor

@greptileai review latest head

@yucheng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 05dcf54. Configure here.

devin-ai-integration Bot and others added 4 commits July 16, 2026 21:17
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
@yucheng-berri

Copy link
Copy Markdown
Contributor

@greptileai review latest head

@yucheng-berri

Copy link
Copy Markdown
Contributor

Regarding the confidence-score gap ("the incremental path bypasses _select_messages_for_apply_guardrail, so skip_system_message_in_guardrail and skip_tool_message_in_guardrail are silently unenforced on a session's first turn"): the bypass is real but it cannot unenforce those two flags, because they are not implemented in _select_messages_for_apply_guardrail. They are enforced upstream in the endpoint translation handlers while inputs["texts"] is being built: _extract_inputs early-returns for role=="system" and role=="tool" (litellm/llms/openai/chat/guardrail_translation/handler.py), and the registry applies the per-guardrail flags as instance attributes (litellm/proxy/guardrails/guardrail_registry.py). The incremental scan diffs the already-filtered list, so skipped content is never present to scan, on the first turn or any later one. The only flag the bypass does affect is experimental_use_latest_role_message_only, which is documented in the description's validation section as a known gap

This was verified live before being encoded in a test: a proxy configured with only_scan_new_messages: true, skip_system_message_in_guardrail: true, and skip_tool_message_in_guardrail: true sent a first-turn conversation containing a system prompt, an assistant tool call, and a tool result to a real Bedrock ApplyGuardrail; the wire payload contained neither the system prompt nor the tool result, and the follow-up turn scanned only the newly appended segments

Commit 79c1719 adds TestIncrementalScanRespectsSkipFlags to the OpenAI handler test file covering exactly this combination: first turn scans no system or tool content, second turn scans only new eligible content

@yucheng-berri

Copy link
Copy Markdown
Contributor

@greptileai review latest head

@yucheng-berri
yucheng-berri merged commit fa6b209 into litellm_internal_staging Jul 22, 2026
77 of 81 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_guardrail_only_scan_new_messages branch July 22, 2026 16:57
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