Worker¶
Worker process internals: dispatcher, consumer, heartbeat, leader election, shutdown.
taskq.worker itself is a lazy __getattr__ shim (re-exports selected names from its
submodules on first access) and renders no useful members on its own. The directives below
target the concrete submodules instead. See also the Workers guide
for a task-oriented walkthrough.
Process entry point, registration, producer/consumer loops¶
run ¶
Worker-runtime wiring helpers and process entry point.
This module forms the production seam between WorkerDeps assembly
(open_worker_deps, deps.py) and the heartbeat task spawn. It also hosts
the worker process entry point worker_main and the _main bootstrap
coroutine that wires the full TaskGroup of long-lived siblings.
Deviations from the original sketch
- Signal handlers go through
install_signal_handlers, not inline lambdas. orchestrate_shutdowntakes notgparameter.ProcessScope/ThreadScope/LoopScopeare bootstrapped insideopen_worker_depsrather than before it (M3 single-process deployment — process exit and deps exit are coterminal; see_maincomment block).- The
_local_queue_seedkeyword-only parameter is a test seam, not public API. local_queuemaxsize usesmax_concurrency(notbatch_size— nobatch_sizefield exists onWorkerSettings).
M1 stub consumers accept a stub_work_timeout keyword-only parameter
(default 60.0 s) that controls the sentinel sleep duration. Integration
tests may pass a shorter override (e.g. stub_work_timeout=2.0) when
seeding jobs that must complete naturally during a short test run. The
bootstrap accepts the default; M2 replaces the stubs with the
real producer/consumer.
__all__
module-attribute
¶
__all__ = [
"_main",
"consumer_loop_stub",
"deregister_worker",
"di_consumer_loop",
"producer_loop",
"producer_loop_stub",
"register_worker",
"worker_main",
]
worker_main ¶
worker_main(
settings: WorkerSettings,
*,
actor_registry: Mapping[str, ActorRef[Any, Any]]
| None = None,
di_registry: ProviderRegistry | None = None,
cron_registry: list[CronScheduleSpec] | None = None,
) -> int
Worker process entry point.
Runs _main under an asyncio.Runner and returns its int result.
Uses Runner (not asyncio.run) for finer control over teardown.
actor_registry is a mapping from short name to :class:ActorRef
containing every @actor-decorated handler this worker intends to
run. Forwarded to :func:_main for the bootstrap config sync.
di_registry is an optional pre-configured :class:ProviderRegistry
containing application-specific provider registrations (database pools,
HTTP clients, etc.). When supplied, the worker uses it instead of
creating a fresh registry — callers must NOT call validate() before
passing it here; the worker calls validate() as part of its bootstrap
sequence. WorkerSettings and Clock are registered automatically
if not already present.
cron_registry is an optional list of :class:CronScheduleSpec
objects to auto-register at startup. When None (the default),
get_registered_crons() is used instead — schedules declared via
the @cron decorator are auto-discovered. When an explicit list
is passed (even empty []), only those schedules are registered;
decorator-registered schedules are skipped. For each spec, a direct
INSERT INTO … cron_schedules is executed inside
try/except asyncpg.UniqueViolationError: pass — the DB (actor, name)
UNIQUE constraint prevents duplicates, so concurrent worker replicas
can safely race. Startup auto-discovery is create-only,
skip-on-conflict: existing cron_schedules rows are never
modified by the registration pass. If a @cron decorator's
parameters change after the schedule was first registered, the
operator must manually update or delete and recreate the schedule.
Source code in src/taskq/worker/_bootstrap.py
__getattr__ ¶
Source code in src/taskq/worker/run.py
make_heartbeat_kwargs ¶
make_heartbeat_kwargs(
deps: WorkerDeps,
worker_id: UUID,
backend: Backend,
cancel_wake_event: Event | None = None,
) -> dict[str, object]
Return keyword arguments that wire a cancel controller and optional cancel-wake event into heartbeat_loop for a given worker.
Usage (production, owned by the orchestration layer)::
kwargs = make_heartbeat_kwargs(deps, worker_id, backend, cancel_wake_event)
await heartbeat_loop(deps, worker_id, shutdown, **kwargs)
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
|
Source code in src/taskq/worker/run.py
producer_loop
async
¶
producer_loop(
deps: WorkerDeps,
local_queue: Queue[JobRow],
shutdown_event: Event,
producer_stop_event: Event,
*,
backend: Backend,
worker_id: UUID,
) -> None
Dispatch pending jobs from the database and feed them into local_queue.
On each iteration the producer:
- Waits for a wake signal (NOTIFY-driven
asyncio.Event) or thepoll_intervalfallback timer — whichever fires first. - Calls
backend.dispatch_batch()to atomically claim up tolocal_queue.maxsize - local_queue.qsize()pending jobs (pending → running) usingFOR UPDATE SKIP LOCKED. - Puts each returned :class:
JobRowontolocal_queuefor the consumer tasks.
Exits cleanly when either shutdown_event or producer_stop_event
is set.
Source code in src/taskq/worker/run.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
producer_loop_stub
async
¶
producer_loop_stub(
deps: WorkerDeps,
local_queue: Queue[JobRow],
shutdown_event: Event,
producer_stop_event: Event,
*,
backend: Backend,
worker_id: UUID,
) -> None
Observe producer_stop_event and shutdown_event; exit cleanly.
Outer loop: while not (producer_stop_event.is_set() or shutdown_event.is_set()).
Body races producer_stop_event.wait() against shutdown_event.wait() via
asyncio.wait(..., return_when=FIRST_COMPLETED); the loser is cancelled
to avoid a pending-task leak.
Source code in src/taskq/worker/run.py
consumer_loop_stub
async
¶
consumer_loop_stub(
deps: WorkerDeps,
local_queue: Queue[JobRow],
shutdown_event: Event,
*,
backend: Backend,
worker_id: UUID,
stub_work_timeout: float = 60.0,
) -> None
Pull one job per iteration, register, sleep sentinel, write terminal status.
Outer loop: while not shutdown_event.is_set().
Races local_queue.get() against shutdown_event.wait(); on shutdown
win the queue waiter is cancelled and the stub returns cleanly.
On job get the stub registers in deps.active_jobs, awaits a cancellable
sentinel, writes terminal state via backend (shielded), and deregisters
in finally.
Source code in src/taskq/worker/run.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
di_consumer_loop
async
¶
di_consumer_loop(
deps: WorkerDeps,
local_queue: Queue[JobRow],
shutdown_event: Event,
*,
backend: Backend,
worker_id: UUID,
registry: ProviderRegistry,
process_scope: ProcessScope,
thread_scope: ThreadScope,
loop_scope: LoopScope,
actor_registry: Mapping[str, ActorRef[Any, Any]],
enqueuer: SubJobEnqueuer,
) -> None
Pull one job per iteration and dispatch via dispatch_one_job.
Outer loop: while not shutdown_event.is_set().
Races local_queue.get() against shutdown_event.wait(); on shutdown
win the queue waiter is cancelled and the loop returns cleanly.
Each job is dispatched through dispatch_one_job which composes build_actor_scope + consume_one_job, providing DI-aware actor invocation with per-invocation TRANSIENT scope teardown.
Source code in src/taskq/worker/run.py
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
register_worker
async
¶
Register the current worker in taskq.workers and return its UUID.
Generates a UUIDv7, inserts a row into {schema}.workers, and returns
the new UUID. Acquires from pool with a 2.0 s timeout; on timeout or
connection error the failure is logged and re-raised (registering is
fatal).
If settings.worker_label or settings.workgroup_instance are set,
they are stored directly for cross-process correlation and health checking.
Source code in src/taskq/worker/run.py
deregister_worker
async
¶
Remove the worker row from {schema}.workers (best-effort).
Acquires from pool with a 2.0 s timeout. On timeout or connection
error, logs a structured warning deregister_worker_failed and
returns without raising — the recovery sweep is the backstop and
shutdown MUST NOT block on this cleanup.
Source code in src/taskq/worker/run.py
Maintenance leader (election, sweeps, cron, prune/archive)¶
leader ¶
Maintenance leader: election, watchdog, and recovery sweeps. A single elected leader per cluster runs cooperative loops inside one asyncio.TaskGroup: election, watchdog, scheduled-wake (sweep 3), cron, sweep (sweeps 1/2/4), prune (sweep 5), archive expiry (sweep 6), stale worker cleanup, queue depth, and reservation slots. Non-leader pods retry election periodically and skip the gated work. Failover SLA: Worker killed ≤ heartbeat_interval + 1 s Partition detect ≤ watchdog_interval + heartbeat_interval + 2 s PG failover ≤ heartbeat_interval Watchdog detect ≤ watchdog_interval + heartbeat_interval
__all__
module-attribute
¶
__all__ = [
"ARCHIVE_EXPIRY_LOCK_NAME",
"MAINTENANCE_LEADER_LOCK_NAME",
"PRUNE_LOCK_NAME",
"ArchiveExpiryResult",
"MaintenanceLeader",
"PruneResult",
"_build_retention_per_status",
"_load_actor_retention_overrides",
"_schedule_utc_to_cron",
"archive_expiry_sweep",
"cleanup_stale_workers",
"prune_terminal_jobs",
]
MAINTENANCE_LEADER_LOCK_NAME
module-attribute
¶
ArchiveExpiryResult
dataclass
¶
PruneResult
dataclass
¶
PruneResult(
total_deleted: int,
archived: int,
by_actor: dict[str, int],
by_status: dict[str, int],
cutoffs: dict[str, datetime],
duration_ms: int,
)
MaintenanceLeader ¶
Elected leader that runs watchdog, sweeps, cron, and prune loops.
Source code in src/taskq/worker/leader.py
run
async
¶
Source code in src/taskq/worker/leader.py
archive_expiry_sweep
async
¶
archive_expiry_sweep(
conn: ConnLike,
*,
batch_size: int = 10000,
schema: str = "taskq",
) -> ArchiveExpiryResult
Source code in src/taskq/worker/_leader_shared.py
cleanup_stale_workers
async
¶
cleanup_stale_workers(
conn: ConnLike,
*,
worker_id: UUID,
staleness: timedelta,
schema: str = "taskq",
) -> int
Delete worker rows whose last_seen_at exceeds staleness.
The caller's worker_id is never deleted. Returns the number of rows
removed. Worker-level cascade (maintenance_leader, job_attempts)
is handled by the DDL ON DELETE clauses — no extra sweeping needed.
Source code in src/taskq/worker/_leader_shared.py
prune_terminal_jobs
async
¶
prune_terminal_jobs(
conn: ConnLike,
*,
retention_per_status: dict[str, timedelta],
archive_retention: timedelta,
batch_size: int = 10000,
schema: str = "taskq",
actor_overrides: dict[str, timedelta] | None = None,
) -> PruneResult
Source code in src/taskq/worker/_leader_shared.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
Dispatch¶
dispatch ¶
Dispatch per-job DI dispatch.
:func:dispatch_one_job composes :func:build_actor_scope with
:func:consume_one_job so the worker's per-job dispatch path is DI-aware:
actors with Annotated[T, Scope.X] parameters receive resolved instances
at dispatch time, scoped to their effective scope, with TRANSIENT teardown
running per invocation.
The dispatch SQL constants and the dispatch_batch asyncpg helper live
in :mod:taskq.backend._dispatch_sql (backend layer). This module
imports them from there since worker → backend is the correct layer
direction.
dispatch_one_job
async
¶
dispatch_one_job(
*,
backend: Backend,
deps: WorkerDeps,
job: JobRow,
worker_id: UUID,
registry: ProviderRegistry,
process_scope: ProcessScope,
thread_scope: ThreadScope,
loop_scope: LoopScope,
actor_ref: ActorRef[BaseModel, BaseModel | None],
actor_config: ActorConfigLike,
clock: Clock,
active_jobs: ActiveJobRegistry | None = None,
max_retry_backoff: timedelta = timedelta(hours=24),
logger_arg: BoundLogger | None = None,
enqueuer: SubJobEnqueuer,
) -> None
Dispatch one job through the DI-resolved actor scope.
- Create the CONSUMER span with link to the PRODUCER span.
- Validate the payload against actor_ref's payload schema.
- Build the interim JobContext with the CONSUMER span.
- Open build_actor_scope to resolve DI kwargs.
- Hand the resolved kwargs to consume_one_job via a run_actor closure that injects them.
- TRANSIENT scope is closed on exit (regardless of outcome).
- Record consumer-path metrics outside the span body.
Source code in src/taskq/worker/dispatch.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
Heartbeat and cancellation¶
heartbeat ¶
Heartbeat loop and cancel-poll seam.
Each tick acquires one connection from heartbeat_pool, opens a single transaction, and atomically extends workers.last_seen_at, jobs lock / heartbeat columns, and reservation_slots leases for jobs locked by this worker. After max_heartbeat_failures consecutive connection failures, isolate_self proactively transitions running jobs and signals shutdown.
heartbeat_loop
async
¶
heartbeat_loop(
deps: WorkerDeps,
worker_id: UUID,
shutdown: Event,
*,
cancel_controller: CancelController | None = None,
cancel_wake_event: Event | None = None,
) -> None
Source code in src/taskq/worker/heartbeat.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
isolate_self
async
¶
Source code in src/taskq/worker/heartbeat.py
cancel ¶
Active-job tracking, cancel-poll hook factory.
This module implements ActiveJobRegistry — the loop-scoped in-process map
of running jobs — the _ActiveJob dataclass, and the CancelController
class that drives the five-phase cancel-poll loop.
CancelController exposes two methods that heartbeat_loop calls on every
tick:
-
run_in_tx(conn)— runs inside the heartbeat transaction. Phases 1, 2, and the phase-3 eligibility check happen here. Phase-3 jobs are queued into_pending_abandonsrather than callingmark_abandoneddirectly, becausemark_abandoneduses a separate pool connection that would deadlock on the row lock that the heartbeat transaction still holds. -
run_post_tx()— called byheartbeat_loopAFTER the transaction block exits (and therefore after the transaction has committed and released its row locks). Drains_pending_abandons, callingmark_abandoned+ deregister for each entry.
Key correctness invariants ():
- _by_id mutations (register/deregister) are protected by asyncio.Lock.
- all() is synchronous: in asyncio's single-threaded model no other
coroutine can mutate _by_id between the list-copy and return unless
there is an intervening await. all() has no await, so the
copy is atomic from the event-loop perspective. The lock is NOT acquired
in all() — acquiring an asyncio.Lock requires await and would force
a coroutine boundary that breaks the atomicity guarantee.
- cancel_observed_at uses asyncio.get_running_loop().time() (monotonic
event-loop clock), never time.time() or datetime.now().
- Phase-2 PG write (conn.execute) happens BEFORE task.cancel() in
code order with NO intervening await (PG-first invariant).
- No try/except inside the phase-2 block — PG-write failures propagate
to heartbeat_loop's outer handler.
- run_post_tx is always called after run_in_tx on the same tick, even
when run_in_tx raises; heartbeat_loop must call it in a finally
block (or equivalent) to drain any entries queued before the error.
__all__
module-attribute
¶
CancelController ¶
Bases: Protocol
Structural interface for cancel-poll controllers.
heartbeat_loop calls run_in_tx inside the open heartbeat
transaction and run_post_tx immediately after the transaction commits.
Implementations must satisfy this two-phase contract.
The concrete production implementation is _CancelController, constructed
via make_cancel_controller. Test stubs need only implement these two
methods to satisfy the type.
run_in_tx
async
¶
ActiveJobRegistry ¶
Loop-scoped in-process map of running jobs on this worker.
One instance per worker process, constructed in _main() / WorkerDeps
before the TaskGroup is entered. Multiple workers in the same process (test
scenarios) each carry their own independent registry.
Thread-safety: not applicable — asyncio workers are single-threaded. The
asyncio.Lock on _by_id prevents interleaving between coroutines that
await register / await deregister while the heartbeat or consumer is
also running.
Public surface per
register(job_id, task, ctx) -> None(async)deregister(job_id) -> None(async)get(job_id) -> _ActiveJob | None(sync)all() -> list[_ActiveJob](sync snapshot copy)count() -> int(sync)
Source code in src/taskq/worker/cancel.py
register
async
¶
Register a job as in-flight.
The lock ensures no concurrent deregister sees an inconsistent state.
Source code in src/taskq/worker/cancel.py
deregister
async
¶
Remove a job from the registry (idempotent — ignores missing keys).
get ¶
Return the registry entry for job_id, or None if absent.
Synchronous and lock-free: safe to call from the heartbeat hook or any non-mutating code path between awaits.
Source code in src/taskq/worker/cancel.py
all ¶
Return a snapshot copy of all in-flight entries.
Synchronous: in asyncio's cooperative multitasking, no other coroutine
can mutate _by_id while this method runs (there is no await
between list(...) and return). The copy ensures the caller's
for loop cannot raise RuntimeError: dictionary changed size during
iteration even if register/deregister are called in later
coroutine steps.
Callers that need a fresh count after iterating must call count()
separately.
Source code in src/taskq/worker/cancel.py
count ¶
make_cancel_controller ¶
Construct a CancelController for the given worker.
Validates schema_name eagerly (before any ticks run) so misconfiguration
is surfaced at startup rather than on the first heartbeat.
Source code in src/taskq/worker/cancel.py
Shutdown¶
shutdown ¶
Two-phase shutdown orchestration.
Consumers (orchestrate_shutdown, health endpoints) MUST observe
deps.shutdown_phase set at the START of each phase, BEFORE any
per-phase work. Value NONE (0) means the worker is running normally.
Phase ordering invariant: NONE (0) → DRAINING (1) → CANCELLING (2) → FORCING (3) → ABANDONING (4).
SIGQUIT is not registered; produces a core dump on Linux. Use tini or
ulimit -c 0 for containerised deployments.
The second-SIGTERM contract: if the second SIGTERM arrives during
FORCING or ABANDONING, setting escalate_event is a no-op — the
orchestrator is already past CANCELLING.
__all__
module-attribute
¶
__all__ = [
"ShutdownPhase",
"drain_local_queue_to_pending",
"install_signal_handlers",
"orchestrate_shutdown",
]
ShutdownPhase ¶
Bases: IntEnum
Worker shutdown phase.
NONE — running normally. DRAINING — stop accepting new dispatch, finish in-flight jobs. CANCELLING — cooperative cancel of remaining jobs. FORCING — force-cancel grace, terminal writes shielded. ABANDONING — pod must be replaced to reclaim slots.
drain_local_queue_to_pending
async
¶
Re-pend every job this worker locked but never started.
Issues a single bounded-timeout UPDATE that clears the lock on rows
where locked_by_worker = $worker_id AND status = 'running' AND
started_at IS NULL. On pool exhaustion or connection error the
helper logs a warning and returns 0 so the recovery sweep acts as
the backstop rather than a deadlocked shutdown.
Returns:
| Type | Description |
|---|---|
int
|
Number of rows updated, or 0 on timeout / connection error. |
Source code in src/taskq/worker/shutdown.py
orchestrate_shutdown
async
¶
orchestrate_shutdown(
deps: WorkerDeps,
settings: WorkerSettings,
worker_id: UUID,
shutdown_event: Event,
escalate_event: Event | None = None,
*,
backend: Backend,
) -> int
Run the four-phase shutdown orchestration.
Phases are DRAINING → CANCELLING → FORCING → ABANDONING, followed by
leader_conn close and shutdown_event.set(). Each phase is assigned
to deps.shutdown_phase BEFORE any per-phase work.
Returns 0 on clean exit.
Source code in src/taskq/worker/shutdown.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
install_signal_handlers ¶
install_signal_handlers(
loop: AbstractEventLoop,
deps: WorkerDeps,
worker_id: UUID,
shutdown_event: Event,
escalate_event: Event,
backend: Backend,
orchestrator_holder: list[Task[int]],
) -> None
Register SIGTERM/SIGINT handlers with a three-signal escalation counter.
First signal schedules orchestrate_shutdown via loop.create_task
and appends the created task to orchestrator_holder so that _main
can later await it for the exit code. Second signal sets
escalate_event to fast-advance CANCELLING → FORCING. Third signal
calls sys.exit(1) (Kubernetes SIGKILL is the hard backstop).
The signal counter is closure-scoped — each call to this function creates
a fresh, independent counter. The handler callable contains zero
await or I/O.