From 7b79da02f71164e5b5834d55450142d72c80a125 Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:18:01 -0700 Subject: [PATCH 1/8] feat: pg_query_timeout_sec property --- CHANGELOG.md | 6 + benchmarks/support/benchmark_services.rb | 4 + .../driver_dialects/driver_dialect.rb | 12 ++ .../driver_dialects/pg_driver_dialect.rb | 94 +++++++++++++- .../driver_dialects/pg_query_timeout_error.rb | 38 ++++++ .../errors/pg_error_handler.rb | 8 ++ .../monitoring/cluster_topology_monitor.rb | 9 +- .../global_cluster_topology_monitor.rb | 4 +- .../plugins/blue_green/status_monitor.rb | 9 +- .../plugins/failover_plugin.rb | 12 +- .../initial_connection_strategy_plugin.rb | 5 +- .../kms_encryption/connection_source.rb | 6 +- .../postgresql.rb | 1 + .../property_definition.rb | 24 ++++ .../services/dialect_service.rb | 24 +++- .../wrapper_property.rb | 9 +- spec/unit/aws_postgresql_adapter_spec.rb | 18 +++ .../mysql2_driver_dialect_spec.rb | 6 + .../driver_dialects/pg_driver_dialect_spec.rb | 121 ++++++++++++++++++ spec/unit/errors/pg_error_handler_spec.rb | 27 ++++ spec/unit/failover_plugin_spec.rb | 43 +++++++ .../cluster_topology_monitor_spec.rb | 22 ++++ .../global_cluster_topology_monitor_spec.rb | 10 ++ .../encryption/connection_source_spec.rb | 13 ++ .../encryption/kms_encryption_utility_spec.rb | 7 +- ...initial_connection_strategy_plugin_spec.rb | 2 + spec/unit/property_definition_spec.rb | 14 ++ spec/unit/services/dialect_service_spec.rb | 68 ++++++++++ 28 files changed, 596 insertions(+), 20 deletions(-) create mode 100644 lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 47ad7198..273cfb74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] +### :magic_wand: Added +- The `pg_query_timeout_sec` property for PostgreSQL (`pg`): a client-side timeout, in seconds, for the wrapper's own queries. + - **Queries covered:** topology, host role checks, dialect detection, Blue/Green status, the failover `ROLLBACK`, and the KMS Encryption Plugin's key store. It never applies to application queries. + - **On expiry:** the query fails with a `PgDriverDialect::QueryTimeoutError` (a `PG::ConnectionBad`) that the wrapper treats as a network error (`ActiveRecord::ConnectionFailed` under `aws_postgresql`). A connection the wrapper opened itself is closed. The application's own connection, which the failover `ROLLBACK` can run on, is left open for its owner to close, or swapped under a successful failover. + - **Default:** `0` (no timeout), except for the topology and Blue/Green monitors, which use `5` seconds unless the property is set and can be overridden by `topology_monitoring_pg_query_timeout_sec` and `bg_monitoring_pg_query_timeout_sec` respectively, setting these to `0` disables the timeout. + ### :bug: Fixed - Fixed the `aws_postgresql` ActiveRecord adapter keeping ActiveRecord's prepared statement cache when a failover happened while ActiveRecord checked a connection (`active?`) or reset it (`reset!`). Those calls bypass the adapter's error translation, so after the failover every query prepared before it failed with `Method invoked against old connection` until ActiveRecord discarded the connection. The adapter now clears the cache and re-applies the connection's settings there too. - **Behavior change:** a successful failover during ActiveRecord's connection check (`active?`) no longer raises `FailoverSuccessError`: no statement of the application's was in flight, so the adapter reconnects silently, as ActiveRecord does for a dead connection, and the next statement runs on the new writer. `TransactionStateUnknownError` is still raised when an ActiveRecord transaction was open, because that transaction was lost; otherwise `active?` returns `false`. A failover during `reset!` completes the reset on the new writer instead of raising. `active?` returns `false`, and `reset!` raises `ActiveRecord::ConnectionFailed`, when failover fails. `aws_mysql2` and `aws_trilogy` are unchanged by these `active?`/`reset!` changes. diff --git a/benchmarks/support/benchmark_services.rb b/benchmarks/support/benchmark_services.rb index c2b57c9b..ad7c0501 100644 --- a/benchmarks/support/benchmark_services.rb +++ b/benchmarks/support/benchmark_services.rb @@ -78,6 +78,10 @@ def db_dialect end def update_dialect(_connection); end + + def with_query_timeout(_connection, close_on_timeout:, timeout_sec: nil) + yield + end end class StubConnectionService diff --git a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb index 29c51895..50ff7d15 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb @@ -56,6 +56,18 @@ def execute_with_params(connection, sql, params) raise NotImplementedError end + # Bounds the wrapper-internal queries (#execute, #execute_with_params) that run on +connection+ inside + # the block to +timeout_sec+ seconds in total. Application queries are never bounded. + # Only the PostgreSQL dialect can bound a query itself (the other drivers have +read_timeout+), so this + # yields unchanged by default. + # + # @param close_on_timeout [Boolean] true if the wrapper owns +connection+ and may close it on timeout, + # false if the application owns it and it must be left open + # @param timeout_sec [Numeric, nil] the bound; nil or non-positive leaves the block unbounded + def with_query_timeout(_connection, close_on_timeout:, timeout_sec: nil) + yield + end + # Rewrites +?+ placeholders into the driver's native placeholder syntax. # @param sql [String] SQL written with +?+ placeholders # @return [String] diff --git a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb index c39e3507..bba84724 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb @@ -21,6 +21,9 @@ module DriverDialects class PgDriverDialect include DriverDialect + QUERY_TIMEOUT_SCOPE_KEY = :aws_advanced_ruby_driver_wrapper_pg_query_timeouts + private_constant :QUERY_TIMEOUT_SCOPE_KEY + # Every pg call that talks to the server. A call that is not listed here is handed straight # to the driver, bypassing the plugin pipeline. # @@ -97,12 +100,51 @@ def connect(host_info, config) ::PG::Connection.new(**prepare_connect_config(host_info, config)) end + # Bounds the wrapper-internal queries (#execute, #execute_with_params) run on +connection+ inside the + # block to +timeout_sec+ seconds in total (one deadline per query, not reset as data arrives). + # libpq has no client-side query timeout, and TCP keepalives or tcp_user_timeout only see the next hop, + # so a database that stops answering behind a proxy would otherwise block a query indefinitely. The wait + # is on the socket, so it holds behind such a proxy. + # + # The scope is the calling fiber and only +connection+; queries on other connections, and every + # application query, are unaffected. A +nil+ or non-positive timeout leaves the block unbounded. + # Nested scopes on the same connection: the innermost wins. + # + # @param close_on_timeout [Boolean] true if the wrapper owns +connection+ (a monitor's, or one it has + # not handed out yet): on timeout it is abandoned and closed. false if the application owns it: + # the error is raised and the connection is left for its owner to close. + # @raise [PgDriverDialect::QueryTimeoutError] from a bounded query that gets no reply in time + def with_query_timeout(connection, close_on_timeout:, timeout_sec: nil) + timeout = timeout_sec.to_f + return yield unless timeout.positive? + + scopes = (Thread.current[QUERY_TIMEOUT_SCOPE_KEY] ||= {}.compare_by_identity) + had_previous = scopes.key?(connection) + previous = scopes[connection] + scopes[connection] = [timeout, close_on_timeout] + begin + yield + ensure + if had_previous + scopes[connection] = previous + else + scopes.delete(connection) + end + end + end + def execute(connection, sql) - connection.exec(sql) + timeout, close_on_timeout = query_timeout_for(connection) + return connection.exec(sql) unless timeout + + await_result(connection, timeout, close_on_timeout) { connection.send_query(sql) } end def execute_with_params(connection, sql, params) - connection.exec_params(sql, params) + timeout, close_on_timeout = query_timeout_for(connection) + return connection.exec_params(sql, params) unless timeout + + await_result(connection, timeout, close_on_timeout) { connection.send_query_params(sql, params) } end # pg uses numbered +$1+, +$2+ ... placeholders. @@ -213,6 +255,54 @@ def apply_monitoring_defaults(driver_props) driver_props[:connect_timeout] ||= DEFAULT_MONITORING_TIMEOUT_SEC end + # The [timeout_sec, close_on_timeout] in force for +connection+ on this fiber, or nil. + def query_timeout_for(connection) + Thread.current[QUERY_TIMEOUT_SCOPE_KEY]&.[](connection) + end + + # Sends a query and waits for its results, giving up when the whole result has not arrived within +timeout+ seconds. + # On timeout a query is still pending on the connection, so it cannot be reused; it is abandoned and + # closed when +close_on_timeout+, and left alone otherwise. + # @raise [PgDriverDialect::QueryTimeoutError] on timeout + def await_result(connection, timeout, close_on_timeout) + yield + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout + last = nil + loop do + while connection.is_busy + remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) + unless remaining.positive? && connection.socket_io.wait_readable(remaining) + last&.clear + logger.info( + "Wrapper query timed out after #{timeout}s on #{describe_connection(connection)}; " \ + "#{close_on_timeout ? 'closing the connection' : 'leaving the connection open for its owner'}." + ) + if close_on_timeout + abandon_connection(connection) + close_connection(connection) + end + # A no-op once loaded; kept for callers that use the dialect without the postgresql entry point. + require_relative 'pg_query_timeout_error' + raise QueryTimeoutError, timeout + end + connection.consume_input + end + result = connection.get_result + break if result.nil? + + last&.clear + last = result + end + last&.check + last + end + + def describe_connection(connection) + "#{connection.host}:#{connection.port}" + rescue StandardError + 'an unknown host' + end + # PG reads transaction state directly from the connection. # Returns nil for PQTRANS_UNKNOWN (broken) and PQTRANS_ACTIVE (command in flight) # so SessionStateService falls back to SQL inference. diff --git a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error.rb b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error.rb new file mode 100644 index 00000000..960b18c9 --- /dev/null +++ b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Loaded on demand (see PgDriverDialect#await_result): it inherits from PG::ConnectionBad, which needs the pg gem. +require 'pg' + +module AwsAdvancedRubyDriverWrapper + module DriverDialects + class PgDriverDialect + # Raised when a wrapper-internal query gets no reply within its timeout (see #with_query_timeout). + # + # It is a +PG::ConnectionBad+, so callers that rescue the driver's connection error handle it, and + # PgErrorHandler#network_error? recognizes it by class. The trailing newline is deliberate: ActiveRecord + # tells a libpq failure (message ends in a newline, the query may have reached the server) from a + # pg-internal one (no newline, never sent) and maps the former to ActiveRecord::ConnectionFailed, which + # is right for a query that was sent. Keep it, and avoid the phrases "connection is closed" and "no + # connection to the server", which ActiveRecord matches first. + class QueryTimeoutError < ::PG::ConnectionBad + def initialize(timeout_sec) + super("wrapper internal query timed out after #{timeout_sec}s\n") + end + end + end + end +end diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb index 0d6ca58e..179acf7c 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb @@ -109,6 +109,8 @@ def read_only_error_by_sql_state?(sql_state, _error_code = nil) def connection_bad_network_error?(error) return false unless defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad) + # A timed-out wrapper query is a connection failure by class, whatever its message says. + return true if query_timeout_error?(error) msg = error.message&.downcase return false if msg.nil? @@ -118,6 +120,12 @@ def connection_bad_network_error?(error) CONNECT_FAILURE_MESSAGES.any? { |pattern| msg.include?(pattern) } end + # The error class is only defined once pg has loaded it, on the first timeout, so nothing else can be one. + def query_timeout_error?(error) + defined?(DriverDialects::PgDriverDialect::QueryTimeoutError) && + error.is_a?(DriverDialects::PgDriverDialect::QueryTimeoutError) + end + def server_rejection?(msg) SERVER_REJECTION_MESSAGES.any? { |pattern| msg.include?(pattern) } end diff --git a/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb b/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb index 3d512a11..daf7e18d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb @@ -107,7 +107,7 @@ def force_refresh(verify_writer, timeout_sec) end else # Monitoring thread is mid-query. Detach without closing — the monitoring thread will close the - # connection after its query completes (via read_timeout for MySQL or keepalives for PG). + # connection after its query completes (via read_timeout for MySQL or pg_query_timeout_sec for PG). @monitoring_connection.set(nil, close_old: false) end @verified_writer = false @@ -395,7 +395,8 @@ def attempt_host_connection(host_info, attempts) end def check_host_role(conn) - @service_container.dialect_service.db_dialect.host_role(conn) + dialect_service = @service_container.dialect_service + dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) { dialect_service.db_dialect.host_role(conn) } rescue StandardError => e logger.debug("[#{@cluster_id}] host_role check failed: #{e.message}") nil @@ -502,7 +503,9 @@ def fetch_topology_and_update_cache(conn) end def query_topology(conn) - @topology_utils.query_topology(conn, @initial_host_info, @instance_template) + @service_container.dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) do + @topology_utils.query_topology(conn, @initial_host_info, @instance_template) + end end def stored_hosts diff --git a/lib/aws_advanced_ruby_driver_wrapper/monitoring/global_cluster_topology_monitor.rb b/lib/aws_advanced_ruby_driver_wrapper/monitoring/global_cluster_topology_monitor.rb index e5ddc38f..78a996d4 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/monitoring/global_cluster_topology_monitor.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/monitoring/global_cluster_topology_monitor.rb @@ -52,7 +52,9 @@ def initialize( private def query_topology(conn) - @topology_utils.query_global_topology(conn, initial_host_info, @instance_templates_by_region) + @service_container.dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) do + @topology_utils.query_global_topology(conn, initial_host_info, @instance_templates_by_region) + end end def resolve_instance_template(instance_id, conn) diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb index 75bd5b06..d05d4c0b 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/blue_green/status_monitor.rb @@ -297,10 +297,13 @@ def collect_status conn = @connection.get return if conn.nil? || connection_closed?(conn) - return unless status_available?(conn) + dialect_service = @service_container.dialect_service + return unless dialect_service.with_monitoring_query_timeout(conn, @status_monitor_wrapper_props) { status_available?(conn) } - dialect = @service_container.dialect_service.db_dialect - status_entries = parse_status_entries(conn, dialect) + dialect = dialect_service.db_dialect + status_entries = dialect_service.with_monitoring_query_timeout(conn, @status_monitor_wrapper_props) do + parse_status_entries(conn, dialect) + end status_info = resolve_status_info(status_entries) apply_status_info(status_info, status_entries) verify_connection_host(status_info) diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb index b0857d10..c6df4b9c 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb @@ -319,7 +319,10 @@ def invalidate_current_connection return unless @service_container.session_state_service.in_transaction? begin - driver_dialect.execute(conn, 'ROLLBACK') + # The application owns this connection: bound the wait, but leave it open if the ROLLBACK times out. + dialect_service.with_query_timeout(conn, close_on_timeout: false) do + driver_dialect.execute(conn, 'ROLLBACK') + end rescue StandardError nil end @@ -534,7 +537,8 @@ def try_original_writer(original_writer, original_writer_still_writer) def attempt_reader_connection(host_info) conn = @service_container.plugin_manager.connect(host_info, connection_service.driver_props, false, plugin_to_skip: self) # Since the roles in the host list might not be accurate, we execute a query to check the instance's role. - role = db_dialect.host_role(conn) + # A candidate connection the wrapper opened and has not handed out, so it may be closed on timeout. + role = dialect_service.with_query_timeout(conn, close_on_timeout: true) { db_dialect.host_role(conn) } if role == Host::HostRole::READER || @failover_mode != FailoverMode::STRICT_READER updated_host = host_info.deep_dup(role: role) @@ -577,7 +581,9 @@ def verified_connection(is_initial_connection, host_info, driver_props, connect_ end conn = connect_func.call - if db_dialect.host_role(conn) == Host::HostRole::WRITER + # Not handed to the application yet, so the wrapper may close it on timeout. + role = dialect_service.with_query_timeout(conn, close_on_timeout: true) { db_dialect.host_role(conn) } + if role == Host::HostRole::WRITER host_service.refresh_host_list return conn end diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/initial_connection_strategy_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/initial_connection_strategy_plugin.rb index c406375e..5ac1e74d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/initial_connection_strategy_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/initial_connection_strategy_plugin.rb @@ -108,7 +108,10 @@ def connect_with_retry(host_info, url_type, substitution_strategy, role_to_verif return conn end - conn_role = dialect_service.db_dialect.host_role(conn) + # A candidate the wrapper opened and has not handed out, so it may be closed on timeout. + conn_role = dialect_service.with_query_timeout(conn, close_on_timeout: true) do + dialect_service.db_dialect.host_role(conn) + end if conn_role == role_to_verify success = true return conn diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/connection_source.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/connection_source.rb index 3e14091e..b647ab37 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/connection_source.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/kms_encryption/connection_source.rb @@ -52,7 +52,11 @@ def with_connection(operation: nil) connection = open_runtime_connection(operation) begin - yield connection + # The wrapper owns this connection, so a query that gets no reply in time (when + # pg_query_timeout_sec is set) closes it. + @service_container.dialect_service.with_query_timeout(connection, close_on_timeout: true) do + yield connection + end ensure close_runtime_connection(connection) end diff --git a/lib/aws_advanced_ruby_driver_wrapper/postgresql.rb b/lib/aws_advanced_ruby_driver_wrapper/postgresql.rb index a5e2c879..d9d4081b 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/postgresql.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/postgresql.rb @@ -510,6 +510,7 @@ def forget_large_object(_args, _result, _sql) def ensure_pg! require 'pg' + require_relative 'driver_dialects/pg_query_timeout_error' rescue LoadError raise LoadError, "WrapperPgConnection requires 'pg'. Add it to your Gemfile: gem 'pg'" end diff --git a/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb b/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb index 91bb4a82..e916750d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/property_definition.rb @@ -48,6 +48,17 @@ module PropertyDefinition end end + PG_QUERY_TIMEOUT_MAX_SEC = 900.0 + + PG_QUERY_TIMEOUT_SEC_VALIDATOR = lambda do |val, name| + next if val.nil? + + number = Float(val, exception: false) + unless number&.finite? && number >= 0 && number <= PG_QUERY_TIMEOUT_MAX_SEC + raise ArgumentError, "#{name} must be a number from 0 to #{PG_QUERY_TIMEOUT_MAX_SEC.to_i} seconds, got: #{val.inspect}" + end + end + # -- General -- CLUSTER_ID = WrapperProperty.new(:cluster_id, 'Unique identifier for the database cluster', default_value: '1', type: String) PLUGINS = WrapperProperty.new(:wrapper_plugins, 'Comma-separated list of plugin codes', default_value: 'failover,initial_connection', @@ -177,6 +188,19 @@ module PropertyDefinition type: Integer ) + PG_QUERY_TIMEOUT_SEC = WrapperProperty.new( + :pg_query_timeout_sec, + 'PostgreSQL only: client-side timeout in seconds for the wrapper\'s own queries (topology, host role, ' \ + 'dialect detection, Blue/Green status, failover ROLLBACK, KMS key store). It never applies to application ' \ + 'queries. The wait is on the socket, so it detects a database that stops answering even behind a TCP proxy. ' \ + 'On expiry the query fails as a connection error; a connection the wrapper opened itself is closed, while the ' \ + 'application\'s connection is left open for its owner. The timeout is one deadline for the whole query, not ' \ + 'reset as data arrives. Must be between 0 and 900 (15 minutes); 0 disables it. The topology monitor and the ' \ + 'Blue/Green monitors use this value when it is set and otherwise 5 seconds; override them with ' \ + 'topology_monitoring_pg_query_timeout_sec and bg_monitoring_pg_query_timeout_sec.', + default_value: 0.0, type: Float, validator: PG_QUERY_TIMEOUT_SEC_VALIDATOR + ) + # -- Blue/Green -- BGD_ID = WrapperProperty.new(:bgd_id, 'Blue/Green Deployment identifier that helps the driver to distinguish different deployments.', default_value: '1', type: String) diff --git a/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb b/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb index 0400e44e..c2bf6a12 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb @@ -92,6 +92,27 @@ def dialect_for_code(code) end end + # Runs the block with the wrapper's own queries on +connection+ bounded by +timeout_sec+, or by the + # +pg_query_timeout_sec+ property when none is given (0 by default, so unbounded). Application queries + # are never bounded. See DriverDialects::DriverDialect#with_query_timeout. + # + # @param close_on_timeout [Boolean] true if the wrapper owns +connection+, false if the application does + def with_query_timeout(connection, close_on_timeout:, timeout_sec: nil, &) + timeout_sec ||= PropertyDefinition::PG_QUERY_TIMEOUT_SEC.get_float(@connection_service.wrapper_props) + driver_dialect.with_query_timeout(connection, close_on_timeout: close_on_timeout, timeout_sec: timeout_sec, &) + end + + # Bounds a monitor's own queries on +connection+, which the monitor owns, so it is closed on timeout. + # +monitoring_wrapper_props+ is the monitor's props with its prefixed overrides merged in, so an explicit + # +pg_query_timeout_sec+, including 0, wins. Unset gives DriverDialect::DEFAULT_MONITORING_TIMEOUT_SEC (the + # bound monitors already use for connect_timeout), so a monitor never blocks indefinitely on a silent database. + def with_monitoring_query_timeout(connection, monitoring_wrapper_props, &) + timeout_sec = PropertyDefinition::PG_QUERY_TIMEOUT_SEC.get_float( + monitoring_wrapper_props, default: DriverDialects::DriverDialect::DEFAULT_MONITORING_TIMEOUT_SEC + ) + with_query_timeout(connection, close_on_timeout: true, timeout_sec: timeout_sec, &) + end + # Refines the dialect after a connection is established by querying the server # (e.g. checking for Aurora-specific functions/tables). # @@ -109,7 +130,8 @@ def update_dialect(connection) candidate = dialect_for_code(candidate_code) raise Errors::AwsError, "Unknown dialect code: #{candidate_code}" unless candidate - next unless candidate.dialect?(connection) + # The connection has not been handed to the application yet, so the wrapper may close it. + next unless with_query_timeout(connection, close_on_timeout: true) { candidate.dialect?(connection) } @can_update = false @dialect_code = candidate_code diff --git a/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb b/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb index 5cb1c497..db2446ba 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb @@ -27,8 +27,9 @@ def initialize(name, description, default_value: nil, type: nil, validator: nil) end # @return [String, Boolean, Integer, nil] the value from props, or the property's default - def get(props, override = nil) - override&.key?(@name) ? override.fetch(@name, @default_value) : props.fetch(@name, @default_value) + # @param default [Object] used instead of the property's default when the key is in neither +props+ nor +override+ + def get(props, override = nil, default: @default_value) + override&.key?(@name) ? override.fetch(@name, default) : props.fetch(@name, default) end def get_bool(props, override = nil) @@ -43,8 +44,8 @@ def get_int(props, override = nil) val.is_a?(Integer) ? val : val.to_i end - def get_float(props, override = nil) - val = get(props, override) + def get_float(props, override = nil, default: @default_value) + val = get(props, override, default: default) val.is_a?(Float) ? val : val.to_f end diff --git a/spec/unit/aws_postgresql_adapter_spec.rb b/spec/unit/aws_postgresql_adapter_spec.rb index 6d9aa061..afde72df 100644 --- a/spec/unit/aws_postgresql_adapter_spec.rb +++ b/spec/unit/aws_postgresql_adapter_spec.rb @@ -169,6 +169,24 @@ def connect_failing_with(message, client_config = config) end end + context 'when exception is a PG query timeout from the wrapper' do + let(:pool) { instance_double(ActiveRecord::ConnectionAdapters::ConnectionPool) } + + before do + require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' + adapter.instance_variable_set(:@pool, pool) + end + + # Stock ActiveRecord decides, with no wrapper-specific configuration: a PG::ConnectionBad whose message + # ends in a newline is a failure after the query was sent, not "never sent". + it 'is translated by ActiveRecord to ConnectionFailed, not ConnectionNotEstablished' do + exception = AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) + + result = adapter.translate_exception(exception, message: message, sql: sql, binds: binds) + expect(result).to be_a(ActiveRecord::ConnectionFailed) + end + end + context 'when exception is a FailoverSuccessError' do it 'returns the original exception and reconfigures the connection' do exception = AwsAdvancedRubyDriverWrapper::Errors::FailoverSuccessError.new diff --git a/spec/unit/driver_dialects/mysql2_driver_dialect_spec.rb b/spec/unit/driver_dialects/mysql2_driver_dialect_spec.rb index b1c6bab1..4b71321d 100644 --- a/spec/unit/driver_dialects/mysql2_driver_dialect_spec.rb +++ b/spec/unit/driver_dialects/mysql2_driver_dialect_spec.rb @@ -150,6 +150,12 @@ end end + describe '#with_query_timeout' do + it 'yields unchanged, since mysql2 bounds reads with read_timeout' do + expect(dialect.with_query_timeout(double('Connection'), close_on_timeout: true, timeout_sec: 5) { :result }).to eq(:result) + end + end + describe '#abandon_connection' do it 'turns off automatic_close instead of closing the connection' do allow(connection).to receive(:closed?).and_return(false) diff --git a/spec/unit/driver_dialects/pg_driver_dialect_spec.rb b/spec/unit/driver_dialects/pg_driver_dialect_spec.rb index f7c92a6f..39866ecd 100644 --- a/spec/unit/driver_dialects/pg_driver_dialect_spec.rb +++ b/spec/unit/driver_dialects/pg_driver_dialect_spec.rb @@ -15,6 +15,7 @@ # limitations under the License. require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect' +require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' require 'aws_advanced_ruby_driver_wrapper/host/host_info' require 'aws_advanced_ruby_driver_wrapper/postgresql' @@ -53,6 +54,126 @@ end end + describe '#with_query_timeout' do + let(:io) { instance_double(IO) } + let(:other) { instance_double(PG::Connection) } + + before { allow(connection).to receive_messages(socket_io: io, finished?: false, host: 'db.example', port: 5432) } + + def silent_server + allow(connection).to receive(:send_query) + allow(connection).to receive(:send_query_params) + allow(connection).to receive(:is_busy).and_return(true) + allow(io).to receive_messages(wait_readable: nil, reopen: nil) + end + + it 'does not bound queries outside the block' do + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) { nil } + expect(connection).to receive(:exec).with('SELECT 1').and_return(:ok) + expect(dialect.execute(connection, 'SELECT 1')).to eq(:ok) + end + + it 'raises QueryTimeoutError and closes an owned connection when the socket never becomes readable' do + silent_server + expect(connection).to receive(:close) + expect do + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) { dialect.execute(connection, 'SELECT 1') } + end.to raise_error(described_class::QueryTimeoutError, /timed out after 0.05s/) + end + + it 'logs the timeout, the host and whether the connection was closed' do + silent_server + allow(connection).to receive_messages(close: nil) + allow(io).to receive(:reopen) + allow(dialect).to receive(:logger).and_return(logger = instance_double(Logger, debug: nil, error: nil, info: nil)) + expect do + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) { dialect.execute(connection, 'SELECT 1') } + end.to raise_error(described_class::QueryTimeoutError) + expect(logger).to have_received(:info).with(/timed out after 0.05s on db.example:5432; closing the connection/) + end + + it 'leaves the connection open and unmodified when close_on_timeout is false' do + silent_server + expect(connection).not_to receive(:close) + expect(io).not_to receive(:reopen) + expect do + dialect.with_query_timeout(connection, close_on_timeout: false, timeout_sec: 0.05) { dialect.execute(connection, 'ROLLBACK') } + end.to raise_error(described_class::QueryTimeoutError) + end + + it 'bounds execute_with_params too' do + silent_server + allow(connection).to receive(:close) + expect do + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) do + dialect.execute_with_params(connection, 'SELECT $1', [1]) + end + end.to raise_error(described_class::QueryTimeoutError) + end + + it 'returns the last result when the server answers' do + result = instance_double(PG::Result, check: nil) + allow(connection).to receive(:send_query) + allow(connection).to receive(:is_busy).and_return(false) + allow(connection).to receive(:get_result).and_return(result, nil) + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) do + expect(dialect.execute(connection, 'SELECT 1')).to eq(result) + end + end + + it 'only bounds the given connection' do + expect(other).to receive(:exec).with('SELECT 1').and_return(:ok) + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) do + expect(dialect.execute(other, 'SELECT 1')).to eq(:ok) + end + end + + it 'leaves the block unbounded for a zero or nil timeout' do + [0.0, nil].each do |timeout| + expect(connection).to receive(:exec).with('SELECT 1').and_return(:ok) + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: timeout) do + expect(dialect.execute(connection, 'SELECT 1')).to eq(:ok) + end + end + end + + it 'lets the innermost scope win and restores the outer one' do + silent_server + outer_result = nil + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 10) do + expect do + dialect.with_query_timeout(connection, close_on_timeout: false, timeout_sec: 0.05) { dialect.execute(connection, 'SELECT 1') } + end.to raise_error(described_class::QueryTimeoutError, /0.05s/) + expect(dialect.send(:query_timeout_for, connection)).to eq([10.0, true]) + outer_result = :restored + end + expect(outer_result).to eq(:restored) + expect(dialect.send(:query_timeout_for, connection)).to be_nil + end + + it 'removes the scope when the block raises' do + expect { dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 1) { raise 'boom' } }.to raise_error('boom') + expect(dialect.send(:query_timeout_for, connection)).to be_nil + end + + it 'does not leak into other threads' do + seen = nil + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 1) do + Thread.new { seen = dialect.send(:query_timeout_for, connection) }.join + end + expect(seen).to be_nil + end + end + + describe 'QueryTimeoutError' do + it 'is a PG::ConnectionBad, ending in a newline so ActiveRecord maps it to ConnectionFailed' do + error = described_class::QueryTimeoutError.new(5) + expect(error).to be_a(PG::ConnectionBad) + expect(error.message).to end_with("\n") + expect(error.message).not_to match(/connection is closed|no connection to the server/i) + end + end + describe '#closed?' do it 'delegates to connection.finished?' do allow(connection).to receive(:finished?).and_return(true) diff --git a/spec/unit/errors/pg_error_handler_spec.rb b/spec/unit/errors/pg_error_handler_spec.rb index c7467932..2c2bc33e 100644 --- a/spec/unit/errors/pg_error_handler_spec.rb +++ b/spec/unit/errors/pg_error_handler_spec.rb @@ -88,6 +88,33 @@ end end + describe '#network_error? for a wrapper query timeout' do + before { require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' } + + let(:timeout_error) { AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) } + + it 'is a network error by class' do + expect(handler.network_error?(timeout_error)).to be true + end + + it 'is a network error when wrapped in a cause chain' do + wrapper = begin + begin + raise timeout_error + rescue PG::ConnectionBad + raise StandardError, 'outer' + end + rescue StandardError => e + e + end + expect(handler.network_error?(wrapper)).to be true + end + + it 'does not make a plain ConnectionBad with the same message a network error' do + expect(handler.network_error?(PG::ConnectionBad.new(timeout_error.message))).to be false + end + end + describe '#network_error?' do it 'detects network error from exception' do error = build_pg_error('57P01') diff --git a/spec/unit/failover_plugin_spec.rb b/spec/unit/failover_plugin_spec.rb index c5d4b982..9641e102 100644 --- a/spec/unit/failover_plugin_spec.rb +++ b/spec/unit/failover_plugin_spec.rb @@ -68,6 +68,8 @@ read_only_error?: false) end + before { allow(dialect_service).to receive(:with_query_timeout) { |_conn, **_opts, &block| block.call } } + let(:session_state_service) do double('session_state_service', in_transaction?: false, 'in_transaction=': nil) end @@ -240,6 +242,40 @@ end end + context 'when a network error occurs inside a transaction' do + let(:network_error) { StandardError.new('connection lost') } + let(:pipeline_callable) { -> { raise network_error } } + + before do + allow(db_dialect).to receive(:host_role).and_return(host_role::WRITER) + plugin.connect(writer_host, props, true, -> { connection }) + + allow(session_state_service).to receive(:in_transaction?).and_return(true) + allow(dialect_service).to receive(:network_error?).with(network_error).and_return(true) + allow(host_service).to receive(:force_refresh_host_list?).and_return(true) + allow(host_service).to receive(:set_availability) + allow(connection_service).to receive(:update_current_connection) + allow(driver_dialect).to receive(:close_connection) + writer_result = AwsAdvancedRubyDriverWrapper::Utils::RetryUtil::Result.new(new_connection, writer_host) + allow(retry_util).to receive(:connect_to_writer).and_return(writer_result) + end + + it 'bounds the ROLLBACK on the application connection and leaves it open if it times out' do + expect(dialect_service).to receive(:with_query_timeout).with(connection, close_on_timeout: false) + .and_yield + expect(driver_dialect).to receive(:execute).with(connection, 'ROLLBACK') + expect { plugin.execute('connection.exec', pipeline_callable) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::TransactionStateUnknownError) + end + + it 'does not fail the failover when the ROLLBACK times out' do + allow(driver_dialect).to receive(:execute).with(connection, 'ROLLBACK').and_raise(PG::ConnectionBad) + expect(driver_dialect).not_to receive(:close_connection).with(connection) + expect { plugin.execute('connection.exec', pipeline_callable) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::TransactionStateUnknownError) + end + end + context 'when a non-network error occurs' do let(:app_error) { StandardError.new('syntax error') } let(:pipeline_callable) { -> { raise app_error } } @@ -563,6 +599,13 @@ result = plugin.connect(writer_cluster_host, props, true, pipeline_callable) expect(result).to eq(connection) end + + it 'bounds the role check on a connection the wrapper has not handed out, closing it on timeout' do + allow(host_service).to receive(:refresh_host_list) + expect(dialect_service).to receive(:with_query_timeout).with(connection, close_on_timeout: true) + .and_yield + plugin.connect(writer_cluster_host, props, true, pipeline_callable) + end end context 'when writer cluster resolves to a reader (stale DNS)' do diff --git a/spec/unit/monitoring/cluster_topology_monitor_spec.rb b/spec/unit/monitoring/cluster_topology_monitor_spec.rb index 2ce58ff3..4f76bd77 100644 --- a/spec/unit/monitoring/cluster_topology_monitor_spec.rb +++ b/spec/unit/monitoring/cluster_topology_monitor_spec.rb @@ -56,6 +56,8 @@ let(:db_dialect) { instance_double('DbDialect') } let(:driver_dialect) { instance_double('DriverDialect', close_connection: nil, apply_monitoring_defaults: nil, closed?: false) } let(:dialect_service) { instance_double('DialectService', db_dialect: db_dialect, driver_dialect: driver_dialect) } + + before { allow(dialect_service).to receive(:with_monitoring_query_timeout) { |_conn, _props, &block| block.call } } let(:connection_config) do instance_double('ConnectionConfig', wrapper_props: { cluster_topology_refresh_rate_sec: 0.1, @@ -225,6 +227,26 @@ end end + describe 'query timeout' do + def build_monitor(wrapper_props) + described_class.new( + service_container: service_container, cluster_id: cluster_id, instance_template: instance_template, + topology_utils: topology_utils, monitoring_driver_props: { host: 'localhost', port: 5432 }, + monitoring_wrapper_props: wrapper_props + ) + end + + it 'bounds the topology query with the monitor props' do + build_monitor(pg_query_timeout_sec: 1.5).send(:query_topology, mock_connection) + expect(dialect_service).to have_received(:with_monitoring_query_timeout).with(mock_connection, { pg_query_timeout_sec: 1.5 }) + end + + it 'bounds the host role check the same way' do + build_monitor(pg_query_timeout_sec: 1.5).send(:check_host_role, mock_connection) + expect(dialect_service).to have_received(:with_monitoring_query_timeout).with(mock_connection, { pg_query_timeout_sec: 1.5 }) + end + end + describe 'regular mode' do it 'periodically fetches topology and updates cache' do # Set up a verified writer connection so monitor is in regular mode diff --git a/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb b/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb index 1ea7a640..39d63b1e 100644 --- a/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb +++ b/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb @@ -108,6 +108,7 @@ allow(topology_utils).to receive(:query_global_topology) { [writer_host, reader_east, reader_west] } allow(db_dialect).to receive(:host_role).and_return(AwsAdvancedRubyDriverWrapper::Host::HostRole::WRITER) allow(plugin_manager).to receive(:internal_connect).and_return(mock_connection) + allow(dialect_service).to receive(:with_monitoring_query_timeout) { |_conn, _props, &block| block.call } end after do @@ -130,6 +131,15 @@ end end + describe 'query timeout' do + it 'bounds the global topology query like the base monitor does' do + monitor.send(:query_topology, mock_connection) + + expect(dialect_service).to have_received(:with_monitoring_query_timeout).with(mock_connection, {}) + expect(topology_utils).to have_received(:query_global_topology) + end + end + describe 'multi-region topology caching' do it 'stores hosts from multiple regions in the topology cache' do monitor.start diff --git a/spec/unit/plugins/encryption/connection_source_spec.rb b/spec/unit/plugins/encryption/connection_source_spec.rb index 8a526bcb..5b0e0c9b 100644 --- a/spec/unit/plugins/encryption/connection_source_spec.rb +++ b/spec/unit/plugins/encryption/connection_source_spec.rb @@ -27,6 +27,8 @@ end let(:plugin_manager) { double('PluginManager') } let(:dialect_service) { double('DialectService', driver_dialect: dialect) } + + before { allow(dialect_service).to receive(:with_query_timeout) { |_conn, **_opts, &block| block.call } } let(:service_container) do double('ServiceContainer', connection_service: connection_service, plugin_manager: plugin_manager, dialect_service: dialect_service) @@ -67,6 +69,12 @@ def initialize(**kwargs) expect(source.with_connection { |_c| 42 }).to eq(42) end + it 'does not bound a caller-owned connection' do + allow(dialect_service).to receive(:with_query_timeout) + source.with_connection { |c| c } + expect(dialect_service).not_to have_received(:with_query_timeout) + end + it 'never closes it (a plain double would raise if #close were called)' do expect(connection).not_to receive(:close) 2.times { expect(source.with_connection { |c| c }).to be(connection) } @@ -87,6 +95,11 @@ def initialize(**kwargs) expect(plugin_manager).to have_received(:internal_connect).with(host, driver_props, wrapper_props, false) end + it 'bounds the wrapper-owned connection, which it may close on timeout' do + source.with_connection(operation: 'X') { |c| c } + expect(dialect_service).to have_received(:with_query_timeout).with(opened, close_on_timeout: true) + end + it 'closes the opened connection afterward' do source.with_connection { |c| c } expect(dialect).to have_received(:close_connection).with(opened) diff --git a/spec/unit/plugins/encryption/kms_encryption_utility_spec.rb b/spec/unit/plugins/encryption/kms_encryption_utility_spec.rb index fa550893..ab559b8d 100644 --- a/spec/unit/plugins/encryption/kms_encryption_utility_spec.rb +++ b/spec/unit/plugins/encryption/kms_encryption_utility_spec.rb @@ -36,7 +36,12 @@ driver_props: { host: 'db' }, wrapper_props: props), plugin_manager: plugin_manager, - dialect_service: instance_double(services::DialectService, driver_dialect: driver_dialect)) + dialect_service: dialect_service) + end + let(:dialect_service) do + instance_double(services::DialectService, driver_dialect: driver_dialect).tap do |service| + allow(service).to receive(:with_query_timeout) { |_conn, **_opts, &block| block.call } + end end # Both caches are off, so that building the database backed components neither queries the # metadata tables nor leaves a cleanup thread behind. diff --git a/spec/unit/plugins/initial_connection_strategy_plugin_spec.rb b/spec/unit/plugins/initial_connection_strategy_plugin_spec.rb index 563b0106..1c2aadf9 100644 --- a/spec/unit/plugins/initial_connection_strategy_plugin_spec.rb +++ b/spec/unit/plugins/initial_connection_strategy_plugin_spec.rb @@ -58,6 +58,8 @@ network_error?: false, read_only_error?: false) end + + before { allow(mock_dialect_service).to receive(:with_query_timeout) { |_conn, **_opts, &block| block.call } } let(:mock_host_service) do double('HostService', all_hosts: [writer_host_info, reader_host_info], diff --git a/spec/unit/property_definition_spec.rb b/spec/unit/property_definition_spec.rb index 776ea390..4c66e1a5 100644 --- a/spec/unit/property_definition_spec.rb +++ b/spec/unit/property_definition_spec.rb @@ -18,6 +18,20 @@ require 'aws_advanced_ruby_driver_wrapper/property_definition' RSpec.describe AwsAdvancedRubyDriverWrapper::PropertyDefinition do + describe 'PG_QUERY_TIMEOUT_SEC validation' do + let(:prop) { described_class::PG_QUERY_TIMEOUT_SEC } + + it 'accepts 0, the 900 second maximum, numeric strings and nil' do + [0, 0.5, '2.5', 900, nil].each { |v| expect { prop.validate!(v) }.not_to raise_error } + end + + it 'rejects negative, non-finite, non-numeric and over-maximum values' do + [-1, Float::INFINITY, Float::NAN, 'abc', 900.1].each do |v| + expect { prop.validate!(v) }.to raise_error(ArgumentError, /pg_query_timeout_sec must be a number from 0 to 900/) + end + end + end + describe '.wrapper_property?' do it 'returns true for known wrapper properties' do expect(described_class.wrapper_property?(:wrapper_plugins)).to be true diff --git a/spec/unit/services/dialect_service_spec.rb b/spec/unit/services/dialect_service_spec.rb index 44c899f4..0484b7d7 100644 --- a/spec/unit/services/dialect_service_spec.rb +++ b/spec/unit/services/dialect_service_spec.rb @@ -265,6 +265,74 @@ def build_service_with_container(driver_name, host: 'localhost', wrapper_props: end end + describe '#with_query_timeout' do + let(:connection) { double('Connection') } + let(:driver_dialect) { double('DriverDialect') } + + def service_with(wrapper_props) + service = build_service(:postgresql, wrapper_props: wrapper_props) + allow(service).to receive(:driver_dialect).and_return(driver_dialect) + service + end + + it 'bounds by the pg_query_timeout_sec property when no timeout is given' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: false, timeout_sec: 7.0).and_yield + service_with(pg_query_timeout_sec: 7.0).with_query_timeout(connection, close_on_timeout: false) { :ignored } + end + + it 'is unbounded (0) by default' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: true, timeout_sec: 0.0).and_yield + service_with({}).with_query_timeout(connection, close_on_timeout: true) { :ignored } + end + + it 'prefers an explicit timeout, including 0, over the property' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: true, timeout_sec: 0.0).and_yield + service_with(pg_query_timeout_sec: 7.0) + .with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.0) { :ignored } + end + + it 'returns the block result' do + allow(driver_dialect).to receive(:with_query_timeout) { |*_args, **_opts, &block| block.call } + expect(service_with({}).with_query_timeout(connection, close_on_timeout: true) { :result }).to eq(:result) + end + end + + describe '#with_monitoring_query_timeout' do + let(:connection) { double('Connection') } + let(:driver_dialect) { double('DriverDialect') } + + let(:service) do + build_service(:postgresql).tap { |svc| allow(svc).to receive(:driver_dialect).and_return(driver_dialect) } + end + + it 'defaults to a bound so a monitor never blocks indefinitely, closing the monitor-owned connection' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: true, timeout_sec: 5).and_yield + service.with_monitoring_query_timeout(connection, {}) { :ignored } + end + + it 'uses pg_query_timeout_sec from the monitor props when set' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: true, timeout_sec: 2.5).and_yield + service.with_monitoring_query_timeout(connection, { pg_query_timeout_sec: 2.5 }) { :ignored } + end + + it 'lets an explicit 0 disable the bound' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: true, timeout_sec: 0.0).and_yield + service.with_monitoring_query_timeout(connection, { pg_query_timeout_sec: 0.0 }) { :ignored } + end + + it 'ignores the connection-level property in favor of the monitor props' do + expect(driver_dialect).to receive(:with_query_timeout).with(connection, close_on_timeout: true, timeout_sec: 5).and_yield + svc = build_service(:postgresql, wrapper_props: { pg_query_timeout_sec: 30.0 }) + allow(svc).to receive(:driver_dialect).and_return(driver_dialect) + svc.with_monitoring_query_timeout(connection, {}) { :ignored } + end + + it 'returns the block result' do + allow(driver_dialect).to receive(:with_query_timeout) { |*_args, **_opts, &block| block.call } + expect(service.with_monitoring_query_timeout(connection, {}) { :result }).to eq(:result) + end + end + describe '#update_dialect' do context 'PostgreSQL driver' do let(:connection) { instance_double('PG::Connection') } From 658bd34136b286a7e7363029c122de7a1b3d0943 Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:32:47 -0700 Subject: [PATCH 2/8] fix: propagate dialect timeout --- .../db_dialects/aurora_pg_dialect.rb | 8 ++++++-- .../db_dialects/global_pg_dialect.rb | 6 ++++-- .../db_dialects/multi_az_cluster_pg_dialect.rb | 4 +++- .../db_dialects/rds_pg_dialect.rb | 4 +++- .../db_dialects/utils/dialect_utils.rb | 14 +++++++++++++- spec/unit/services/dialect_service_spec.rb | 10 ++++++++++ 6 files changed, 39 insertions(+), 7 deletions(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb index a1517686..0eb1062d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb @@ -74,13 +74,17 @@ def dialect?(connection) result = @driver_dialect.execute(connection, AURORA_UTILS_EXIST_QUERY) return false unless result.any? return false unless result.first['aurora_stat_utils'] == 't' - rescue StandardError + rescue StandardError => e + raise if DialectUtils.query_timeout_error?(e) + return false end result = @driver_dialect.execute(connection, TOPOLOGY_EXISTS_QUERY) !result.nil? && result.any? - rescue StandardError + rescue StandardError => e + raise if DialectUtils.query_timeout_error?(e) + false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb index 40c67ba3..179ec007 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb @@ -53,13 +53,15 @@ def dialect?(connection) return false unless check_existence_queries(@driver_dialect, connection, GLOBAL_STATUS_FUNC_EXISTS_QUERY, GLOBAL_INSTANCE_STATUS_FUNC_EXISTS_QUERY) - result = connection.exec(REGION_COUNT_QUERY) + result = @driver_dialect.execute(connection, REGION_COUNT_QUERY) return false unless result.any? row = result.first aws_region_count = row.is_a?(Hash) ? row.values.first.to_i : row[0].to_i aws_region_count > 1 - rescue StandardError + rescue StandardError => e + raise if DialectUtils.query_timeout_error?(e) + false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb index 5c7b399b..c7f0c191 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb @@ -49,7 +49,9 @@ def dialect?(connection) row = result.first !row['multi_az_db_cluster_source_dbi_resource_id'].nil? - rescue StandardError + rescue StandardError => e + raise if DialectUtils.query_timeout_error?(e) + false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb index 323b6168..c7e3ed99 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb @@ -59,7 +59,9 @@ def dialect?(connection) return true if rds_tools_enabled && !aurora_utils_enabled end - rescue StandardError + rescue StandardError => e + raise if DialectUtils.query_timeout_error?(e) + return false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb index 7cfaee85..5aef22b3 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb @@ -19,6 +19,16 @@ module AwsAdvancedRubyDriverWrapper module DbDialects module DialectUtils + # Whether +error+ is the PG driver dialect's query timeout. Dialect detection must not read a timeout as + # "not this dialect": the answer is unknown, so the error has to reach the caller. + # + # The class is only defined once pg_query_timeout_error.rb is loaded, so it is never named in a +rescue+ + # clause (a missing constant there would raise NameError while an error is being handled). + def self.query_timeout_error?(error) + defined?(DriverDialects::PgDriverDialect::QueryTimeoutError) == 'constant' && + error.is_a?(DriverDialects::PgDriverDialect::QueryTimeoutError) + end + # Returns the instance identity for the given connection. # # @param driver_dialect [Object] the driver dialect used to execute queries @@ -63,7 +73,9 @@ def check_existence_queries(driver_dialect, connection, *queries) return false if result.nil? || result.none? end true - rescue StandardError + rescue StandardError => e + raise if DialectUtils.query_timeout_error?(e) + false end end diff --git a/spec/unit/services/dialect_service_spec.rb b/spec/unit/services/dialect_service_spec.rb index 0484b7d7..b520db36 100644 --- a/spec/unit/services/dialect_service_spec.rb +++ b/spec/unit/services/dialect_service_spec.rb @@ -356,6 +356,16 @@ def service_with(wrapper_props) expect(result).to eq(original_dialect) end + it 'propagates a query timeout and does not cache the endpoint dialect' do + require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' + timeout_error = AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) + allow(connection).to receive(:exec).and_raise(timeout_error) + described_class.known_endpoint_dialects.remove(host) + + expect { service.update_dialect(connection) }.to raise_error(timeout_error.class) + expect(described_class.known_endpoint_dialects.get(host)).to be_nil + end + it 'updates to GlobalPgDialect when global functions exist' do aurora_utils_result = [{ 'aurora_stat_utils' => 't' }] global_status_result = [{ 'regproc' => 'aurora_global_db_status' }] From 14f3ea91f3863536c12322f2caed6e15ceec52df Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:01:18 -0700 Subject: [PATCH 3/8] fix: add timeout to query_id_and_name --- .../services/host_service.rb | 5 ++++- spec/unit/services/host_service_spec.rb | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper/services/host_service.rb b/lib/aws_advanced_ruby_driver_wrapper/services/host_service.rb index 698842c5..d7503e51 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/services/host_service.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/services/host_service.rb @@ -209,7 +209,10 @@ def get_cached_host_info(connection, connection_host_info) end def query_id_and_name(connection) - @service_container.dialect_service.db_dialect.instance_identity(connection) + dialect_service = @service_container.dialect_service + dialect_service.with_query_timeout(connection, close_on_timeout: false) do + dialect_service.db_dialect.instance_identity(connection) + end rescue StandardError [nil, nil] end diff --git a/spec/unit/services/host_service_spec.rb b/spec/unit/services/host_service_spec.rb index 41521887..f9d9b621 100644 --- a/spec/unit/services/host_service_spec.rb +++ b/spec/unit/services/host_service_spec.rb @@ -31,6 +31,8 @@ let(:dialect) { instance_double('Dialect') } let(:dialect_service) { instance_double('DialectService', db_dialect: dialect) } + before { allow(dialect_service).to receive(:with_query_timeout) { |_conn, **_opts, &block| block.call } } + let(:connection_service) { instance_double('ConnectionService') } let(:service_container) do @@ -281,6 +283,14 @@ expect(result).to eq(reader) end + it 'bounds the identity query without closing the connection on timeout' do + expect(dialect_service).to receive(:with_query_timeout).with(connection, close_on_timeout: false).and_yield + allow(dialect).to receive(:instance_identity).with(connection).and_return(['reader-id', nil]) + allow(host_list_provider).to receive(:refresh).and_return(hosts) + + expect(service.identify_host(connection)).to eq(reader) + end + it 'returns nil when instance_identity returns nil' do allow(dialect).to receive(:instance_identity).with(connection).and_return([nil, nil]) allow(host_list_provider).to receive(:refresh).and_return(hosts) From 0bef40314c01a303f93646d7cb098cda0c814f5b Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:02:19 -0700 Subject: [PATCH 4/8] fix: param above return in wrapper_property.rb --- lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb b/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb index db2446ba..4baf51d6 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/wrapper_property.rb @@ -26,8 +26,8 @@ def initialize(name, description, default_value: nil, type: nil, validator: nil) @validator = validator end - # @return [String, Boolean, Integer, nil] the value from props, or the property's default # @param default [Object] used instead of the property's default when the key is in neither +props+ nor +override+ + # @return [String, Boolean, Integer, Float, nil] the value from props, or the property's default def get(props, override = nil, default: @default_value) override&.key?(@name) ? override.fetch(@name, default) : props.fetch(@name, default) end @@ -44,6 +44,8 @@ def get_int(props, override = nil) val.is_a?(Integer) ? val : val.to_i end + # @param default [Object] used instead of the property's default when the key is in neither +props+ nor +override+ + # @return [Float] def get_float(props, override = nil, default: @default_value) val = get(props, override, default: default) val.is_a?(Float) ? val : val.to_f From 2a6f343ca8c19b4ec6f5203ff0dcc867f0048489 Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:03:23 -0700 Subject: [PATCH 5/8] fix: add timeout to attempt_connection --- .../utils/retry_util.rb | 9 +++++++- spec/unit/retry_util_spec.rb | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb b/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb index fb18c008..c7005e07 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb @@ -119,7 +119,7 @@ def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) conn = plugin_manager.connect(candidate, @connection_service.driver_props, false, plugin_to_skip: plugin_to_skip) # Since the roles in the host list might not be accurate, we execute a query to check the instance's role. - role = verify_role.nil? ? nil : @dialect_service.db_dialect.host_role(conn) + role = verify_role.nil? ? nil : check_role(conn) if verify_role.nil? return Result.new(conn, candidate) elsif verify_role == role @@ -135,6 +135,13 @@ def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) nil end + def check_role(conn) + # A candidate the wrapper opened and has not handed out, so it may be closed on timeout. + @dialect_service.with_query_timeout(conn, close_on_timeout: true) do + @dialect_service.db_dialect.host_role(conn) + end + end + def select_candidate(hosts, role, strategy) @host_service.select_host(hosts, role, strategy) rescue StandardError => e diff --git a/spec/unit/retry_util_spec.rb b/spec/unit/retry_util_spec.rb index 39488e08..034ff587 100644 --- a/spec/unit/retry_util_spec.rb +++ b/spec/unit/retry_util_spec.rb @@ -62,6 +62,7 @@ end before do + allow(dialect_service).to receive(:with_query_timeout) { |_conn, **_opts, &block| block.call } allow(host_service).to receive(:select_host) do |hosts, role, _strategy| host_selector.select_host(hosts, role) end @@ -102,6 +103,28 @@ end end + context 'when checking the role of a candidate' do + before do + allow(plugin_manager).to receive(:connect).and_return(connection) + allow(db_dialect).to receive(:host_role).with(connection).and_return(host_role::WRITER) + end + + it 'bounds the role check and allows closing the connection on timeout' do + expect(dialect_service).to receive(:with_query_timeout).with(connection, close_on_timeout: true).and_yield + retry_util.connect_to_writer(plugin_to_skip, plugin_manager, deadline: Time.now + 5) + end + + it 'closes the connection and retries when the role check times out' do + require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' + timeout_error = AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) + allow(db_dialect).to receive(:host_role).with(connection).and_raise(timeout_error) + expect(driver_dialect).to receive(:close_connection).with(connection).at_least(:once) + expect do + retry_util.connect_to_writer(plugin_to_skip, plugin_manager, deadline: Time.now + 0.15) + end.to raise_error(Timeout::Error) + end + end + context 'when no writer is in the topology' do before do allow(host_service).to receive(:all_hosts).and_return([reader_host]) From 6a3ca664c3b71bbd46fe64d20f75117e32fa4e6f Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:05:41 -0700 Subject: [PATCH 6/8] refactor: query_timeout_error? to driver dialect --- .../db_dialects/aurora_pg_dialect.rb | 4 +-- .../db_dialects/global_pg_dialect.rb | 2 +- .../multi_az_cluster_pg_dialect.rb | 2 +- .../db_dialects/rds_pg_dialect.rb | 2 +- .../db_dialects/utils/dialect_utils.rb | 12 +------- .../driver_dialects/driver_dialect.rb | 6 ++++ .../driver_dialects/pg_driver_dialect.rb | 5 ++++ .../errors/pg_error_handler.rb | 8 +----- .../driver_dialects/pg_driver_dialect_spec.rb | 28 +++++++++++++++++++ 9 files changed, 46 insertions(+), 23 deletions(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb index 0eb1062d..37ebd52f 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/aurora_pg_dialect.rb @@ -75,7 +75,7 @@ def dialect?(connection) return false unless result.any? return false unless result.first['aurora_stat_utils'] == 't' rescue StandardError => e - raise if DialectUtils.query_timeout_error?(e) + raise if @driver_dialect.query_timeout_error?(e) return false end @@ -83,7 +83,7 @@ def dialect?(connection) result = @driver_dialect.execute(connection, TOPOLOGY_EXISTS_QUERY) !result.nil? && result.any? rescue StandardError => e - raise if DialectUtils.query_timeout_error?(e) + raise if @driver_dialect.query_timeout_error?(e) false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb index 179ec007..ec4389ee 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/global_pg_dialect.rb @@ -60,7 +60,7 @@ def dialect?(connection) aws_region_count = row.is_a?(Hash) ? row.values.first.to_i : row[0].to_i aws_region_count > 1 rescue StandardError => e - raise if DialectUtils.query_timeout_error?(e) + raise if @driver_dialect.query_timeout_error?(e) false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb index c7f0c191..c0af8c67 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/multi_az_cluster_pg_dialect.rb @@ -50,7 +50,7 @@ def dialect?(connection) row = result.first !row['multi_az_db_cluster_source_dbi_resource_id'].nil? rescue StandardError => e - raise if DialectUtils.query_timeout_error?(e) + raise if @driver_dialect.query_timeout_error?(e) false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb index c7e3ed99..7d638cbb 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/rds_pg_dialect.rb @@ -60,7 +60,7 @@ def dialect?(connection) return true if rds_tools_enabled && !aurora_utils_enabled end rescue StandardError => e - raise if DialectUtils.query_timeout_error?(e) + raise if @driver_dialect.query_timeout_error?(e) return false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb index 5aef22b3..07f1a1cc 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/db_dialects/utils/dialect_utils.rb @@ -19,16 +19,6 @@ module AwsAdvancedRubyDriverWrapper module DbDialects module DialectUtils - # Whether +error+ is the PG driver dialect's query timeout. Dialect detection must not read a timeout as - # "not this dialect": the answer is unknown, so the error has to reach the caller. - # - # The class is only defined once pg_query_timeout_error.rb is loaded, so it is never named in a +rescue+ - # clause (a missing constant there would raise NameError while an error is being handled). - def self.query_timeout_error?(error) - defined?(DriverDialects::PgDriverDialect::QueryTimeoutError) == 'constant' && - error.is_a?(DriverDialects::PgDriverDialect::QueryTimeoutError) - end - # Returns the instance identity for the given connection. # # @param driver_dialect [Object] the driver dialect used to execute queries @@ -74,7 +64,7 @@ def check_existence_queries(driver_dialect, connection, *queries) end true rescue StandardError => e - raise if DialectUtils.query_timeout_error?(e) + raise if driver_dialect.query_timeout_error?(e) false end diff --git a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb index 50ff7d15..5ede6200 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/driver_dialect.rb @@ -147,6 +147,12 @@ def sql_state(_exception) nil end + # Whether +error+ is this driver's timeout for a wrapper-internal query (see #with_query_timeout). + # Dialect detection must not read a timeout as "not this dialect": the answer is unknown, so it has to propagate. + def query_timeout_error?(_error) + false + end + def network_bound_methods COMMON_NETWORK_BOUND_METHODS end diff --git a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb index bba84724..1a6b9d1e 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/driver_dialects/pg_driver_dialect.rb @@ -228,6 +228,11 @@ def sql_state(exception) exception.result.error_field(::PG::PG_DIAG_SQLSTATE) end + # The error class is loaded on demand (it needs the pg gem), so check that it is defined before using it. + def query_timeout_error?(error) + defined?(QueryTimeoutError) == 'constant' && error.is_a?(QueryTimeoutError) + end + def network_bound_methods NETWORK_BOUND_METHODS end diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb index 179acf7c..1c542db1 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb @@ -110,7 +110,7 @@ def read_only_error_by_sql_state?(sql_state, _error_code = nil) def connection_bad_network_error?(error) return false unless defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad) # A timed-out wrapper query is a connection failure by class, whatever its message says. - return true if query_timeout_error?(error) + return true if @driver_dialect.query_timeout_error?(error) msg = error.message&.downcase return false if msg.nil? @@ -120,12 +120,6 @@ def connection_bad_network_error?(error) CONNECT_FAILURE_MESSAGES.any? { |pattern| msg.include?(pattern) } end - # The error class is only defined once pg has loaded it, on the first timeout, so nothing else can be one. - def query_timeout_error?(error) - defined?(DriverDialects::PgDriverDialect::QueryTimeoutError) && - error.is_a?(DriverDialects::PgDriverDialect::QueryTimeoutError) - end - def server_rejection?(msg) SERVER_REJECTION_MESSAGES.any? { |pattern| msg.include?(pattern) } end diff --git a/spec/unit/driver_dialects/pg_driver_dialect_spec.rb b/spec/unit/driver_dialects/pg_driver_dialect_spec.rb index 39866ecd..1ea4be88 100644 --- a/spec/unit/driver_dialects/pg_driver_dialect_spec.rb +++ b/spec/unit/driver_dialects/pg_driver_dialect_spec.rb @@ -54,6 +54,19 @@ end end + describe '#query_timeout_error?' do + it 'is true only for the query timeout' do + expect(dialect.query_timeout_error?(described_class::QueryTimeoutError.new(5))).to be true + expect(dialect.query_timeout_error?(PG::ConnectionBad.new('x'))).to be false + expect(dialect.query_timeout_error?(StandardError.new('x'))).to be false + end + + it 'does not raise when the timeout class is not defined' do + hide_const('AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError') + expect(dialect.query_timeout_error?(StandardError.new('x'))).to be false + end + end + describe '#with_query_timeout' do let(:io) { instance_double(IO) } let(:other) { instance_double(PG::Connection) } @@ -121,6 +134,21 @@ def silent_server end end + it 'raises the server error from the result, not a timeout, and keeps the connection' do + error = PG::UndefinedFunction.new('function aurora_stat_utils() does not exist') + result = instance_double(PG::Result) + allow(result).to receive(:check).and_raise(error) + allow(result).to receive(:clear) + allow(connection).to receive(:send_query) + allow(connection).to receive(:is_busy).and_return(false) + allow(connection).to receive(:get_result).and_return(result, nil) + expect(connection).not_to receive(:close) + + dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) do + expect { dialect.execute(connection, 'SELECT aurora_stat_utils()') }.to raise_error(PG::UndefinedFunction) + end + end + it 'only bounds the given connection' do expect(other).to receive(:exec).with('SELECT 1').and_return(:ok) dialect.with_query_timeout(connection, close_on_timeout: true, timeout_sec: 0.05) do From b5a352cd383ba924d0871daa4d3fc2740541b48c Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:08:59 -0700 Subject: [PATCH 7/8] test: ROLLBACK test with QueryTimeoutError --- spec/unit/failover_plugin_spec.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spec/unit/failover_plugin_spec.rb b/spec/unit/failover_plugin_spec.rb index 9641e102..c1c3599f 100644 --- a/spec/unit/failover_plugin_spec.rb +++ b/spec/unit/failover_plugin_spec.rb @@ -269,7 +269,9 @@ end it 'does not fail the failover when the ROLLBACK times out' do - allow(driver_dialect).to receive(:execute).with(connection, 'ROLLBACK').and_raise(PG::ConnectionBad) + require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' + timeout_error = AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) + allow(driver_dialect).to receive(:execute).with(connection, 'ROLLBACK').and_raise(timeout_error) expect(driver_dialect).not_to receive(:close_connection).with(connection) expect { plugin.execute('connection.exec', pipeline_callable) } .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::TransactionStateUnknownError) From b4c26b65d77f66aaff46d07e2baa3aeeb7f89121 Mon Sep 17 00:00:00 2001 From: Sophia Chu <112967780+sophia-bq@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:17:16 -0700 Subject: [PATCH 8/8] test: per dialect query timeout tests --- spec/unit/services/dialect_service_spec.rb | 68 ++++++++++++++++++---- 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/spec/unit/services/dialect_service_spec.rb b/spec/unit/services/dialect_service_spec.rb index b520db36..4f55e557 100644 --- a/spec/unit/services/dialect_service_spec.rb +++ b/spec/unit/services/dialect_service_spec.rb @@ -356,16 +356,6 @@ def service_with(wrapper_props) expect(result).to eq(original_dialect) end - it 'propagates a query timeout and does not cache the endpoint dialect' do - require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' - timeout_error = AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) - allow(connection).to receive(:exec).and_raise(timeout_error) - described_class.known_endpoint_dialects.remove(host) - - expect { service.update_dialect(connection) }.to raise_error(timeout_error.class) - expect(described_class.known_endpoint_dialects.get(host)).to be_nil - end - it 'updates to GlobalPgDialect when global functions exist' do aurora_utils_result = [{ 'aurora_stat_utils' => 't' }] global_status_result = [{ 'regproc' => 'aurora_global_db_status' }] @@ -619,4 +609,62 @@ def service_with(wrapper_props) end end end + + describe 'dialect detection on a query timeout' do + before { require 'aws_advanced_ruby_driver_wrapper/driver_dialects/pg_query_timeout_error' } + + let(:dialects) { AwsAdvancedRubyDriverWrapper::DbDialects } + let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect.new } + let(:timeout_error) { AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect::QueryTimeoutError.new(5) } + let(:connection) { instance_double('PG::Connection') } + let(:host) { 'my-cluster.cluster-xyz.us-east-2.rds.amazonaws.com' } + let(:service) { build_service_with_container(:postgresql, host: host) } + let(:server_result) { [{ 'aurora_stat_utils' => 't', 'rds_tools' => 't' }] } + + # [dialect, the query that times out]: every other query succeeds, so each rescue in each dialect is the one + # exercised, not just the first one reached. + [ + %i[AuroraPgDialect AURORA_UTILS_EXIST_QUERY], + %i[AuroraPgDialect TOPOLOGY_EXISTS_QUERY], + %i[GlobalPgDialect AURORA_UTILS_EXIST_QUERY], + %i[GlobalPgDialect GLOBAL_STATUS_FUNC_EXISTS_QUERY], + %i[GlobalPgDialect REGION_COUNT_QUERY], + %i[MultiAzClusterPgDialect IS_RDS_CLUSTER_QUERY], + %i[RdsPgDialect PG_PROC_EXISTS_QUERY], + %i[RdsPgDialect EXTENSIONS_EXIST_SQL], + %i[PgDialect PG_PROC_EXISTS_QUERY] + ].each do |klass_name, query_name| + context "when #{klass_name} times out on #{query_name}" do + let(:candidate) { dialects.const_get(klass_name).new(driver_dialect) } + + before do + timing_out_query = dialects.const_get(klass_name).const_get(query_name) + allow(driver_dialect).to receive(:execute) do |_conn, query| + raise timeout_error if query == timing_out_query + + server_result + end + end + + it 'raises from #dialect?' do + expect { candidate.dialect?(connection) }.to raise_error(timeout_error.class) + end + + it 'propagates from #update_dialect and does not cache the endpoint dialect' do + allow(service).to receive(:dialect_for_code).and_return(candidate) + + expect { service.update_dialect(connection) }.to raise_error(timeout_error.class) + expect(described_class.known_endpoint_dialects.get(host)).to be_nil + end + end + end + + it 'still reads a query error that is not a timeout as "not this dialect"' do + allow(driver_dialect).to receive(:execute).and_raise(PG::UndefinedTable.new('nope')) + [dialects::AuroraPgDialect, dialects::GlobalPgDialect, dialects::MultiAzClusterPgDialect, + dialects::RdsPgDialect, dialects::PgDialect].each do |klass| + expect(klass.new(driver_dialect).dialect?(connection)).to be(false), klass.name + end + end + end end