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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
* Async (asyncio) counterpart of the wrapper (`aws_advanced_python_wrapper.aio`), targeting sync parity for the shipped plugins: failover v2, read/write splitting, EFM v2, IAM auth, AWS Secrets Manager, federated + Okta auth, Aurora connection tracker, cluster topology monitor, custom endpoint, stale DNS, Aurora initial connection strategy, simple read/write splitting, developer plugin, blue/green deployment, limitless, fastest-response strategy. Backed by psycopg async and aiomysql, with async SQLAlchemy support via `create_async_engine` (`postgresql+aws_wrapper_psycopg://` serves both sync and async; MySQL async uses `mysql+aws_wrapper_aiomysql://`). Includes `AsyncConnectionProvider`/`AsyncPooledConnectionProvider`, `AsyncSessionStateService`, an async IdP factory registry, and `release_resources_async()` for background-task teardown. ([PR #1257](https://github.com/aws/aws-advanced-python-wrapper/pull/1257))

### :bug: Fixed
* `socket_timeout` no longer treats time queued in the shared `DriverDialectExecutor` as query time. The timeout clock starts when a worker begins the call. If the queue-wait bound expires while the call is still queued, the future is cancelled so it cannot run later on the same connection; if the worker starts in that window, the existing abort/drain path runs. Queue wait is bounded by `max(timeout * 2, timeout + 5)` seconds so a saturated pool cannot stall a caller for a minute. ([Issue #1278](https://github.com/aws/aws-advanced-python-wrapper/issues/1278))
* Cross-thread use-after-free (SIGSEGV) when an offloaded query times out (e.g. during failover) and the connection is later closed or reused while the query is still running: on timeout the driver dialects now shut down the connection socket and wait for the worker to unwind before propagating, and leak rather than close a connection whose worker cannot be drained. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252))
* Schema-qualified every function, operator, cast and catalog reference in the PostgreSQL queries the driver issues internally, so a session `search_path` cannot redirect them. This covers the queries issued by the asynchronous Aurora host list provider as well. ([PR #1262](https://github.com/aws/aws-advanced-python-wrapper/pull/1262), [PR #1270](https://github.com/aws/aws-advanced-python-wrapper/pull/1270))
* Connection properties whose name indicates a credential are now masked when connection properties are logged. Previously only `password` was masked, so properties such as `idp_password` and the `monitoring-` and `blue-green-monitoring-` prefixed passwords were logged in clear text. The Secrets Manager properties remain readable, since they identify a secret rather than hold one. ([PR #1270](https://github.com/aws/aws-advanced-python-wrapper/pull/1270))
Expand Down
134 changes: 104 additions & 30 deletions aws_advanced_python_wrapper/utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

import functools
import threading
from concurrent.futures import Future
from concurrent.futures import TimeoutError as FuturesTimeoutError
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple
from weakref import WeakSet

if TYPE_CHECKING:
Expand Down Expand Up @@ -66,6 +67,93 @@ def is_connection_abandoned(conn: Optional[Connection]) -> bool:
return False


def _queue_wait_bound_sec(timeout_sec: float) -> float:
# Queue delay is not charged against the operation timeout, but a
# saturated pool must not stall the caller for a minute. Bound queue wait
# to the larger of 2x the timeout and timeout+5s: a 5s socket_timeout
# waits at most 10s for a worker (not 60s), while a 0.2s timeout still
# has 5.2s to get scheduled.
timeout_sec = float(timeout_sec)
return max(timeout_sec * 2.0, timeout_sec + 5.0)


class _WorkGate:
"""Handshake so a worker cannot start ``func`` after the caller gives up."""

def __init__(self) -> None:
self._lock = threading.Lock()
self._abandoned = False
self.started = threading.Event()

def try_start(self) -> bool:
with self._lock:
if self._abandoned:
return False
self.started.set()
return True

def mark_abandoned(self) -> None:
with self._lock:
self._abandoned = True

def abandon_if_not_started(self) -> bool:
"""Return True if the worker already started; otherwise prevent start."""
with self._lock:
if self.started.is_set():
return True
self._abandoned = True
return False


def _submit_timed_call(
executor: Executor, func: Callable[..., Any], *args: Any, **kwargs: Any
) -> Tuple[Future, _WorkGate]:
"""Submit ``func``; the timeout clock starts only after ``try_start``."""
gate = _WorkGate()

def invoke() -> Any:
if not gate.try_start():
return None
return func(*args, **kwargs)

return executor.submit(invoke), gate


def _give_up_if_still_queued(future: Future, gate: _WorkGate) -> None:
"""Cancel queued work, or leave an in-flight call for abort/drain.

``future.cancel()`` is True only while the task is still queued. If it
returns False the worker has started (or just finished); the caller
treats that as started and must abort/drain. The gate stops ``func``
from running if the worker is still in the handshake.
"""
if future.cancel():
gate.mark_abandoned()
return
gate.abandon_if_not_started()


def _drain_timed_out_worker(
future: Future,
timeout_sec: float,
driver_dialect: Optional[DriverDialect],
conn: Optional[Connection]) -> None:
if conn is None or driver_dialect is None:
return
driver_dialect.abort_connection(conn)
try:
future.result(timeout=timeout_sec)
except FuturesTimeoutError:
# The worker still has not finished: abort_connection could not
# interrupt it (e.g. the mysql C-extension, where it is a no-op).
# Closing this connection now would free it under the running
# query and crash the process, so mark it abandoned -- close
# paths skip it and the worker frees it when it finishes.
mark_connection_abandoned(conn)
except Exception: # noqa: BLE001 - worker raised its own error; it has drained
pass


def preserve_transaction_status_with_timeout(executor: Executor, timeout_sec, driver_dialect: DriverDialect, conn: Connection):
"""
Timeout decorator, timeout in seconds
Expand All @@ -77,28 +165,21 @@ def func_wrapper(*args, **kwargs):

initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)

future = executor.submit(func, *args, **kwargs)

future, gate = _submit_timed_call(executor, func, *args, **kwargs)
try:
if not gate.started.wait(timeout=_queue_wait_bound_sec(timeout_sec)):
_give_up_if_still_queued(future, gate)
raise FuturesTimeoutError()
result = future.result(timeout=timeout_sec)
except FuturesTimeoutError:
# The query is still running on the worker thread. Interrupt its
# socket so it unwinds, then WAIT for the worker to finish before
# propagating -- otherwise the caller may close/reuse this
# connection while the worker is still reading it, a cross-thread
# use-after-free in the driver (env-4 SIGSEGV).
driver_dialect.abort_connection(conn)
try:
future.result(timeout=timeout_sec)
except FuturesTimeoutError:
# The worker still has not finished: abort_connection could not
# interrupt it (e.g. the mysql C-extension, where it is a no-op).
# Closing this connection now would free it under the running
# query and crash the process, so mark it abandoned -- close
# paths skip it and the worker frees it when it finishes.
mark_connection_abandoned(conn)
except Exception: # noqa: BLE001 - worker raised its own error; it has drained
pass
# use-after-free in the driver (env-4 SIGSEGV). Skip abort when
# the call never left the executor queue (cancelled above).
if gate.started.is_set():
_drain_timed_out_worker(future, timeout_sec, driver_dialect, conn)
raise

if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
Expand Down Expand Up @@ -132,23 +213,16 @@ def timeout_decorator(func):
@functools.wraps(func)
def func_wrapper(*args, **kwargs):

future = executor.submit(func, *args, **kwargs)

future, gate = _submit_timed_call(executor, func, *args, **kwargs)
try:
# raises TimeoutError on timeout
if not gate.started.wait(timeout=_queue_wait_bound_sec(timeout_sec)):
_give_up_if_still_queued(future, gate)
raise FuturesTimeoutError()
# raises TimeoutError on timeout, measured from worker start
return future.result(timeout=timeout_sec)
except FuturesTimeoutError:
if conn is not None and driver_dialect is not None:
driver_dialect.abort_connection(conn)
try:
future.result(timeout=timeout_sec)
except FuturesTimeoutError:
# Worker uninterruptible (e.g. mysql C-extension). Closing
# conn now would crash the process; mark it abandoned so
# close paths skip it and the worker frees it on completion.
mark_connection_abandoned(conn)
except Exception: # noqa: BLE001 - worker raised its own error; it has drained
pass
if gate.started.is_set():
_drain_timed_out_worker(future, timeout_sec, driver_dialect, conn)
raise

return func_wrapper
Expand Down
181 changes: 180 additions & 1 deletion tests/unit/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,22 @@
# limitations under the License.

import threading
from concurrent.futures import ThreadPoolExecutor
import time
from concurrent.futures import Future, ThreadPoolExecutor
from concurrent.futures import TimeoutError as FuturesTimeoutError
from typing import Optional
from unittest.mock import MagicMock

import pytest

from aws_advanced_python_wrapper.driver_dialect import DriverDialect
from aws_advanced_python_wrapper.errors import QueryTimeoutError
from aws_advanced_python_wrapper.pep249_methods import DbApiMethod
from aws_advanced_python_wrapper.utils import decorators as decorators_mod
from aws_advanced_python_wrapper.utils.decorators import (
is_connection_abandoned, mark_connection_abandoned,
preserve_transaction_status_with_timeout, timeout)
from aws_advanced_python_wrapper.utils.properties import Properties


class _Conn:
Expand Down Expand Up @@ -131,3 +137,176 @@ def stuck():
finally:
release.set()
executor.shutdown(wait=True)


def _saturate_pool(executor: ThreadPoolExecutor, hold_sec: float) -> None:
"""Occupy every worker so a later submit sits in the queue."""
workers = executor._max_workers
started = threading.Barrier(workers + 1)

def occupy():
started.wait(timeout=2)
time.sleep(hold_sec)

for _ in range(workers):
executor.submit(occupy)
started.wait(timeout=2)


def test_timeout_queued_fast_call_does_not_use_submit_clock():
# Issue #1278: future.result(timeout=...) starts at submit, so queue time
# counts as query time. A fast call sitting behind a saturated pool must
# still succeed once a worker runs it.
executor = ThreadPoolExecutor(max_workers=1)
try:
_saturate_pool(executor, hold_sec=0.5)

def fast():
return "ok"

assert timeout(executor, 0.2)(fast)() == "ok"
finally:
executor.shutdown(wait=True)


def test_preserve_transaction_queued_fast_call_does_not_use_submit_clock():
executor = ThreadPoolExecutor(max_workers=1)
conn = _Conn()
try:
_saturate_pool(executor, hold_sec=0.5)

def fast():
return "ok"

wrapped = preserve_transaction_status_with_timeout(
executor, 0.2, _dialect(), conn)(fast)
assert wrapped() == "ok"
finally:
executor.shutdown(wait=True)


def test_timeout_slow_call_still_times_out_after_start():
executor = ThreadPoolExecutor(max_workers=1)

def slow():
time.sleep(0.6)
return "done"

wrapped = timeout(executor, 0.2)(slow)
try:
with pytest.raises(FuturesTimeoutError):
wrapped()
finally:
executor.shutdown(wait=True)


def test_execute_queued_fast_call_does_not_raise_query_timeout():
# DriverDialect.execute maps the decorator TimeoutError to QueryTimeoutError.
# Saturating DriverDialectExecutor makes a fast execute time out on main.
dialect = DriverDialect(Properties({"socket_timeout": "0.2"}))
occupy_pool = ThreadPoolExecutor(max_workers=1)
dialect._thread_pool = occupy_pool
try:
_saturate_pool(occupy_pool, hold_sec=0.5)
assert dialect.execute(
DbApiMethod.CURSOR_EXECUTE.method_name, lambda: "ok") == "ok"
finally:
occupy_pool.shutdown(wait=True)


def test_queue_bound_expiry_cancels_queued_work_and_skips_conn(monkeypatch):
# Issue #1278 follow-up: when the queue-wait bound expires while the call
# is still queued, the work must never run and the connection must not be
# aborted/touched after the caller has already timed out.
monkeypatch.setattr(decorators_mod, "_queue_wait_bound_sec", lambda timeout_sec: 0.15)
executor = ThreadPoolExecutor(max_workers=1)
conn = _Conn()
occupy_hold = threading.Event()
occupy_started = threading.Event()
ran = threading.Event()
dialect = _dialect()

def occupy():
occupy_started.set()
occupy_hold.wait(timeout=5)

def queued():
ran.set()
return "ran"

executor.submit(occupy)
assert occupy_started.wait(timeout=2)
wrapped = timeout(executor, 0.2, dialect, conn)(queued)
try:
with pytest.raises(FuturesTimeoutError):
wrapped()
assert ran.is_set() is False
dialect.abort_connection.assert_not_called()
occupy_hold.set()
time.sleep(0.2)
assert ran.is_set() is False
finally:
occupy_hold.set()
executor.shutdown(wait=True)


def test_queue_bound_expiry_race_starts_then_drains(monkeypatch):
# Bound expires in the same window the worker starts: cancel() is False,
# so abort/drain must run (the call is in-flight on conn).
monkeypatch.setattr(decorators_mod, "_queue_wait_bound_sec", lambda timeout_sec: 0.15)

class _CancelStartsExecutor:
def submit(self, fn, *args, **kwargs):
future = Future()

def run():
try:
result = fn(*args, **kwargs)
except BaseException as exc:
future.set_exception(exc)
else:
future.set_result(result)

def cancel_starts_then_fails() -> bool:
if future.set_running_or_notify_cancel():
threading.Thread(target=run, daemon=True).start()
# Let invoke() pass try_start before we report cancel() == False.
time.sleep(0.1)
return False

future.cancel = cancel_starts_then_fails # type: ignore[method-assign]
return future

hold = threading.Event()
ran = threading.Event()
conn = _Conn()
dialect = _dialect(abort_releases=hold)

def work():
ran.set()
hold.wait(timeout=5)
return "done"

try:
with pytest.raises(FuturesTimeoutError):
timeout(_CancelStartsExecutor(), 0.2, dialect, conn)(work)()
assert ran.wait(timeout=2)
dialect.abort_connection.assert_called()
finally:
hold.set()


def test_execute_slow_call_still_raises_query_timeout():
dialect = DriverDialect(Properties({"socket_timeout": "0.2"}))
pool = ThreadPoolExecutor(max_workers=1)
dialect._thread_pool = pool

def slow():
time.sleep(0.6)
return "done"

try:
with pytest.raises(QueryTimeoutError):
dialect.execute(DbApiMethod.CURSOR_EXECUTE.method_name, slow)
finally:
pool.shutdown(wait=True)