Skip to content

v0.4.0 - Keep workers moving and control Python retries

Choose a tag to compare

@Kludex Kludex released this 05 Oct 19:00
ee2c450

🐘 Keep workers moving and control Python retries

pgtask is a task queue, scheduler, and durable workflow runtime that keeps every piece of state in PostgreSQL. No broker, no coordinator, no extension.

This release batches worker outcomes, stops idle database polling, and keeps oversized results, broken schedules, listener reconnects, and routine shutdowns from disrupting unrelated work. Python handlers can now choose terminal failures and catch a step's original exception.

pip install pgtask==0.4.0

🚀 Move work with fewer database operations

  • Batch task completions and failures (#16). Workers flush transitions with size and deadline bounds while preserving ordered responses and lease fencing. In the pull request's benchmark of 10,000 no-op tasks at concurrency 100, drain throughput increased from 4,803 to 6,550 tasks per second and database transactions fell by about 80%.
  • Let idle workers sleep (#48). Empty task, schedule, and wait queues now return no deadline instead of an immediate deadline, so workers stop repeatedly querying an idle database.
  • Drain retention backlogs without whole-table scans (#57). Each retention tick processes up to 16 batches per queue for terminal tasks and idempotency keys. New indexes speed up history cleanup, and worker rows and capabilities are removed after the worker has been expired for 24 hours by default. Python exposes retention_enabled, retention_batch_size, and retention_interval.
  • Browse large queue lists in bounded pages (#71). The observer dashboard lists 100 queues at a time with a name-based cursor. The database aggregates only the queues needed for the page, rather than every queue ever created.

🧱 Keep disruptive work from blocking progress

  • Isolate outcomes PostgreSQL cannot store (#55). A result over 1 MiB fails its own task terminally with result_too_large. Errors over 256 KiB are truncated, and NUL characters are escaped. If a batch is still rejected, workers write its transitions individually so unrelated tasks do not wait for lease expiry and run again.
  • Keep healthy schedules moving past a broken definition (#56). A deterministic materialization failure is isolated and deferred for one minute instead of rolling back the entire batch. Failed schedule and wait sweeps also back off rather than spinning.
  • Re-arm durable waits after an administrator retry (#56). Finishing a task resolves its outstanding signal waits, and signal and child-result waits reuse stale registrations instead of failing on a duplicate key.
  • Return unfinished tasks promptly during shutdown (#58). After the grace period, workers cancel remaining handlers and release their fenced leases without consuming retry budget. Python exposes shutdown_grace; cancelling worker.run() now follows the same graceful shutdown path before re-raising CancelledError.
  • Catch up after a silent listener reconnect (#58). Workers wake their task and schedule loops when the notification connection reconnects. Result waits re-read task state, so a missed notification does not force a wait until the next poll.

🐍 Make Python failure handling explicit

  • Choose terminal failures by exception type (#72, #73). Raising pgtask.NonRetryableError, a subclass, or an exception explicitly caused by one fails the task without further retries. Nested exception groups are terminal when any member meets that rule, including groups from the exceptiongroup backport on Python 3.10.
  • Catch a step's original exception (#73). A failing task.step() raises the operation's own ordinary exception object, preserving its attributes, cause, and traceback. Handler failures also record a retryable boolean; readers must still accept older and database-generated errors without that field.
  • Distinguish retry budget from durable resumptions (#67). Task.failed_attempts exposes the failures and lease losses counted by max_attempts, while Task.attempt also counts resumptions. pgtask.TaskSuspended is now public so broad exception handlers can re-raise durable suspensions.

🧪 Keep stress tests focused on real failures

Schedule property tests now clean up their stored schedules instead of leaving a backlog that stalls later worker tests (#61). Linearizability checks deterministically cover committed writes whose replies are lost, without depending on whether a timeout beats a database round trip (#62). Administrator tests inspect their own schedule row instead of depending on the first page of shared data (#65).

The SQL mutation sweep matches the current attempt-budget expressions and tests forged lease tokens across completion, failure, sleep, waits, and spawn. Mutations that are equivalent under the existing invariants are documented and excluded from the score rather than reported as missed bugs (#70). The task-lifecycle model also covers fenced shutdown releases and separates failed attempts from claims (#58).


⬆️ Upgrading

This release adds migrations 0010, 0011, 0013, 0014, and 0015. Run migrations with the new CLI before replacing workers:

PGTASK_DATABASE_URL="$DATABASE_URL" pgtask migrate

The storage protocol remains unchanged: the database supports 1..=2, and workers require protocol 2. The migrations preserve existing SQL function signatures, so 0.3.0 and 0.4.0 workers can share the migrated database during a rolling upgrade. The Helm chart runs the migration hook before replacing worker Deployments.

Large tables: migration 0014 builds two indexes that can block writes while they are created. To avoid that build-time write lock, create them concurrently before running migrations, outside a transaction:

CREATE INDEX CONCURRENTLY IF NOT EXISTS tasks_terminal_retention_idx
    ON pgtask.tasks (queue_name, completed_at, id)
    WHERE state IN ('succeeded', 'failed', 'cancelled');

CREATE INDEX CONCURRENTLY IF NOT EXISTS result_waits_result_task_idx
    ON pgtask.result_waits (result_task_id);

Python exception handling: a step's ordinary exception is no longer wrapped in RuntimeError. Runtime-detected terminal errors, such as an invalid JSON step result or a corrupt signal checkpoint, now raise NonRetryableError instead. Update handlers that relied on catching the old wrapper. TaskSuspended remains an Exception; re-raise it before a broad except Exception around durable calls.

History readers: attempt history can now contain state = 'released', and signal-wait history can contain outcome = 'cancelled'. Rust code constructing a complete WorkerConfig literal must supply the new expired_worker_retention field.

Shutdown timing: lease release is best effort and waits at most five seconds after the grace period. Keep the pod termination grace period longer than shutdown_grace so release can run. Any lease that cannot be released still expires and consumes a failed attempt during recovery.


📦 What ships

Artifact Contents
Rust crates pgtask, pgtask-core, pgtask-postgres, pgtask-worker, pgtask-otel, pgtask-cli, pgtask-web
Python wheel Stable ABI for CPython 3.10+ on Linux, macOS, and Windows, plus a source distribution
npm @pgtask/client for Node.js 20 or newer
Go module github.com/Kludex/pgtask/sdks/go for Go 1.25 or newer
Container image ghcr.io/kludex/pgtask:0.4.0, multi-architecture, Sigstore signed
Helm chart Signed OCI chart with per-queue worker Deployments, migration Job, probes, and optional autoscaling

PostgreSQL 16, 17, and 18 are tested.


⚠️ Not ready for production

This is a preview. The engine passes its suite against real PostgreSQL and has never run a production workload. The Rust, Python, SQL, CLI, and telemetry surfaces may change before 1.0; the storage protocol range is the compatibility contract in the meantime.

Delivery is at least once. A handler can finish an external side effect and lose its lease before recording the result, so handlers must be safe to run again.


Documentation: https://kludex.github.io/pgtask/

Full changelog: v0.3.0...v0.4.0