Repository navigation
feat(cli): add taskiq postgresql cleanup - #75
Merged
Merged
Conversation
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
marked this pull request as ready for review
December 3, 2026 23:34
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_cleanupregisters (therecommended path); by the built-in timer
startup()starts whenresult_ttland
cleanup_intervalare set; or by the application callingcleanup()itself. All three need Python code running inside the application.
This PR adds
taskiq postgresql cleanup, a CLI command for a one-off cleanupor for a scheduler outside Python (the operating system's cron, a Kubernetes
CronJob). It also adds an optionalpg_cronrecipe: the command can print thecron.schedulecall that has PostgreSQL run the cleanup itself. The librarynever requires, creates or probes
pg_cron.What it adds
The command (new module
taskiq_postgresql/cli_cleanup.py, registered bytaskiq_postgresql/cli.py):taskiq postgresql cleanup TARGET [TARGET ...] [--older-than SECONDS] [--batch-size N] [--dry-run | --pg-cron SCHEDULE] [--job-name NAME] [--database NAME]TARGETis read as bytaskiq postgresql migrate(module:object, and--app-dir). The command acts on everyPostgresqlResultBackendthe targetsbring. A target with no result backend is an error.
result_ttl,cleanup_batch_sizeat a time while a batch is full, ascleanup()does. Itprints the count on stderr.
--older-than SECONDSand--batch-size Nreplace the backend's values forthat run. On a backend without
result_ttl,--older-thanalone sets theage. With neither, the command exits with 1.
--older-thanbelow a backend'sresult_ttlprints a warning on stderr(results clients may not have read yet are deleted) and goes on.
--dry-runcounts the due results, prints the count and the number ofbatches on stderr, takes no lock and deletes nothing.
--pg-cron SCHEDULEconnects to nothing. It prints onecron.schedulecallper result backend on stdout.
SCHEDULEmust pass the grammarregister_cleanupuses, then the catalog's character rule.--job-name NAME(defaulttaskiq_postgresql.cleanup.<table>) and--database NAME, which printscron.schedule_in_database(...)instead, need--pg-cron. Each one is refused (exit 2) when the targets hold more than oneresult backend.
--pg-cronis refused (exit 2) for a backend whose built-in timer would run,i.e. one with both
result_ttlandcleanup_intervalset(
taskiq_postgresql/cli_cleanup.py:395).register_cleanupis stricter: itrefuses any backend with
cleanup_intervalset.--pg-cronrefuses only abackend whose timer would run (
result_ttlandcleanup_intervalboth set),so a backend with
cleanup_intervalset and noresult_ttlis accepted when--older-thangives the age.--dry-runand--pg-cronare mutually exclusive.connection strings, only the first is kept, as
collect_componentsalreadydoes. 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.
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
CronJobdoes not alert. 1 means an error: noresult backend in the targets, no
result_ttland no--older-than, or aconnection 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 textCleanupQueryproduces is unchanged byte for byte.The same template renders
cleanup_script(rows.py:316), aScriptwiththe four values written as typed literals instead of binds. The new
CleanupCountQuery(rows.py:400) counts the rows older than an age with thesame predicate, with no lock and no
LIMIT. The limitsMAX_CLEANUP_SECONDSand
MAX_CLEANUP_BATCH_SIZE(formerly_MAX_RESULT_TTLand_MAX_BATCH_SIZEin
result_backend.py) and the checkscheck_cleanup_secondsandcheck_cleanup_batch_size, whichresult_backend.pynow calls instead oftesting inline, are here.
cron.py(new):cleanup_cron_script,cleanup_unschedule_script,cleanup_job_name,script_lines, and the checkscheck_cron_job_name,check_cron_schedule_textandcheck_cron_database_name. One templatewrites
cron.schedule,cron.schedule_in_databaseandcron.unschedule.Result store (
taskiq_postgresql/core/stores/results.py):ResultStore.cleanup_runreturns aCleanupRun(deleted, lock_held), so theCLI can say when the lock stopped a run.
ResultStore.cleanupreturns(await self.cleanup_run(...)).deleted, so thepublic
PostgresqlResultBackend.cleanup()is unchanged.count_older,cron_script, the helperresult_store(backend),and
TableStore.bound(dsn), which binds the store for a block and closes itafterwards, also when the block raises.
Docs: README "Cleaning up old results" gains:
pg_cronsection, checked against thepg_cronREADME at tagv1.6.8:install,
shared_preload_librariesand restart,CREATE EXTENSION,cron.database_name, the job's libpq connection,search_path, the printedSQL, one batch per run, job names, privileges,
cron.job_run_details, a heldlock, unschedule, and two databases.
docs/architecture.mdandAGENTS.mddescribe the new module and statements.Changes for existing users
None intended:
PostgresqlResultBackend.cleanup(), itsconstructor arguments and
ResultStore.cleanupkeep their signatures andreturn values.
pyproject.toml,uv.lockand.github/are untouched.result_ttlandcleanup_batch_sizechecks through the catalog functions, with the sameerror texts as before. New cases in
tests/unit/test_result_ttl.pypin thosetexts.
int(cleanup_batch_size)rather than theobject it was given. This only matters for an
intsubclass, and the range ischecked on that converted value.
taskiq postgresql --helpand itsshort_helpmention the new command.
CHANGELOG.md.Security notes
Scriptand the
pg_croncall have no binds. Each value is checked again in thebuilder, then written as a single-quoted literal by
_sql_literal. Thatfunction doubles
'and switches toE'...'with doubled backslashes whenthe value holds a backslash, so the text reads the same under either
standard_conforming_stringssetting. The cleanup command is quoted whole asone literal, never with
$$. Numbers are written from the exactfloat/intthe check returns, so a subclass cannot supply its own text.Identifierrule (ADR 0008).--older-than: anything that is not a finite number above 0 and at most100 years.
--batch-size: anything that is not an int from 1 to 2147483647.--pg-cron:register_cleanup's grammar, then only0-9 * , / -andspaces, 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 Unicodecategory
Cc,Cf(zero-width and bidi controls),Cs,ZlorZp(
taskiq_postgresql/core/sql/catalog/cron.py:46).pg_cronis never created, required or probed.--pg-cronopens noconnection and only prints text. No module reads
cron.*tables.pg_cronREADME, a jobruns in the database where
cron.scheduleis called, with the permissions ofthe calling role. Each run's
DELETEfires the table's triggers. The tablename, and any unqualified function a trigger calls, resolve through that
role's
search_path. The README (README.md:560-571) says to schedule the jobwith 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. Itsexample sets
search_path = taskiqand leavespublicout on purpose.privilege, and a lock held for good stops every cleanup path without a failure
being reported. "A held lock" (
README.md:578) gives apg_locks×pg_stat_activityquery for the session holding it, and says to watch thetable'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.
--pg-cronnever 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-reviewandconventional-title. The test jobs are in https://github.com/z22092/taskiq-postgresql/actions/runs/47226151363.What the suite covers:
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.
Scriptdeletes the same rows and takes the same lock key asCleanupQuery;--dry-run, the warning belowresult_ttl, a held lock(exit 0 and the stderr line), a table without the migration step (exit 1)
and an unreachable server (exit 1).
pg_cronblocks with whatcleanupprints, and run the README's lock query against a real server.Not verified in CI:
pg_cronbehaviour: the test image has nopg_cron. The DB testscreate stand-in
cron.scheduleandcron.schedule_in_databasefunctions in acronschema and read back the arguments the printed call hands them. TheREADME marks the
pg_cronpoints it could not confirm against its own docsas things to check: scheduling a name that already exists, the privilege
cron.schedule_in_databaseneeds, and whethercron.unscheduleremoves ajob made in another database.
execof the generated Alembic revision(
tests/test_readme_examples.py:1378) is pre-existing. The sameexecis atline 1368 of the base.
Checklist
pre-commit run --all-filespasses (the CIlintjob on the final head is the proof; see above)driverfixture and run once per driver; the unit and README tests need no driver)🤖 Generated with Claude Code