[BUG] Python guardrail redaction is not source-aware: an output-only block still redacts the user's clean input
Checks
- [x] I have updated to the lastest minor and patch version of Strands
- [x] I have checked the documentation and this is not expected behavior
- [x] I have searched ./issues and there are no duplicates of my issue
SDK Language
Python
Strands Version
monorepo main @ c0776c008be7d16367f7d5cca792a635fa0b92b1 (installed with pip install -e '.[dev]' from strands-py/)
Language Runtime Version
Python 3.12.13
Operating System
Amazon Linux 2023.12.20260710 (Linux 6.1.161-18.298.amzn2023.aarch64)
Installation Method
git clone
Steps to Reproduce
A Bedrock guardrail configured on both input and output, where the input assessment comes back clean (action: "NONE", detected: False) and only the output assessment blocks (action: "BLOCKED", detected: True), still causes the user's clean prompt to be overwritten with [User input redacted.] in conversation history.
The SDK already has the right primitive but doesn't apply it per side. _has_blocked_guardrail (strands-py/src/strands/models/bedrock.py:785) checks each side independently via the recursive _find_detected_and_blocked_policy (:1199, which looks for action == "BLOCKED" and detected) — but it collapses the answer to a single bool:
# strands-py/src/strands/models/bedrock.py:785-805
def _has_blocked_guardrail(self, guardrail_data: dict[str, Any]) -> bool:
input_assessment = guardrail_data.get("inputAssessment", {})
output_assessments = guardrail_data.get("outputAssessments", {})
if any(self._find_detected_and_blocked_policy(a) for a in input_assessment.values()):
return True
if any(self._find_detected_and_blocked_policy(a) for a in output_assessments.values()):
return True
return False
…and _generate_redaction_events takes no guardrail_data argument at all — it emits purely off config flags:
# strands-py/src/strands/models/bedrock.py:807-831
def _generate_redaction_events(self) -> list[StreamEvent]:
events: list[StreamEvent] = []
if self.config.get("guardrail_redact_input", True): # :815 default TRUE
events.append({"redactContent": {"redactUserContentMessage": ...}})
if self.config.get("guardrail_redact_output", False): # :827 default False
events.append({"redactContent": {"redactAssistantContentMessage": ...}})
Both call sites are "did anything block anywhere" → "fire every configured redaction":
# :1025-1027 (converse_stream path)
if self._has_blocked_guardrail(guardrail_data):
for event in self._generate_redaction_events():
callback(event)
# :1039-1042 (non-streaming converse path) — same shape
So which side blocked is computed and then discarded. Agent-side, redactUserContentMessage overwrites self.messages[-1]["content"] (strands-py/src/strands/agent/agent.py:1304-1312, via _redact_user_content at :1619).
Repro — BedrockModel with a mocked boto3 client (same fixture style as strands-py/tests/strands/models/test_bedrock.py), plus a real Agent on the same model:
======================================================================
PART A: BedrockModel.stream() directly (non-streaming converse path)
======================================================================
Input assessment: action=NONE, detected=False (clean)
Output assessment: action=BLOCKED, detected=True (blocked)
All emitted redactContent events:
{'redactContent': {'redactUserContentMessage': '[User input redacted.]'}}
{'redactContent': {'redactAssistantContentMessage': '[Assistant output redacted.]'}}
redactUserContentMessage emitted? True (BUG if True: input was clean)
redactAssistantContentMessage emitted? True (correct: output was blocked)
======================================================================
PART B: real Agent wired to the same mocked model
======================================================================
User prompt sent: 'What is on the cactus?'
agent.messages after the call:
[0] role='user' content=[{'text': '[User input redacted.]'}]
[1] role='assistant' content=[{'text': '[Assistant output redacted.]'}]
The user's clean prompt is gone. Happy to contribute the repro as a unit test.
Expected Behavior
Redaction should be source-aware: only redact the user's input when the input side actually blocked, and only redact the assistant's output when the output side actually blocked. _find_detected_and_blocked_policy already computes exactly this signal per side — it just needs to be threaded through to _generate_redaction_events instead of collapsed to one bool.
Actual Behavior
Any block on either side triggers every configured redaction. With the default guardrail_redact_input=True, an output-only intervention destroys the user's clean prompt in conversation history — and since the message log is what gets persisted and resent, that loss is permanent.
Additional Context
Not a regression — present on main (c0776c008), independent of any open PR.
No existing test covers it. Checked strands-py/tests/strands/models/test_bedrock.py (test_stream_stream_input_guardrails, test_stream_stream_output_guardrails, test_stream_output_guardrails_redacts_input_and_output, test_stream_output_no_blocked_guardrails_doesnt_redact, test_stream_output_no_guardrail_redact, test_stream_input_guardrails, test_stream_output_guardrails, test_stream_output_guardrails_redacts_output) and strands-py/tests/strands/agent/test_agent.py (test_agent_redacts_input_on_triggered_guardrail, test_agent_restored_from_session_management_with_redacted_input, test_redact_user_content). Every case has one side present-and-blocked with the other side's key simply absent — none has a side present-and-clean. test_stream_output_guardrails_redacts_input_and_output asserts today's coupling as intended behavior, but with inputAssessment omitted entirely, so it doesn't cover the case above.
Cross-language: this is the Python twin of finding 2 in the review of #3608. TypeScript has the same class of gap and #3608 proposes gating on guardrailData.inputAssessment !== undefined / outputAssessments !== undefined — a presence check, which is not equivalent (the keys are populated whenever that side was assessed, clean or not; see the AWS GuardrailTraceAssessment shape). Python already has the semantically correct action == "BLOCKED" and detected walk, so ideally both SDKs converge on Python's primitive applied per side. Tagging as sdk-parity territory — fixing one without the other leaves the two SDKs making different redaction decisions for the same trace.
Possible Solution
Split the per-side answer and pass it down. Sketch:
def _blocked_guardrail_sides(self, guardrail_data: dict[str, Any]) -> tuple[bool, bool]:
"""Return (input_blocked, output_blocked)."""
input_blocked = any(
self._find_detected_and_blocked_policy(a) for a in guardrail_data.get("inputAssessment", {}).values()
)
output_blocked = any(
self._find_detected_and_blocked_policy(a) for a in guardrail_data.get("outputAssessments", {}).values()
)
return input_blocked, output_blocked
def _generate_redaction_events(self, *, input_blocked: bool, output_blocked: bool) -> list[StreamEvent]:
events: list[StreamEvent] = []
if input_blocked and self.config.get("guardrail_redact_input", True):
...
if output_blocked and self.config.get("guardrail_redact_output", False):
...
return events
Both methods are private, so the signature change is internal — but note test_stream_output_guardrails_redacts_input_and_output currently asserts the coupled behavior and would need updating, and the guardrails user guide (site/src/content/docs/user-guide/safety-security/guardrails.mdx) describes redaction without the input/output distinction. Also worth keeping in mind that a guardrail can block on input because of tool-result content, since with no guardContent scoping Bedrock assesses the whole request body — so "input blocked" doesn't necessarily mean "the human's prompt was the problem". That target-selection question is being discussed on #3608 and #2992.
Related Issues
Split out from the review of #3608 (finding 2 — the TypeScript side of the same gap). Related: #2992, #1077 / #1080. TypeScript-side sibling filed as #3612 (trace: 'disabled' disabling redaction entirely), which has the same structural dependency in Python at bedrock.py:1038-1042.
Thanks for reporting this!
I understand that the bedrock guardrailing feature is lacking the granularity to redact based on bedrocks guardrail response. I am interested in a feature like this, but would like to see a proposal for how to implement this before I would feel comfortable reviewing a pull request on it. This is not a bug, but working as intended, so the proposed solution above would actually break existing implementations. Please include a proposal, with some sample code, for how to fix this issue!
Thanks for clarifying that the current behavior is intentional and that changing it directly would be breaking. I would be interested in working on this after aligning on a backward-compatible design.
My proposal is to keep the current behavior as the default and add an opt-in source-aware redaction mode. The exact public name is open to maintainer preference; for example:
model = BedrockModel(
guardrail_id="...",
guardrail_version="...",
guardrail_redaction_mode="blocked_source", # default: "configured"
guardrail_redact_input=True,
guardrail_redact_output=True,
)
Proposed semantics:
configured(default): preserve today's behavior. If either side is blocked, emit every redaction event enabled byguardrail_redact_input/guardrail_redact_output.blocked_source: when guardrail trace assessments are available, emit input redaction only wheninputAssessmentcontains a blocked/detected policy, and output redaction only whenoutputAssessmentsdoes.- If trace data is unavailable, fall back to the existing configured behavior rather than fail open. The documentation would note that precise source-aware behavior requires guardrail trace data.
A possible internal shape would be:
def _blocked_guardrail_sides(
self, guardrail_data: dict[str, Any]
) -> tuple[bool, bool]:
input_blocked = any(
self._find_detected_and_blocked_policy(assessment)
for assessment in guardrail_data.get("inputAssessment", {}).values()
)
output_blocked = any(
self._find_detected_and_blocked_policy(assessment)
for assessment in guardrail_data.get("outputAssessments", {}).values()
)
return input_blocked, output_blocked
Those two signals would be passed to redaction-event generation instead of being collapsed into one boolean. Both streaming and non-streaming paths would use the same helper.
I would cover at least these cases with mocked Bedrock responses:
- legacy/default mode retains the current coupled behavior;
- source-aware mode with input-only blocking;
- source-aware mode with output-only blocking;
- source-aware mode with both sides blocked;
- source-aware mode with neither side blocked;
- missing trace falls back to the current behavior;
- an Agent-level assertion confirms a clean user message is retained for an output-only block.
Would an opt-in mode with this fallback policy be an acceptable direction? I will wait for alignment on the API name and fallback semantics before opening a PR.
It looks like the issue is with the guardrail logic not distinguishing between input and output blocking, causing unnecessary redaction of clean inputs. I'd check how _has_blocked_guardrail and _generate_redaction_events interact with the configuration flags.
Adding a reproduction that shows a practical impact of the current redaction behavior, in case it helps the design discussion here and in #1639 / #1978 / #2992.
Setup. strands-agents 1.64.0 on Amazon Bedrock (Claude Sonnet 4.6, eu-west-1). BedrockModel(guardrail_id=..., guardrail_version=..., guardrail_trace="enabled") with the defaults, so guardrail_latest_message is off. The guardrail has one denied topic. It blocks input and does not check output. The agent has one tool, and the tool returns content that would hit the denied topic.
Steps.
- Turn 1: the model calls the tool and summarizes its result. Output isn't checked, so the turn ends with
end_turn, and the blocked-topic text (the tool result and the assistant's summary of it) is now in history. - Turn 2: the user sends a harmless follow-up ("Thanks. Is there anything else I should know?"). The whole conversation is sent as guardrail input, so the call is blocked (
guardrail_intervened). ApplyGuardrail on each message alone confirms the trigger: the tool result and the summary trip input, the follow-up on its own doesn't. - Redaction replaces
messages[-1], which is the harmless follow-up. The messages that caused the block stay in history. - Every later turn in that session is blocked the same way. If the caller re-sends after
guardrail_intervened, it never ends. We stopped at 8 of 8 blocked attempts; each attempt is a model call plus a guardrail check.
Changes that avoided it in the same setup.
guardrail_latest_message=TrueonBedrockModel: only the latest user text is checked, so earlier content can't keep blocking the session. Follow-up passed on the first try.- A guardrail that also checks output: the offending answer never reaches history. (We confirmed this on an AgentCore harness, where
guardrail_latest_messageisn't exposed.)
So the current behavior can leave a session permanently blocked whenever the content the guardrail is reacting to isn't the message being redacted. That seems relevant to whichever opt-in design lands here. I'm happy to share the script if useful.
I also opened #6137, a docs-only PR that describes the current redaction behavior on the guardrails page and documents guardrail_latest_message=True. It doesn't change any code.