This is an automated email from the ASF dual-hosted git repository.
o-nikolas 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 97054e16194 Retry Bedrock guardrail changes while the guardrail is in
transition (#77225)
97054e16194 is described below
commit 97054e16194b93a1c7ec7e05f8624c4f86d1074d
Author: Ramit Kataria <[email protected]>
AuthorDate: Thu Nov 19 16:42:20 2026 -0700
Retry Bedrock guardrail changes while the guardrail is in transition
(#77225)
Amazon Bedrock rejects DeleteGuardrail, UpdateGuardrail and
CreateGuardrailVersion with "This guardrail can't be modified at this time"
while the guardrail is in a transitional status, such as the short VERSIONING
window after a version is published. The task failed, and a rejected delete
left the guardrail behind.
Waiting for READY in the operators that change a guardrail (#76646) covers
a guardrail changed earlier in the same Dag. A guardrail changed outside the
Dag, or by a task that opted out of waiting, could still fail the next task
that touches it.
Bedrock reports this as a ValidationException, the code it also uses for
invalid input, so that code is retried only with this message.
ConflictException, which all three APIs document for a conflict, is retried as
well in case Bedrock switches to it.
---
.../providers/amazon/aws/operators/bedrock.py | 70 +++++++++--
.../unit/amazon/aws/operators/test_bedrock.py | 131 +++++++++++++++++++++
2 files changed, 194 insertions(+), 7 deletions(-)
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 233ddfe5494..2eca55ee0ef 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
+++ b/providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
@@ -17,10 +17,12 @@
from __future__ import annotations
import json
+import logging
from collections.abc import Sequence
from time import sleep
from typing import TYPE_CHECKING, Any, Literal
+import tenacity
from botocore.exceptions import ClientError
from airflow.providers.amazon.aws.hooks.bedrock import (
@@ -51,6 +53,7 @@ from airflow.utils.helpers import prune_dict
if TYPE_CHECKING:
from airflow.providers.amazon.aws.triggers.bedrock import
BedrockBaseBatchInferenceTrigger
from airflow.sdk import Context
+ from airflow.sdk.types import Logger
class BedrockInvokeModelOperator(AwsBaseOperator[BedrockRuntimeHook]):
@@ -1489,16 +1492,47 @@ class
BedrockCreateGuardrailOperator(AwsBaseOperator[BedrockHook]):
return guardrail_id
+def _is_guardrail_in_transition_error(exception: BaseException) -> bool:
+ if not isinstance(exception, ClientError):
+ return False
+ error = exception.response.get("Error", {})
+ code = error.get("Code")
+ # Bedrock reports a guardrail in a transitional status as a
ValidationException, the code it
+ # also uses for invalid input, so only the message tells the two apart.
ConflictException is
+ # what the guardrail APIs document for a conflict, so it is retried in
case Bedrock switches to it.
+ return code == "ConflictException" or (
+ code == "ValidationException" and "be modified at this time" in
error.get("Message", "")
+ )
+
+
+def _build_guardrail_in_transition_retrying(
+ logger: Logger | logging.Logger, waiter_delay: int, waiter_max_attempts:
int
+) -> tenacity.Retrying:
+ return tenacity.Retrying(
+ retry=tenacity.retry_if_exception(_is_guardrail_in_transition_error),
+ wait=tenacity.wait_fixed(waiter_delay),
+ stop=tenacity.stop_after_attempt(waiter_max_attempts),
+ before_sleep=tenacity.before_sleep_log(logger, logging.WARNING),
+ reraise=True,
+ )
+
+
class BedrockDeleteGuardrailOperator(AwsBaseOperator[BedrockHook]):
"""
Delete an Amazon Bedrock guardrail.
+ Amazon Bedrock rejects the delete while the guardrail is in a transitional
status, for example
+ right after a version is published. The operator retries until the
guardrail can be deleted.
+
.. seealso::
For more information on how to use this operator, take a look at the
guide:
:ref:`howto/operator:BedrockDeleteGuardrailOperator`
:param guardrail_identifier: The ID or ARN of the guardrail to delete.
(templated)
:param guardrail_version: Optional version number to delete a specific
version. (templated)
+ :param waiter_delay: Time in seconds to wait before retrying a delete that
was rejected because
+ the guardrail was in a transitional status. (default: 2)
+ :param waiter_max_attempts: Maximum number of times to attempt the delete.
(default: 60)
"""
aws_hook_class = BedrockHook
@@ -1509,11 +1543,15 @@ class
BedrockDeleteGuardrailOperator(AwsBaseOperator[BedrockHook]):
*,
guardrail_identifier: str,
guardrail_version: str | None = None,
+ waiter_delay: int = 2,
+ waiter_max_attempts: int = 60,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.guardrail_identifier = guardrail_identifier
self.guardrail_version = guardrail_version
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
def execute(self, context: Context) -> None:
self.log.info("Deleting Bedrock guardrail %s",
self.guardrail_identifier)
@@ -1523,7 +1561,9 @@ class
BedrockDeleteGuardrailOperator(AwsBaseOperator[BedrockHook]):
"guardrailVersion": self.guardrail_version,
}
)
- self.hook.conn.delete_guardrail(**kwargs)
+ _build_guardrail_in_transition_retrying(self.log, self.waiter_delay,
self.waiter_max_attempts)(
+ self.hook.conn.delete_guardrail, **kwargs
+ )
self.log.info("Deleted guardrail %s", self.guardrail_identifier)
@@ -1534,6 +1574,10 @@ class
BedrockCreateGuardrailVersionOperator(AwsBaseOperator[BedrockHook]):
Guardrails are created as DRAFT. This operator publishes a numbered version
that can be referenced in production workloads.
+ Amazon Bedrock rejects the call while the guardrail is in a transitional
status, for example
+ right after another version is published. The operator retries until the
version can be created,
+ whether or not ``wait_for_completion`` is set.
+
.. seealso::
For more information on how to use this operator, take a look at the
guide:
:ref:`howto/operator:BedrockCreateGuardrailVersionOperator`
@@ -1542,8 +1586,10 @@ class
BedrockCreateGuardrailVersionOperator(AwsBaseOperator[BedrockHook]):
: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)
+ :param waiter_delay: Time in seconds to wait between status checks, and
before retrying a call
+ that was rejected because the guardrail was in a transitional status.
(default: 2)
+ :param waiter_max_attempts: Maximum number of attempts to check for
guardrail readiness, and to
+ create the version. (default: 60)
"""
aws_hook_class = BedrockHook
@@ -1588,7 +1634,9 @@ class
BedrockCreateGuardrailVersionOperator(AwsBaseOperator[BedrockHook]):
"description": self.description,
}
)
- response = self.hook.conn.create_guardrail_version(**kwargs)
+ response = _build_guardrail_in_transition_retrying(
+ self.log, self.waiter_delay, self.waiter_max_attempts
+ )(self.hook.conn.create_guardrail_version, **kwargs)
guardrail_id = response["guardrailId"]
version = response["version"]
self.log.info("Guardrail %s version %s created.", guardrail_id,
version)
@@ -1603,6 +1651,10 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
"""
Update an Amazon Bedrock guardrail configuration.
+ Amazon Bedrock rejects the update while the guardrail is in a transitional
status, for example
+ right after a version is published. The operator retries until the update
is accepted, whether
+ or not ``wait_for_completion`` is set.
+
.. seealso::
For more information on how to use this operator, take a look at the
guide:
:ref:`howto/operator:BedrockUpdateGuardrailOperator`
@@ -1617,8 +1669,10 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
: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)
+ :param waiter_delay: Time in seconds to wait between status checks, and
before retrying an update
+ that was rejected because the guardrail was in a transitional status.
(default: 2)
+ :param waiter_max_attempts: Maximum number of attempts to check for
guardrail readiness, and to
+ update the guardrail. (default: 60)
"""
aws_hook_class = BedrockHook
@@ -1672,7 +1726,9 @@ class
BedrockUpdateGuardrailOperator(AwsBaseOperator[BedrockHook]):
"sensitiveInformationPolicyConfig":
self.sensitive_information_policy_config,
}
)
- response = self.hook.conn.update_guardrail(**kwargs)
+ response = _build_guardrail_in_transition_retrying(
+ self.log, self.waiter_delay, self.waiter_max_attempts
+ )(self.hook.conn.update_guardrail, **kwargs)
guardrail_id = response["guardrailId"]
self.log.info("Updated guardrail %s version %s", guardrail_id,
response["version"])
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 7b9e36769b2..e8b75706767 100644
--- a/providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
+++ b/providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
@@ -1341,7 +1341,24 @@ class TestBedrockCreateGuardrailOperator:
GUARDRAIL_ID = "abc123"
+def _build_guardrail_in_transition_error(operation_name: str) -> ClientError:
+ return ClientError(
+ {
+ "Error": {
+ "Code": "ValidationException",
+ "Message": "This guardrail can't be modified at this time.",
+ }
+ },
+ operation_name,
+ )
+
+
class TestBedrockDeleteGuardrailOperator:
+ IN_TRANSITION_ERROR =
_build_guardrail_in_transition_error("DeleteGuardrail")
+ CONFLICT_ERROR = ClientError(
+ {"Error": {"Code": "ConflictException", "Message": "Conflict"}},
"DeleteGuardrail"
+ )
+
def setup_method(self):
self.operator = BedrockDeleteGuardrailOperator(
task_id="delete_guardrail",
@@ -1373,6 +1390,69 @@ class TestBedrockDeleteGuardrailOperator:
guardrailIdentifier=GUARDRAIL_ID, guardrailVersion="1"
)
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(IN_TRANSITION_ERROR, id="in_transition"),
+ pytest.param(CONFLICT_ERROR, id="conflict"),
+ ],
+ )
+ @mock.patch("time.sleep", return_value=None)
+ @mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
+ def test_execute_retries_while_guardrail_is_in_transition(self, mock_conn,
mock_sleep, error):
+ mock_client = mock.MagicMock()
+ mock_client.delete_guardrail.side_effect = [error, error, {}]
+ mock_conn.return_value = mock_client
+
+ self.operator.execute({})
+
+ assert mock_client.delete_guardrail.call_count == 3
+ assert mock_sleep.call_args_list == [mock.call(2), mock.call(2)]
+
+ @mock.patch("time.sleep", return_value=None)
+ @mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
+ def test_execute_stops_retrying_after_max_attempts(self, mock_conn,
mock_sleep):
+ op = BedrockDeleteGuardrailOperator(
+ task_id="delete_guardrail",
+ guardrail_identifier=GUARDRAIL_ID,
+ waiter_delay=7,
+ waiter_max_attempts=2,
+ )
+ mock_client = mock.MagicMock()
+ mock_client.delete_guardrail.side_effect = self.IN_TRANSITION_ERROR
+ mock_conn.return_value = mock_client
+
+ with pytest.raises(ClientError):
+ op.execute({})
+
+ assert mock_client.delete_guardrail.call_count == 2
+ mock_sleep.assert_called_once_with(7)
+
+ @pytest.mark.parametrize(
+ ("code", "message"),
+ [
+ pytest.param("ValidationException", "Invalid guardrail
identifier", id="other_message"),
+ pytest.param(
+ "AccessDeniedException", "This guardrail can't be modified at
this time.", id="other_code"
+ ),
+ ],
+ )
+ @mock.patch("time.sleep", return_value=None)
+ @mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
+ def test_execute_does_not_retry_other_errors(self, mock_conn, mock_sleep,
code, message):
+ mock_client = mock.MagicMock()
+ mock_client.delete_guardrail.side_effect = [
+ self.IN_TRANSITION_ERROR,
+ ClientError({"Error": {"Code": code, "Message": message}},
"DeleteGuardrail"),
+ ]
+ mock_conn.return_value = mock_client
+
+ with pytest.raises(ClientError, match=message):
+ self.operator.execute({})
+
+ assert mock_client.delete_guardrail.call_count == 2
+ mock_sleep.assert_called_once_with(2)
+
def test_template_fields(self):
validate_template_fields(self.operator)
@@ -1440,6 +1520,30 @@ class TestBedrockCreateGuardrailVersionOperator:
)
assert result == "2"
+ @mock.patch("time.sleep", return_value=None)
+ @mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
+ def test_execute_retries_while_guardrail_is_in_transition(self, mock_conn,
mock_sleep):
+ op = BedrockCreateGuardrailVersionOperator(
+ task_id="create_guardrail_version",
+ guardrail_identifier=GUARDRAIL_ID,
+ wait_for_completion=False,
+ waiter_delay=7,
+ )
+ error = _build_guardrail_in_transition_error("CreateGuardrailVersion")
+ mock_client = mock.MagicMock()
+ mock_client.create_guardrail_version.side_effect = [
+ error,
+ error,
+ {"guardrailId": GUARDRAIL_ID, "version": "1"},
+ ]
+ mock_conn.return_value = mock_client
+
+ result = op.execute({})
+
+ assert result == "1"
+ assert mock_client.create_guardrail_version.call_count == 3
+ assert mock_sleep.call_args_list == [mock.call(7), mock.call(7)]
+
def test_template_fields(self):
validate_template_fields(self.operator)
@@ -1481,6 +1585,33 @@ class TestBedrockUpdateGuardrailOperator:
mock_client.update_guardrail.assert_called_once()
_assert_guardrail_waiter_called(mock_get_waiter,
expected_waiter_config)
+ @mock.patch("time.sleep", return_value=None)
+ @mock.patch.object(BedrockHook, "conn", new_callable=mock.PropertyMock)
+ def test_execute_retries_while_guardrail_is_in_transition(self, mock_conn,
mock_sleep):
+ op = BedrockUpdateGuardrailOperator(
+ task_id="update_guardrail",
+ guardrail_identifier=GUARDRAIL_ID,
+ guardrail_name="updated-guardrail",
+ blocked_input_messaging="Blocked.",
+ blocked_outputs_messaging="Blocked.",
+ wait_for_completion=False,
+ waiter_delay=7,
+ )
+ error = _build_guardrail_in_transition_error("UpdateGuardrail")
+ mock_client = mock.MagicMock()
+ mock_client.update_guardrail.side_effect = [
+ error,
+ error,
+ {"guardrailId": GUARDRAIL_ID, "version": "DRAFT"},
+ ]
+ mock_conn.return_value = mock_client
+
+ result = op.execute({})
+
+ assert result == GUARDRAIL_ID
+ assert mock_client.update_guardrail.call_count == 3
+ assert mock_sleep.call_args_list == [mock.call(7), mock.call(7)]
+
def test_template_fields(self):
validate_template_fields(self.operator)