Metadata-Version: 2.4
Name: fastpluggy-db-purge
Version: 1.2.7
Summary: Centralized database retention management and purge plugin for FastPluggy
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: FastPluggy<1,>=0.5.3
Requires-Dist: sqlalchemy>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Requires-Dist: fastpluggy-tasks-worker; extra == "tests"
Requires-Dist: psycopg2-binary>=2.9; extra == "tests"
Requires-Dist: fastpluggy-metrics>=0.1.5; extra == "tests"
Provides-Extra: e2e
Requires-Dist: fastpluggy-cli; extra == "e2e"
Requires-Dist: playwright>=1.40.0; extra == "e2e"
Dynamic: license-file

# fastpluggy-db-purge

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

Centralized database retention management and purge plugin for FastPluggy.

## Features

- Auto-discover all database tables with row counts and sizes
- Per-table retention policies via admin UI
- Plugin-declared purge targets via `fp_purge_targets` hook — declaring a
  table upserts a **disabled** rule an admin enables to validate (see below)
- Manual and scheduled purge with batched deletes
- Full audit trail of purge operations
- Prometheus metrics through the `metrics` plugin (rows deleted, runs, duration, stalled purges, suspended tables)
- Two guards on the purge that runs by itself: a table that keeps failing is suspended, the table
  of a plugin that is not loaded is skipped (see [Guards](#guards-of-the-purge-that-runs-by-itself))

## Installation

```bash
pip install fastpluggy-db-purge
```

## Configuration

| Setting | Default | Description |
|---------|---------|-------------|
| `default_retention_days` | 30 | Global fallback retention |
| `default_timestamp_column` | `updated_at` | Global fallback timestamp column |
| `batch_size` | 5000 | Rows per DELETE batch |
| `auto_purge_enabled` | False | Enable scheduled purge |
| `auto_purge_cron` | `0 4 * * *` | Cron schedule (daily 4am UTC) |
| `max_consecutive_failures` | 3 | Failed runs in a row after which a table is suspended (0 = retry for ever) |

## The scheduled purge on the dashboard

`auto_purge_enabled` is only half of what decides whether the scheduled purge runs: its schedule
is a tasks_worker schedule (`db_purge_all`), which an admin can disable or delete on the Schedules
page, and nothing starts it without a beat process. The dashboard shows what will really happen,
under the global defaults:

| The line says | Meaning | What to do |
|---|---|---|
| the cron expression, **Next run** (date, UTC, and in how long), **Last run** with a link to its task | it is scheduled | nothing |
| Next run: **due now** | tasks_worker starts it at its next tick: a time its cron names has passed without a start (no beat was running then) | nothing |
| **No beat process runs** | scheduled, but no tasks_worker beat is alive to start it | start a worker with the beat |
| On, but its schedule is **disabled** on the Schedules page | the setting is on, the tasks_worker schedule is off | switch auto-purge off and on |
| On, but tasks_worker **has no schedule** for it | the schedule was deleted | switch auto-purge off and on |
| On, but ... **is not a cron expression** | `auto_purge_cron` cannot be read | correct the setting |
| On, but **tasks_worker is not loaded** | nothing can run a schedule | install or enable tasks_worker, or run purges from the page |
| **Off** | the setting is off | - |

What to know:

- **Switching the scheduled purge on starts no purge**: tasks_worker starts a cron schedule at the
  times its cron names only, the first one after it was switched on. Use "Purge All" for a purge
  now.
- "Last run" is the last start by the scheduler. A purge started by hand ("Run now", "Purge All")
  is not a scheduled run and does not move it. What each run did is in the purge history.
- The line is read when the page is loaded; it does not refresh by itself.

## Declaring purge targets from another plugin

A plugin can declare its own tables as purgeable from its `on_load_complete()`:

```python
from fastpluggy_plugin.db_purge.hooks import register_purge_target

register_purge_target("task_reports", "end_time", default_retention_days=30)
```

This does two things:

1. Registers the table + declared defaults in the in-memory registry, so it
   shows on the DB Purge dashboard (marked *declared by plugin*).
2. Upserts a persistent rule in `fp_purge_rules`, created **disabled**. An admin
   must enable it in the web UI before anything is deleted — a validation gate,
   so declaring a table can never silently purge its data.

If the plugin later changes what it declares (timestamp column or retention),
the rule is refreshed and **re-disabled** for the admin to re-validate.
Provenance is tracked by a `declared_hash` column: plugin-managed rows carry the
hash; admin-created rows have `declared_hash = NULL` and are never touched by the
hook.

To exclude a config/system table from purge entirely:

```python
from fastpluggy_plugin.db_purge.hooks import register_purge_excluded

register_purge_excluded("my_plugin_config")
```

### Asking what will happen to a table

Installing db_purge does not purge a declared table: its rule waits for an admin,
and the scheduled purge is off by default. A plugin can ask, to say so on its own
pages:

```python
from fastpluggy_plugin.db_purge.hooks import purge_status

purge_status("task_reports", "task_contexts")
# {"auto_purge_enabled": False,
#  "tables": {"task_reports":  {"state": "disabled", "retention_days": 30},
#             "task_contexts": {"state": "undeclared", "retention_days": None}}}
```

| `state` | Meaning |
|---|---|
| `enabled` | An admin enabled the rule: rows older than `retention_days` go when a purge runs. |
| `disabled` | The rule exists and waits for an admin. Nothing is deleted. |
| `excluded` | The table is never purged (an admin's or a plugin's choice). |
| `undeclared` | No rule. |

It is a read: it declares and changes nothing, and it answers before db_purge has
loaded. With `auto_purge_enabled` off, an enabled rule only applies when an admin
runs a purge by hand.
Without a table name it reports every table that has a rule.

### What the admin is told

db_purge says itself, in the core advisories (admin badge, Advisories page, plugin
pages), when a declared table is never purged:

| Id | When |
|---|---|
| `db_purge.rules_not_enabled:<hash>` | plugins declared tables whose rules are disabled or were deleted: one line for all of them, naming the first five; the hash names the set, so a dismissal holds until a table joins or leaves it |
| `db_purge.auto_purge.off` | rules are enabled but the scheduled purge is off |

Both are `warning`, category `config`, and can be dismissed. An excluded table is a
decision and is not reported. A plugin that stores history declares it with
`register_purge_target()` and has nothing more to do; when db_purge is not loaded the
core says so for every plugin that lists it in `integrates_with`.

## Guards of the purge that runs by itself

The scheduled purge and "purge all" run every enabled rule without anybody watching. Two guards
make them leave a table alone. Each time, the run writes a `skipped` row in the history with the
reason, and the dashboard shows a badge next to the rule.

| Guard | When | Badge | Way out |
|---|---|---|---|
| A table that keeps failing | its last `max_consecutive_failures` purges all failed (3 by default) | Suspended | Remove the cause, then run a purge of that table from the page. A purge that succeeds lifts the suspension. |
| The table of a plugin that is not loaded | a plugin declared the table (`register_purge_target`) and has not declared it since this process started | Plugin not loaded | Reinstall the plugin, or delete the rule and create your own. |

What to know:

- **A purge of one table run by an admin is never held back.** It is how a suspended table is tried
  again, and how a table left behind by a removed plugin is emptied on purpose.
- **Correcting a rule does not lift a suspension**: nothing proved yet that the correction works.
  The purge by hand does. A dry run does not count either way.
- **Only real, finished runs count** in the series of failures: dry runs, skipped runs and runs
  still `running` are ignored.
- **"Not loaded" is decided in the process that runs the purge**, from what plugins declared since
  it started. The task worker loads the plugins like the web app does. A plugin disabled from the
  admin pages keeps its declaration until that process restarts.
- Rules an admin created are not tied to a plugin: the second guard never applies to them.

## Observability

### Audit Trail

All purge runs (manual, scheduled, and dry-run) are logged to `fp_purge_logs`:

```sql
-- Recent purges
SELECT table_name, rows_deleted, duration_ms, status, executed_at, executed_by
FROM fp_purge_logs
ORDER BY executed_at DESC LIMIT 20;

-- Failed purges
SELECT table_name, error_message, executed_at
FROM fp_purge_logs
WHERE status = 'error'
ORDER BY executed_at DESC;

-- Stalled purges (running, no progress for 1 hour)
SELECT table_name, executed_at, updated_at, executed_by
FROM fp_purge_logs
WHERE status = 'running' AND COALESCE(updated_at, executed_at) < NOW() - INTERVAL '1 hour';

-- Tables a run left alone, and why (see Guards)
SELECT table_name, error_message, executed_at
FROM fp_purge_logs
WHERE status = 'skipped'
ORDER BY executed_at DESC;
```

`status` is `running`, `success`, `error` or `skipped`. A skipped row deleted nothing; its
`error_message` holds the reason.

### Events

| Event | When | Payload |
|---|---|---|
| `db_purge.table_suspended` | the failed run that reaches `max_consecutive_failures` on a table. Once per series of failures, not at each run that then skips the table. | `table`, `failures`, `error` (the last error) |

The same moment is also emitted as `notification.create` (`title`, `message`,
`category="warning"`, `data={"table": ...}`), the convention a notification plugin listens to when
one is loaded. With no listener, both do nothing.

Events are emitted in the process that ran the purge, usually a task worker, and heard by the
listeners registered in that same process.

### Metrics

The plugin declares the `metrics` capability. When the
[`metrics`](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/metrics) plugin
(>= 0.1.5, for histogram exposition) is installed and enabled, it serves these
series on its Prometheus endpoint (`/plugin-pkg/metrics/api/prometheus`). The
plugin adds no route of its own.

| Metric | Type | Labels | Meaning |
|--------|------|--------|---------|
| `fp_db_purge_rows_deleted_total` | counter | `table` | Rows deleted, including the committed batches of a failed or still-running purge |
| `fp_db_purge_runs_total` | counter | `table`, `status` | Finished purges, `status` = `success` or `error` (skipped runs are not counted) |
| `fp_db_purge_duration_seconds` | histogram | `table` | Duration of finished purges (buckets 1 s to 1 h) |
| `fp_db_purge_stalled_runs` | gauge | — | Purges `running` with no progress for 1 hour that no purge or plugin start has closed yet: the process was most likely killed ([#3](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/db_purge/-/work_items/3)) |
| `fp_db_purge_suspended_tables` | gauge | — | Enabled rules whose table is skipped after too many failed runs in a row (see [Guards](#guards-of-the-purge-that-runs-by-itself)) |

All values are computed from `fp_purge_logs` on each scrape, so purges run by a
tasks_worker in another process or container are counted too. `fp_purge_logs`
is never purged (core-excluded), so the counters only go up. Dry runs are left
out. The stalled-runs check compares against the database clock, the same one
that writes `executed_at` and `updated_at`.

Example alerts:

```promql
# A purge failed in the last day
increase(fp_db_purge_runs_total{status="error"}[1d]) > 0
# A purge has been stuck for over an hour
fp_db_purge_stalled_runs > 0
# A table is no longer purged: it failed too many times in a row
fp_db_purge_suspended_tables > 0
```

### Logging

Purge lifecycle events are logged at INFO level:

```
[db_purge] Declared purge target (disabled, awaiting admin): task_reports
Purge task_reports: deleted 5000 rows (total: 5000)
db_purge_all: task_reports — deleted 25000 rows (success)
```

Errors are logged at ERROR with full tracebacks.

## Failure Modes

### DB statement timeout during purge

**Symptom**: Purge fails with `statement_timeout` error

**Cause**: Large table (>1TB) with slow DELETE or COUNT(*)

**Recovery**: 
- COUNT(*) is skipped automatically above 1GB (since v1.0.1)
- Reduce `batch_size` setting to smaller chunks (default 5000)
- Increase DB `statement_timeout` if appropriate for your workload

### Hard crash mid-purge (OOM, kill -9)

**What happens**: the run's row stays `running` with the rows deleted by its committed batches
(`rows_deleted`, updated after each batch). Once it shows no progress for one hour, the next purge
or the next start of the plugin turns it into an `error` whose message starts with
"interrupted:". Until then `fp_db_purge_stalled_runs` counts it.

**Recovery**: none needed. The next purge deletes the rest: it is an idempotent
`DELETE WHERE ts < cutoff`.

### Two purges of the same table

A purge of a table that another purge is deleting from (a `running` row with progress in the last
hour) is not started: the history gets a `skipped` row, "another purge of this table is running".
Dry runs are not held back.

### Scheduled purge keeps running after toggle OFF

Fixed in v1.0.4 ([#4](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/db_purge/-/work_items/4)):
the auto-purge setting now enables or disables the `db_purge_all` schedule row,
both on load and from the dashboard toggle. On an older version, disable the
task by hand in the tasks_worker scheduled tasks table.

### Purging table from uninstalled plugin

**Risk**: Enabled purge rule for a table whose owning plugin was uninstalled

**Prevention** (since v1.2.0): the scheduled purge and "purge all" skip a table that a plugin
declared when that plugin is not loaded, and the history says so (see
[Guards](#guards-of-the-purge-that-runs-by-itself)). It takes effect when the process that runs
the purge restarts without the plugin. Rules an admin created by hand are not covered: disable
them yourself before removing what they relied on.

**Recovery**: If data was incorrectly purged, restore from DB backup

### A table fails at every scheduled run

**Symptom**: the same error for the same table in the history, night after night

**Since v1.2.0**: after `max_consecutive_failures` failed runs in a row (3 by default) the table is
suspended: later runs skip it, the dashboard shows "Suspended", `fp_db_purge_suspended_tables`
goes up and `db_purge.table_suspended` is emitted once.

**Recovery**: read the error in the history, remove the cause (often a wrong timestamp column in
the rule), then run a purge of that table from the page. A success lifts the suspension.

## Upgrade Notes

### v1.0.0 → v1.0.1+

**Schema migration**: `declared_hash` column added automatically on first load (idempotent `ALTER TABLE ADD COLUMN`)

**Rollback**: If downgrading to <1.0.0, drop the column:
```sql
ALTER TABLE fp_purge_rules DROP COLUMN declared_hash;
```

### v0.x → v1.0.0

**Breaking**: Plugin-declared rules now re-disable on declaration change. Previously-enabled rules may need re-validation after upgrade.

## Contributing

For implementation patterns, testing requirements, and development pitfalls, see
[CONTRIBUTING.md](CONTRIBUTING.md).
