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:
- a pre-constructed, caller-owned resource (TaskQ uses it but never closes it, you close it in your own lifespan), or
- 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_MAX_CACHED_STATEMENT_LIFETIME
module-attribute
¶
DEFAULT_MAX_CACHEABLE_STATEMENT_SIZE
module-attribute
¶
ADMISSION_LOCK_BUDGET_FIELDS
module-attribute
¶
ADMISSION_LOCK_BUDGET_FIELDS: Final[tuple[str, ...]] = (
"token_bucket_lock_timeout_ms",
"sliding_window_lock_timeout_ms",
)
StatementCacheKwargs ¶
Bases: TypedDict
The create_pool kwargs :func:statement_cache_kwargs produces.
PoolSizeKwargs ¶
PoolLifecycleKwargs ¶
DirectTlsKwargs ¶
Bases: TypedDict
The direct_tls kwarg :func:direct_tls_kwargs produces.
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 (pg_dsn_direct role). Caller-owned if set.
dispatcher_pool_factory
class-attribute
instance-attribute
¶
Factory for the dispatcher pool. TaskQ-owned.
heartbeat_pool
class-attribute
instance-attribute
¶
Heartbeat pool (pg_dsn_direct, heartbeat_command_timeout). Caller-owned.
heartbeat_pool_factory
class-attribute
instance-attribute
¶
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 (pg_dsn_pooled role). Caller-owned.
worker_pool_factory
class-attribute
instance-attribute
¶
Factory for the worker pool. TaskQ-owned.
notify_conn
class-attribute
instance-attribute
¶
Dedicated LISTEN connection. Caller-owned. TaskQ still issues LISTEN.
notify_conn_factory
class-attribute
instance-attribute
¶
Factory for the LISTEN connection. TaskQ-owned.
leader_conn
class-attribute
instance-attribute
¶
Dedicated advisory-lock connection. Caller-owned.
leader_conn_factory
class-attribute
instance-attribute
¶
Factory for the advisory-lock connection. TaskQ-owned.
redis_client
class-attribute
instance-attribute
¶
Redis client for progress fanout / rate limiting. Caller-owned.
redis_client_factory
class-attribute
instance-attribute
¶
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__ ¶
Reject concrete + factory for the same role (configuration error).
Source code in src/taskq/connections.py
has_any ¶
True if any override (concrete or factory) is set.
Source code in src/taskq/connections.py
same_pg_endpoint ¶
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
role_reaches_pooler ¶
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
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
pool_size_kwargs ¶
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
clamp_pool_min_size ¶
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
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
pool_lifecycle_kwargs ¶
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
apply_tcp_keepalive ¶
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
keepalive_conn ¶
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
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
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | |
force_custom_plan
async
¶
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
dispatch_connection_class ¶
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
direct_tls_kwargs ¶
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
bounded_lock_budget_ms ¶
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
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
dispatcher_command_timeout_secs ¶
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 derivesconfigured / sharefrom the floor (:func:lock_budget_command_timeout_secs); - the bounded maintenance sweeps, which arm
statement_timeout(and the derived cumulativetransaction_timeout) fromevent_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
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
unwrap_physical_conn ¶
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
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
connection_init_hook ¶
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.