sqlspec 0.72.1__py3-none-any.whl → 0.73.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -454,7 +454,7 @@ def resolve_rowcount(cursor: Any) -> int:
454
454
  if not has_rowcount(cursor):
455
455
  return 0
456
456
  rowcount = cursor.rowcount
457
- if isinstance(rowcount, int) and rowcount >= 0:
457
+ if isinstance(rowcount, int) and not isinstance(rowcount, bool) and rowcount >= 0:
458
458
  return rowcount
459
459
  return 0
460
460
 
@@ -476,12 +476,12 @@ def normalize_lastrowid(cursor: Any) -> int | None:
476
476
  if not has_rowcount(cursor):
477
477
  return None
478
478
  rowcount = cursor.rowcount
479
- if not isinstance(rowcount, int) or rowcount <= 0:
479
+ if isinstance(rowcount, bool) or not isinstance(rowcount, int) or rowcount <= 0:
480
480
  return None
481
481
  if not has_lastrowid(cursor):
482
482
  return None
483
483
  last_id = cursor.lastrowid
484
- return last_id if isinstance(last_id, int) else None
484
+ return last_id if isinstance(last_id, int) and not isinstance(last_id, bool) else None
485
485
 
486
486
 
487
487
  async def execute_cache_hit(
@@ -526,7 +526,11 @@ async def execute_cache_hit(
526
526
  else:
527
527
  await cursor.execute(compiled_sql)
528
528
  if not cached.operation_profile.returns_rows:
529
- result = DMLResult(cached.operation_type, resolve_rowcount(cursor))
529
+ affected_rows = resolve_rowcount(cursor)
530
+ last_inserted_id = (
531
+ normalize_lastrowid(cursor) if cached.operation_type == "INSERT" and affected_rows > 0 else None
532
+ )
533
+ result = DMLResult(cached.operation_type, affected_rows, last_inserted_id)
530
534
  else:
531
535
  fetched_data = await cursor.fetchall()
532
536
  rows, column_names, _row_format = collect_rows(
@@ -453,7 +453,7 @@ def resolve_rowcount(cursor: Any) -> int:
453
453
  if not has_rowcount(cursor):
454
454
  return 0
455
455
  rowcount = cursor.rowcount
456
- if isinstance(rowcount, int) and rowcount >= 0:
456
+ if isinstance(rowcount, int) and not isinstance(rowcount, bool) and rowcount >= 0:
457
457
  return rowcount
458
458
  return 0
459
459
 
@@ -475,12 +475,12 @@ def normalize_lastrowid(cursor: Any) -> int | None:
475
475
  if not has_rowcount(cursor):
476
476
  return None
477
477
  rowcount = cursor.rowcount
478
- if not isinstance(rowcount, int) or rowcount <= 0:
478
+ if isinstance(rowcount, bool) or not isinstance(rowcount, int) or rowcount <= 0:
479
479
  return None
480
480
  if not has_lastrowid(cursor):
481
481
  return None
482
482
  last_id = cursor.lastrowid
483
- return last_id if isinstance(last_id, int) else None
483
+ return last_id if isinstance(last_id, int) and not isinstance(last_id, bool) else None
484
484
 
485
485
 
486
486
  async def execute_cache_hit(
@@ -525,7 +525,11 @@ async def execute_cache_hit(
525
525
  else:
526
526
  await cursor.execute(compiled_sql)
527
527
  if not cached.operation_profile.returns_rows:
528
- result = DMLResult(cached.operation_type, resolve_rowcount(cursor))
528
+ affected_rows = resolve_rowcount(cursor)
529
+ last_inserted_id = (
530
+ normalize_lastrowid(cursor) if cached.operation_type == "INSERT" and affected_rows > 0 else None
531
+ )
532
+ result = DMLResult(cached.operation_type, affected_rows, last_inserted_id)
529
533
  else:
530
534
  fetched_data = await cursor.fetchall()
531
535
  rows, column_names, _row_format = collect_rows(
@@ -1,6 +1,8 @@
1
1
  """AsyncPG database configuration with direct field-based configuration."""
2
2
 
3
3
  import asyncio
4
+ import logging
5
+ import math
4
6
  from collections.abc import Mapping, Sequence
5
7
  from contextlib import suppress
6
8
  from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, NotRequired, Self, TypedDict, cast, overload
@@ -26,10 +28,15 @@ from sqlspec.adapters.asyncpg._typing import AsyncpgPoolConnectionProxyMeta as P
26
28
  from sqlspec.adapters.asyncpg._typing import AsyncpgRawConnection as Connection
27
29
  from sqlspec.adapters.asyncpg._typing import AsyncpgRecord as Record
28
30
  from sqlspec.adapters.asyncpg.core import (
31
+ DEFAULT_CONNECTOR_RETRY_COUNT,
32
+ DEFAULT_CONNECTOR_RETRY_DELAY,
33
+ DEFAULT_CONNECTOR_RETRY_MAX_DELAY,
29
34
  apply_driver_features,
30
35
  build_connection_config,
36
+ calculate_connector_backoff_seconds,
31
37
  create_mapped_exception,
32
38
  default_statement_config,
39
+ is_transient_connector_error,
33
40
  register_json_codecs,
34
41
  register_pgvector_support,
35
42
  )
@@ -48,7 +55,7 @@ from sqlspec.exceptions import ImproperConfigurationError, MissingDependencyErro
48
55
  from sqlspec.extensions.events import EventRuntimeHints
49
56
  from sqlspec.typing import ALLOYDB_CONNECTOR_INSTALLED, CLOUD_SQL_CONNECTOR_INSTALLED, PGVECTOR_INSTALLED
50
57
  from sqlspec.utils.config_tools import normalize_connection_config
51
- from sqlspec.utils.logging import get_logger
58
+ from sqlspec.utils.logging import get_logger, log_with_context
52
59
  from sqlspec.utils.serializers import from_json, to_json
53
60
  from sqlspec.utils.tenant import TenantContextPayload
54
61
 
@@ -92,6 +99,22 @@ _SESSION_RESET_SQL: Final[str] = (
92
99
  _CLOUD_SQL_INSTANCE_PARTS: Final[int] = 3
93
100
  _ALLOYDB_URI_PARTS: Final[int] = 8
94
101
  _AUTH_TOKEN_DEFAULT_INACTIVE_LIFETIME: Final[float] = 1800.0
102
+ _CONNECTOR_EXCLUDED_CONNECT_KWARGS: Final[frozenset[str]] = frozenset({
103
+ "database",
104
+ "db",
105
+ "direct_tls",
106
+ "driver",
107
+ "dsn",
108
+ "enable_iam_auth",
109
+ "host",
110
+ "instance_connection_string",
111
+ "instance_uri",
112
+ "ip_type",
113
+ "password",
114
+ "port",
115
+ "ssl",
116
+ "user",
117
+ })
95
118
  _ASYNCPG_ENDPOINT_IDENTITY_KEYS: Final[tuple[str, ...]] = (
96
119
  "dsn",
97
120
  "conninfo",
@@ -227,6 +250,12 @@ class AsyncpgDriverFeatures(TypedDict):
227
250
  """Use IAM database authentication with the AlloyDB Python Connector."""
228
251
  alloydb_ip_type: NotRequired[str]
229
252
  """AlloyDB network path (``PUBLIC``, ``PRIVATE``, or ``PSC``; defaults to ``PRIVATE``)."""
253
+ connector_retry_count: NotRequired[int]
254
+ """Maximum retry attempts on transient Cloud SQL or AlloyDB connector errors (defaults to ``3``; ``0`` disables retries)."""
255
+ connector_retry_delay: NotRequired[float]
256
+ """Initial backoff delay in seconds before jittered exponential connector retries (defaults to ``0.5``)."""
257
+ connector_retry_max_delay: NotRequired[float]
258
+ """Upper bound in seconds on exponential backoff between connector retry attempts (defaults to ``5.0``)."""
230
259
  enable_alloydb_columnar: NotRequired[bool]
231
260
  """Enable ``google_columnar_engine.enable_columnar_scan=on`` at session startup or per transaction."""
232
261
  enable_pgcopy_binary: NotRequired[bool]
@@ -260,24 +289,32 @@ class _AsyncpgCloudSqlConnector:
260
289
  self._password = password
261
290
  self._database = database
262
291
 
263
- async def __call__(self) -> "AsyncpgConnection":
292
+ async def __call__(self, *args: Any, **kwargs: Any) -> "AsyncpgConnection":
293
+ _ = args
264
294
  connector = self._config._get_cloud_sql_connector()
265
295
  if connector is None:
266
296
  msg = "Cloud SQL connector is not initialized"
267
297
  raise ImproperConfigurationError(msg)
268
- conn_kwargs: dict[str, Any] = {
269
- "instance_connection_string": self._config.driver_features["cloud_sql_instance"],
270
- "driver": "asyncpg",
271
- "enable_iam_auth": self._config.driver_features.get("cloud_sql_enable_iam_auth", False),
272
- "ip_type": self._config.driver_features.get("cloud_sql_ip_type", "PRIVATE"),
273
- }
298
+ conn_kwargs: dict[str, Any] = _filter_connector_connect_kwargs(kwargs)
299
+ conn_kwargs["instance_connection_string"] = self._config.driver_features["cloud_sql_instance"]
300
+ conn_kwargs["driver"] = "asyncpg"
301
+ conn_kwargs["enable_iam_auth"] = self._config.driver_features.get("cloud_sql_enable_iam_auth", False)
302
+ conn_kwargs["ip_type"] = self._config.driver_features.get("cloud_sql_ip_type", "PRIVATE")
274
303
  if self._user:
275
304
  conn_kwargs["user"] = self._user
276
305
  if self._password:
277
306
  conn_kwargs["password"] = self._password
278
307
  if self._database:
279
308
  conn_kwargs["db"] = self._database
280
- return cast("AsyncpgConnection", await connector.connect_async(**conn_kwargs))
309
+ max_retries, base_backoff, max_backoff = self._config._connector_retry_settings()
310
+ return await _connect_with_retry(
311
+ connector.connect_async,
312
+ conn_kwargs,
313
+ connector_name="cloud_sql",
314
+ max_retries=max_retries,
315
+ base_backoff_seconds=base_backoff,
316
+ max_backoff_seconds=max_backoff,
317
+ )
281
318
 
282
319
 
283
320
  class _AsyncpgAlloydbConnector:
@@ -289,24 +326,32 @@ class _AsyncpgAlloydbConnector:
289
326
  self._password = password
290
327
  self._database = database
291
328
 
292
- async def __call__(self) -> "AsyncpgConnection":
329
+ async def __call__(self, *args: Any, **kwargs: Any) -> "AsyncpgConnection":
330
+ _ = args
293
331
  connector = self._config._get_alloydb_connector()
294
332
  if connector is None:
295
333
  msg = "AlloyDB connector is not initialized"
296
334
  raise ImproperConfigurationError(msg)
297
- conn_kwargs: dict[str, Any] = {
298
- "instance_uri": self._config.driver_features["alloydb_instance_uri"],
299
- "driver": "asyncpg",
300
- "enable_iam_auth": self._config.driver_features.get("enable_alloydb_iam_auth", False),
301
- "ip_type": self._config.driver_features.get("alloydb_ip_type", "PRIVATE"),
302
- }
335
+ conn_kwargs: dict[str, Any] = _filter_connector_connect_kwargs(kwargs)
336
+ conn_kwargs["instance_uri"] = self._config.driver_features["alloydb_instance_uri"]
337
+ conn_kwargs["driver"] = "asyncpg"
338
+ conn_kwargs["enable_iam_auth"] = self._config.driver_features.get("enable_alloydb_iam_auth", False)
339
+ conn_kwargs["ip_type"] = self._config.driver_features.get("alloydb_ip_type", "PRIVATE")
303
340
  if self._user:
304
341
  conn_kwargs["user"] = self._user
305
342
  if self._password:
306
343
  conn_kwargs["password"] = self._password
307
344
  if self._database:
308
345
  conn_kwargs["db"] = self._database
309
- return cast("AsyncpgConnection", await connector.connect(**conn_kwargs))
346
+ max_retries, base_backoff, max_backoff = self._config._connector_retry_settings()
347
+ return await _connect_with_retry(
348
+ connector.connect,
349
+ conn_kwargs,
350
+ connector_name="alloydb",
351
+ max_retries=max_retries,
352
+ base_backoff_seconds=base_backoff,
353
+ max_backoff_seconds=max_backoff,
354
+ )
310
355
 
311
356
 
312
357
  class _AsyncpgSessionFactory(AsyncPoolSessionFactory):
@@ -472,7 +517,12 @@ class AsyncpgConfig(AsyncDatabaseConfig[AsyncpgConnection, "Pool[Record]", Async
472
517
  self._setup_alloydb_connector(config)
473
518
 
474
519
  connect = config.pop("connect", None)
475
- connection = await connect() if connect is not None else await asyncpg_connect(**config)
520
+ if connect is None:
521
+ connection = await asyncpg_connect(**config)
522
+ elif isinstance(connect, (_AsyncpgCloudSqlConnector, _AsyncpgAlloydbConnector)):
523
+ connection = await connect(**config)
524
+ else:
525
+ connection = await connect()
476
526
  user_init = self.connection_config.get("init")
477
527
  try:
478
528
  await self._init_connection(connection)
@@ -668,6 +718,12 @@ class AsyncpgConfig(AsyncDatabaseConfig[AsyncpgConnection, "Pool[Record]", Async
668
718
  """Return the configured AlloyDB connector instance."""
669
719
  return self._alloydb_connector
670
720
 
721
+ def _connector_retry_settings(self) -> "tuple[int, float, float]":
722
+ max_retries = int(self.driver_features.get("connector_retry_count", DEFAULT_CONNECTOR_RETRY_COUNT))
723
+ base_backoff = float(self.driver_features.get("connector_retry_delay", DEFAULT_CONNECTOR_RETRY_DELAY))
724
+ max_backoff = float(self.driver_features.get("connector_retry_max_delay", DEFAULT_CONNECTOR_RETRY_MAX_DELAY))
725
+ return max_retries, base_backoff, max_backoff
726
+
671
727
  def _validate_connector_config(self) -> None:
672
728
  """Validate Google Cloud connector configuration.
673
729
 
@@ -675,6 +731,30 @@ class AsyncpgConfig(AsyncDatabaseConfig[AsyncpgConnection, "Pool[Record]", Async
675
731
  ImproperConfigurationError: If configuration is invalid.
676
732
  MissingDependencyError: If required connector packages are not installed.
677
733
  """
734
+ raw_max_retries = self.driver_features.get("connector_retry_count", DEFAULT_CONNECTOR_RETRY_COUNT)
735
+ if isinstance(raw_max_retries, bool) or not isinstance(raw_max_retries, int) or raw_max_retries < 0:
736
+ msg = "connector_retry_count must be a non-negative integer"
737
+ raise ImproperConfigurationError(msg)
738
+
739
+ backoff_values: list[float] = []
740
+ for key, default in (
741
+ ("connector_retry_delay", DEFAULT_CONNECTOR_RETRY_DELAY),
742
+ ("connector_retry_max_delay", DEFAULT_CONNECTOR_RETRY_MAX_DELAY),
743
+ ):
744
+ raw_value = self.driver_features.get(key, default)
745
+ if isinstance(raw_value, bool) or not isinstance(raw_value, (int, float)):
746
+ msg = f"{key} must be a finite non-negative number"
747
+ raise ImproperConfigurationError(msg)
748
+ value = float(raw_value)
749
+ if not math.isfinite(value) or value < 0.0:
750
+ msg = f"{key} must be a finite non-negative number"
751
+ raise ImproperConfigurationError(msg)
752
+ backoff_values.append(value)
753
+
754
+ if backoff_values[1] < backoff_values[0]:
755
+ msg = "connector_retry_max_delay must be greater than or equal to connector_retry_delay"
756
+ raise ImproperConfigurationError(msg)
757
+
678
758
  enable_cloud_sql = self.driver_features.get("enable_cloud_sql", False)
679
759
  enable_alloydb = self.driver_features.get("enable_alloydb", False)
680
760
 
@@ -901,3 +981,46 @@ class AsyncpgConfig(AsyncDatabaseConfig[AsyncpgConnection, "Pool[Record]", Async
901
981
  if self._alloydb_connector is not None:
902
982
  await self._alloydb_connector.close()
903
983
  self._alloydb_connector = None
984
+
985
+
986
+ def _filter_connector_connect_kwargs(kwargs: "Mapping[str, Any]") -> "dict[str, Any]":
987
+ """Return non-``None`` asyncpg connect kwargs not managed by the cloud connector."""
988
+ return {
989
+ key: value
990
+ for key, value in kwargs.items()
991
+ if value is not None and key not in _CONNECTOR_EXCLUDED_CONNECT_KWARGS
992
+ }
993
+
994
+
995
+ async def _connect_with_retry(
996
+ connect_fn: "Callable[..., Awaitable[Any]]",
997
+ conn_kwargs: "dict[str, Any]",
998
+ *,
999
+ connector_name: str,
1000
+ max_retries: int,
1001
+ base_backoff_seconds: float,
1002
+ max_backoff_seconds: float,
1003
+ ) -> "AsyncpgConnection":
1004
+ """Invoke a connector coroutine with bounded backoff on transient failures."""
1005
+ attempt = 0
1006
+ while True:
1007
+ try:
1008
+ return cast("AsyncpgConnection", await connect_fn(**conn_kwargs))
1009
+ except Exception as exc:
1010
+ if attempt >= max_retries or not is_transient_connector_error(exc):
1011
+ raise
1012
+ retry_delay = calculate_connector_backoff_seconds(attempt, base_backoff_seconds, max_backoff_seconds)
1013
+ log_with_context(
1014
+ logger,
1015
+ logging.WARNING,
1016
+ "connector.retry",
1017
+ adapter="asyncpg",
1018
+ connector=connector_name,
1019
+ attempt=attempt + 1,
1020
+ max_retries=max_retries,
1021
+ delay_seconds=round(retry_delay, 3),
1022
+ error_type=type(exc).__name__,
1023
+ )
1024
+ if retry_delay > 0.0:
1025
+ await asyncio.sleep(retry_delay)
1026
+ attempt += 1
@@ -4,13 +4,14 @@ import asyncio
4
4
  import contextlib
5
5
  import datetime as dt
6
6
  import re
7
+ import secrets
7
8
  import sys
8
9
  from collections.abc import Sized
9
- from typing import TYPE_CHECKING, Any, NamedTuple
10
+ from typing import TYPE_CHECKING, Any, Final, NamedTuple
10
11
 
11
12
  from mypy_extensions import mypyc_attr
12
13
 
13
- from sqlspec.adapters.asyncpg._typing import AsyncpgPostgresError
14
+ from sqlspec.adapters.asyncpg._typing import AsyncpgInterfaceError, AsyncpgPostgresError
14
15
  from sqlspec.adapters.asyncpg._typing import asyncpg_module as asyncpg
15
16
  from sqlspec.core.config_runtime import resolve_runtime_statement_config
16
17
  from sqlspec.core.parameters._registry import build_statement_config_from_profile
@@ -23,6 +24,7 @@ from sqlspec.exceptions import (
23
24
  ForeignKeyViolationError,
24
25
  ImproperConfigurationError,
25
26
  IntegrityError,
27
+ MissingDependencyError,
26
28
  NotNullViolationError,
27
29
  OperationalError,
28
30
  OperationCancelledError,
@@ -53,6 +55,9 @@ if TYPE_CHECKING:
53
55
  from sqlspec.core.statement import SQL, StatementConfig
54
56
 
55
57
  __all__ = (
58
+ "DEFAULT_CONNECTOR_RETRY_COUNT",
59
+ "DEFAULT_CONNECTOR_RETRY_DELAY",
60
+ "DEFAULT_CONNECTOR_RETRY_MAX_DELAY",
56
61
  "AsyncpgStreamSource",
57
62
  "NormalizedStackOperation",
58
63
  "apply_driver_features",
@@ -60,12 +65,14 @@ __all__ = (
60
65
  "build_postgres_storage_params_sql",
61
66
  "build_profile",
62
67
  "build_statement_config",
68
+ "calculate_connector_backoff_seconds",
63
69
  "collect_rows",
64
70
  "configure_parameter_serializers",
65
71
  "create_mapped_exception",
66
72
  "default_statement_config",
67
73
  "driver_profile",
68
74
  "execute_cache_hit",
75
+ "is_transient_connector_error",
69
76
  "parse_status",
70
77
  "register_json_codecs",
71
78
  "register_pgvector_support",
@@ -79,6 +86,71 @@ EXPECTED_REGEX_GROUPS = 3
79
86
  logger = get_logger("sqlspec.adapters.asyncpg.core")
80
87
  _PGVECTOR_MISSING_LOGGED = False
81
88
  _JSONB_BINARY_VERSION = b"\x01"
89
+ _SYSTEM_RANDOM: Final[secrets.SystemRandom] = secrets.SystemRandom()
90
+ _MAX_CONNECTOR_ERROR_DEPTH: Final[int] = 8
91
+ DEFAULT_CONNECTOR_RETRY_COUNT: Final[int] = 3
92
+ DEFAULT_CONNECTOR_RETRY_DELAY: Final[float] = 0.5
93
+ DEFAULT_CONNECTOR_RETRY_MAX_DELAY: Final[float] = 5.0
94
+ _TRANSIENT_HTTP_STATUS_CODES: Final[frozenset[int]] = frozenset({429, 500, 502, 503, 504})
95
+ _TRANSIENT_GRPC_STATUS_NAMES: Final[frozenset[str]] = frozenset({
96
+ "ABORTED",
97
+ "DEADLINE_EXCEEDED",
98
+ "RESOURCE_EXHAUSTED",
99
+ "UNAVAILABLE",
100
+ })
101
+ _PERMANENT_GRPC_STATUS_NAMES: Final[frozenset[str]] = frozenset({
102
+ "ALREADY_EXISTS",
103
+ "CANCELLED",
104
+ "DATA_LOSS",
105
+ "FAILED_PRECONDITION",
106
+ "INVALID_ARGUMENT",
107
+ "NOT_FOUND",
108
+ "OUT_OF_RANGE",
109
+ "PERMISSION_DENIED",
110
+ "UNAUTHENTICATED",
111
+ "UNIMPLEMENTED",
112
+ })
113
+ _PERMANENT_API_CORE_ERROR_NAMES: Final[tuple[str, ...]] = (
114
+ "AlreadyExists",
115
+ "BadRequest",
116
+ "Cancelled",
117
+ "Conflict",
118
+ "DataLoss",
119
+ "DuplicateCredentialArgs",
120
+ "FailedPrecondition",
121
+ "Forbidden",
122
+ "InvalidArgument",
123
+ "MethodNotAllowed",
124
+ "MethodNotImplemented",
125
+ "NotFound",
126
+ "OutOfRange",
127
+ "PermissionDenied",
128
+ "PreconditionFailed",
129
+ "Unauthenticated",
130
+ "Unauthorized",
131
+ )
132
+ _TRANSIENT_API_CORE_ERROR_NAMES: Final[tuple[str, ...]] = (
133
+ "Aborted",
134
+ "BadGateway",
135
+ "DeadlineExceeded",
136
+ "GatewayTimeout",
137
+ "InternalServerError",
138
+ "ResourceExhausted",
139
+ "ServiceUnavailable",
140
+ "TooManyRequests",
141
+ )
142
+ _PERMANENT_CLOUD_SQL_ERROR_NAMES: Final[tuple[str, ...]] = (
143
+ "AutoIAMAuthNotSupported",
144
+ "CacheClosedError",
145
+ "ClosedConnectorError",
146
+ "CloudSQLIPTypeError",
147
+ "ConnectorLoopError",
148
+ "DnsLoopError",
149
+ "IncompatibleDriverError",
150
+ "PlatformNotSupportedError",
151
+ "TLSVersionError",
152
+ )
153
+ _PERMANENT_ALLOYDB_ERROR_NAMES: Final[tuple[str, ...]] = ("ClosedConnectorError", "IPTypeNotFoundError")
82
154
 
83
155
 
84
156
  class NormalizedStackOperation(NamedTuple):
@@ -276,6 +348,9 @@ def apply_driver_features(
276
348
  processed_features.setdefault("enable_pg_textsearch", True)
277
349
  processed_features.setdefault("enable_cloud_sql", False)
278
350
  processed_features.setdefault("enable_alloydb", False)
351
+ processed_features.setdefault("connector_retry_count", DEFAULT_CONNECTOR_RETRY_COUNT)
352
+ processed_features.setdefault("connector_retry_delay", DEFAULT_CONNECTOR_RETRY_DELAY)
353
+ processed_features.setdefault("connector_retry_max_delay", DEFAULT_CONNECTOR_RETRY_MAX_DELAY)
279
354
  processed_features.setdefault("enable_events", True)
280
355
  processed_features.setdefault("events_backend", "notify")
281
356
  raw_pooler_mode = processed_features.get("pooler_mode")
@@ -327,6 +402,65 @@ def parse_status(status: Any) -> int:
327
402
  return 0
328
403
 
329
404
 
405
+ def is_transient_connector_error(error: BaseException) -> bool:
406
+ """Return whether a Cloud SQL or AlloyDB connector error is transient and retryable.
407
+
408
+ Inspects loaded optional connector/RPC modules via ``sys.modules`` to avoid eager
409
+ imports when cloud connectors are unused. Walks bounded causal links
410
+ (``cause``, ``raw_error``, ``__cause__``, and unsuppressed ``__context__``) and
411
+ fails fast on permanent configuration, authentication, permission, not-found,
412
+ closed-connector, cancellation, and PostgreSQL protocol errors.
413
+
414
+ Args:
415
+ error: Exception raised while establishing a connector-backed connection.
416
+
417
+ Returns:
418
+ ``True`` if the failure is transient and safe to retry, otherwise ``False``.
419
+ """
420
+ stack: list[BaseException] = [error]
421
+ seen: set[int] = set()
422
+ depth = 0
423
+ default_verdict = False
424
+ while stack and depth < _MAX_CONNECTOR_ERROR_DEPTH:
425
+ current = stack.pop()
426
+ obj_id = id(current)
427
+ if obj_id in seen:
428
+ continue
429
+ seen.add(obj_id)
430
+ depth += 1
431
+
432
+ verdict = _classify_connector_error(current)
433
+ if verdict is not None:
434
+ return verdict
435
+ if _is_retryable_connector_wrapper(current):
436
+ default_verdict = True
437
+
438
+ next_candidates = _next_connector_error_causes(current)
439
+ stack.extend(candidate for candidate in reversed(next_candidates) if id(candidate) not in seen)
440
+ return default_verdict
441
+
442
+
443
+ def calculate_connector_backoff_seconds(attempt: int, base_delay_seconds: float, max_delay_seconds: float) -> float:
444
+ """Calculate jittered exponential backoff delay in seconds for connector retries.
445
+
446
+ Caps the exponential term before applying half-jitter so retries spread across
447
+ the upper half of ``[0, capped]`` when competing callers start concurrently.
448
+
449
+ Args:
450
+ attempt: Zero-based retry attempt index (``0`` before the first retry).
451
+ base_delay_seconds: Initial delay in seconds before capping/jitter.
452
+ max_delay_seconds: Upper bound in seconds for any single retry delay.
453
+
454
+ Returns:
455
+ Non-negative delay in seconds.
456
+ """
457
+ if base_delay_seconds <= 0.0 or max_delay_seconds <= 0.0:
458
+ return 0.0
459
+ exponent = min(max(attempt, 0), 30)
460
+ capped = min(base_delay_seconds * (2**exponent), max_delay_seconds)
461
+ return _SYSTEM_RANDOM.uniform(capped / 2.0, capped)
462
+
463
+
330
464
  def resolve_many_rowcount(parameter_sets: Any, *, fallback_count: "int | None" = None) -> int:
331
465
  """Resolve execute_many rowcount using the parameter payload size."""
332
466
  if fallback_count is not None:
@@ -792,6 +926,147 @@ def _create_postgres_error(
792
926
  return exc
793
927
 
794
928
 
929
+ def _instance_of_module_attrs(error: BaseException, module: Any, names: "tuple[str, ...]") -> bool:
930
+ for name in names:
931
+ candidate = getattr(module, name, None)
932
+ if isinstance(candidate, type) and isinstance(error, candidate):
933
+ return True
934
+ return False
935
+
936
+
937
+ def _extract_grpc_status_name(error: BaseException) -> "str | None":
938
+ raw_status: Any = getattr(error, "grpc_status_code", None)
939
+ if raw_status is None:
940
+ code_attr = getattr(error, "code", None)
941
+ if callable(code_attr):
942
+ try:
943
+ raw_status = code_attr()
944
+ except TypeError:
945
+ raw_status = None
946
+ if raw_status is None:
947
+ return None
948
+ status_name = getattr(raw_status, "name", None)
949
+ if isinstance(status_name, str) and status_name:
950
+ return status_name.strip().upper()
951
+ if isinstance(raw_status, str) and raw_status:
952
+ normalized = raw_status.strip().upper()
953
+ if "." in normalized:
954
+ normalized = normalized.rsplit(".", maxsplit=1)[-1]
955
+ return normalized
956
+ return None
957
+
958
+
959
+ def _classify_connector_error(error: BaseException) -> "bool | None":
960
+ if not isinstance(error, Exception):
961
+ return False
962
+ if isinstance(
963
+ error,
964
+ (
965
+ ImproperConfigurationError,
966
+ MissingDependencyError,
967
+ ValueError,
968
+ TypeError,
969
+ KeyError,
970
+ AsyncpgPostgresError,
971
+ AsyncpgInterfaceError,
972
+ ),
973
+ ):
974
+ return False
975
+ if isinstance(error, (TimeoutError, ConnectionError)):
976
+ return True
977
+
978
+ cloud_sql_exc_mod = sys.modules.get("google.cloud.sql.connector.exceptions")
979
+ if cloud_sql_exc_mod is not None:
980
+ if _instance_of_module_attrs(error, cloud_sql_exc_mod, _PERMANENT_CLOUD_SQL_ERROR_NAMES):
981
+ return False
982
+ if _instance_of_module_attrs(error, cloud_sql_exc_mod, ("ResourceExhaustedError",)):
983
+ return None
984
+
985
+ alloydb_exc_mod = sys.modules.get("google.cloud.alloydbconnector.exceptions")
986
+ if alloydb_exc_mod is not None and _instance_of_module_attrs(
987
+ error, alloydb_exc_mod, _PERMANENT_ALLOYDB_ERROR_NAMES
988
+ ):
989
+ return False
990
+
991
+ api_core_exc_mod = sys.modules.get("google.api_core.exceptions")
992
+ if api_core_exc_mod is not None:
993
+ if _instance_of_module_attrs(error, api_core_exc_mod, ("RetryError",)):
994
+ return None
995
+ if _instance_of_module_attrs(error, api_core_exc_mod, _TRANSIENT_API_CORE_ERROR_NAMES):
996
+ return True
997
+ if _instance_of_module_attrs(error, api_core_exc_mod, _PERMANENT_API_CORE_ERROR_NAMES):
998
+ return False
999
+
1000
+ auth_exc_mod = sys.modules.get("google.auth.exceptions")
1001
+ if auth_exc_mod is not None:
1002
+ if _instance_of_module_attrs(error, auth_exc_mod, ("DefaultCredentialsError", "OAuthError")):
1003
+ return False
1004
+ if _instance_of_module_attrs(error, auth_exc_mod, ("TransportError",)):
1005
+ return True
1006
+ if (
1007
+ _instance_of_module_attrs(error, auth_exc_mod, ("RefreshError",))
1008
+ and getattr(error, "retryable", False) is True
1009
+ ):
1010
+ return True
1011
+
1012
+ aiohttp_mod = sys.modules.get("aiohttp")
1013
+ if aiohttp_mod is not None:
1014
+ if _instance_of_module_attrs(
1015
+ error,
1016
+ aiohttp_mod,
1017
+ (
1018
+ "ClientSSLError",
1019
+ "ClientConnectorCertificateError",
1020
+ "ClientConnectorSSLError",
1021
+ "ServerFingerprintMismatch",
1022
+ ),
1023
+ ):
1024
+ return False
1025
+ if _instance_of_module_attrs(error, aiohttp_mod, ("ClientResponseError",)):
1026
+ status = getattr(error, "status", None)
1027
+ return isinstance(status, int) and not isinstance(status, bool) and status in _TRANSIENT_HTTP_STATUS_CODES
1028
+ if _instance_of_module_attrs(
1029
+ error,
1030
+ aiohttp_mod,
1031
+ ("ServerTimeoutError", "ClientConnectionError", "ServerDisconnectedError", "ClientConnectorError"),
1032
+ ):
1033
+ return True
1034
+
1035
+ grpc_status_name = _extract_grpc_status_name(error)
1036
+ if grpc_status_name is not None:
1037
+ if grpc_status_name in _PERMANENT_GRPC_STATUS_NAMES:
1038
+ return False
1039
+ if grpc_status_name in _TRANSIENT_GRPC_STATUS_NAMES:
1040
+ return True
1041
+
1042
+ return None
1043
+
1044
+
1045
+ def _is_retryable_connector_wrapper(error: BaseException) -> bool:
1046
+ cloud_sql_exc_mod = sys.modules.get("google.cloud.sql.connector.exceptions")
1047
+ if cloud_sql_exc_mod is not None and _instance_of_module_attrs(
1048
+ error, cloud_sql_exc_mod, ("ResourceExhaustedError",)
1049
+ ):
1050
+ return True
1051
+ api_core_exc_mod = sys.modules.get("google.api_core.exceptions")
1052
+ return api_core_exc_mod is not None and _instance_of_module_attrs(error, api_core_exc_mod, ("RetryError",))
1053
+
1054
+
1055
+ def _next_connector_error_causes(error: BaseException) -> "list[BaseException]":
1056
+ causes: list[BaseException] = []
1057
+ retry_cause = getattr(error, "cause", None)
1058
+ if isinstance(retry_cause, BaseException):
1059
+ causes.append(retry_cause)
1060
+ raw_error = getattr(error, "raw_error", None)
1061
+ if isinstance(raw_error, BaseException):
1062
+ causes.append(raw_error)
1063
+ if error.__cause__ is not None:
1064
+ causes.append(error.__cause__)
1065
+ if error.__context__ is not None and not error.__suppress_context__:
1066
+ causes.append(error.__context__)
1067
+ return causes
1068
+
1069
+
795
1070
  driver_profile = build_profile()
796
1071
 
797
1072
  default_statement_config = build_statement_config()