Metadata-Version: 2.4
Name: fastpluggy-tasks-worker
Version: 0.5.0
Summary: Task Runner plugin for Fastpluggy
Author: FastPluggy Team
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: FastPluggy<1,>=0.17.0
Requires-Dist: croniter
Requires-Dist: psutil
Provides-Extra: rabbitmq
Requires-Dist: pika>=1.3.0; extra == "rabbitmq"
Provides-Extra: postgres
Requires-Dist: SQLAlchemy>=2.0; extra == "postgres"
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pytest-timeout>=2.1; extra == "dev"
Requires-Dist: testcontainers[postgres,rabbitmq,redis]>=4.0.0; extra == "dev"
Requires-Dist: redis>=5.0; extra == "dev"
Requires-Dist: psycopg2-binary>=2.9; extra == "dev"
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: httpx>=0.27; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Requires-Dist: pytest-asyncio>=0.21; extra == "tests"
Requires-Dist: pytest-timeout>=2.1; extra == "tests"
Requires-Dist: testcontainers[postgres,rabbitmq,redis]>=4.0.0; extra == "tests"
Requires-Dist: redis>=5.0; extra == "tests"
Requires-Dist: psycopg2-binary>=2.9; extra == "tests"
Requires-Dist: fastpluggy-db-purge>=1.1.4; extra == "tests"
Provides-Extra: e2e
Requires-Dist: playwright>=1.40.0; extra == "e2e"
Requires-Dist: fastpluggy-example-plugin; extra == "e2e"
Dynamic: license-file

# FastPluggy Task Runner

![Task Runner](https://img.shields.io/badge/FastPluggy-Task%20Runner-blue)
[![Release](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/tasks_worker/-/badges/release.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/tasks_worker/-/releases)
[![Pipeline Status](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/tasks_worker/badges/main/pipeline.svg?key_text=CI)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/tasks_worker/-/pipelines?ignore_skipped=true)
[![Coverage](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/tasks_worker/badges/main/coverage.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/tasks_worker/-/pipelines)

A powerful and extensible **task execution framework** for Python, built on top of [FastPluggy](https://fastpluggy.xyz).  
Register, run, monitor, and schedule background tasks over a pluggable broker (`memory`, `local`, `postgres`, `redis`, `rabbitmq`), with per-task logs, progress, locks, and an admin UI.

---

## ✨ Features

- 🔧 Task registration with metadata (`description`, `tags`, `schedule`, `topic`, `allow_concurrent`)
- 🧠 Dynamic form generation from the function signature
- 📅 CRON / interval scheduler (beat), with standby takeover and health gauges
- 🔁 Automatic retries per task (`max_retries`, `retry_delay`, `retry_backoff`, `NoRetry`), waited out in the broker, with a per-attempt history; plus manual retry from the UI, linked to the original task via `parent_task_id`
- 🔒 Non-concurrent execution and per-entity locks (`lock_key_resolver`), with a lock-conflict policy
- 🧵 Per-topic concurrency limits, drain, purge, and dead-letter queues
- 🛑 Cancellation on every broker, from the UI, the API or `TaskWorker.cancel(task_id)`; running tasks stop cooperatively at `raise_if_cancelled()`
- ⏱ Per-task timeouts (`timeout=` on `submit()` or the decorator), enforced at the same cooperative check
- 📝 Captured task logs and progress (`TaskWorker.set_task_progression`), stored with the report
- 📊 Admin UI for tasks, running tasks, schedules, locks, broker debug, and duration analytics
- 💾 Persistent task context and report (`fp_task_contexts`, `fp_task_reports`); who purges them:
  [Task history & retention](#task-history--retention)
- 📈 Prometheus gauges via the FastPluggy metrics capability (see [docs/observability.md](docs/observability.md))
- 🌳 Task trees via `parent_task_id`: chaining, fan-out and completion joins (see [docs/orchestration.md](docs/orchestration.md))
- 🔎 Auto-discovery of task definitions from loaded modules, and of the tasks and periodic tasks of a Celery app (`celery_compat`)
- 📣 Internal event bus (`TaskEventBus`) with DB, telemetry and broker-broadcast subscribers

> **Notifications** (mail, ntfy, push when a task fails) are not part of this plugin: the old notifier
> system was removed in 0.4.0 (#28). They come from notification_center rules on task events
> (open/fastpluggy/plugins/notification_center#16). Task logs are shown live on the task details page
> since 0.3.334, by polling, not WebSocket: see [`docs/live-logs.md`](docs/live-logs.md).

---

## 🛠️ How It Works

```python
from fastpluggy_plugin.tasks_worker import TaskWorker

@TaskWorker.register(
    description="Sync data every 5 mins",
    schedule="*/5 * * * *",   # cron string, or an int interval in seconds
    allow_concurrent=False,
    topic="sync",
)
def sync_data_task():
    print("Sync running...")

# Submit from code; returns the task_id
task_id = TaskWorker.submit(sync_data_task)
result = TaskWorker.wait_for_task(task_id, timeout=30)
```

Tasks with a `schedule` are registered as scheduled tasks automatically when task discovery runs
(`enable_auto_task_discovery`, on by default).

### Automatic retry

```python
from fastpluggy_plugin.tasks_worker import TaskWorker, NoRetry

@TaskWorker.register(max_retries=3, retry_delay=10, retry_backoff=2)  # up to 4 runs: +10 s, +20 s, +40 s
def sync_remote(account_id: int):
    if not account_exists(account_id):
        raise NoRetry(f"account {account_id} is gone")   # fails for good, no retry
    call_flaky_api(account_id)                             # any other exception is retried

TaskWorker.submit(sync_remote, kwargs={"account_id": 1})                  # inherits 3 / 10 s / ×2
TaskWorker.submit(sync_remote, kwargs={"account_id": 1}, max_retries=0)   # no retry this time
```

- **`max_retries`**: extra runs after the first one fails (`0` = no retry; `-1`/"for ever" is refused).
  **`retry_delay`**: seconds before the first retry. **`retry_backoff`**: multiplier per retry
  (default `1` = fixed delay). Each delay is capped at 1 h.
- **Resolution**, field by field: an explicit `submit()` argument, then the schedule's override, then
  the decorator, then the default. `None` means "not set".
- **The wait happens in the broker**, not in the worker: the failed message goes back with
  `nack(delay=…)`, so the worker slot is free meanwhile and a retry survives a worker restart on
  `postgres` / `rabbitmq`. On RabbitMQ the delay is rounded up to a delay bucket
  ([broker matrix](docs/broker/broker-matrix.md)).
- **Same task, same `task_id`**: each attempt is the same message delivered again. The report shows
  `status=retrying` between attempts, `attempts` = the current execution number, and
  `attempt_history` keeps one entry per execution (status, worker, duration, delay, error,
  traceback, logs cut to `attempt_log_max_chars`). The task details page lists them. Inside the task,
  `TaskContext.attempt` is the 1-based execution number.
- **Not retried:** `NoRetry`, a task function that cannot be imported, a lost lock (requeued without
  spending an attempt), a cancellation. After the last attempt the task is `FAILED` with
  `reason=retries_exhausted`, and the message is acked (no dead-letter).
- **Scheduled tasks** inherit the decorator; the schedule edit page can override the three values
  (empty field = inherit).
- **At-least-once**: a retried task runs again from the start, so make side effects idempotent.
- **Worker crashes count as attempts**, and the orphan reaper dead-letters an orphaned message after
  `orphan_max_attempts` claims (default 5). For tasks with more retries than that, raise
  `orphan_max_attempts` above `max_retries + 1`.
- **A worker that cannot process a message at all** (the handler itself raises: unreadable payload,
  database down while reporting — not the task failing) requeues it hidden for 1 s, 2 s, 4 s…
  (capped at 60 s), then after `handler_error_max_attempts` deliveries (default 5, plus the task's
  own `max_retries`) dead-letters it and marks the task `FAILED` with `reason=handler_error`.
  Before 0.3.322 it was requeued at once, forever: a hot loop (#48).

### Cancellation

```python
from fastpluggy_plugin.tasks_worker import TaskWorker, raise_if_cancelled

@TaskWorker.register(description="Render every page of a report")
def render_report(report_id: int):
    for page in pages(report_id):
        raise_if_cancelled()      # stops here once a cancel was requested
        render(page)

TaskWorker.cancel(task_id)        # or the Cancel button, or POST /api/task/{id}/cancel
```

- **Queued**: removed from the broker, it never runs (`cancelled`, HTTP 200). On RabbitMQ a queue
  cannot be edited, so the request is spread to every node and the worker that claims it drops it.
- **Held by a worker** (claimed and waiting for a slot, or running): a cancel request is recorded
  (`cancel_requested`, HTTP 202). The worker drops it before it starts; a running task stops at its
  next `raise_if_cancelled()` (or reads `is_cancel_requested()`). A thread cannot be killed: a task
  that never checks runs to its end, and the admin page shows it as "cancel requested".
- A task cancelled after it failed is not retried. Details per broker in
  [docs/tasks-page.md](docs/tasks-page.md#cancel).
- **Timeouts** use the same check: give a task `timeout=` (on `submit()` or the decorator, or
  `default_task_timeout_seconds` for the worker) and past it `raise_if_cancelled()` raises
  `TaskTimedOut` and the report ends `timeout`. See [docs/task-timeouts.md](docs/task-timeouts.md).

### Stopping a process that runs workers (SIGTERM)

When a process that runs workers exits (an app that embeds them with `start_workers_if_available()`
and stops on SIGTERM through uvicorn, the `fastpluggy tasks-worker start` CLI, or the end of
`main`), each worker:

1. stops claiming; the messages it holds but has not started go back to the broker (they never
   ran, so the next worker runs them);
2. waits at most **`worker_shutdown_max_wait_seconds`** (default `0`, env
   `WORKER_SHUTDOWN_MAX_WAIT_SECONDS`, must be >= 0) for its running tasks to finish on their own:
   no cancellation is asked, a task that ends in time ends `success` or `failed` as usual, and the
   process leaves as soon as the last one ended. It logs at INFO how many tasks it waits for and
   until when. `0` skips this step;
3. asks the tasks still running to stop: `raise_if_cancelled()` raises and the report ends
   `cancelled` ("the worker shut down while the task ran");
4. waits for them at most **`worker_shutdown_grace_seconds`** (default 8 s, env
   `WORKER_SHUTDOWN_GRACE_SECONDS`). A task still running then is closed `cancelled` ("still
   running … the process exited without waiting for it"), the `atexit` hooks run (worker
   unregistered, `fp-brokerd` stopped), and the process exits with code 0 without that task's
   thread, which cannot be killed.

**A task cancelled by the shutdown (step 3 or 4) is not replayed**: its message is acknowledged.
A run cut short may already have done part of its work (an e-mail sent, a payment posted, a file
half written), and running it again from the start would repeat it; a task that brings its worker
down (memory, a crash) would also be replayed at every restart, forever. A task that is safe to run
again (idempotent) asks for the replay at registration:

```python
@TaskWorker.register(requeue_on_shutdown=True)   # default False
def rebuild_search_index():
    ...
```

Its message then goes back to the broker for the next worker, and the report says so ("…;
requeue_on_shutdown: its message went back to the queue"). On a broker that keeps its queue
outside the process (`postgres`, `rabbitmq`, `redis`), the next worker to start runs it again: the
process exits only once its dispatchers have ended, so the message is back in the queue, never left
claimed by the worker that stopped (which only the beat's orphan reaper would hand back).

**Stop timeout.** The stop can take up to max wait + grace (+ about a second for the exit hooks).
Docker sends SIGKILL 10 s after SIGTERM by default, systemd after `TimeoutStopSec` (90 s by
default): set them above that total, or the process is killed mid-way, reports left `running`.
With the defaults (0 + 8 s) Docker's 10 s are enough. With a max wait, for example in Compose:

```yaml
services:
  app:
    environment:
      WORKER_SHUTDOWN_MAX_WAIT_SECONDS: "60"   # let running tasks finish for up to 60 s
      WORKER_SHUTDOWN_GRACE_SECONDS: "8"       # then cancel, and wait 8 s more at most
    stop_grace_period: 75s                     # above 60 + 8; Docker's default is 10 s
```

(`docker stop -t 75`, Kubernetes `terminationGracePeriodSeconds: 75`, systemd
`TimeoutStopSec=75`.)

`start_workers_if_available()` also makes SIGTERM a normal exit when nothing handles it yet (default
action, main thread), so the steps above run. uvicorn hands the SIGTERM it caught back to the
previous handler once it stopped; with the default action that killed the process on the spot (no
`atexit`, reports left `running`), except as pid 1 in a container, where it does nothing.

With the `memory` and `local` brokers the queue lives in the process (in `fp-brokerd` for `local`)
and is lost with it: the exit logs, as a WARNING, `N queued message(s) of <topic> are lost`.

Further reading:

- [docs/README.md](docs/README.md): index of all technical docs.
- [Broker matrix](docs/broker/broker-matrix.md): which broker gives which guarantees.
- [Orphan recovery](docs/broker/orphan-recovery.md): how a dead worker's in-flight messages are
  recovered, and why an unreaped one silently wedges a topic's concurrency.
- [Jinja template globals](docs/jinja_template_globals.md): `task_submit_url` and the JS globals for
  triggering tasks from a page.

---

## 📋 Roadmap

What is planned is in [ROADMAP.md](ROADMAP.md), the only roadmap of this repository.

---

## Standalone Worker

Run task workers as a standalone long-running process, independent of the FastAPI dev server:

```bash
# Worker only (consumes and executes tasks)
fastpluggy tasks-worker start

# Worker + scheduler (beat) — simple setups, dev
fastpluggy tasks-worker start --beat

# Standalone scheduler (recommended for production)
fastpluggy tasks-worker beat

# Use RabbitMQ in production
fastpluggy tasks-worker start --broker-type rabbitmq --broker-dsn amqp://user:pass@rabbit:5672/

# Consume only specific topics with 4 threads per worker
fastpluggy tasks-worker start --topics email,reports --max-workers 4

# Verbose logging for debugging
fastpluggy tasks-worker start --log-level DEBUG

# Multiple workers with PostgreSQL broker
fastpluggy tasks-worker start -n 3 --broker-type postgres --broker-dsn postgresql+psycopg2://localhost/tasks

# Redis or Valkey broker (pip install "fastpluggy-tasks-worker[redis]")
fastpluggy tasks-worker start -n 3 --broker-type redis --broker-dsn redis://localhost:6379/0

# Inspect: registered workers, and the effective broker configuration
fastpluggy tasks-worker workers
fastpluggy tasks-worker info
```

The process blocks until interrupted with `Ctrl+C` or `SIGTERM`, then performs a graceful shutdown
(running tasks: see [Stopping a process that runs workers](#stopping-a-process-that-runs-workers-sigterm)).

### RabbitMQ vhost auto-creation

When using the RabbitMQ broker, the worker automatically creates the vhost specified in the DSN if it does not already exist. This uses the RabbitMQ Management HTTP API (port 15672) and grants full permissions to the connecting user. If the management API is unreachable (not exposed, firewalled, or the user lacks admin rights), the check is silently skipped — the worker will connect normally if the vhost already exists, or fail with a clear error if it doesn't.

### Production deployment

For production, run the scheduler (beat) and workers as separate processes:

```bash
# One beat process — reads scheduled tasks from DB, submits when due
fastpluggy tasks-worker beat --broker-type rabbitmq --broker-dsn amqp://...

# N worker processes — consume and execute tasks
fastpluggy tasks-worker start -n 4 --broker-type rabbitmq --broker-dsn amqp://...
```

A worker holds at most **`worker_prefetch`** messages at once: running, or claimed and waiting for a
thread. `0` (the default) means its pool size, so it never claims what it cannot start, and the next
worker gets the rest (#49). Set it a little above the pool to hide claim latency. On RabbitMQ it also
bounds the consumer prefetch (the sum of this process's workers, and the topic's own limit if lower),
where it used to be 32 per topic.

An administrator can change the **slots** of a live worker (how many tasks it runs at once) from
the Workers & queues page: the worker's Info dialog, or its own page, has a Slots field; scripts use
`POST /api/broker/workers/{worker_id}/capacity?capacity=N` (no `capacity` = back to the start
value). The request goes through the broker, the worker applies it at its next heartbeat (a few
seconds), and the page shows "N requested" until then. A lower count stops no running task: it takes
effect as they finish. The request ends with the worker: a restart starts from `-n` / `max_workers`
again. With the default `worker_prefetch` the claim budget follows the new count; an explicit
`worker_prefetch` stays as configured (#131).

#### Beat resilience (standby takeover, ≥0.3.288)

Only one beat runs at a time (a dedup guard skips beat startup when a live beat registration
exists). Since 0.3.288 that guard is no longer one-shot: a worker that skipped beat keeps
**standing by** — it re-runs the guard every `beat_standby_poll_seconds` (default 15s) and takes
over the moment no live beat remains (claim, then smallest-live-beat-`worker_id`-wins verify, so
concurrent standbys can't double-start). This fixes the container-recreate race (#14) where the
successor booted seconds after the dying beat's last heartbeat, saw it as "live", skipped beat
permanently — and every scheduled task silently stopped until the next restart. Opt out with
`beat_standby_enabled=false`.

A standalone beat (`fastpluggy tasks-worker beat`, `TaskWorker.start_beat()`) stands by the same
way since 0.3.390 (#60): it stays in the foreground, prints that it waits for the live beat to go
away, and takes over through the same claim and tie-break. Two beat containers thus relay each
other. With `beat_standby_enabled=false` the command exits with code 1 instead.

#### Starting the beat from the app entrypoint (`start_beat`)

An app that boots its workers with `start_workers_if_available()` (the generated entrypoint) starts
the beat only when **`start_beat`** is true: `START_BEAT=1` in the environment of exactly one worker
process, or the plugin setting. It defaults to **false**, so an app that sets neither has no
scheduler, and no schedule ever fires.

That state is logged (#45). A worker started without the beat checks, 60 s after boot and then
every `beat_absence_warn_seconds` (default 300; `0` turns it off), that a live beat runs
somewhere. While none does and schedules are enabled, it logs at WARNING:

```
3 enabled scheduled task(s), but no beat scheduler runs anywhere: they will NOT fire. Start exactly one beat: ...
```

The pre-2025 opt-in `TasksWorkerSettings.beat_enabled` (a settings row nothing had read since
2025) is migrated once at boot: `true` becomes `start_beat=True` unless `start_beat` is already
set, and the old row is deleted. An env `START_BEAT` still overrides it per process.

#### Monitoring the scheduler

Two gauges ship via the FastPluggy metrics capability (aggregator route):

- `fastpluggy_broker_beats` — live beat-role workers. **0 with enabled schedules = scheduler dead;
  alert on it.**
- `fastpluggy_schedule_overdue_seconds` — worst `now − expected_next_run` across enabled schedules
  (0 = on time). Catches both a dead beat and a single wedged schedule, cron or interval.

The **Schedules** page (sidebar entry) shows every schedule with its state and its latest runs:

| State | Meaning |
|---|---|
| Healthy | On time, and the last finished run did not fail |
| Failing | Last finished run failed, or the beat fired it but no run was ever recorded |
| Late | More than 1 min past its expected next run (the beat polls every `scheduler_frequency` s) |
| Never ran | Never fired yet (a cron schedule waits for the first time its cron names, see [When a schedule starts](docs/schedules-page.md#when-a-schedule-starts)), or just fired and still queued |
| Disabled | `enabled = false`; listed last, no next run |

The success rate is the share of *finished* runs (the last 25 by default) that succeeded; queued
and running runs are not counted. Times are shown in the browser's local time zone; cron
expressions are read as UTC. Without stored history (`store_task_db` off) the page only tells
whether the beat triggers each schedule. See [docs/schedules-page.md](docs/schedules-page.md).

#### Upgrading from < 0.3.326: repair the report history once

Before 0.3.326 reports were never closed, and the watchdog of each new container rewrote every
report of the previous containers to `dead` (#46). After upgrading, run the task
**`maintenance.repair_report_history`** once (Run now in the task list, or
`TaskWorker.submit(repair_report_history)` from `fastpluggy_plugin.tasks_worker.tasks.repair_reports`):

- a `dead` report with the old watchdog message and a `duration` had finished: it goes back to
  `success`, or `failed` if it recorded an error. Its original result is lost. Reports without a
  duration really died and stay `dead`;
- final reports still open get `finished=true`.

It works in batches of `batch_size` (2000), each committed on its own, and never runs twice at
once. A crash loses nothing: rerun it and it resumes. `max_batches` caps one run; the result
`{restored, closed, remaining}` says whether another run is needed.

#### Reports left `running` by a dead worker (≥0.3.332)

A worker that dies mid-task never writes its final status, so its report stays
`running`. The beat now closes these reports every `watchdog_interval_seconds`
(600 s), with no schedule to add. A report is judged by its worker's heartbeat,
never by age, so long-running daemon tasks of live workers are left alone. On
upgrade, the first pass also clears the backlog of old ones, in batches. Details
and settings: [`docs/broker/orphan-recovery.md`](docs/broker/orphan-recovery.md#the-report-side-the-watchdog-55).

### Task history & retention

With `store_task_db` on (the default), every task writes one row in each of two tables, and
**tasks_worker never deletes them**:

| Table | What it holds | Purge on | Grows by |
|---|---|---|---|
| `fp_task_reports` | status, result, logs, error and attempt history of each task | `end_time` | one row per task |
| `fp_task_contexts` | function, arguments and options of each task | `created_at` | one row per task |
| `fp_task_schedule` | the scheduled tasks (cron, interval, enabled) | **never** | one row per schedule |

`fp_task_schedule` is configuration, not history. Its only timestamp is the last run: purging on it
deletes the schedules that have not run lately.

#### Report writes per task (`store_claim_reports`)

A successful task writes its report 4 times: `created` and `queued` when a worker takes the
message, then `running` and `success`. The first two come a few milliseconds before `running`,
in the same thread. A task waiting in the broker has no report row either way: `submit()` writes
only its context, and the Active tab and the Overview read waiting tasks from the broker.

`store_claim_reports` is on by default. For an app that runs many short tasks,
`store_claim_reports=false` (env `STORE_CLAIM_REPORTS`) skips those two writes. `running` then writes the first report, with the same `enqueued_at`.
Measured in one process (memory broker, 1 executor, no-op tasks, #91):

| Reports in | 4 writes (default) | 2 writes |
|---|---|---|
| PostgreSQL 18 | 97 to 102 tasks/s, 9.3 ms CPU per task | 120 to 126 tasks/s, 6.7 ms |
| SQLite, WAL (FastPluggy 0.4.114) | 155 to 158 tasks/s, 7.0 ms | 182 to 192 tasks/s, 5.4 ms |

What is lost: a worker that dies or hangs inside its lock attempt leaves no `created` row behind.
The broker still shows the message as taken by that worker, and its orphan recovery requeues it.
A busy lock still writes its own `skipped` or `rejected` report.

Retention belongs to the [`db_purge`](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/db_purge)
plugin (0.1.8 or later). Pick one:

- **With `db_purge` installed.** At load, tasks_worker declares the two history tables to it (the
  columns above, 30 days) and excludes `fp_task_schedule`. That deletes nothing yet. Two things are
  off until an admin turns them on, on the DB Purge page:
  1. the rule of each table, created disabled so that declaring a table never deletes its data;
  2. the scheduled purge (`auto_purge_enabled`, off by default; daily at 04:00 UTC once on). It is
     a scheduled task of tasks_worker (`db_purge_all`), so it needs a running beat.
- **Without `db_purge`.** The two tables grow for ever and purging them is yours, for example:

  ```sql
  DELETE FROM fp_task_reports  WHERE end_time   < now() - interval '30 days';
  DELETE FROM fp_task_contexts WHERE created_at < now() - interval '30 days';
  ```

  (PostgreSQL syntax; delete in batches on a large table.)

The admin says when the history is not being purged, in its advisories (badge, Advisories page,
plugin pages): the core when `db_purge` is not loaded (tasks_worker declares it in
`integrates_with`, and its `companion_reasons` makes the advisory say that the task history is
never purged), and `db_purge` itself (1.2.5 or later) when a history table's rule is not
enabled or the scheduled purge is off. A table you **excluded** in DB Purge is your decision and is
not reported.

A report whose task never finished has no `end_time` and is never purged on that column. The beat
closes the reports of dead workers (above), which gives them one.

### Options

| Option | Commands | Description |
|--------|----------|-------------|
| `-n`, `--workers` | `start` | Number of workers to start (default: `$WORKER_NUMBER` or 1) |
| `--beat` | `start` | Also start the scheduler alongside workers |
| `--broker-type` | `start`, `beat`, `workers` | Broker backend: `local`, `memory`, `rabbitmq`, `postgres`, `redis` (overrides `$BROKER_TYPE`) |
| `--broker-dsn` | `start`, `beat`, `workers` | Broker connection string (overrides `$BROKER_DSN`) |
| `--topics` | `start` | Comma-separated list of topics to consume (default: all) |
| `--max-workers` | `start` | Thread pool size per worker (default: 8) |
| `--log-level` | `start`, `beat` | Logging level: `DEBUG`, `INFO`, `WARNING`, `ERROR` (default: `INFO`) |

### Topic Routing

Topics determine which queue tasks are published to and consumed from. Resolution order:

1. **`FORCE_TASK_TOPIC`** — if set, overrides everything. Both publish and consume use this value.
2. **Explicit `topic=` argument** — passed to `TaskWorker.submit(my_task, topic="email")`.
3. **Function metadata** — set via `@TaskWorker.register(topic="reports")`.
4. **`DEFAULT_TOPIC`** — fallback (default: `"default"`).

| Setting | Env var | Description |
|---------|---------|-------------|
| `default_topic` | `DEFAULT_TOPIC` | Fallback topic for publish and consume (default: `"default"`) |
| `force_task_topic` | `FORCE_TASK_TOPIC` | Hard override — locks both publish and consume to this value |

**Examples:**

```bash
# Pin a worker to a specific queue (useful for dedicated workers or debugging)
FORCE_TASK_TOPIC=gpu-worker fastpluggy tasks-worker start

# Two workers on the same machine, each consuming a different queue
FORCE_TASK_TOPIC=worker-a fastpluggy tasks-worker start &
FORCE_TASK_TOPIC=worker-b fastpluggy tasks-worker start &

# Normal mode — worker consumes all topics, tasks route via metadata or default
fastpluggy tasks-worker start
```

---

## 🔔 Notifications on failure

tasks_worker never sends a message itself: it says on the app's event bus how each task ended, and a notification plugin's rules decide who is told and how.

| Event | When | Payload |
|-------|------|---------|
| `tasks_worker.task_failed` | a task failed for good: `failed` (after its retries), `error`, `timeout`, or `dead` (the watchdog found its worker gone) | `title`, `message`, `task_id`, `task_name`, `function`, `topic`, `origin`, `schedule_id`, `status`, `reason`, `error`, `attempt`, `url` |
| `tasks_worker.task_succeeded` | a task ended well | same fields |

A retry, a cancellation or a refusal emits nothing. `url` is the path of the task's page; `error` is cut at 1000 characters (the page has the whole traceback). Both events declare `key=["function"]`: a rule's anti-spam delay counts per function, and a success after a failure ends it (the "recovered" message). They are emitted in the process that ran the task, so the notification plugin must be loaded in the worker process too: each worker says in its heartbeat whether a listener of its process hears them (`task_ends_heard`), and when a rule watches a schedule, the Schedules page names the live workers that hear nothing, where those rules never fire. A worker older than 0.4.3 says nothing and is not named.

With notification_center (0.4.1+) loaded, the **Schedules** page shows it: a bell next to a schedule a rule watches (red while that rule is failing), *Rule: <name>* or *Notify on failure…* in its ⋯ menu, and a *Notifications* section in its side panel. *Notify on failure…* (admins only) opens a new rule already set on `tasks_worker.task_failed` for that function. Without a notification plugin, the page shows none of it.

## 🔐 Authentication and roles

Every route of the plugin (API, admin pages, debug actions, scheduler, monitoring) requires an
authenticated user when the FastPluggy app has an `auth_manager`. `get_router()` mounts all routers
under one parent carrying `require_authentication`, so a new router is covered automatically (#27).
Apps without an `auth_manager` stay open, which is FastPluggy's normal behaviour.

Signing in is not enough: the plugin answers administrators (the `fp_admin` role).

| | Signed in, not an administrator | Administrator |
|---|---|---|
| Read: pages, read APIs, logs | 403 by default; allowed with `allow_read_only_access_to_all` | allowed |
| Act: submit, retry, cancel, purge, drain, release a lock, change a schedule | 403, whatever the setting | allowed |

- **`allow_read_only_access_to_all`** (plugin settings, default off) opens reading to every
  signed-in user: the menu entries appear and the pages are drawn without their action buttons.
- **Submitting a task from a page** (`submitTask()`, the `TaskRunButton` widget) is an action:
  administrators only. Anybody else gets a 403, and the helper says so in its notification.

Details, limits and how it is tested: [docs/access.md](docs/access.md).

---

## 🧪 Testing

This plugin includes comprehensive test coverage with pytest.

### Running Tests Locally

```bash
# Install development dependencies (CI installs ".[tests,postgres]")
pip install -e ".[dev,postgres,rabbitmq]"

# Run all tests (Postgres/RabbitMQ/Redis broker tests start testcontainers, so Docker is needed)
pytest tests/

# Run tests with coverage report
pytest tests/ --cov=src --cov-report=term-missing

# Run one file
pytest tests/brokers/test_local.py -v

# Lint (pyflakes and ASYNC rules, configured in pyproject.toml) - the `ruff` CI job runs the same command
ruff check src tests benchmarks
```

Every test has a 120 s deadline (`pytest.ini`, #25); see `CLAUDE.md` before changing it.

### CI/CD Integration

`run_tests` runs on merge requests and on `main`, with a 55% coverage floor. `ruff` fails the
pipeline on an unused import or variable, an undefined name, or a blocking call inside `async def`. A Playwright e2e job
(`e2e/`) drives the admin UI against the `memory` broker and refreshes `docs/screenshots/e2e/`.
Merging a `pyproject.toml` version bump to `main` tags and publishes the release.

---

## 📦 Tech Stack

- FastAPI + FastPluggy
- SQLAlchemy + SQLite/PostgreSQL
- Jinja2 + Bootstrap (Tabler)
- Brokers: in-process memory, multiprocessing `BaseManager` (local), PostgreSQL, Redis/Valkey (redis-py), RabbitMQ (pika)

---

## 🧠 Philosophy

This runner is built to be:

- **Introspective**: auto-generate UIs from functions
- **Composable**: integrate with your FastPluggy app
- **Scalable**: support single-machine and multi-worker environments
- **Extensible**: event-bus subscribers, pluggable brokers, message converters, CRON

---

## 📎 License


Released under the MIT License, see [LICENSE](LICENSE).

## 🚀 Contributions Welcome!

Open issues, send PRs, share ideas —  
Let’s build the most pluggable Python task runner together.

### Database support
The models use the generic SQLAlchemy `JSON` type, so the plugin runs on both SQLite and PostgreSQL.
CI runs without `DATABASE_URL`, i.e. on FastPluggy's SQLite fallback, apart from the broker tests
that start a PostgreSQL testcontainer. The `postgres` **broker** needs PostgreSQL.
