This is an automated email from the ASF dual-hosted git repository.
ferruzzi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 5f43598cb16 Fix Bedrock guardrail operators returning before guardrail
is ready (#76646)
5f43598cb16 is described below
commit 5f43598cb169b599a855a1262d1db0405c52dc6e
Author: Ramit Kataria <[email protected]>
AuthorDate: Thu Nov 19 15:42:05 2026 -0700
Fix Bedrock guardrail operators returning before guardrail is ready (#76646)
The create, update and create-version guardrail operators returned as
soon as the API call responded, while the guardrail could still be in a
transitional status. After a version is published, for example, the
DRAFT version reports VERSIONING for a few hundred milliseconds. Any
task that modified the guardrail right after, such as a delete following
a version publish, could fail with "This guardrail can't be modified at
this time". This made the example_bedrock_guardrail system test flaky,
and each failure leaked a guardrail because the delete never ran to
completion.
The operators now wait by default, which needs the bedrock:GetGuardrail
permission. A changelog warning documents that and how to opt out.
The create-version operator also waits before it publishes. A wait that
failed only afterwards, for example for a role without that permission,
would leave the version in place and each retry would publish another.
---
providers/amazon/docs/changelog.rst | 6 ++
.../providers/amazon/aws/operators/bedrock.py | 76 +++++++++++++++++--
.../providers/amazon/aws/waiters/bedrock.json | 43 +++++++++++
.../unit/amazon/aws/operators/test_bedrock.py | 85 +++++++++++++++++++---
.../tests/unit/amazon/aws/waiters/test_bedrock.py | 39 ++++++++++
5 files changed, 234 insertions(+), 15 deletions(-)
diff --git a/providers/amazon/docs/changelog.rst
b/providers/amazon/docs/changelog.rst
index e1cc68887ec..ea690844de0 100644
--- a/providers/amazon/docs/changelog.rst
+++ b/providers/amazon/docs/changelog.rst
@@ -26,6 +26,12 @@
Changelog
---------
+.. warning::
+ ``BedrockCreateGuardrailOperator``, ``BedrockUpdateGuardrailOperator`` and
+ ``BedrockCreateGuardrailVersionOperator`` now wait for the guardrail to
reach ``READY`` before
+ returning, so the task role needs the ``bedrock:GetGuardrail`` permission.
Pass
+ ``wait_for_completion=False`` to restore the previous behaviour.
+
9.41.0
......
diff --git
a/providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
b/providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
index c8e3a5c5ace..233ddfe5494 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
+++ b/providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
@@ -1373,8 +1373,8 @@ class
BedrockCreateGuardrailOperator(AwsBaseOperator[BedrockHook]):
Create an Amazon Bedrock guardrail to implement safeguards for generative
AI applications.
A guardrail can filter harmful content, block denied topics, filter words,
- and mask sensitive information. The guardrail is created with a DRAFT
version
- that is immediately usable.
+ and mask sensitive information. The guardrail is created with a DRAFT
version,
+ which is usable once it reaches READY. The operator waits for that by
default.
.. seealso::
For more information on how to use this operator, take a look at the
guide:
@@ -1393,6 +1393,9 @@ class
BedrockCreateGuardrailOperator(AwsBaseOperator[BedrockHook]):
:param tags: Tags to attach to the guardrail.
:param if_exists: Behavior when a guardrail with the same name already
exists.
``"fail"`` raises an error, ``"skip"`` returns the existing guardrail
ID.
+ :param wait_for_completion: Whether to wait for the guardrail to reach
READY status. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks.
(default: 2)
+ :param waiter_max_attempts: Maximum number of attempts to check for
guardrail readiness. (default: 60)
"""
aws_hook_class = BedrockHook
@@ -1424,6 +1427,9 @@ class
BedrockCreateGuardrailOperator(AwsBaseOperator[BedrockHook]):
kms_key_id: str | None = None,
tags: list[dict[str, str]] | None = None,
if_exists: Literal["fail", "skip"] = "skip",
+ wait_for_completion: bool = True,
+ waiter_delay: int = 2,
+ waiter_max_attempts: int = 60,
**kwargs,
) -> None:
super().__init__(**kwargs)
@@ -1439,6 +1445,9 @@ class
BedrockCreateGuardrailOperator(AwsBaseOperator[BedrockHook]):
self.kms_key_id = kms_key_id
self.tags = tags
self.if_exists = if_exists
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
def execute(self, context: Context) -> str:
kwargs: dict[str, Any] = prune_dict(
@@ -1468,6 +1477,15 @@ class
BedrockCreateGuardrailOperator(AwsBaseOperator[BedrockHook]):
else:
raise
self.log.info("Guardrail %s: %s", self.guardrail_name, guardrail_id)
+
+ if self.wait_for_completion:
+ self.log.info("Waiting for guardrail %s to be ready.",
guardrail_id)
+ self.hook.get_waiter("guardrail_ready").wait(
+ guardrailIdentifier=guardrail_id,
+ guardrailVersion="DRAFT",
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts":
self.waiter_max_attempts},
+ )
+
return guardrail_id
@@ -1522,6 +1540,10 @@ class
BedrockCreateGuardrailVersionOperator(AwsBaseOperator[BedrockHook]):
:param guardrail_identifier: The ID or ARN of the guardrail to version.
(templated)
:param description: Optional description for this version. (templated)
+ :param wait_for_completion: Whether to wait for the guardrail to be in
READY status, both before
+ creating the version and after. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks.
(default: 2)
+ :param waiter_max_attempts: Maximum number of attempts to check for
guardrail readiness. (default: 60)
"""
aws_hook_class = BedrockHook
@@ -1532,13 +1554,33 @@ class
BedrockCreateGuardrailVersionOperator(AwsBaseOperator[BedrockHook]):
*,
guardrail_identifier: str,
description: str | None = None,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 2,
+ waiter_max_attempts: int = 60,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.guardrail_identifier = guardrail_identifier
self.description = description
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+
+ def _wait_for_guardrail_ready(self, guardrail_identifier: str) -> None:
+ self.log.info("Waiting for guardrail %s to be ready.",
guardrail_identifier)
+ self.hook.get_waiter("guardrail_ready").wait(
+ guardrailIdentifier=guardrail_identifier,
+ guardrailVersion="DRAFT",
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts":
self.waiter_max_attempts},
+ )
def execute(self, context: Context) -> str:
+ if self.wait_for_completion:
+ # A wait that fails only after the version is published, for
example when the role lacks
+ # bedrock:GetGuardrail, makes every retry publish another version.
Waiting first fails
+ # the task while there is still nothing to duplicate.
+ self._wait_for_guardrail_ready(self.guardrail_identifier)
+
self.log.info("Creating version for guardrail %s",
self.guardrail_identifier)
kwargs: dict[str, Any] = prune_dict(
{
@@ -1547,8 +1589,13 @@ class
BedrockCreateGuardrailVersionOperator(AwsBaseOperator[BedrockHook]):
}
)
response = self.hook.conn.create_guardrail_version(**kwargs)
+ guardrail_id = response["guardrailId"]
version = response["version"]
- self.log.info("Guardrail %s version %s created.",
response["guardrailId"], version)
+ self.log.info("Guardrail %s version %s created.", guardrail_id,
version)
+
+ if self.wait_for_completion:
+ self._wait_for_guardrail_ready(guardrail_id)
+
return version
@@ -1569,6 +1616,9 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
:param content_policy_config: Optional content filter policy configuration
dict.
:param word_policy_config: Optional word filter policy configuration dict.
:param sensitive_information_policy_config: Optional sensitive information
policy dict.
+ :param wait_for_completion: Whether to wait for the guardrail to return to
READY status. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks.
(default: 2)
+ :param waiter_max_attempts: Maximum number of attempts to check for
guardrail readiness. (default: 60)
"""
aws_hook_class = BedrockHook
@@ -1588,6 +1638,9 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
content_policy_config: dict[str, Any] | None = None,
word_policy_config: dict[str, Any] | None = None,
sensitive_information_policy_config: dict[str, Any] | None = None,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 2,
+ waiter_max_attempts: int = 60,
**kwargs,
) -> None:
super().__init__(**kwargs)
@@ -1600,6 +1653,9 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
self.content_policy_config = content_policy_config
self.word_policy_config = word_policy_config
self.sensitive_information_policy_config =
sensitive_information_policy_config
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
def execute(self, context: Context) -> str:
self.log.info("Updating guardrail %s", self.guardrail_identifier)
@@ -1617,8 +1673,18 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
}
)
response = self.hook.conn.update_guardrail(**kwargs)
- self.log.info("Updated guardrail %s version %s",
response["guardrailId"], response["version"])
- return response["guardrailId"]
+ guardrail_id = response["guardrailId"]
+ self.log.info("Updated guardrail %s version %s", guardrail_id,
response["version"])
+
+ if self.wait_for_completion:
+ self.log.info("Waiting for guardrail %s to be ready.",
guardrail_id)
+ self.hook.get_waiter("guardrail_ready").wait(
+ guardrailIdentifier=guardrail_id,
+ guardrailVersion="DRAFT",
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts":
self.waiter_max_attempts},
+ )
+
+ return guardrail_id
class BedrockCreateEvaluationJobOperator(AwsBaseOperator[BedrockHook]):
diff --git
a/providers/amazon/src/airflow/providers/amazon/aws/waiters/bedrock.json
b/providers/amazon/src/airflow/providers/amazon/aws/waiters/bedrock.json
index 8e3f96996ef..65e85ccacee 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/waiters/bedrock.json
+++ b/providers/amazon/src/airflow/providers/amazon/aws/waiters/bedrock.json
@@ -202,6 +202,49 @@
"state": "success"
}
]
+ },
+ "guardrail_ready": {
+ "delay": 2,
+ "maxAttempts": 60,
+ "operation": "GetGuardrail",
+ "acceptors": [
+ {
+ "matcher": "path",
+ "argument": "status",
+ "expected": "READY",
+ "state": "success"
+ },
+ {
+ "matcher": "path",
+ "argument": "status",
+ "expected": "CREATING",
+ "state": "retry"
+ },
+ {
+ "matcher": "path",
+ "argument": "status",
+ "expected": "UPDATING",
+ "state": "retry"
+ },
+ {
+ "matcher": "path",
+ "argument": "status",
+ "expected": "VERSIONING",
+ "state": "retry"
+ },
+ {
+ "matcher": "path",
+ "argument": "status",
+ "expected": "FAILED",
+ "state": "failure"
+ },
+ {
+ "matcher": "path",
+ "argument": "status",
+ "expected": "DELETING",
+ "state": "failure"
+ }
+ ]
}
}
}
diff --git a/providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
b/providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
index 006bbd30327..7b9e36769b2 100644
--- a/providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
+++ b/providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
@@ -24,7 +24,7 @@ from typing import TYPE_CHECKING
from unittest import mock
import pytest
-from botocore.exceptions import ClientError
+from botocore.exceptions import ClientError, WaiterError
from moto import mock_aws
from airflow.providers.amazon.aws.hooks.bedrock import (
@@ -1200,6 +1200,26 @@ class TestBedrockBatchInferenceOperator:
GUARDRAIL_NAME = "test-guardrail"
GUARDRAIL_ID = "abc123"
+GUARDRAIL_WAIT_CASES = [
+ pytest.param({}, {"Delay": 2, "MaxAttempts": 60}, id="default_wait"),
+ pytest.param(
+ {"waiter_delay": 1, "waiter_max_attempts": 3}, {"Delay": 1,
"MaxAttempts": 3}, id="custom_wait"
+ ),
+ pytest.param({"wait_for_completion": False}, None, id="no_wait"),
+]
+
+
+def _assert_guardrail_waiter_called(mock_get_waiter, expected_waiter_config,
call_count=1):
+ if expected_waiter_config is None:
+ mock_get_waiter.assert_not_called()
+ else:
+ wait_call = mock.call(
+ guardrailIdentifier=GUARDRAIL_ID,
+ guardrailVersion="DRAFT",
+ WaiterConfig=expected_waiter_config,
+ )
+ assert mock_get_waiter.call_args_list == [mock.call(mock.ANY,
"guardrail_ready")] * call_count
+ assert mock_get_waiter.return_value.wait.call_args_list == [wait_call]
* call_count
class TestBedrockCreateGuardrailOperator:
@@ -1211,8 +1231,17 @@ class TestBedrockCreateGuardrailOperator:
blocked_outputs_messaging="Output blocked.",
)
+ @pytest.mark.parametrize(("wait_kwargs", "expected_waiter_config"),
GUARDRAIL_WAIT_CASES)
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
- def test_execute(self, mock_conn):
+ def test_execute(self, mock_conn, mock_get_waiter, wait_kwargs,
expected_waiter_config):
+ op = BedrockCreateGuardrailOperator(
+ task_id="create_guardrail",
+ guardrail_name=GUARDRAIL_NAME,
+ blocked_input_messaging="Input blocked.",
+ blocked_outputs_messaging="Output blocked.",
+ **wait_kwargs,
+ )
mock_client = mock.MagicMock()
mock_client.create_guardrail.return_value = {
"guardrailId": GUARDRAIL_ID,
@@ -1221,7 +1250,7 @@ class TestBedrockCreateGuardrailOperator:
}
mock_conn.return_value = mock_client
- result = self.operator.execute({})
+ result = op.execute({})
mock_client.create_guardrail.assert_called_once_with(
name=GUARDRAIL_NAME,
@@ -1229,9 +1258,11 @@ class TestBedrockCreateGuardrailOperator:
blockedOutputsMessaging="Output blocked.",
)
assert result == GUARDRAIL_ID
+ _assert_guardrail_waiter_called(mock_get_waiter,
expected_waiter_config)
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
- def test_execute_with_policies(self, mock_conn):
+ def test_execute_with_policies(self, mock_conn, _):
op = BedrockCreateGuardrailOperator(
task_id="create_guardrail",
guardrail_name=GUARDRAIL_NAME,
@@ -1254,9 +1285,10 @@ class TestBedrockCreateGuardrailOperator:
assert "contentPolicyConfig" in call_kwargs
assert result == GUARDRAIL_ID
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
@mock.patch.object(BedrockHook, "get_guardrail_id_by_name",
return_value=GUARDRAIL_ID)
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
- def test_execute_skip_existing(self, mock_conn, mock_get_id):
+ def test_execute_skip_existing(self, mock_conn, mock_get_id,
mock_get_waiter):
mock_client = mock.MagicMock()
mock_client.create_guardrail.side_effect = ClientError(
{"Error": {"Code": "ConflictException", "Message": "Already
exists"}},
@@ -1268,6 +1300,7 @@ class TestBedrockCreateGuardrailOperator:
assert result == GUARDRAIL_ID
mock_get_id.assert_called_once_with(GUARDRAIL_NAME)
+ _assert_guardrail_waiter_called(mock_get_waiter, {"Delay": 2,
"MaxAttempts": 60})
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
def test_execute_fail_on_conflict(self, mock_conn):
@@ -1351,8 +1384,15 @@ class TestBedrockCreateGuardrailVersionOperator:
guardrail_identifier=GUARDRAIL_ID,
)
+ @pytest.mark.parametrize(("wait_kwargs", "expected_waiter_config"),
GUARDRAIL_WAIT_CASES)
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
- def test_execute(self, mock_conn):
+ def test_execute(self, mock_conn, mock_get_waiter, wait_kwargs,
expected_waiter_config):
+ op = BedrockCreateGuardrailVersionOperator(
+ task_id="create_guardrail_version",
+ guardrail_identifier=GUARDRAIL_ID,
+ **wait_kwargs,
+ )
mock_client = mock.MagicMock()
mock_client.create_guardrail_version.return_value = {
"guardrailId": GUARDRAIL_ID,
@@ -1360,13 +1400,27 @@ class TestBedrockCreateGuardrailVersionOperator:
}
mock_conn.return_value = mock_client
- result = self.operator.execute({})
+ result = op.execute({})
mock_client.create_guardrail_version.assert_called_once_with(guardrailIdentifier=GUARDRAIL_ID)
assert result == "1"
+ _assert_guardrail_waiter_called(mock_get_waiter,
expected_waiter_config, call_count=2)
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
- def test_execute_with_description(self, mock_conn):
+ def test_execute_creates_no_version_when_wait_before_fails(self,
mock_conn, mock_get_waiter):
+ mock_get_waiter.return_value.wait.side_effect = WaiterError(
+ name="guardrail_ready", reason="AccessDeniedException",
last_response={}
+ )
+
+ with pytest.raises(WaiterError):
+ self.operator.execute({})
+
+ mock_conn.return_value.create_guardrail_version.assert_not_called()
+
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
+ @mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
+ def test_execute_with_description(self, mock_conn, _):
op = BedrockCreateGuardrailVersionOperator(
task_id="create_guardrail_version",
guardrail_identifier=GUARDRAIL_ID,
@@ -1400,8 +1454,18 @@ class TestBedrockUpdateGuardrailOperator:
blocked_outputs_messaging="Blocked.",
)
+ @pytest.mark.parametrize(("wait_kwargs", "expected_waiter_config"),
GUARDRAIL_WAIT_CASES)
+ @mock.patch.object(BedrockHook, "get_waiter", autospec=True)
@mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
- def test_execute(self, mock_conn):
+ def test_execute(self, mock_conn, mock_get_waiter, wait_kwargs,
expected_waiter_config):
+ op = BedrockUpdateGuardrailOperator(
+ task_id="update_guardrail",
+ guardrail_identifier=GUARDRAIL_ID,
+ guardrail_name="updated-guardrail",
+ blocked_input_messaging="Blocked.",
+ blocked_outputs_messaging="Blocked.",
+ **wait_kwargs,
+ )
mock_client = mock.MagicMock()
mock_client.update_guardrail.return_value = {
"guardrailId": GUARDRAIL_ID,
@@ -1411,10 +1475,11 @@ class TestBedrockUpdateGuardrailOperator:
}
mock_conn.return_value = mock_client
- result = self.operator.execute({})
+ result = op.execute({})
assert result == GUARDRAIL_ID
mock_client.update_guardrail.assert_called_once()
+ _assert_guardrail_waiter_called(mock_get_waiter,
expected_waiter_config)
def test_template_fields(self):
validate_template_fields(self.operator)
diff --git a/providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock.py
b/providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock.py
index 9c0dd81d53e..796f7cfd9f0 100644
--- a/providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock.py
+++ b/providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock.py
@@ -195,3 +195,42 @@ class
TestBatchInferenceScheduledWaiter(TestBedrockCustomWaitersBase):
BedrockHook().get_waiter(self.WAITER_NAME).wait(
jobIdentifier="job_arn", WaiterConfig={"Delay": 0.01,
"MaxAttempts": 1}
)
+
+
+class TestGuardrailReadyWaiter(TestBedrockCustomWaitersBase):
+ WAITER_NAME = "guardrail_ready"
+
+ @pytest.fixture
+ def mock_get_guardrail(self):
+ with mock.patch.object(self.client, "get_guardrail", autospec=True) as
mock_getter:
+ yield mock_getter
+
+ def test_guardrail_ready(self, mock_get_guardrail):
+ mock_get_guardrail.return_value = {"status": "READY"}
+
+ BedrockHook().get_waiter(self.WAITER_NAME).wait(
+ guardrailIdentifier="guardrail_id", guardrailVersion="DRAFT"
+ )
+
+ @pytest.mark.parametrize("state", ["FAILED", "DELETING"])
+ def test_guardrail_failed(self, state, mock_get_guardrail):
+ mock_get_guardrail.return_value = {"status": state}
+
+ with pytest.raises(botocore.exceptions.WaiterError):
+ BedrockHook().get_waiter(self.WAITER_NAME).wait(
+ guardrailIdentifier="guardrail_id", guardrailVersion="DRAFT"
+ )
+
+ @pytest.mark.parametrize("state", ["CREATING", "UPDATING", "VERSIONING"])
+ def test_guardrail_wait(self, state, mock_get_guardrail):
+ wait = {"status": state}
+ success = {"status": "READY"}
+ mock_get_guardrail.side_effect = [wait, wait, success]
+
+ BedrockHook().get_waiter(self.WAITER_NAME).wait(
+ guardrailIdentifier="guardrail_id",
+ guardrailVersion="DRAFT",
+ WaiterConfig={"Delay": 0.01, "MaxAttempts": 3},
+ )
+
+ assert mock_get_guardrail.call_count == 3