From b79ae4df288d5cf2ecaba63359de9e36d1d34f50 Mon Sep 17 00:00:00 2001 From: hippi345 <13539685+hippi345@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:40:01 +0000 Subject: [PATCH 1/2] fix: start socket_timeout clock when executor work begins Queue time in the shared DriverDialectExecutor no longer counts against socket_timeout, so a fast query waiting behind a saturated pool does not raise QueryTimeoutError. A call that actually runs too long still times out. --- .../utils/decorators.py | 96 +++++++++++++------ tests/unit/test_decorators.py | 96 +++++++++++++++++++ 2 files changed, 162 insertions(+), 30 deletions(-) diff --git a/aws_advanced_python_wrapper/utils/decorators.py b/aws_advanced_python_wrapper/utils/decorators.py index 38519e3f8..2cb02df5a 100644 --- a/aws_advanced_python_wrapper/utils/decorators.py +++ b/aws_advanced_python_wrapper/utils/decorators.py @@ -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: @@ -66,6 +67,55 @@ 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 + # permanently saturated pool must not hang the caller forever. + return max(float(timeout_sec) * 10.0, 60.0) + + +def _submit_and_wait_until_running( + executor: Executor, timeout_sec: float, func: Callable[..., Any], *args: Any, **kwargs: Any +) -> Tuple[Future, threading.Event]: + """Submit ``func`` and wait until a worker starts it. + + ``future.result(timeout=...)`` starts its clock at submit, so time spent + queued in a shared executor would otherwise count as query time + (see GitHub issue #1278). The operation timeout applies only after the + worker begins. + """ + started = threading.Event() + + def invoke() -> Any: + started.set() + return func(*args, **kwargs) + + future = executor.submit(invoke) + if started.wait(timeout=_queue_wait_bound_sec(timeout_sec)) or future.done() or started.is_set(): + return future, started + raise FuturesTimeoutError() + + +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 @@ -77,28 +127,21 @@ def func_wrapper(*args, **kwargs): initial_transaction_status: bool = driver_dialect.is_in_transaction(conn) - future = executor.submit(func, *args, **kwargs) - + started = threading.Event() + future: Optional[Future] = None try: + future, started = _submit_and_wait_until_running( + executor, timeout_sec, func, *args, **kwargs) 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. + if future is not None and 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): @@ -132,23 +175,16 @@ def timeout_decorator(func): @functools.wraps(func) def func_wrapper(*args, **kwargs): - future = executor.submit(func, *args, **kwargs) - + started = threading.Event() + future: Optional[Future] = None try: - # raises TimeoutError on timeout + future, started = _submit_and_wait_until_running( + executor, timeout_sec, func, *args, **kwargs) + # 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 future is not None and started.is_set(): + _drain_timed_out_worker(future, timeout_sec, driver_dialect, conn) raise return func_wrapper diff --git a/tests/unit/test_decorators.py b/tests/unit/test_decorators.py index 086312bf7..246e255eb 100644 --- a/tests/unit/test_decorators.py +++ b/tests/unit/test_decorators.py @@ -13,6 +13,7 @@ # limitations under the License. import threading +import time from concurrent.futures import ThreadPoolExecutor from concurrent.futures import TimeoutError as FuturesTimeoutError from typing import Optional @@ -20,9 +21,13 @@ 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.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: @@ -131,3 +136,94 @@ 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_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) From 37287cc59640ffbe225af9b7957ca6426e73bd43 Mon Sep 17 00:00:00 2001 From: hippi345 <13539685+hippi345@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:04:47 +0000 Subject: [PATCH 2/2] fix: cancel queued timeout work and shrink the queue-wait bound On queue-wait expiry, cancel the future and block the worker from starting the call after the caller gives up. If cancel loses the race, run abort/drain. Bound queue wait by max(timeout*2, timeout+5). --- CHANGELOG.md | 1 + .../utils/decorators.py | 98 +++++++++++++------ tests/unit/test_decorators.py | 85 +++++++++++++++- 3 files changed, 153 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae5e20c68..c311cb515 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/aws_advanced_python_wrapper/utils/decorators.py b/aws_advanced_python_wrapper/utils/decorators.py index 2cb02df5a..1d756553d 100644 --- a/aws_advanced_python_wrapper/utils/decorators.py +++ b/aws_advanced_python_wrapper/utils/decorators.py @@ -69,30 +69,68 @@ def is_connection_abandoned(conn: Optional[Connection]) -> bool: def _queue_wait_bound_sec(timeout_sec: float) -> float: # Queue delay is not charged against the operation timeout, but a - # permanently saturated pool must not hang the caller forever. - return max(float(timeout_sec) * 10.0, 60.0) + # 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) -def _submit_and_wait_until_running( - executor: Executor, timeout_sec: float, func: Callable[..., Any], *args: Any, **kwargs: Any -) -> Tuple[Future, threading.Event]: - """Submit ``func`` and wait until a worker starts it. + return executor.submit(invoke), gate - ``future.result(timeout=...)`` starts its clock at submit, so time spent - queued in a shared executor would otherwise count as query time - (see GitHub issue #1278). The operation timeout applies only after the - worker begins. - """ - started = threading.Event() - def invoke() -> Any: - started.set() - return func(*args, **kwargs) +def _give_up_if_still_queued(future: Future, gate: _WorkGate) -> None: + """Cancel queued work, or leave an in-flight call for abort/drain. - future = executor.submit(invoke) - if started.wait(timeout=_queue_wait_bound_sec(timeout_sec)) or future.done() or started.is_set(): - return future, started - raise FuturesTimeoutError() + ``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( @@ -127,11 +165,11 @@ def func_wrapper(*args, **kwargs): initial_transaction_status: bool = driver_dialect.is_in_transaction(conn) - started = threading.Event() - future: Optional[Future] = None + future, gate = _submit_timed_call(executor, func, *args, **kwargs) try: - future, started = _submit_and_wait_until_running( - executor, timeout_sec, func, *args, **kwargs) + 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 @@ -139,8 +177,8 @@ def func_wrapper(*args, **kwargs): # 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). Skip abort when - # the call never left the executor queue. - if future is not None and started.is_set(): + # 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 @@ -175,15 +213,15 @@ def timeout_decorator(func): @functools.wraps(func) def func_wrapper(*args, **kwargs): - started = threading.Event() - future: Optional[Future] = None + future, gate = _submit_timed_call(executor, func, *args, **kwargs) try: - future, started = _submit_and_wait_until_running( - executor, timeout_sec, func, *args, **kwargs) + 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 future is not None and started.is_set(): + if gate.started.is_set(): _drain_timed_out_worker(future, timeout_sec, driver_dialect, conn) raise diff --git a/tests/unit/test_decorators.py b/tests/unit/test_decorators.py index 246e255eb..a9ac45f4d 100644 --- a/tests/unit/test_decorators.py +++ b/tests/unit/test_decorators.py @@ -14,7 +14,7 @@ import threading import time -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from concurrent.futures import TimeoutError as FuturesTimeoutError from typing import Optional from unittest.mock import MagicMock @@ -24,6 +24,7 @@ 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) @@ -213,6 +214,88 @@ def test_execute_queued_fast_call_does_not_raise_query_timeout(): 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)