Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/#semantic-versioning-200).

## [Unreleased]

### :magic_wand: Added
* The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275))

## [3.1.0] - 2026-08-24
### :magic_wand: Added
* Python 3.14 support. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252))
Expand Down
10 changes: 10 additions & 0 deletions aws_advanced_python_wrapper/failover_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def __init__(self, plugin_service: PluginService, props: Properties):
self._writer_failover_handler: WriterFailoverHandler

self._enable_failover_setting = WrapperProperties.ENABLE_FAILOVER.get_bool(self._properties)
self._preserve_driver_exception_type = WrapperProperties.PRESERVE_DRIVER_EXCEPTION_TYPE.get_bool(self._properties)
self._failover_timeout_sec = WrapperProperties.FAILOVER_TIMEOUT_SEC.get_float(self._properties)
self._failover_cluster_topology_refresh_rate_sec = WrapperProperties.FAILOVER_CLUSTER_TOPOLOGY_REFRESH_RATE_SEC.get_float(
self._properties)
Expand Down Expand Up @@ -175,6 +176,15 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args:

self._pick_new_connection()
self._last_exception = ex

# This line is only reachable if the original error does not trigger a connection switch.
if self._preserve_driver_exception_type:
# Re-raise the error as-is.
raise

# Replacing the error discards the driver's exception class, which is what SQLAlchemy,
# Django and similar libraries classify a failure by. Kept as the default for backwards
# compatibility.
raise AwsWrapperError(Messages.get_formatted("FailoverPlugin.DetectedException", str(ex)), ex) from ex

def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]):
Expand Down
17 changes: 12 additions & 5 deletions aws_advanced_python_wrapper/failover_v2_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from __future__ import annotations

import time
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Set
from typing import TYPE_CHECKING, Any, Callable, Dict, NoReturn, Optional, Set

from aws_advanced_python_wrapper.pep249_methods import DbApiMethod

Expand Down Expand Up @@ -83,6 +83,7 @@ def __init__(self, plugin_service: PluginService, props: Properties):
strategy = WrapperProperties.FAILOVER_READER_HOST_SELECTOR_STRATEGY.get(self._properties)
self._failover_reader_host_selector_strategy: str = strategy if strategy is not None else ""
self._enable_connect_failover = WrapperProperties.ENABLE_CONNECT_FAILOVER.get_bool(self._properties)
self._preserve_driver_exception_type = WrapperProperties.PRESERVE_DRIVER_EXCEPTION_TYPE.get_bool(self._properties)

self._closed_explicitly = False
self._is_closed = False
Expand All @@ -109,13 +110,11 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args,
self._invalid_invocation_on_closed_connection()

try:
result = execute_func()
return execute_func()
except Exception as e:
logger.debug("FailoverPlugin.DetectedException", str(e))
self._deal_with_original_exception(e)

return result

def init_host_provider(
self,
props: Properties,
Expand Down Expand Up @@ -195,7 +194,7 @@ def _invalid_invocation_on_closed_connection(self) -> None:
else:
raise AwsWrapperError("No operations allowed after connection closed")

def _deal_with_original_exception(self, original_exception: Exception) -> None:
def _deal_with_original_exception(self, original_exception: Exception) -> NoReturn:
if (self._last_exception_dealt_with != original_exception and
(self._should_exception_trigger_connection_switch(original_exception))):
self._invalidate_current_connection()
Expand All @@ -204,6 +203,14 @@ def _deal_with_original_exception(self, original_exception: Exception) -> None:
self._pick_new_connection()
self._last_exception_dealt_with = original_exception

# This line is only reachable if the original error does not trigger a connection switch.
if self._preserve_driver_exception_type:
# Re-raise the error as-is.
raise original_exception

# Replacing the error discards the driver's exception class, which is what SQLAlchemy,
# Django and similar libraries classify a failure by. Kept as the default for backwards
# compatibility.
raise AwsWrapperError(Messages.get_formatted("FailoverPlugin.DetectedException", str(original_exception)), original_exception) \
from original_exception

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,18 @@
What this module DOES do
------------------------
Normalize *raw driver-native* DBAPI errors (``mysql.connector.errors.*`` /
``psycopg.*`` / ``pymysql.*``) into the wrapper's PEP-249 equivalents, for plugin
chains that do not already re-wrap them (``iam`` / ``aws_secrets_manager`` / no
plugins). Without that SA cannot classify them at all, so e.g. ``has_table``
never sees MySQL's 1146 and ``create_all`` fails.
``psycopg.*`` / ``pymysql.*``) into the wrapper's PEP-249 equivalents. SA cannot
classify driver-native errors at all, because ``loaded_dbapi`` is this package
rather than the driver: without the normalization ``has_table`` never sees
MySQL's 1146 and ``create_all`` fails, and an application's
``except sqlalchemy.exc.IntegrityError:`` never fires on a duplicate key.

A driver error arrives here raw from any chain that does not substitute it --
``iam`` / ``aws_secrets_manager`` / no plugins, and the ``failover`` /
``failover_v2`` plugins once ``preserve_driver_exception_type`` is set. At that
property's default those plugins replace the driver error with a generic
``AwsWrapperError``, which is already a wrapper PEP-249 error, so it is passed
through untouched and SA can only classify it as ``sqlalchemy.exc.DBAPIError``.
"""

from __future__ import annotations
Expand All @@ -71,21 +79,11 @@ def _normalize_driver_error(e, driver_error_module):
"""Translate a raw driver-native DBAPI error into the wrapper's PEP-249
equivalent so SQLAlchemy's classifier recognizes it.

SA wraps an exception into ``sqlalchemy.exc.DBAPIError`` (enabling
SQLAlchemy wraps an error into ``sqlalchemy.exc.DBAPIError`` (enabling
``has_table`` / ``is_disconnect`` / retry handling) only when
``isinstance(e, dialect.dbapi.Error)`` -- and ``dialect.dbapi.Error`` is the
wrapper's PEP-249 ``Error``. Plugin chains that re-wrap driver errors as
``AwsWrapperError`` (e.g. failover) are already recognized, but auth-only
chains (``iam`` / ``aws_secrets_manager`` / no plugins) let the raw driver
error (``mysql.connector.errors.*``, ``psycopg.*``, ``pymysql.*``) escape --
which SA cannot classify, so e.g. ``has_table`` never catches a 1146
"table doesn't exist" and ``create_all`` fails.

Returns an equivalent wrapper PEP-249 error (same PEP-249 subtype matched by
name; ``errno`` / ``sqlstate`` / ``pgcode`` preserved so the dialect's
``_extract_error_code`` still reads the numeric code; original chained via
``__cause__``), or ``None`` if ``e`` is already a wrapper error or not a
recognizable driver error (caller should re-raise the original).
``isinstance(e, dialect.dbapi.Error)``.

Wrap and return an equivalent wrapper PEP-249 `dialect.dbapi.Error`` if necessary.
"""
from aws_advanced_python_wrapper import pep249
if isinstance(e, pep249.Error):
Expand Down
9 changes: 0 additions & 9 deletions aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ def create_connect_args(self, url):
return args, kwargs

def _extract_error_code(self, exception: BaseException) -> int:
# Plugins such as failover re-raise the underlying driver error
# wrapped in an ``AwsWrapperError``, which hides the numeric MySQL
# error code that SA's ``has_table`` / ``is_disconnect`` logic keys
# off. In particular ``has_table`` must see 1146 ("table doesn't
# exist") to return False so ``create_all`` can proceed -- otherwise
# the wrapped error propagates and ORM table setup fails. Unwrap to
# the underlying mysql-connector error so the stock classifier can
# read ``.errno``. Restores the override that main's
# SqlAlchemyOrmMysqlDialect carried before it was dropped in the merge.
from aws_advanced_python_wrapper.errors import AwsWrapperError
if isinstance(exception, AwsWrapperError) and exception.driver_error is not None:
exception = exception.driver_error
Expand Down
8 changes: 8 additions & 0 deletions aws_advanced_python_wrapper/utils/properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,14 @@ class WrapperProperties:
"Reader connection attempt timeout in seconds during a reader failover process.",
30,
)
PRESERVE_DRIVER_EXCEPTION_TYPE = WrapperProperty(
"preserve_driver_exception_type",
"""Re-raise a target driver exception unchanged when it does not trigger a connection switch,
instead of replacing it with an AwsWrapperError. The driver's exception class is what SQLAlchemy,
Django and similar libraries use to classify a failure, so preserving it keeps a duplicate key
reaching the application as an integrity error rather than a generic database error.""",
False,
)

# Failover2Plugin properties
FAILOVER_READER_HOST_SELECTOR_STRATEGY = WrapperProperty(
Expand Down
22 changes: 21 additions & 1 deletion docs/using-the-python-wrapper/SqlAlchemySupport.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,27 @@ Wrapper errors are classified so SQLAlchemy maps them to the correct `sqlalchemy
| `UnsupportedOperationError` | `sqlalchemy.exc.NotSupportedError` |
| `AwsWrapperError` (generic) | `sqlalchemy.exc.DBAPIError` |

Applications writing SA retry loops can `except sqlalchemy.exc.OperationalError` and catch failover events naturally. Target-driver exceptions (e.g., `psycopg.errors.*`, `mysql.connector.errors.*`) are not remapped and flow through SA's dialect-specific classification unchanged.
Applications writing SQLAlchemy retry loops can `except sqlalchemy.exc.OperationalError` and catch failover events naturally.

### Target driver errors

An error raised by the target driver that is not a failover condition — a duplicate key, a syntax error, a constraint violation — keeps its PEP-249 category only if the failover plugins are told to preserve it:

```python
engine = create_engine(
"mysql+aws_wrapper_mysqlconnector://user:password@my-cluster.cluster-xyz.us-east-2.rds.amazonaws.com/db"
"?preserve_driver_exception_type=True"
)

try:
session.add(obj)
session.commit()
except sqlalchemy.exc.IntegrityError: # duplicate key, FK violation, ...
session.rollback()
```
The `failover` and `failover_v2` plugins currently wrap a target driver error that does not trigger failover in a generic `AwsWrapperError`, which SQLAlchemy can only classify as `sqlalchemy.exc.DBAPIError`. Applications catching these errors with `except sqlalchemy.exc.IntegrityError:` therefore do not match them. The driver's error is still reachable as `err.orig.driver_error`.

Set the [`preserve_driver_exception_type`](./using-plugins/UsingTheFailover2Plugin.md#failover-plugin-v2-configuration-parameters) parameter to `True` to propagate target driver errors as-is, so SQLAlchemy classifies them by PEP-249 category and `except sqlalchemy.exc.IntegrityError:` matches again.

## Resource cleanup

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ With the `failover_v2` plugin:
> - **`enable_connect_failover`** *(boolean, default `True`)* — accepted by the async plugin for API parity with sync v2, but async failover currently only triggers on the execute path. When async grows connect-time failover, this flag will gate that path.
> - **`telemetry_failover_additional_top_trace`** *(boolean, default `False`)* — honored by both sync v2 and async. When `True`, the per-failover span is also emitted at `FORCE_TOP_LEVEL` so backends that sample only top-level spans (e.g. X-Ray, OTLP-with-head-sampling) still capture failover events.
> - **`init_host_provider` plugin hook** — sync v2 uses this to install `MonitoringRdsHostListProvider`. Async injects the `AsyncHostListProvider` at plugin construction, so no analogous hook is exposed.
> - **`preserve_driver_exception_type`** *(boolean, default `False`)* — sync only. The async plugin always re-raises a driver exception that does not trigger failover, which is the behavior this parameter enables for sync.

## Using the Failover Plugin v2
The Failover Plugin, not the Failover Plugin v2, will be enabled by default if the [`wrapperPlugins`](../UsingThePythonWrapper.md#connection-plugin-manager-parameters) value is not specified. If you would like to override the default plugins, you can explicitly include the failover plugin v2 in your list of plugins by adding the plugin code `failover_v2` to the [`wrapperPlugins`](../UsingThePythonWrapper.md#aws-advanced-Python-wrapper-parameters) value, or by adding it to the current [driver profile](../UsingThePythonWrapper.md#connection-plugin-manager-parameters). After you load the plugin, the failover v2 feature will be enabled.
Expand All @@ -75,6 +76,7 @@ In addition to the parameters that you can configure for the underlying driver,
| `cluster_topology_high_refresh_rate_ms` | Integer | No | Interval of time in milliseconds to wait between attempts to update cluster topology after the writer has come back online following a failover event. It corresponds to the increased monitoring rate described earlier. Usually, the topology monitoring component uses this increased monitoring rate for 30s after a new writer was detected. | `100` |
| `failover_reader_host_selector_strategy` | String | No | Strategy used to select a reader host during failover. For more information on the available reader selection strategies, see this [table](../ReaderSelectionStrategies.md). | `random` |
| `enable_connect_failover` | Boolean | No | Enable/disable cluster-aware failover if the initial connection to the database fails due to a network exception. Note that this may result in a connection to a different instance in the cluster than was specified by the URL. | `False` |
| `preserve_driver_exception_type` | Boolean | No | Re-raise the target driver's error unchanged when it does not trigger failover, instead of wrapping it with an `AwsWrapperError`. This allows libraries such as SQLAlchemy and Django to better classify and handle them by their PEP-249 category. | `False` |


Please refer to the original [Failover Plugin](./UsingTheFailoverPlugin.md) for more details about error codes, configurations, connection pooling and sample codes.
Expand Down
Loading
Loading