Metadata-Version: 2.4
Name: fastpluggy-tasks-worker
Version: 0.3.352
Summary: Task Runner plugin for Fastpluggy
Author: FastPluggy Team
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: FastPluggy<1,>=0.4.95
Requires-Dist: fastpluggy-crud-tools>=0.2.12
Requires-Dist: croniter
Requires-Dist: psutil
Requires-Dist: python-dateutil>=2.9.0
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: dev
Requires-Dist: pytest>=7.0; 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]>=4.0.0; extra == "dev"
Requires-Dist: psycopg2-binary>=2.9; extra == "dev"
Provides-Extra: tests
Requires-Dist: pytest>=7.0; 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]>=4.0.0; extra == "tests"
Requires-Dist: psycopg2-binary>=2.9; extra == "tests"
Provides-Extra: e2e
Requires-Dist: playwright>=1.40.0; extra == "e2e"
Requires-Dist: fastpluggy-example-plugin; extra == "e2e"

# 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`, `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`)
- 📈 Prometheus gauges via the FastPluggy metrics capability (see [docs/observability.md](docs/observability.md))

> **Not implemented today:** notifications (#28). 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/running-tasks-page.md](docs/running-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).

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

### ✅ Completed / In Progress

- [x] Task registration with metadata (`description`, `tags`, `schedule`, `topic`, `allow_concurrent`)
- [x] Dynamic task form rendering via metadata
- [x] Internal event bus (`TaskEventBus`) with DB, telemetry and broker-broadcast subscribers
- [x] Context/report tracking in DB
- [x] Task trees via `parent_task_id` (retry linking + pipeline chaining / fan-out / completion joins — see [docs/orchestration.md](docs/orchestration.md))
- [x] CRON-based scheduler loop
- [x] Web UI for:
  - Task logs
  - Task reports
  - Scheduled tasks
  - Locks
  - Running tasks: server-side filters (name, status, topic, worker), sort, pagination, live refresh ([docs](docs/running-tasks-page.md))
- [x] Broker-level task locks (per task or per entity via `lock_key_resolver`), with a force-release UI
- [x] Cancel, per task or on a selection, on every broker: queued tasks are removed, held ones dropped before they start or stopped cooperatively (#31)

---

### 📌 Upcoming Features

#### 🔁 Task Queue Enhancements
- [ ] Notifications on task events (#28)
- [x] Live task logs on the details page, polled while the task runs (#287, 0.3.334)
- [ ] Priority & rate-limit execution
- [ ] Per-user concurrency limits
- [ ] Task dependencies / DAG runner

#### 🧠 Task Registry & Detection
- [x] Auto-discovery of task definitions from modules
- [x] Celery-style shared task detection


#### 💾 Persistence & Rehydration
- [x] Save function reference + args for replay/retry
- [x] Task dependency tree and retry visualization

#### 🌐 Remote Workers
- [ ] Register and manage remote workers
- [ ] Assign tasks based on tags/strategies
- [x] Remote heartbeat & health monitoring

#### 📈 Observability
- [x] Prometheus gauges for broker, scheduler and task telemetry
- [ ] Per-task resource metrics via `psutil` (CPU, memory, threads)
- [ ] UI views for thread/process diagnostics

---

## 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

# 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.

### 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.

#### 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`.

#### 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 **Scheduled Monitoring** page (sidebar entry, also linked from the Dashboard; only mounted
when `store_task_db` is on) shows every schedule with its last runs:

| Status | Meaning |
|---|---|
| Operational | Last finished run succeeded and the schedule is on time |
| Issues | 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) |
| Waiting for first run | Never fired yet, or just fired and still queued |
| Disabled | `enabled = false`; listed last, no next run |

Uptime is the share of *finished* runs (last N, "Reports per task") that succeeded; queued and
running runs are not counted. Times are shown in the browser's local time zone.

#### 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).

### 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` (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
```

---

## 🔐 Authentication

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.

---

## 🧪 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 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, 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

MIT – Use freely and contribute 💙

---

## 🚀 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.
