Skip to content

Connections (BYO / Factories)

Connection hook points: WorkerConnections per-role overrides and the PoolFactory / ConnFactory / RedisFactory type aliases. See the Managed Identities & BYO Connections guide for the ownership model and deployment patterns.

connections

Connection hook points, bring-your-own resources or factories.

TaskQ constructs its asyncpg pools, dedicated connections, and Redis client internally from DSN strings by default. This module lets you replace any of those with either:

  1. a pre-constructed, caller-owned resource (TaskQ uses it but never closes it, you close it in your own lifespan), or
  2. a zero-arg async factory that TaskQ invokes at the right point in its lifecycle and closes the result of on teardown (TaskQ-owned).

Fields left None fall back to the existing DSN construction, so the hook points are purely additive.

See the managed-identities deployment guide (docs/guides/managed-identities.md); :mod:taskq.auth provides vendor-neutral credential providers and factory builders, with provider-specific implementations in :mod:taskq.aad, :mod:taskq.aws, and :mod:taskq.vault.

Ownership rule

  • Pre-constructed objects are caller-owned. TaskQ never closes them, close them in your own finally / lifespan.
  • Factory-produced objects are TaskQ-owned. TaskQ closes them on teardown via its :class:~contextlib.AsyncExitStack.

Passing both a concrete resource and a factory for the same role is a configuration error (caught in :meth:WorkerConnections.__post_init__).

__all__ module-attribute

__all__ = [
    "DEFAULT_MAX_CACHEABLE_STATEMENT_SIZE",
    "DEFAULT_MAX_CACHED_STATEMENT_LIFETIME",
    "DEFAULT_PG_CONNECT_TIMEOUT",
    "DEFAULT_POOL_MAX_QUERIES",
    "DEFAULT_STATEMENT_CACHE_SIZE",
    "POOL_MIN_SIZE_AUTO",
    "ConnFactory",
    "DirectTlsKwargs",
    "PoolFactory",
    "PoolLifecycleKwargs",
    "PoolSizeKwargs",
    "RedisFactory",
    "StatementCacheKwargs",
    "WorkerConnections",
    "bounded_lock_budget_ms",
    "clamp_pool_min_size",
    "connection_init_hook",
    "direct_tls_kwargs",
    "dispatch_connection_class",
    "dispatcher_command_timeout_secs",
    "force_custom_plan",
    "keepalive_conn",
    "lock_budget_command_timeout_secs",
    "lock_budget_pairs",
    "pool_connection_init",
    "pool_lifecycle_kwargs",
    "pool_size_kwargs",
    "resolve_pool_min_size",
    "role_reaches_pooler",
    "same_pg_endpoint",
    "statement_cache_kwargs",
    "with_connection_init",
]

DEFAULT_STATEMENT_CACHE_SIZE module-attribute

DEFAULT_STATEMENT_CACHE_SIZE = 512

DEFAULT_MAX_CACHED_STATEMENT_LIFETIME module-attribute

DEFAULT_MAX_CACHED_STATEMENT_LIFETIME = 3600

DEFAULT_MAX_CACHEABLE_STATEMENT_SIZE module-attribute

DEFAULT_MAX_CACHEABLE_STATEMENT_SIZE: Final[int] = 131072

DEFAULT_POOL_MAX_QUERIES module-attribute

DEFAULT_POOL_MAX_QUERIES: Final[int] = 1000000

DEFAULT_PG_CONNECT_TIMEOUT module-attribute

DEFAULT_PG_CONNECT_TIMEOUT: Final[float] = 10.0

POOL_MIN_SIZE_AUTO module-attribute

POOL_MIN_SIZE_AUTO: Final[str] = 'auto'

ADMISSION_LOCK_BUDGET_FIELDS module-attribute

ADMISSION_LOCK_BUDGET_FIELDS: Final[tuple[str, ...]] = (
    "token_bucket_lock_timeout_ms",
    "sliding_window_lock_timeout_ms",
)

PoolFactory

PoolFactory = Callable[[], Awaitable[Pool]]

ConnFactory

ConnFactory = Callable[[], Awaitable[Connection]]

RedisFactory

RedisFactory = Callable[[], Awaitable[Redis]]

StatementCacheKwargs

Bases: TypedDict

The create_pool kwargs :func:statement_cache_kwargs produces.

statement_cache_size instance-attribute

statement_cache_size: int

max_cached_statement_lifetime instance-attribute

max_cached_statement_lifetime: int

max_cacheable_statement_size instance-attribute

max_cacheable_statement_size: int

PoolSizeKwargs

Bases: TypedDict

The create_pool kwargs :func:pool_size_kwargs produces.

init_size instance-attribute

init_size: int

min_size instance-attribute

min_size: int

max_size instance-attribute

max_size: int

PoolLifecycleKwargs

Bases: TypedDict

The create_pool lifecycle kwargs :func:pool_lifecycle_kwargs produces.

max_inactive_connection_lifetime instance-attribute

max_inactive_connection_lifetime: float

max_queries instance-attribute

max_queries: int

timeout instance-attribute

timeout: float

DirectTlsKwargs

Bases: TypedDict

The direct_tls kwarg :func:direct_tls_kwargs produces.

direct_tls instance-attribute

direct_tls: bool

WorkerConnections dataclass

WorkerConnections(
    dispatcher_pool: Pool | None = None,
    dispatcher_pool_factory: PoolFactory | None = None,
    heartbeat_pool: Pool | None = None,
    heartbeat_pool_factory: PoolFactory | None = None,
    worker_pool: Pool | None = None,
    worker_pool_factory: PoolFactory | None = None,
    notify_conn: Connection | None = None,
    notify_conn_factory: ConnFactory | None = None,
    leader_conn: Connection | None = None,
    leader_conn_factory: ConnFactory | None = None,
    redis_client: Redis | None = None,
    redis_client_factory: RedisFactory | None = None,
)

Per-role connection overrides for the worker.

Each role has a <role> (pre-constructed, caller-owned) and a <role>_factory (zero-arg async factory, TaskQ-owned) slot. Leave both None for DSN-based construction (the default).

Example, AAD-managed-identity worker::

from azure.identity.aio import DefaultAzureCredential
from taskq.aad import EntraIdProvider
from taskq.auth import make_pg_pool_factory
from taskq.connections import WorkerConnections

cred = DefaultAzureCredential()
provider = EntraIdProvider(cred)

connections = WorkerConnections(
    dispatcher_pool_factory=make_pg_pool_factory(
        settings.pg_dsn_direct, provider, max_size=settings.dispatcher_pool_size,
    ),
    heartbeat_pool_factory=make_pg_pool_factory(
        settings.pg_dsn_direct, provider,
        max_size=settings.heartbeat_pool_size,
        command_timeout=settings.heartbeat_command_timeout,
    ),
    worker_pool_factory=make_pg_pool_factory(
        settings.pg_dsn_pooled, provider, max_size=settings.worker_pool_size,
    ),
)

Example, share an app-wide pool (caller-owned)::

connections = WorkerConnections(worker_pool=app_state.pg_pool)

dispatcher_pool class-attribute instance-attribute

dispatcher_pool: Pool | None = None

Dispatcher pool (pg_dsn_direct role). Caller-owned if set.

dispatcher_pool_factory class-attribute instance-attribute

dispatcher_pool_factory: PoolFactory | None = None

Factory for the dispatcher pool. TaskQ-owned.

heartbeat_pool class-attribute instance-attribute

heartbeat_pool: Pool | None = None

Heartbeat pool (pg_dsn_direct, heartbeat_command_timeout). Caller-owned.

heartbeat_pool_factory class-attribute instance-attribute

heartbeat_pool_factory: PoolFactory | None = None

Factory for the heartbeat pool. TaskQ-owned. command_timeout is your responsibility when overriding, set it on create_pool.

worker_pool class-attribute instance-attribute

worker_pool: Pool | None = None

Worker pool (pg_dsn_pooled role). Caller-owned.

worker_pool_factory class-attribute instance-attribute

worker_pool_factory: PoolFactory | None = None

Factory for the worker pool. TaskQ-owned.

notify_conn class-attribute instance-attribute

notify_conn: Connection | None = None

Dedicated LISTEN connection. Caller-owned. TaskQ still issues LISTEN.

notify_conn_factory class-attribute instance-attribute

notify_conn_factory: ConnFactory | None = None

Factory for the LISTEN connection. TaskQ-owned.

leader_conn class-attribute instance-attribute

leader_conn: Connection | None = None

Dedicated advisory-lock connection. Caller-owned.

leader_conn_factory class-attribute instance-attribute

leader_conn_factory: ConnFactory | None = None

Factory for the advisory-lock connection. TaskQ-owned.

redis_client class-attribute instance-attribute

redis_client: Redis | None = None

Redis client for progress fanout / rate limiting. Caller-owned.

redis_client_factory class-attribute instance-attribute

redis_client_factory: RedisFactory | None = None

Factory for the Redis client. TaskQ-owned.

The client a factory returns replaces the one TaskQ builds from TASKQ_REDIS_URL — including its resilience defaults. TaskQ-built clients set health_check_interval=30, socket_keepalive=True, a 5s socket_timeout (pinned to redis-py 8.x's asyncio default — the bound the fail-closed wall stands on), and a 1-attempt exponential-backoff Retry (0.02s base, 0.1s cap — see taskq._redis_client's RETRY_RETRIES for why one) with retry_on_error=[ConnectionError, TimeoutError] (see taskq._redis_client). A factory-built client must set these kwargs itself — without them an idle-closed broker connection surfaces as a raw ConnectionError in the progress-stream pubsub and as the limiter's fail-closed warning noise (see docs/guides/managed-identities.md).

__post_init__

__post_init__() -> None

Reject concrete + factory for the same role (configuration error).

Source code in src/taskq/connections.py
def __post_init__(self) -> None:
    """Reject concrete + factory for the same role (configuration error)."""
    for concrete, factory in (
        ("dispatcher_pool", "dispatcher_pool_factory"),
        ("heartbeat_pool", "heartbeat_pool_factory"),
        ("worker_pool", "worker_pool_factory"),
        ("notify_conn", "notify_conn_factory"),
        ("leader_conn", "leader_conn_factory"),
        ("redis_client", "redis_client_factory"),
    ):
        if getattr(self, concrete) is not None and getattr(self, factory) is not None:
            raise ValueError(
                f"WorkerConnections: provide either {concrete!r} or "
                f"{factory!r}, not both (role would be ambiguous)."
            )

has_any

has_any() -> bool

True if any override (concrete or factory) is set.

Source code in src/taskq/connections.py
def has_any(self) -> bool:
    """True if any override (concrete or factory) is set."""
    return any(
        getattr(self, name) is not None
        for name in (
            "dispatcher_pool",
            "dispatcher_pool_factory",
            "heartbeat_pool",
            "heartbeat_pool_factory",
            "worker_pool",
            "worker_pool_factory",
            "notify_conn",
            "notify_conn_factory",
            "leader_conn",
            "leader_conn_factory",
            "redis_client",
            "redis_client_factory",
        )
    )

same_pg_endpoint

same_pg_endpoint(first: object, second: object) -> bool

Whether two DSNs dial the same server endpoint.

This is the topology question behind TASKQ_PG_IS_POOLED with a split DSN pair: a pair whose endpoints are equal is not a split at all (an operator templating the same PgBouncer URL into both role variables, say), so treating it as one would hand the direct roles a prepared-statement cache and a session GUC across a pooler that remaps server connections.

Ambiguity fails closed toward the pooler: a DSN that does not parse as an endpoint is reported as the same, because the cost of guessing wrong in that direction is a cold statement cache, while the other direction is the pooler-incompatible one. Host comparison is case-insensitive and a missing port means libpq's default 5432, so two spellings of one server compare equal.

Source code in src/taskq/connections.py
def same_pg_endpoint(first: object, second: object) -> bool:
    """Whether two DSNs dial the same server endpoint.

    This is the topology question behind ``TASKQ_PG_IS_POOLED`` with a split
    DSN pair: a pair whose endpoints are equal is not a split at all (an
    operator templating the same PgBouncer URL into both role variables, say),
    so treating it as one would hand the direct roles a prepared-statement
    cache and a session GUC across a pooler that remaps server connections.

    Ambiguity fails closed toward the pooler: a DSN that does not parse as an
    endpoint is reported as the same, because the cost of guessing wrong in
    that direction is a cold statement cache, while the other direction is the
    pooler-incompatible one. Host comparison is case-insensitive and a missing
    port means libpq's default 5432, so two spellings of one server compare
    equal.
    """
    left = _pg_endpoint(first)
    right = _pg_endpoint(second)
    if left is None or right is None:
        return True
    return left == right

role_reaches_pooler

role_reaches_pooler(
    settings: TaskQSettings, *, direct_role: bool
) -> bool

Whether one of TaskQ's pool roles actually terminates at a pooler.

TASKQ_PG_IS_POOLED is a deployment-wide declaration, but a split-DSN topology gives the direct roles their own non-pooler endpoint (TASKQ_PG_DSN_DIRECT: dispatcher, heartbeat, the per-slot pool, the admin/CLI pools), so the declaration must not strip their prepared-statement caches. Where neither role DSN is configured independently the roles share pg_dsn - the DSN the operator declared pooled - and every role reaches the pooler. A pooled-only override leaves the base pg_dsn as the direct endpoint, so it is a split too - unless both name one endpoint, which is what has_separate_direct_dsn decides: the split is an endpoint question, never a "was the field set" one.

direct_role names which family the caller is building: True for a pool dialed from the direct DSN, False for one dialed from the pooled DSN (the worker pool, the client pool).

Source code in src/taskq/connections.py
def role_reaches_pooler(settings: TaskQSettings, *, direct_role: bool) -> bool:
    """Whether one of TaskQ's pool roles actually terminates at a pooler.

    ``TASKQ_PG_IS_POOLED`` is a deployment-wide declaration, but a
    split-DSN topology gives the direct roles their own non-pooler
    endpoint (``TASKQ_PG_DSN_DIRECT``: dispatcher, heartbeat, the
    per-slot pool, the admin/CLI pools), so the declaration must not strip
    their prepared-statement caches. Where neither role DSN is configured
    independently the roles share ``pg_dsn`` - the DSN the operator declared
    pooled - and every role reaches the pooler. A pooled-only override leaves
    the base ``pg_dsn`` as the direct endpoint, so it is a split too - unless
    both name one endpoint, which is what ``has_separate_direct_dsn`` decides:
    the split is an endpoint question, never a "was the field set" one.

    *direct_role* names which family the caller is building: ``True`` for
    a pool dialed from the direct DSN, ``False`` for one dialed from the
    pooled DSN (the worker pool, the client pool).
    """
    if not getattr(settings, "pg_is_pooled", False):
        return False
    if not direct_role:
        return True
    # A TaskQSettings-only client has no direct endpoint concept at all and
    # passes direct_role=False; only WorkerSettings records the split.
    return not getattr(settings, "has_separate_direct_dsn", False)

statement_cache_kwargs

statement_cache_kwargs(
    settings: TaskQSettings | None = None,
    *,
    direct_role: bool = False,
    dispatch_role: bool = False,
    pooler: bool | None = None,
) -> StatementCacheKwargs

The create_pool kwargs carrying TaskQ's statement-cache tuning.

Bridges :class:~taskq.settings.TaskQSettings to asyncpg.create_pool: pass a loaded settings instance to read the operator-configured values (TASKQ_STATEMENT_CACHE_SIZE / TASKQ_MAX_CACHED_STATEMENT_LIFETIME / TASKQ_MAX_CACHEABLE_STATEMENT_SIZE), or None for the module constants above. The result is the base trio TaskQ pool sites resolve; a role with an open-ended statement family (the actor slot pool) may lower the entry count at its construction site.

direct_role says whether the pool is dialed from the role family's direct DSN (see :func:role_reaches_pooler); it only matters under TASKQ_PG_IS_POOLED. dispatch_role marks the dispatcher itself: when a transaction pooler is allowed to keep prepared statements, its large claim stays above asyncpg's own cacheable cap (and therefore custom-planned) instead of relying on a session GUC across remaps. pooler overrides the topology derivation for builders whose explicit DSN arguments, rather than the loaded settings, determine the endpoint.

When the pool reaches a transaction-mode pooler (TASKQ_PG_IS_POOLED) the size/lifetime pair is 0/0 regardless of the operator's cache tuning: a pooler that remaps server connections between statements can split a prepared statement's Parse from its Bind, and asyncpg's per-connection cache has no way to notice - the only safe cache size is zero. The knob deliberately wins over TASKQ_STATEMENT_CACHE_SIZE: a nonzero cache under a remapping pooler is broken by definition, not a tuning trade-off. The exception is a pooler configured for prepared statements (TASKQ_PG_POOLER_PREPARED_STATEMENTS, PgBouncer >= 1.21 with max_prepared_statements), where the operator has declared that the statements do survive across transactions.

Call sites with a settings instance in scope resolve through this helper and forward the three values as explicit create_pool kwargs (statement_cache_size=kwargs["statement_cache_size"] …): pyright strict rejects a dict[str, int] splat against asyncpg.create_pool's typed keyword-only parameters, and the explicit forwarding keeps the call site type-traced. Sites without a settings instance (the testing fixtures) pass the constants directly. Returns a fresh dict.

Source code in src/taskq/connections.py
def statement_cache_kwargs(
    settings: TaskQSettings | None = None,
    *,
    direct_role: bool = False,
    dispatch_role: bool = False,
    pooler: bool | None = None,
) -> StatementCacheKwargs:
    """The ``create_pool`` kwargs carrying TaskQ's statement-cache tuning.

    Bridges :class:`~taskq.settings.TaskQSettings` to
    ``asyncpg.create_pool``: pass a loaded settings instance to read the
    operator-configured values (``TASKQ_STATEMENT_CACHE_SIZE`` /
    ``TASKQ_MAX_CACHED_STATEMENT_LIFETIME`` /
    ``TASKQ_MAX_CACHEABLE_STATEMENT_SIZE``), or ``None`` for the module
    constants above. The result is the base trio TaskQ pool sites resolve;
    a role with an open-ended statement family (the actor slot pool) may
    lower the entry count at its construction site.

    *direct_role* says whether the pool is dialed from the role family's
    direct DSN (see :func:`role_reaches_pooler`); it only matters under
    ``TASKQ_PG_IS_POOLED``. *dispatch_role* marks the dispatcher itself:
    when a transaction pooler is allowed to keep prepared statements, its
    large claim stays above asyncpg's own cacheable cap (and therefore
    custom-planned) instead of relying on a session GUC across remaps.
    *pooler* overrides the topology derivation for builders whose explicit
    DSN arguments, rather than the loaded settings, determine the endpoint.

    When the pool reaches a transaction-mode pooler
    (``TASKQ_PG_IS_POOLED``) the size/lifetime pair is ``0``/``0``
    regardless of the operator's cache tuning: a pooler that remaps server
    connections between statements can split a prepared statement's Parse
    from its Bind, and asyncpg's per-connection cache has no way to notice
    - the only safe cache size is zero. The knob deliberately wins over
    ``TASKQ_STATEMENT_CACHE_SIZE``: a nonzero cache under a remapping
    pooler is broken by definition, not a tuning trade-off. The exception
    is a pooler configured for prepared statements
    (``TASKQ_PG_POOLER_PREPARED_STATEMENTS``, PgBouncer >= 1.21 with
    ``max_prepared_statements``), where the operator has declared that the
    statements do survive across transactions.

    Call sites with a settings instance in scope resolve through this
    helper and forward the three values as **explicit** ``create_pool``
    kwargs (``statement_cache_size=kwargs["statement_cache_size"]`` …):
    pyright strict rejects a ``dict[str, int]`` splat against
    ``asyncpg.create_pool``'s typed keyword-only parameters, and the
    explicit forwarding keeps the call site type-traced. Sites without a
    settings instance (the testing fixtures) pass the constants directly.
    Returns a fresh dict.
    """
    if settings is None:
        return {
            "statement_cache_size": DEFAULT_STATEMENT_CACHE_SIZE,
            "max_cached_statement_lifetime": DEFAULT_MAX_CACHED_STATEMENT_LIFETIME,
            "max_cacheable_statement_size": DEFAULT_MAX_CACHEABLE_STATEMENT_SIZE,
        }
    reaches_pooler = (
        role_reaches_pooler(settings, direct_role=direct_role) if pooler is None else pooler
    )
    if reaches_pooler and not settings.pg_pooler_prepared_statements:
        return {
            "statement_cache_size": 0,
            "max_cached_statement_lifetime": 0,
            "max_cacheable_statement_size": settings.max_cacheable_statement_size,
        }
    cacheable_size = settings.max_cacheable_statement_size
    if reaches_pooler and dispatch_role:
        cacheable_size = min(cacheable_size, _ASYNCPG_DEFAULT_MAX_CACHEABLE_STATEMENT_SIZE)
    return {
        "statement_cache_size": settings.statement_cache_size,
        "max_cached_statement_lifetime": settings.max_cached_statement_lifetime,
        "max_cacheable_statement_size": cacheable_size,
    }

pool_size_kwargs

pool_size_kwargs(
    init_size: int, max_size: int, *, min_size: int = 0
) -> PoolSizeKwargs

The create_pool sizing kwargs every TaskQ-built pool passes.

init_size is the number of connections the pool opens up front (the warm max_size for the per-slot pool, one for the role pools); max_size is its ceiling. min_size defaults to 0 so max_inactive_connection_lifetime keeps recycling idle connections and every replacement authenticates with a freshly fetched credential; a caller passes :func:resolve_pool_min_size's answer to raise the floor deliberately.

A floor above the ceiling is refused here, naming the setting: asyncpg would refuse the same combination with a bare "min_size is greater than max_size" that names neither the knob nor the pool it came from. A floor above init_size raises the warm-up count to meet it (asyncpg requires init_size >= min_size), which is what "the pool never drops below N" means for a pool that opens smaller.

Forward the result as keyword arguments (asyncpg.create_pool(dsn, **pool_size_kwargs(1, 4))): pyright traces a TypedDict splat through create_pool's typed parameters, where a bare dict[str, int] splat would erase the types.

Source code in src/taskq/connections.py
def pool_size_kwargs(init_size: int, max_size: int, *, min_size: int = 0) -> PoolSizeKwargs:
    """The ``create_pool`` sizing kwargs every TaskQ-built pool passes.

    *init_size* is the number of connections the pool opens up front (the
    warm ``max_size`` for the per-slot pool, one for the role pools);
    *max_size* is its ceiling. *min_size* defaults to ``0`` so
    ``max_inactive_connection_lifetime`` keeps recycling idle connections
    and every replacement authenticates with a freshly fetched credential;
    a caller passes :func:`resolve_pool_min_size`'s answer to raise the
    floor deliberately.

    A floor above the ceiling is refused here, naming the setting: asyncpg
    would refuse the same combination with a bare "min_size is greater than
    max_size" that names neither the knob nor the pool it came from. A floor
    above *init_size* raises the warm-up count to meet it (asyncpg requires
    ``init_size >= min_size``), which is what "the pool never drops below N"
    means for a pool that opens smaller.

    Forward the result as keyword arguments (``asyncpg.create_pool(dsn,
    **pool_size_kwargs(1, 4))``): pyright traces a ``TypedDict`` splat
    through ``create_pool``'s typed parameters, where a bare
    ``dict[str, int]`` splat would erase the types.
    """
    if min_size > max_size:
        raise ValueError(
            f"min_size ({min_size}) exceeds max_size ({max_size}): "
            "TASKQ_POOL_MIN_SIZE cannot be larger than the pool it pins"
        )
    return {
        "init_size": max(init_size, min_size),
        "min_size": min_size,
        "max_size": max_size,
    }

clamp_pool_min_size

clamp_pool_min_size(
    floor: int, max_size: int, *, pool_name: str
) -> int

Clamp TASKQ_POOL_MIN_SIZE to a pool whose ceiling is not a setting.

pool_size_kwargs refuses a floor above the ceiling, which is right for the role pools (TASKQ_DISPATCHER_POOL_SIZE and friends let the operator fix the mismatch). Three pools derive their ceiling from something else - the supervisor health pool from the health-checked worker count, the slot pool from max_concurrency, and the UI admin pool from a fixed 4 - so a floor that is valid for the fleet would otherwise abort startup. Clamping keeps the operator's floor for those pools while naming, in the log, the exact pool, the configured floor and the ceiling it was cut to: silently degrading a documented operator pin would leave a warm-connection count nobody can explain.

Source code in src/taskq/connections.py
def clamp_pool_min_size(floor: int, max_size: int, *, pool_name: str) -> int:
    """Clamp ``TASKQ_POOL_MIN_SIZE`` to a pool whose ceiling is not a setting.

    ``pool_size_kwargs`` refuses a floor above the ceiling, which is right for
    the role pools (``TASKQ_DISPATCHER_POOL_SIZE`` and friends let the operator
    fix the mismatch). Three pools derive their ceiling from something else -
    the supervisor health pool from the health-checked worker count, the slot
    pool from ``max_concurrency``, and the UI admin pool from a fixed 4 - so a
    floor that is valid for the fleet would otherwise abort startup. Clamping
    keeps the operator's floor for those pools while naming, in the log, the
    exact pool, the configured floor and the ceiling it was cut to: silently
    degrading a documented operator pin would leave a warm-connection count
    nobody can explain.
    """
    if floor <= max_size:
        return floor
    from taskq.obs import get_logger

    get_logger(__name__).warning(
        "pool-min-size-clamped",
        pool=pool_name,
        configured_min_size=floor,
        clamped_min_size=max_size,
        max_size=max_size,
    )
    return max_size

resolve_pool_min_size

resolve_pool_min_size(
    raw: str | int,
    *,
    provider_backed: bool,
    where: str = "TASKQ_POOL_MIN_SIZE",
) -> int

The asyncpg min_size floor a pool should be built with.

raw is TASKQ_POOL_MIN_SIZE: "auto" or a non-negative integer. "auto" resolves to 0 for a provider_backed pool (one built through a credential provider) and 1 otherwise.

Why the two answers differ: asyncpg 0.32's min_size is a floor the pool maintains - it spawns background replacements and exempts them from max_inactive_connection_lifetime. For a provider-backed pool that is exactly wrong: a pinned connection never expires, so it never re-authenticates with a freshly fetched credential, and the deployment runs on borrowed time after the token expires (#1323). For a pool built from a static DSN the floor only costs one idle connection and buys a warm one, so a quiet pool does not drain to zero and make the next caller - or the first dispatch of a burst - pay connection establishment.

A configured integer is honoured for a static-credential pool. A provider-backed pool refuses any nonzero floor: pinning a connection would defeat per-connection credential refresh even when the operator asked for it explicitly. Raises :class:ValueError for anything else, naming where the value came from.

Source code in src/taskq/connections.py
def resolve_pool_min_size(
    raw: str | int, *, provider_backed: bool, where: str = "TASKQ_POOL_MIN_SIZE"
) -> int:
    """The asyncpg ``min_size`` floor a pool should be built with.

    *raw* is ``TASKQ_POOL_MIN_SIZE``: ``"auto"`` or a non-negative
    integer. ``"auto"`` resolves to ``0`` for a *provider_backed* pool
    (one built through a credential provider) and ``1`` otherwise.

    Why the two answers differ: asyncpg 0.32's ``min_size`` is a floor the
    pool *maintains* - it spawns background replacements and exempts them
    from ``max_inactive_connection_lifetime``. For a provider-backed pool
    that is exactly wrong: a pinned connection never expires, so it never
    re-authenticates with a freshly fetched credential, and the deployment
    runs on borrowed time after the token expires (#1323). For a pool
    built from a static DSN the floor only costs one idle connection and
    buys a warm one, so a quiet pool does not drain to zero and make the
    next caller - or the first dispatch of a burst - pay connection
    establishment.

    A configured integer is honoured for a static-credential pool. A
    provider-backed pool refuses any nonzero floor: pinning a connection
    would defeat per-connection credential refresh even when the operator
    asked for it explicitly. Raises :class:`ValueError` for anything else,
    naming *where* the value came from.
    """
    text = str(raw).strip().lower()
    if text == POOL_MIN_SIZE_AUTO:
        return 0 if provider_backed else 1
    try:
        floor = int(text)
    except ValueError as exc:
        raise ValueError(
            f"{where} must be '{POOL_MIN_SIZE_AUTO}' or a non-negative integer, got {raw!r}"
        ) from exc
    if floor < 0:
        raise ValueError(
            f"{where} must be '{POOL_MIN_SIZE_AUTO}' or a non-negative integer, got {raw!r}"
        )
    if provider_backed and floor > 0:
        raise ValueError(
            f"{where} must be 0 or '{POOL_MIN_SIZE_AUTO}' when a credential provider "
            "is active: a maintained floor pins a connection that cannot rotate "
            "onto a fresh credential"
        )
    return floor

pool_lifecycle_kwargs

pool_lifecycle_kwargs(
    settings: TaskQSettings,
) -> PoolLifecycleKwargs

The connection-lifecycle create_pool kwargs for one pool.

max_inactive_connection_lifetime carries the operator's TASKQ_POOL_MAX_INACTIVE_LIFETIME jittered by up to +/-25% per pool build. Without the jitter every pool of a fleet booted together recycles its idle connections on the same tick, so a warmed pool (the per-slot pool above all, whose connections are all opened at build time) hands the database a fleet-wide reconnect burst - each paying a TCP connect, a TLS handshake and, on a credential-provider deployment, a token fetch - instead of a steady trickle. A lifetime of 0 disables recycling, and is passed through untouched (there is no instant to spread).

max_queries (TASKQ_POOL_MAX_QUERIES) and timeout (TASKQ_PG_CONNECT_TIMEOUT, asyncpg's per-host connect timeout) are forwarded as configured.

Call this once per pool build - the jitter is the point, so two pools built from one settings instance must not share a draw.

Source code in src/taskq/connections.py
def pool_lifecycle_kwargs(settings: TaskQSettings) -> PoolLifecycleKwargs:
    """The connection-lifecycle ``create_pool`` kwargs for one pool.

    ``max_inactive_connection_lifetime`` carries the operator's
    ``TASKQ_POOL_MAX_INACTIVE_LIFETIME`` jittered by up to +/-25% per pool
    build. Without the jitter every pool of a fleet booted together
    recycles its idle connections on the same tick, so a warmed pool (the
    per-slot pool above all, whose connections are all opened at build
    time) hands the database a fleet-wide reconnect burst - each paying a
    TCP connect, a TLS handshake and, on a credential-provider deployment,
    a token fetch - instead of a steady trickle. A lifetime of ``0``
    disables recycling, and is passed through untouched (there is no
    instant to spread).

    ``max_queries`` (``TASKQ_POOL_MAX_QUERIES``) and ``timeout``
    (``TASKQ_PG_CONNECT_TIMEOUT``, asyncpg's per-host connect timeout) are
    forwarded as configured.

    Call this once per pool build - the jitter is the point, so two pools
    built from one settings instance must not share a draw.
    """
    lifetime = settings.pool_max_inactive_lifetime
    if lifetime > 0:
        lifetime *= 1.0 + random.uniform(  # noqa: S311  # Why: uniform is for reconnect-timing jitter, not cryptography; same non-crypto use as the notify reconnect back-off.
            -_IDLE_LIFETIME_JITTER, _IDLE_LIFETIME_JITTER
        )
    return {
        "max_inactive_connection_lifetime": lifetime,
        "max_queries": settings.pool_max_queries,
        "timeout": settings.pg_connect_timeout,
    }

apply_tcp_keepalive

apply_tcp_keepalive(sock: socket) -> None

Set the keepalive socket options on an established PostgreSQL socket.

Linux calls the idle option TCP_KEEPIDLE; macOS calls it TCP_KEEPALIVE. Windows exposes the Linux names but expects milliseconds, unlike the seconds used on POSIX. Interval and probe-count options are set when the platform exposes them.

Source code in src/taskq/connections.py
def apply_tcp_keepalive(sock: socket.socket) -> None:
    """Set the keepalive socket options on an established PostgreSQL socket.

    Linux calls the idle option ``TCP_KEEPIDLE``; macOS calls it
    ``TCP_KEEPALIVE``. Windows exposes the Linux names but expects
    milliseconds, unlike the seconds used on POSIX. Interval and probe-count
    options are set when the platform exposes them.
    """
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    if sys.platform == "win32":
        if hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, _TCP_KEEPIDLE * 1000)
        if hasattr(socket, "TCP_KEEPINTVL"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, _TCP_KEEPINTVL * 1000)
    else:
        if sys.platform == "darwin":
            if hasattr(socket, "TCP_KEEPALIVE"):
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, _TCP_KEEPIDLE)
        elif hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, _TCP_KEEPIDLE)
        if hasattr(socket, "TCP_KEEPINTVL"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, _TCP_KEEPINTVL)
    if hasattr(socket, "TCP_KEEPCNT"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, _TCP_KEEPCNT)

keepalive_conn

keepalive_conn(conn: Connection, *, label: str) -> bool

Apply keepalive to an established connection's socket.

Returns True when the option was set. A connection double without a transport (or a wrapped connection) reports False and logs keepalive-skipped rather than raising: keepalive is socket hygiene, never a reason to fail a connection that otherwise works.

Source code in src/taskq/connections.py
def keepalive_conn(conn: asyncpg.Connection, *, label: str) -> bool:
    """Apply keepalive to an established connection's socket.

    Returns ``True`` when the option was set. A connection double without
    a transport (or a wrapped connection) reports ``False`` and logs
    ``keepalive-skipped`` rather than raising: keepalive is socket hygiene,
    never a reason to fail a connection that otherwise works.
    """
    transport = getattr(
        conn, "_transport", None
    )  # Why: asyncpg exposes _transport for socket access and has no public keepalive API; getattr because a fake/wrapped connection may not have one.
    sock: socket.socket | None = (
        transport.get_extra_info("socket") if transport is not None else None
    )
    from taskq.obs import get_logger

    logger = get_logger(__name__)
    if sock is None:
        logger.info("keepalive-skipped", label=label, reason="socket-not-available")
        return False
    try:
        apply_tcp_keepalive(sock)
    except OSError as exc:
        # A unix-domain socket (a documented sidecar deployment) rejects every
        # TCP-level option, and a restricted sandbox can refuse the syscall.
        # This runs in every pool's ``init`` hook, where a raise fails the pool
        # build outright - keepalive is hygiene, never a connection failure.
        logger.info(
            "keepalive-skipped",
            label=label,
            reason="socket-option-unsupported",
            error=str(exc),
        )
        return False
    logger.info(
        "keepalive-applied",
        label=label,
        keepidle=_TCP_KEEPIDLE,
        keepintvl=_TCP_KEEPINTVL,
        keepcnt=_TCP_KEEPCNT,
    )
    return True

pool_connection_init

pool_connection_init(
    *,
    label: str,
    keepalive: bool,
    reconnect_role: str | None = None,
    first_generation_connections: int = 0,
    warm_connections: int | None = None,
    pooler: bool = False,
    probe_timeout: float = DEFAULT_PG_CONNECT_TIMEOUT,
    inner: Callable[[Connection], Awaitable[None]]
    | None = None,
) -> Callable[
    [asyncpg.Connection], CoroutineType[Any, Any, None]
]

The per-connection hook a TaskQ-built pool installs as init=.

asyncpg runs init once for every physical connection a pool opens - the warm set built with the pool, then every replacement after an idle expiry, a max_queries cycle, a dropped backend or a credential reload - which makes it the one place per-connection hygiene can live: an option set on a connection after the pool is built is silently absent on the replacement, and asyncpg's release path runs RESET ALL besides.

first_generation_connections is the pool's first generation: the init_size warm set plus the lazy growth up to max_size. Those physical connections are the pool coming up, not churn, so only an open past that count is recorded as a reconnect on reconnect_role. warm_connections is the deprecated spelling of that argument (it meant "the warm set" when only the warm set was exempt); it is honoured for callers that pass it and resolves to first_generation_connections.

pooler declares that the pool's endpoint is a transaction-mode pooler: the per-connection PG floor check then queries server_version_num over SQL instead of trusting the startup packet the pooler answered. A direct pool keeps the zero-RTT metadata read. probe_timeout bounds that check: hook after its own connect-timeout scope, so a pooler that accepts the handshake and then black-holes the query must not wedge pool creation or a replacement. A timeout terminates the suspect socket before the error propagates, making asyncpg's init-failure cleanup immediate.

inner is a caller-owned per-connection hook - the registered connection's codec/state setup the per-slot pool inherits - and runs last, so its failure closes the connection the way asyncpg's own init contract says.

A hook with nothing to do is still returned: the pool keeps one init callable whatever its settings say, and the alternative (returning None from some arms) would make every call site branch.

Source code in src/taskq/connections.py
def pool_connection_init(
    *,
    label: str,
    keepalive: bool,
    reconnect_role: str | None = None,
    first_generation_connections: int = 0,
    warm_connections: int | None = None,
    pooler: bool = False,
    probe_timeout: float = DEFAULT_PG_CONNECT_TIMEOUT,
    inner: Callable[[asyncpg.Connection], Awaitable[None]] | None = None,
) -> Callable[[asyncpg.Connection], CoroutineType[Any, Any, None]]:
    """The per-connection hook a TaskQ-built pool installs as ``init=``.

    asyncpg runs ``init`` once for every *physical* connection a pool
    opens - the warm set built with the pool, then every replacement after
    an idle expiry, a ``max_queries`` cycle, a dropped backend or a
    credential reload - which makes it the one place per-connection
    hygiene can live: an option set on a connection after the pool is
    built is silently absent on the replacement, and asyncpg's release path
    runs ``RESET ALL`` besides.

    *first_generation_connections* is the pool's first generation: the
    ``init_size`` warm set plus the lazy growth up to ``max_size``. Those
    physical connections are the pool coming up, not churn, so only an open
    past that count is recorded as a reconnect on *reconnect_role*.
    *warm_connections* is the deprecated spelling of that argument (it meant
    "the warm set" when only the warm set was exempt); it is honoured for
    callers that pass it and resolves to *first_generation_connections*.

    *pooler* declares that the pool's endpoint is a transaction-mode pooler:
    the per-connection PG floor check then queries ``server_version_num`` over
    SQL instead of trusting the startup packet the pooler answered. A direct
    pool keeps the zero-RTT metadata read. *probe_timeout* bounds that check:
    hook after its own connect-timeout scope, so a pooler that accepts the
    handshake and then black-holes the query must not wedge pool creation or
    a replacement. A timeout terminates the suspect socket before the error
    propagates, making asyncpg's init-failure cleanup immediate.

    *inner* is a caller-owned per-connection hook - the registered
    connection's codec/state setup the per-slot pool inherits - and runs
    last, so its failure closes the connection the way asyncpg's own ``init``
    contract says.

    A hook with nothing to do is still returned: the pool keeps one init
    callable whatever its settings say, and the alternative (returning
    ``None`` from some arms) would make every call site branch.
    """
    if warm_connections is not None:
        warnings.warn(
            "pool_connection_init(warm_connections=...) is deprecated; pass "
            "first_generation_connections= (the warm set plus lazy growth to "
            "max_size) instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        first_generation_connections = warm_connections

    opened = 0

    async def _init(conn: asyncpg.Connection) -> None:
        nonlocal opened
        from taskq.backend._pg_capabilities import (
            probe_pg_capabilities,
            require_supported_pg,
        )

        try:
            async with asyncio.timeout(probe_timeout):
                require_supported_pg(await probe_pg_capabilities(conn, prefer_sql=pooler))
        except TimeoutError:
            conn.terminate()
            raise
        opened += 1
        # No await between the increment and this read, so the
        # first-generation/reconnect split is exact even when asyncpg opens
        # the warm set concurrently.
        if reconnect_role is not None and opened > first_generation_connections:
            from taskq.obs import record_pool_reconnect

            record_pool_reconnect(reconnect_role)
        if keepalive:
            keepalive_conn(conn, label=label)
        if inner is not None:
            await inner(conn)

    return _init

force_custom_plan async

force_custom_plan(conn: Connection) -> None

Pin one direct dispatcher connection to value-specific query plans.

This runs in the pool's init hook for the first checkout; :func:dispatch_connection_class carries it through later release resets in the same reset batch. There is no startup-packet parameter and no added round in the claim loop. Callers must not install either mechanism on a transaction-pooler connection, where a session GUC need not survive the next server-connection remap.

Source code in src/taskq/connections.py
async def force_custom_plan(conn: asyncpg.Connection) -> None:
    """Pin one direct dispatcher connection to value-specific query plans.

    This runs in the pool's ``init`` hook for the first checkout;
    :func:`dispatch_connection_class` carries it through later release
    resets in the same reset batch. There is no startup-packet parameter
    and no added round in the claim loop. Callers must not install either
    mechanism on a transaction-pooler connection, where a session GUC need
    not survive the next server-connection remap.
    """
    await conn.execute("SELECT set_config('plan_cache_mode', 'force_custom_plan', false)")

dispatch_connection_class

dispatch_connection_class() -> type[Any]

The direct dispatcher's fork-guarded connection class.

asyncpg's release reset includes RESET ALL, which would undo the init-time plan pin before the second checkout. Its documented get_reset_query extension lets the dispatcher re-apply the pin in the SAME reset batch: the driver's advisory-lock/cursor/listener/reset work is preserved verbatim and no statement or round trip is added to the next dispatch. The class is built once, like the base fork guard.

Source code in src/taskq/connections.py
def dispatch_connection_class() -> type[Any]:
    """The direct dispatcher's fork-guarded connection class.

    asyncpg's release reset includes ``RESET ALL``, which would undo the
    init-time plan pin before the second checkout. Its documented
    ``get_reset_query`` extension lets the dispatcher re-apply the pin in
    the SAME reset batch: the driver's advisory-lock/cursor/listener/reset
    work is preserved verbatim and no statement or round trip is added to
    the next dispatch. The class is built once, like the base fork guard.
    """
    from taskq._forkguard import guarded_connection_class

    global _dispatch_connection_class
    if _dispatch_connection_class is not None:
        return _dispatch_connection_class

    _base = guarded_connection_class()

    class DispatchConnection(_base):  # type: ignore[misc, valid-type]  # Why: the base is the runtime fork-guard subclass; see guarded_connection_class.
        def get_reset_query(self) -> str:
            reset_query = cast("str", super().get_reset_query())
            plan_pin = "SET plan_cache_mode = force_custom_plan;"
            if not reset_query:
                return plan_pin
            return f"{reset_query}\n{plan_pin}"

    _dispatch_connection_class = DispatchConnection
    return _dispatch_connection_class

direct_tls_kwargs

direct_tls_kwargs(
    direct_tls: bool, *, dsn: str | None
) -> DirectTlsKwargs

The direct_tls kwarg for a TaskQ-built pool or connection.

TASKQ_PG_DIRECT_TLS opts into PostgreSQL direct TLS (TLS from the first byte, negotiated by the postgresql ALPN protocol, PG 17+) instead of STARTTLS. Returns {"direct_tls": True} when direct_tls is enabled and {} when it is not, so a disabled setting adds no keyword at all: duck-typed create_pool / connect doubles keep working unchanged.

Enabled, dsn must already carry an explicit sslmode of require / verify-ca / verify-full. A missing or weaker sslmode raises :class:ValueError here, before any socket is opened: asyncpg refuses the combination too, but only while parsing connection arguments, which is a long way from the operator who set the env var. The message names the DSN's sslmode and the remedy.

Source code in src/taskq/connections.py
def direct_tls_kwargs(direct_tls: bool, *, dsn: str | None) -> DirectTlsKwargs:
    """The ``direct_tls`` kwarg for a TaskQ-built pool or connection.

    ``TASKQ_PG_DIRECT_TLS`` opts into PostgreSQL direct TLS (TLS from the
    first byte, negotiated by the ``postgresql`` ALPN protocol, PG 17+)
    instead of STARTTLS. Returns ``{"direct_tls": True}`` when *direct_tls*
    is enabled and ``{}`` when it is not, so a disabled setting adds no
    keyword at all: duck-typed ``create_pool`` / ``connect`` doubles keep
    working unchanged.

    Enabled, *dsn* must already carry an explicit ``sslmode`` of
    ``require`` / ``verify-ca`` / ``verify-full``. A missing or weaker
    sslmode raises :class:`ValueError` here, before any socket is opened:
    asyncpg refuses the combination too, but only while parsing connection
    arguments, which is a long way from the operator who set the env var.
    The message names the DSN's sslmode and the remedy.
    """
    if not direct_tls:
        return {}
    sslmode = _dsn_sslmode(dsn)
    if sslmode not in _DIRECT_TLS_SSLMODES:
        rendered = f"sslmode={sslmode}" if sslmode else "no sslmode"
        raise ValueError(
            "direct TLS is enabled (TASKQ_PG_DIRECT_TLS=true) but the connection "
            f"DSN has {rendered}. Direct TLS requires an explicit "
            "sslmode=require, verify-ca or verify-full in TASKQ_PG_DSN "
            "(TASKQ_PG_DSN_DIRECT / TASKQ_PG_DSN_POOLED); set one, or disable "
            "TASKQ_PG_DIRECT_TLS."
        )
    return {"direct_tls": True}

bounded_lock_budget_ms

bounded_lock_budget_ms(
    budget_ms: float, command_timeout_secs: float | None
) -> float

Clamp one enqueue lock budget to fit inside its connection's bound.

Each of the enqueue path's bounded waits is enforced server-side by a lock_timeout GUC whose expiry is the point: it produces the typed refusal (MaxPendingLockTimeoutError, UniqueForLockTimeoutError, IdempotencyKeyLockTimeoutError) naming which contention the caller lost and that retrying is the right response.

A budget at or above the connection's own per-query timeout can never deliver that. asyncpg starts its client-side timer before the SET LOCAL lock_timeout has even executed, so it always fires first: the caller gets a bare TimeoutError naming nothing, the warning line never logs, the backpressure counter never moves, and the typed refusal is unreachable code. Clamping is what makes the configured budget mean what it says, an unclamped budget is not a longer wait, it is no verdict at all.

command_timeout_secs of None is a connection with no client-side bound, so the budget stands as configured; so does a budget of 0 or less, which is the operator asking for an unbounded wait (the lock_timeout GUC convention).

Source code in src/taskq/connections.py
def bounded_lock_budget_ms(budget_ms: float, command_timeout_secs: float | None) -> float:
    """Clamp one enqueue lock budget to fit inside its connection's bound.

    Each of the enqueue path's bounded waits is enforced server-side by a
    ``lock_timeout`` GUC whose expiry is the point: it produces the typed
    refusal (``MaxPendingLockTimeoutError``, ``UniqueForLockTimeoutError``,
    ``IdempotencyKeyLockTimeoutError``) naming which contention the caller
    lost and that retrying is the right response.

    A budget at or above the connection's own per-query timeout can never
    deliver that. asyncpg starts its client-side timer before the
    ``SET LOCAL lock_timeout`` has even executed, so it always fires
    first: the caller gets a bare ``TimeoutError`` naming nothing, the
    warning line never logs, the backpressure counter never moves, and
    the typed refusal is unreachable code. Clamping is what makes the
    configured budget mean what it says, an unclamped budget is not a
    longer wait, it is no verdict at all.

    ``command_timeout_secs`` of ``None`` is a connection with no
    client-side bound, so the budget stands as configured; so does a
    budget of ``0`` or less, which is the operator asking for an
    unbounded wait (the ``lock_timeout`` GUC convention).
    """
    if command_timeout_secs is None or command_timeout_secs <= 0 or budget_ms <= 0:
        return budget_ms
    return min(budget_ms, command_timeout_secs * 1000.0 * _LOCK_BUDGET_COMMAND_TIMEOUT_SHARE)

lock_budget_command_timeout_secs

lock_budget_command_timeout_secs(
    budgets_ms: Iterable[tuple[float, float]],
    *,
    floor_secs: float,
) -> float

The per-query bound a TaskQ-built pool must carry to deliver its configured enqueue lock budgets.

floor_secs is the bound sized for the shipped defaults, at the defaults each budget is delivered clamped to the floor's :data:_LOCK_BUDGET_COMMAND_TIMEOUT_SHARE share by :func:bounded_lock_budget_ms, so the floor is exactly what the pre-knob pool carried and a deployment that sets nothing keeps it.

Each pair in budgets_ms is (configured_ms, default_ms) for one knob. A budget configured ABOVE its shipped default cannot be delivered inside the floor, the clamp would silently cap it back , so the bound is re-derived as configured / share: the widened budget occupies the same share of a larger bound, the clamp no longer bites, and the server-side lock_timeout still fires before the client-side timer (the race the clamp exists to win). Budgets at or below their default never move the bound, and neither does a non-positive one: an unbounded lock wait cannot fit inside any finite bound, and dropping the pool's per-query bound to honor one would remove the black-hole guard every other query relies on.

Source code in src/taskq/connections.py
def lock_budget_command_timeout_secs(
    budgets_ms: Iterable[tuple[float, float]],
    *,
    floor_secs: float,
) -> float:
    """The per-query bound a TaskQ-built pool must carry to deliver its
    configured enqueue lock budgets.

    *floor_secs* is the bound sized for the shipped defaults, at the
    defaults each budget is delivered clamped to the floor's
    :data:`_LOCK_BUDGET_COMMAND_TIMEOUT_SHARE` share by
    :func:`bounded_lock_budget_ms`, so the floor is exactly what the
    pre-knob pool carried and a deployment that sets nothing keeps it.

    Each pair in *budgets_ms* is ``(configured_ms, default_ms)`` for one
    knob. A budget configured ABOVE its shipped default cannot be
    delivered inside the floor, the clamp would silently cap it back ,
    so the bound is re-derived as ``configured / share``: the widened
    budget occupies the same share of a larger bound, the clamp no
    longer bites, and the server-side ``lock_timeout`` still fires
    before the client-side timer (the race the clamp exists to win).
    Budgets at or below their default never move the bound, and neither
    does a non-positive one: an unbounded lock wait cannot fit inside
    any finite bound, and dropping the pool's per-query bound to honor
    one would remove the black-hole guard every other query relies on.
    """
    bound = floor_secs
    for configured_ms, default_ms in budgets_ms:
        if configured_ms > default_ms:
            bound = max(bound, configured_ms / 1000.0 / _LOCK_BUDGET_COMMAND_TIMEOUT_SHARE)
    return bound

dispatcher_command_timeout_secs

dispatcher_command_timeout_secs(
    settings: WorkerSettings,
) -> float

The dispatcher pool's per-query bound, reconciled across its callers.

The dispatcher pool serves two bounded workloads whose server-side budgets must always fire before asyncpg's client-side timer, or the refusal the caller was promised is replaced by a bare TimeoutError:

  • the admission path's enqueue lock waits (token_bucket_lock_timeout_ms / sliding_window_lock_timeout_ms), whose clamp derives configured / share from the floor (:func:lock_budget_command_timeout_secs);
  • the bounded maintenance sweeps, which arm statement_timeout (and the derived cumulative transaction_timeout) from event_writer_statement_timeout_ms. A raised batch budget above the floor would otherwise trip the client timer first: the sweep would report a timeout with no server cancellation behind it, and the breaker would count a client-side race instead of the database refusing a full-size bite.

Both are expressed as the same 80 % share of the bound, so the server budget plus its unwind round trip fits inside the client's.

Source code in src/taskq/connections.py
def dispatcher_command_timeout_secs(settings: WorkerSettings) -> float:
    """The dispatcher pool's per-query bound, reconciled across its callers.

    The dispatcher pool serves two bounded workloads whose server-side
    budgets must always fire before asyncpg's client-side timer, or the
    refusal the caller was promised is replaced by a bare ``TimeoutError``:

    * the admission path's enqueue lock waits (``token_bucket_lock_timeout_ms``
      / ``sliding_window_lock_timeout_ms``), whose clamp derives
      ``configured / share`` from the floor (:func:`lock_budget_command_timeout_secs`);
    * the bounded maintenance sweeps, which arm ``statement_timeout`` (and the
      derived cumulative ``transaction_timeout``) from
      ``event_writer_statement_timeout_ms``. A raised batch budget above the
      floor would otherwise trip the client timer first: the sweep would
      report a timeout with no server cancellation behind it, and the breaker
      would count a client-side race instead of the database refusing a
      full-size bite.

    Both are expressed as the same 80 % share of the bound, so the server
    budget plus its unwind round trip fits inside the client's.
    """
    bound = lock_budget_command_timeout_secs(
        lock_budget_pairs(settings, ADMISSION_LOCK_BUDGET_FIELDS),
        floor_secs=settings.dispatcher_command_timeout,
    )
    batch_ms = float(settings.event_writer_statement_timeout_ms)
    if batch_ms > 0:
        bound = max(bound, batch_ms / 1000.0 / _LOCK_BUDGET_COMMAND_TIMEOUT_SHARE)
    return bound

lock_budget_pairs

lock_budget_pairs(
    settings: TaskQSettings, field_names: Iterable[str]
) -> list[tuple[float, float]]

(configured, shipped default) per lock-budget knob named in field_names, the input :func:lock_budget_command_timeout_secs derives a TaskQ-built pool's per-query bound from.

settings is the loaded settings model the knobs are read from (the client pool reads its enqueue knobs off TaskQSettings; the dispatcher pool reads the admission knobs off WorkerSettings); field_names lists that model's lock-budget field names, spelled once by each caller so the derivation cannot drift onto a different knob. The defaults are read off the model's field metadata, never restated.

Source code in src/taskq/connections.py
def lock_budget_pairs(
    settings: TaskQSettings, field_names: Iterable[str]
) -> list[tuple[float, float]]:
    """``(configured, shipped default)`` per lock-budget knob named in
    *field_names*, the input :func:`lock_budget_command_timeout_secs`
    derives a TaskQ-built pool's per-query bound from.

    *settings* is the loaded settings model the knobs are read from (the
    client pool reads its enqueue knobs off ``TaskQSettings``; the
    dispatcher pool reads the admission knobs off ``WorkerSettings``);
    *field_names* lists that model's lock-budget field names, spelled once
    by each caller so the derivation cannot drift onto a different knob.
    The defaults are read off the model's field metadata, never restated.
    """
    pairs: list[tuple[float, float]] = []
    fields = type(settings).get_fields()
    for field_name in field_names:
        _field_type, field_info = fields[field_name]
        pairs.append((float(getattr(settings, field_name)), float(field_info.default)))
    return pairs

unwrap_physical_conn

unwrap_physical_conn(conn: object) -> object

Return the underlying asyncpg Connection behind a pool proxy, or conn itself.

asyncpg mints a per-acquire PoolConnectionProxy whose _con attribute references the weak-referenceable physical Connection. Raw connections have no _con and return themselves; a detached proxy whose _con is None falls back to conn so callers never key on None.

Source code in src/taskq/connections.py
def unwrap_physical_conn(conn: object) -> object:
    """Return the underlying asyncpg ``Connection`` behind a pool proxy, or *conn* itself.

    ``asyncpg`` mints a per-acquire ``PoolConnectionProxy`` whose ``_con``
    attribute references the weak-referenceable physical ``Connection``.
    Raw connections have no ``_con`` and return themselves; a detached proxy
    whose ``_con`` is ``None`` falls back to *conn* so callers never key on
    ``None``.
    """
    underlying: object = getattr(conn, "_con", None)
    return conn if underlying is None else underlying

with_connection_init

with_connection_init(
    factory: ConnFactory,
    init: Callable[[Connection], Awaitable[None]],
) -> ConnFactory

Wrap a connection factory so init runs on every connection it opens, and so the worker's per-slot pool can inherit the same hook.

init is applied to each produced connection exactly once, right after the factory returns it, the setup= hook position in asyncpg.connect. This is the channel through which per-connection setup (registering type codecs, preparing statements) reaches the connections an actor actually runs on: when the wrapped factory provides the LOOP-scope asyncpg.Connection registration and the worker activates its per-slot transaction pool, the worker reads the declared hook off the registration and passes it as the slot pool's init, so every slot connection gets the same setup. Applied directly to one live connection instead, the same setup is invisible to the slot pool (the driver exposes no read-back) and silently absent above max_concurrency = 1.

Declare the hook here, not inside factory as well: the wrapper applies it, so a factory that also applies it would run it twice on the LOOP-scope connection. If init raises, the produced connection is closed (bounded) before the error propagates, a failed hook means no usable connection, matching asyncpg's own hook contract.

Source code in src/taskq/connections.py
def with_connection_init(
    factory: ConnFactory,
    init: Callable[[asyncpg.Connection], Awaitable[None]],
) -> ConnFactory:
    """Wrap a connection factory so *init* runs on every connection it
    opens, and so the worker's per-slot pool can inherit the same hook.

    *init* is applied to each produced connection exactly once, right
    after the factory returns it, the ``setup=`` hook position in
    ``asyncpg.connect``. This is the channel through which per-connection
    setup (registering type codecs, preparing statements) reaches the
    connections an actor actually runs on: when the wrapped factory
    provides the LOOP-scope ``asyncpg.Connection`` registration and the
    worker activates its per-slot transaction pool, the worker reads the
    declared hook off the registration and passes it as the slot pool's
    ``init``, so every slot connection gets the same setup. Applied
    directly to one live connection instead, the same setup is invisible
    to the slot pool (the driver exposes no read-back) and silently
    absent above ``max_concurrency = 1``.

    Declare the hook here, not inside *factory* as well: the wrapper
    applies it, so a factory that also applies it would run it twice on
    the LOOP-scope connection. If *init* raises, the produced connection
    is closed (bounded) before the error propagates, a failed hook
    means no usable connection, matching asyncpg's own hook contract.
    """

    # Why no return annotation: di registers factories like this one and
    # resolves type hints at registration time (``_collect_dep_edges``),
    # and this module keeps asyncpg under TYPE_CHECKING, a runtime-
    # evaluated ``-> asyncpg.Connection`` would raise NameError there.
    # The declared ``ConnFactory`` return type of this wrapper keeps the
    # boundary typed; pyright infers the body.
    async def _wrapped():
        conn = await factory()
        try:
            await init(conn)
        except BaseException:
            # Why deferred: this module is import-light by design (no
            # taskq runtime imports above), and the failure path is cold.
            # Why bounded: a hook failure during di bootstrap must not
            # leak the connection, and a dead PG must not turn that
            # cleanup into a wedge. The helper never raises, so the
            # hook's own error is always the one that propagates.
            from taskq._close import CLOSE_TIMEOUT_SECS, close_conn_bounded

            await close_conn_bounded(conn, "with-connection-init", CLOSE_TIMEOUT_SECS)
            raise
        return conn

    setattr(_wrapped, _CONNECTION_INIT_HOOK_ATTR, init)
    return _wrapped

connection_init_hook

connection_init_hook(
    factory: object,
) -> Callable[[asyncpg.Connection], Awaitable[None]] | None

The init hook factory declares, if it declares one.

The read half of the inheritance channel, public so an application that hand-rolls its factories can verify its declaration is visible the way the worker sees it. Returns the hook exactly as declared (so the slot pool installs the very callable the LOOP-scope connection got), or None when the factory carries no declaration, a bare closure, a raw asyncpg.connect partial, in which case nothing about its per-connection setup is recoverable.

Source code in src/taskq/connections.py
def connection_init_hook(
    factory: object,
) -> Callable[[asyncpg.Connection], Awaitable[None]] | None:
    """The init hook *factory* declares, if it declares one.

    The read half of the inheritance channel, public so an application
    that hand-rolls its factories can verify its declaration is visible
    the way the worker sees it. Returns the hook exactly as declared (so
    the slot pool installs the very callable the LOOP-scope connection
    got), or ``None`` when the factory carries no declaration, a bare
    closure, a raw ``asyncpg.connect`` partial, in which case nothing
    about its per-connection setup is recoverable.
    """
    hook = getattr(factory, _CONNECTION_INIT_HOOK_ATTR, None)
    if not callable(hook):
        return None
    # Why the string form: asyncpg is TYPE_CHECKING-only in this module,
    # and cast() evaluates its type argument at runtime. The attribute is
    # write-only from the two typed declaring sites above; getattr erases
    # that, so the cast restores the declared contract.
    return cast("Callable[[asyncpg.Connection], Awaitable[None]]", hook)