Repository navigation
feat(guardrails): add only_scan_new_messages for per-session incremental scanning - #33278
yucheng-berri merged 11 commits into
Conversation
…tal scanning Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR adds an opt-in
Confidence Score: 4/5Safe 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.
|
| 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>
…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>
…itellm_guardrail_only_scan_new_messages
…uards Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
|
@greptileai review on latest head |
…sks content, use shared cache Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
|
@greptileai review latest head |
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
|
@greptileai review latest head |
…f incremental scan
|
Regarding the confidence-score gap ("the incremental path bypasses This was verified live before being encoded in a test: a proxy configured with Commit 79c1719 adds |
|
@greptileai review latest head |
fa6b209
into
litellm_internal_staging
Relevant issues
Linear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Captured live at commit
29ca44115eagainst a real Bedrock guardrail (ApplyGuardrail, real Anthropic model responses) through a local proxy withonly_scan_new_messages: true. Two turns share one session viax-litellm-session-id, and--detailed_debuglogs show the exact payload sent to Bedrock each turn.Turn 1 (new session) sends the full initial context to Bedrock:
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:
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/messagesendpoint (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 oneclaudesession (claude -pthenclaude -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 (ParisandAnd Germany? One word.).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 viaextra_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.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.Mechanism lives in the shared
CustomGuardraillayer as two helpers, wired into Bedrock'sapply_guardrail(the path the proxy actually runs for Bedrock via the unified guardrail interface; the earlierasync_pre_call_hookis no longer the live entrypoint):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, elsemetadata.session_id, elselitellm_metadata.session_id). Proxy header extraction already recognizesx-litellm-session-id,x-litellm-trace-id, and anyx-<vendor>-session-id. Claude Code sendsx-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": "..."}(ormetadata.session_id), an HTTP agent sets thex-litellm-session-idheader or alitellm_session_idbody 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
ApplyGuardrailreceives, 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_contentormask_response_contentis 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-checkedCache: 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-localDualCachewhere 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-scansKnown 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 offilter_new_texts_for_sessionfor a follow-up once a guardrail owner sets the default.Tests in
tests/test_litellm/integrations/test_custom_guardrail.pycover 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 intests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.pyexercise the liveapply_guardrailpath 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 carriesmetadata.session_idacross 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 bodylitellm_session_idall map to one session key; blocked segments are never cached and re-scan on retry;skip_system_message_in_guardrailandskip_tool_message_in_guardrailcompose 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-scansTwo combinations misbehave and should be fixed or rejected at config time.
experimental_use_latest_role_message_onlyis 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 responsePre-existing gaps, unchanged by this PR and follow-up ticket material: the /v1/messages input path never scans the top-level
systemfield,tool_usearguments, ortool_resultcontent (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 betterRegression 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
Link to Devin session: https://app.devin.ai/sessions/27b19ab26f3c4437a42d67917a5e5735
Requested by: @ishaan-berri