Skip to content

feat(cli): add taskiq postgresql cleanup - #75

Merged
z22092 merged 28 commits into
mainfrom
feature/cleanup-cli
Dec 3, 2026
Merged

z22092 merged 28 commits into
mainfrom
feature/cleanup-cli

Conversation

@z22092

@z22092 z22092 commented Dec 3, 2026 •

Copy link
Copy Markdown
Owner

What and why

Today a result backend's old results are deleted in one of three ways: by the
taskiq scheduler, through the task register_cleanup registers (the
recommended path); by the built-in timer startup() starts when result_ttl
and cleanup_interval are set; or by the application calling cleanup()
itself. All three need Python code running inside the application.

This PR adds taskiq postgresql cleanup, a CLI command for a one-off cleanup
or for a scheduler outside Python (the operating system's cron, a Kubernetes
CronJob). It also adds an optional pg_cron recipe: the command can print the
cron.schedule call that has PostgreSQL run the cleanup itself. The library
never requires, creates or probes pg_cron.

What it adds

The command (new module taskiq_postgresql/cli_cleanup.py, registered by
taskiq_postgresql/cli.py):

taskiq postgresql cleanup TARGET [TARGET ...] [--older-than SECONDS] [--batch-size N]
                          [--dry-run | --pg-cron SCHEDULE] [--job-name NAME] [--database NAME]
  • TARGET is read as by taskiq postgresql migrate (module:object, and
    --app-dir). The command acts on every PostgresqlResultBackend the targets
    bring. A target with no result backend is an error.
  • With no mode flag it deletes rows not written for result_ttl,
    cleanup_batch_size at a time while a batch is full, as cleanup() does. It
    prints the count on stderr.
  • --older-than SECONDS and --batch-size N replace the backend's values for
    that run. On a backend without result_ttl, --older-than alone sets the
    age. With neither, the command exits with 1.
  • --older-than below a backend's result_ttl prints a warning on stderr
    (results clients may not have read yet are deleted) and goes on.
  • --dry-run counts the due results, prints the count and the number of
    batches on stderr, takes no lock and deletes nothing.
  • --pg-cron SCHEDULE connects to nothing. It prints one cron.schedule call
    per result backend on stdout. SCHEDULE must pass the grammar
    register_cleanup uses, then the catalog's character rule.
  • --job-name NAME (default taskiq_postgresql.cleanup.<table>) and
    --database NAME, which prints cron.schedule_in_database(...) instead, need
    --pg-cron. Each one is refused (exit 2) when the targets hold more than one
    result backend.
  • --pg-cron is refused (exit 2) for a backend whose built-in timer would run,
    i.e. one with both result_ttl and cleanup_interval set
    (taskiq_postgresql/cli_cleanup.py:395). register_cleanup is stricter: it
    refuses any backend with cleanup_interval set. --pg-cron refuses only a
    backend whose timer would run (result_ttl and cleanup_interval both set),
    so a backend with cleanup_interval set and no result_ttl is accepted when
    --older-than gives the age.
  • --dry-run and --pg-cron are mutually exclusive.
  • When two targets bring result backends of the same table with different
    connection strings, only the first is kept, as collect_components already
    does. The command now prints one stderr line for each backend it leaves out.
    The line names the target and the table, never the connection string.
  • The command does not start the backend. So it starts no timer and runs no
    DDL. The table needs the migration step that adds updated_at.

Exit status: 0 on success. That includes a run that found the cleanup lock
held by another session: it deletes nothing more, prints a stderr line that
says so, and exits 0 so that a CronJob does not alert. 1 means an error: no
result backend in the targets, no result_ttl and no --older-than, or a
connection or server error. 2 means a usage error.

SQL catalog (taskiq_postgresql/core/sql/catalog/):

  • rows.py: the existing cleanup statement now comes from one template,
    _CLEANUP_TEMPLATE (rows.py:22), with the age predicate _AGE_CONDITION
    (rows.py:33). The text CleanupQuery produces is unchanged byte for byte.
    The same template renders cleanup_script (rows.py:316), a Script with
    the four values written as typed literals instead of binds. The new
    CleanupCountQuery (rows.py:400) counts the rows older than an age with the
    same predicate, with no lock and no LIMIT. The limits MAX_CLEANUP_SECONDS
    and MAX_CLEANUP_BATCH_SIZE (formerly _MAX_RESULT_TTL and _MAX_BATCH_SIZE
    in result_backend.py) and the checks check_cleanup_seconds and
    check_cleanup_batch_size, which result_backend.py now calls instead of
    testing inline, are here.
  • cron.py (new): cleanup_cron_script, cleanup_unschedule_script,
    cleanup_job_name, script_lines, and the checks check_cron_job_name,
    check_cron_schedule_text and check_cron_database_name. One template
    writes cron.schedule, cron.schedule_in_database and cron.unschedule.

Result store (taskiq_postgresql/core/stores/results.py):

  • ResultStore.cleanup_run returns a CleanupRun(deleted, lock_held), so the
    CLI can say when the lock stopped a run.
  • ResultStore.cleanup returns (await self.cleanup_run(...)).deleted, so the
    public PostgresqlResultBackend.cleanup() is unchanged.
  • Also new: count_older, cron_script, the helper result_store(backend),
    and TableStore.bound(dsn), which binds the store for a block and closes it
    afterwards, also when the block raises.

Docs: README "Cleaning up old results" gains:

  • two optional rows in the comparison table;
  • a CLI section;
  • a pg_cron section, checked against the pg_cron README at tag v1.6.8:
    install, shared_preload_libraries and restart, CREATE EXTENSION,
    cron.database_name, the job's libpq connection, search_path, the printed
    SQL, one batch per run, job names, privileges, cron.job_run_details, a held
    lock, unschedule, and two databases.

docs/architecture.md and AGENTS.md describe the new module and statements.

Changes for existing users

None intended:

  • No public signature changes. PostgresqlResultBackend.cleanup(), its
    constructor arguments and ResultStore.cleanup keep their signatures and
    return values.
  • The catalog gains exports and loses none.
  • pyproject.toml, uv.lock and .github/ are untouched.
  • The result backend constructor now runs its result_ttl and
    cleanup_batch_size checks through the catalog functions, with the same
    error texts as before. New cases in tests/unit/test_result_ttl.py pin those
    texts.
  • One edge: the constructor now keeps int(cleanup_batch_size) rather than the
    object it was given. This only matters for an int subclass, and the range is
    checked on that converted value.
  • The help text changes: taskiq postgresql --help and its short_help
    mention the new command.
  • The PR title is the changelog entry. This PR does not edit CHANGELOG.md.

Security notes

  • Values reach printed SQL only as checked literals. The cleanup Script
    and the pg_cron call have no binds. Each value is checked again in the
    builder, then written as a single-quoted literal by _sql_literal. That
    function doubles ' and switches to E'...' with doubled backslashes when
    the value holds a backslash, so the text reads the same under either
    standard_conforming_strings setting. The cleanup command is quoted whole as
    one literal, never with $$. Numbers are written from the exact
    float/int the check returns, so a subclass cannot supply its own text.
  • What each input refuses:
    • table name: the existing Identifier rule (ADR 0008).
    • --older-than: anything that is not a finite number above 0 and at most
      100 years.
    • --batch-size: anything that is not an int from 1 to 2147483647.
    • --pg-cron: register_cleanup's grammar, then only 0-9 * , / - and
      spaces, at most 100 characters.
    • --job-name: anything outside 1 to 100 ASCII letters, digits, _ . $ -,
      and a name that starts with . $ -.
    • --database: empty, over 63 UTF-8 bytes, or any character of Unicode
      category Cc, Cf (zero-width and bidi controls), Cs, Zl or Zp
      (taskiq_postgresql/core/sql/catalog/cron.py:46).
  • pg_cron is never created, required or probed. --pg-cron opens no
    connection and only prints text. No module reads cron.* tables.
  • The job runs with its role's privileges. Per the pg_cron README, a job
    runs in the database where cron.schedule is called, with the permissions of
    the calling role. Each run's DELETE fires the table's triggers. The table
    name, and any unqualified function a trigger calls, resolve through that
    role's search_path. The README (README.md:560-571) says to schedule the job
    with the role that writes the results, not a superuser, and to keep the job's
    owner no more privileged than the table's owner. Step 6 (README.md:497)
    says to keep schemas other roles can write to off its search_path. Its
    example sets search_path = taskiq and leaves public out on purpose.
  • A held cleanup lock. Any session can take an advisory lock without a
    privilege, and a lock held for good stops every cleanup path without a failure
    being reported. "A held lock" (README.md:578) gives a pg_locks ×
    pg_stat_activity query for the session holding it, and says to watch the
    table's size and the age of its oldest row. A DB test runs that query, taken
    from the README, while another session holds the lock.
  • No DSN in output. --pg-cron never resolves the connection string.
    Warnings carry only the target, the table and numbers. Connection errors go
    through the existing redaction, which leaves out the DSN and its password.
    As in the existing commands, a DSN callable that raises an exception whose own
    text contains the DSN has that text printed.

How it was tested

The tests were not run on the author's machine: local checks were limited to make lint, make typecheck, ruff and reading the diff, so each red step was reasoned from the code, not run. CI on the final head is the proof:

CI passed on the final head c3cb4b4. Passing jobs: test (py3.10), test (py3.10, lowest-direct), test (py3.11), test (py3.12), test (py3.13), test (py3.13, pg17), test (py3.14), test (py3.15), lint, coverage, CodeQL, Analyze (actions), Analyze (python), build, smoke, pip-audit, dependency-review and conventional-title. The test jobs are in https://github.com/z22092/taskiq-postgresql/actions/runs/47226151363.

What the suite covers:

  • Unit: the shared template, the literals and their refusals, the cron
    wrappers, the store paths, and the CLI's flags, usage errors and exit codes.
    A test checks that importing and parsing the command loads no driver and no
    migration code.
  • Database tests, once per driver:
    • the Script deletes the same rows and takes the same lock key as
      CleanupQuery;
    • the CLI's delete, --dry-run, the warning below result_ttl, a held lock
      (exit 0 and the stderr line), a table without the migration step (exit 1)
      and an unreachable server (exit 1).
  • README tests: they compare the README's pg_cron blocks with what
    cleanup prints, and run the README's lock query against a real server.

Not verified in CI:

  • Real pg_cron behaviour: the test image has no pg_cron. The DB tests
    create stand-in cron.schedule and cron.schedule_in_database functions in a
    cron schema and read back the arguments the printed call hands them. The
    README marks the pg_cron points it could not confirm against its own docs
    as things to check: scheduling a name that already exists, the privilege
    cron.schedule_in_database needs, and whether cron.unschedule removes a
    job made in another database.
  • The README test's exec of the generated Alembic revision
    (tests/test_readme_examples.py:1378) is pre-existing. The same exec is at
    line 1368 of the base.

Checklist

  • pre-commit run --all-files passes (the CI lint job on the final head is the proof; see above)
  • Tests cover the change (the database tests take the driver fixture and run once per driver; the unit and README tests need no driver)
  • The PR title is a Conventional Commit (it becomes the changelog entry)
  • README and docstrings are updated if behaviour or public arguments changed

🤖 Generated with Claude Code

z22092 and others added 28 commits December 3, 2026 15:20
The cleanup statement binds its four values; the script a pg_cron job
receives writes them as typed literals from the same template. These tests
pin the script's text, the one template, the folded lock key, the numbers
the script accepts and writes, and the limits the backend shares with it.
They fail until cleanup_script and the checks exist.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The cleanup statement and the script a pg_cron job receives now come from
one template: the statement binds the four values, the script writes them as
typed literals through the catalog's literal helper, the casts staying in
the template. The builder checks the age and the batch size again and
writes the plain number it gets back, so a subclass cannot write its own
text. The backend takes its two limits from the same place.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A dry run counts the results the cleanup would delete for an age. These tests
pin the count's text, that it reads the same age condition as the cleanup
query, and its declared types, plus a catalog case for the server to confirm
them. They fail until CleanupCountQuery exists.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
CleanupCountQuery counts the rows a cleanup would delete for an age, for a
dry run. It formats the same age condition the cleanup template uses, so the
count and the delete cannot disagree on which rows are old. It binds the age,
takes no lock and deletes nothing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The cleanup script is the command a pg_cron job runs. Pin the two calls
that schedule it, cron.schedule and cron.schedule_in_database, as one
template with every value written as a single literal: the job name, the
schedule, the script text and the database name, each checked again by the
builder. The server-side tests hand the rendered call to stand-ins for the
two functions and read the arguments back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Add catalog/cron.py: cleanup_cron_script renders the cleanup script as the
command of cron.schedule, or of cron.schedule_in_database when a database
is given. One template and one builder write every call, each value as a
single literal through the catalog's literal helper, never with $$ (a
table name may hold it). The job name (default derived from the folded
table name), the schedule and the database name are checked again by the
builder. cleanup_unschedule_script names the same job and script_lines puts
the statement terminator on a file of scripts. Nothing connects to pg_cron
or reads its tables.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A cleanup run that ends on a lock another session holds must be told apart
from one that had nothing left to delete, and the store must count the due
rows, render the pg_cron script of its table and be reachable from the
backend. None of it exists yet, so the module fails to import.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
ResultStore, the internal store, gains cleanup_run, which returns a
CleanupRun(deleted, lock_held) so a caller can tell a run that stopped on a
lock another session held from one that had nothing left to delete. A batch
that returns no row still ends the run as before, with the lock not held.
The store also counts the rows a cleanup of an age would delete, renders the
pg_cron call of its table, and result_store reaches it from a backend.

ResultStore.cleanup and PostgresqlResultBackend.cleanup() are unchanged: the
same int, from the same driver calls with the same values. The timer and
register_cleanup do not change either. No SQL text changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Pin the command before it exists: every usage error by the fragment of its
own message, since a parser that does not know the command also exits with
2; the pg_cron mode, which connects nowhere and prints one call per result
backend; the refusal of a backend whose built-in timer would run; the
warning for an age below result_ttl; and, against a server, the run, the
dry run, the lock held by another session and the closed pool.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Delete the results a result backend no longer needs from the command line,
one batch at a time under the cleanup try-lock, through the store's
cleanup_run so the exit status can tell a lock held by another session
(0, with a line on stderr) from a failure. --dry-run counts what is due and
deletes nothing. --pg-cron SCHEDULE prints one cron.schedule call per result
backend, or cron.schedule_in_database with --database, and connects to
nothing; it refuses (usage error) a backend whose built-in timer would run
beside the job. An --older-than below result_ttl warns on stderr and goes on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The README has no cleanup section yet, so the three tests find no
taskiq postgresql cleanup line and no pg_cron SQL block to compare with
what the command prints.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The command and its pg_cron mode were undocumented. The README puts both
after the three existing paths and marks them optional; the pg_cron facts
follow its README at v1.6.8, and what that README does not say is left
as something to check there. architecture.md and AGENTS.md name the new
modules, the store methods and the tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A second result backend that keeps a table another database already has is
left out without a word, and --database is applied to every backend.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The next change takes both rules from the catalog; the text stays the
constructor's own.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
cli.py had grown past 1000 lines with a command the others share only the
dispatch with. cli_cleanup.py keeps the standard-library-only imports.

In the move: one factory builds the five argument types, TableStore.bound
binds and closes a store so the dry run and the delete share one runner,
the mode is chosen once and every usage error leaves through one path, and
the job reads its table, store, dsn, ttl and timer from its backend.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The constructor kept a second copy of the ttl and batch size limits and
of the batch size test. It now asks the catalog and keeps its own message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The job name pattern and the schedule pattern spelled the limits their
messages name. Both come from a constant now; the unused exports of the
cron limits leave the catalog, and a comment that defended a risk the
template does not have is gone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
collect_components keeps the first result backend of a table. A later one
with another connection string was dropped without a word, so its results
were never cleaned. Each is now named on stderr by its TARGET and table,
never by its connection string; a DSN callable is not called to compare.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
One database name would put every backend's table in a database that may
not have it, and the job would fail on every run. --job-name already
refuses several backends; --database now does the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The README text and two docstrings claimed who may write cron.job, that a
job of the same name is replaced and that unschedule ignores the database.
The pg_cron README at v1.6.8 does not say any of it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The README must show a pg_locks query that finds the session holding the
cleanup lock, and its search_path example must not list public; a
database name with a format character (Unicode Cf) must be refused.
Written before the README and the check change, not run locally.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Import cli_cleanup and parse cleanup --help with no driver and no
migrations loaded; the probe also checks that help was printed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The example sits in a numbered step, so its fence is indented and the block
reader skips it: the check now reads indented fences, and fails at the prior
tip because the example lists public. Not run locally.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The job fires the results table's triggers as the scheduling role and
resolves names through its search_path, so a superuser job is a way to
run SQL as the superuser; the search_path example no longer lists
public. A held cleanup lock stops every cleanup without an error, so
the README shows a pg_locks query that finds its holder, and what to
watch on the table.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A zero-width or bidirectional control (Unicode Cf) in --database prints as
nothing or reorders the text around it, so the SQL a person reviews before
running it could differ from what the server gets.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@z22092
z22092 marked this pull request as ready for review December 3, 2026 23:34
@z22092
z22092 merged commit 58e1db6 into main Dec 3, 2026
23 checks passed
@z22092
z22092 deleted the feature/cleanup-cli branch December 3, 2026 23:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant