django-celery-beat-prune 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TheLoops (https://theloops.live)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-celery-beat-prune
3
+ Version: 1.0.0
4
+ Summary: Make CELERY_BEAT_SCHEDULE authoritative for django-celery-beat: a periodic task removed from settings stops running instead of living on as a database row.
5
+ Author-email: TheLoops <support@theloops.live>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://theloops.live/engineering/django-celery-beat-prune
8
+ Project-URL: Source, https://github.com/theloops-live/django-celery-beat-prune
9
+ Keywords: django,celery,celery-beat,django-celery-beat,periodic-tasks,scheduler
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: Celery
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: System :: Distributed Computing
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: django-celery-beat>=2.5
19
+ Requires-Dist: celery>=5.3
20
+ Requires-Dist: Django>=4.2
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == "test"
23
+ Requires-Dist: pytest-django>=4.5; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # django-celery-beat-prune
27
+
28
+ Delete an entry from `CELERY_BEAT_SCHEDULE`, deploy, and with
29
+ [django-celery-beat](https://github.com/celery/django-celery-beat) the task
30
+ **keeps running**. `DatabaseScheduler` copies your settings into the
31
+ `PeriodicTask` table on every Beat start with `update_or_create`, and nothing
32
+ ever deletes. The row stays there and stays enabled, firing on schedule. Nothing
33
+ in the logs says so, and the deploy looks like it worked.
34
+
35
+ This package adds the missing half. Settings become the schedule, and the
36
+ table becomes a copy of it: when Beat starts, rows with no entry in
37
+ `CELERY_BEAT_SCHEDULE` are removed, and each one is named in the log.
38
+
39
+ ```python
40
+ # settings.py
41
+ CELERY_BEAT_SCHEDULER = "django_celery_beat_prune.PruningScheduler"
42
+ ```
43
+
44
+ That's the whole setup. Restart Beat, and any task you have removed from
45
+ settings stops.
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install django-celery-beat-prune
51
+ ```
52
+
53
+ Add the app if you want the management command:
54
+
55
+ ```python
56
+ INSTALLED_APPS = [
57
+ # ...
58
+ "django_celery_beat",
59
+ "django_celery_beat_prune",
60
+ ]
61
+ ```
62
+
63
+ Requires Python 3.10+, Django 4.2+, Celery 5.3+ and django-celery-beat 2.5+.
64
+ CI tests both the oldest and the newest of each.
65
+
66
+ ## What it does, and what it deliberately doesn't
67
+
68
+ - **Rows are deleted, not disabled.** `update_or_create` never writes
69
+ `enabled`. A row disabled by mistake would stay disabled through every later
70
+ restart, and that task would be silently dead. A row deleted by mistake is
71
+ recreated from settings at the next start.
72
+ - **The `enabled` flag is never touched.** Unticking *Enabled* in the admin
73
+ keeps working as the emergency switch that needs no deploy.
74
+ - **An empty schedule prunes nothing.** If `CELERY_BEAT_SCHEDULE` comes back
75
+ empty, settings almost certainly failed to load. Taken literally, an empty
76
+ schedule would delete every row and stop everything, so the package logs a
77
+ warning and leaves the table alone.
78
+ - **Celery's own `celery.backend_cleanup` is kept.** Beat recreates it at every
79
+ start anyway.
80
+ - **One-off tasks are kept by default.** Rows with `one_off=True` are
81
+ normally created from code for a single run and were never meant to be in
82
+ settings.
83
+ - **A pruned task can't fire one last time.** It is also dropped from the
84
+ schedule the running Beat already holds, so it can't fire before Beat next
85
+ re-reads the table.
86
+
87
+ ## Tasks created in the admin
88
+
89
+ If you also create periodic tasks by hand or from code, protect them by name or
90
+ by shell-style pattern:
91
+
92
+ ```python
93
+ CELERY_BEAT_PRUNE_KEEP = ["manual-*", "nightly-export"]
94
+ ```
95
+
96
+ ## Options
97
+
98
+ | Setting | Default | Meaning |
99
+ |---|---|---|
100
+ | `CELERY_BEAT_PRUNE_KEEP` | `()` | Names or patterns (`fnmatch`) never removed |
101
+ | `CELERY_BEAT_PRUNE_DRY_RUN` | `False` | Log what would be removed, remove nothing |
102
+ | `CELERY_BEAT_PRUNE_ONE_OFF` | `False` | Also remove `one_off=True` rows |
103
+
104
+ These are read from your Celery config (`beat_prune_keep`, and so on) or,
105
+ failing that, from the Django settings above.
106
+
107
+ ## Look before you prune
108
+
109
+ The first time, see what would go without restarting Beat:
110
+
111
+ ```bash
112
+ python manage.py prune_periodic_tasks --dry-run
113
+ python manage.py prune_periodic_tasks --keep "manual-*"
114
+ ```
115
+
116
+ The command needs your Celery app to be imported, which it is in the usual
117
+ layout (`from .celery import app as celery_app` in your project's
118
+ `__init__.py`).
119
+
120
+ ## Using the function directly
121
+
122
+ ```python
123
+ from django_celery_beat_prune import prune, Options
124
+
125
+ result = prune(app, Options(keep=("manual-*",), dry_run=True))
126
+ print(result.removed)
127
+ ```
128
+
129
+ ## Why this exists
130
+
131
+ We run [TheLoops](https://theloops.live), which streams pre-recorded video to
132
+ YouTube, Twitch and other platforms around the clock, and its periodic work runs
133
+ on Celery Beat. We once commented a task out of settings because it made
134
+ about 10,000 useless API calls a day. When we later moved Beat's schedule into
135
+ the database, we noticed that on a plain `DatabaseScheduler` that fix would
136
+ have changed nothing. This package is the scheduler we wrote then. The background is in
137
+ [our engineering notes](https://theloops.live/engineering/django-celery-beat-prune).
138
+
139
+ ## License
140
+
141
+ MIT
@@ -0,0 +1,116 @@
1
+ # django-celery-beat-prune
2
+
3
+ Delete an entry from `CELERY_BEAT_SCHEDULE`, deploy, and with
4
+ [django-celery-beat](https://github.com/celery/django-celery-beat) the task
5
+ **keeps running**. `DatabaseScheduler` copies your settings into the
6
+ `PeriodicTask` table on every Beat start with `update_or_create`, and nothing
7
+ ever deletes. The row stays there and stays enabled, firing on schedule. Nothing
8
+ in the logs says so, and the deploy looks like it worked.
9
+
10
+ This package adds the missing half. Settings become the schedule, and the
11
+ table becomes a copy of it: when Beat starts, rows with no entry in
12
+ `CELERY_BEAT_SCHEDULE` are removed, and each one is named in the log.
13
+
14
+ ```python
15
+ # settings.py
16
+ CELERY_BEAT_SCHEDULER = "django_celery_beat_prune.PruningScheduler"
17
+ ```
18
+
19
+ That's the whole setup. Restart Beat, and any task you have removed from
20
+ settings stops.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install django-celery-beat-prune
26
+ ```
27
+
28
+ Add the app if you want the management command:
29
+
30
+ ```python
31
+ INSTALLED_APPS = [
32
+ # ...
33
+ "django_celery_beat",
34
+ "django_celery_beat_prune",
35
+ ]
36
+ ```
37
+
38
+ Requires Python 3.10+, Django 4.2+, Celery 5.3+ and django-celery-beat 2.5+.
39
+ CI tests both the oldest and the newest of each.
40
+
41
+ ## What it does, and what it deliberately doesn't
42
+
43
+ - **Rows are deleted, not disabled.** `update_or_create` never writes
44
+ `enabled`. A row disabled by mistake would stay disabled through every later
45
+ restart, and that task would be silently dead. A row deleted by mistake is
46
+ recreated from settings at the next start.
47
+ - **The `enabled` flag is never touched.** Unticking *Enabled* in the admin
48
+ keeps working as the emergency switch that needs no deploy.
49
+ - **An empty schedule prunes nothing.** If `CELERY_BEAT_SCHEDULE` comes back
50
+ empty, settings almost certainly failed to load. Taken literally, an empty
51
+ schedule would delete every row and stop everything, so the package logs a
52
+ warning and leaves the table alone.
53
+ - **Celery's own `celery.backend_cleanup` is kept.** Beat recreates it at every
54
+ start anyway.
55
+ - **One-off tasks are kept by default.** Rows with `one_off=True` are
56
+ normally created from code for a single run and were never meant to be in
57
+ settings.
58
+ - **A pruned task can't fire one last time.** It is also dropped from the
59
+ schedule the running Beat already holds, so it can't fire before Beat next
60
+ re-reads the table.
61
+
62
+ ## Tasks created in the admin
63
+
64
+ If you also create periodic tasks by hand or from code, protect them by name or
65
+ by shell-style pattern:
66
+
67
+ ```python
68
+ CELERY_BEAT_PRUNE_KEEP = ["manual-*", "nightly-export"]
69
+ ```
70
+
71
+ ## Options
72
+
73
+ | Setting | Default | Meaning |
74
+ |---|---|---|
75
+ | `CELERY_BEAT_PRUNE_KEEP` | `()` | Names or patterns (`fnmatch`) never removed |
76
+ | `CELERY_BEAT_PRUNE_DRY_RUN` | `False` | Log what would be removed, remove nothing |
77
+ | `CELERY_BEAT_PRUNE_ONE_OFF` | `False` | Also remove `one_off=True` rows |
78
+
79
+ These are read from your Celery config (`beat_prune_keep`, and so on) or,
80
+ failing that, from the Django settings above.
81
+
82
+ ## Look before you prune
83
+
84
+ The first time, see what would go without restarting Beat:
85
+
86
+ ```bash
87
+ python manage.py prune_periodic_tasks --dry-run
88
+ python manage.py prune_periodic_tasks --keep "manual-*"
89
+ ```
90
+
91
+ The command needs your Celery app to be imported, which it is in the usual
92
+ layout (`from .celery import app as celery_app` in your project's
93
+ `__init__.py`).
94
+
95
+ ## Using the function directly
96
+
97
+ ```python
98
+ from django_celery_beat_prune import prune, Options
99
+
100
+ result = prune(app, Options(keep=("manual-*",), dry_run=True))
101
+ print(result.removed)
102
+ ```
103
+
104
+ ## Why this exists
105
+
106
+ We run [TheLoops](https://theloops.live), which streams pre-recorded video to
107
+ YouTube, Twitch and other platforms around the clock, and its periodic work runs
108
+ on Celery Beat. We once commented a task out of settings because it made
109
+ about 10,000 useless API calls a day. When we later moved Beat's schedule into
110
+ the database, we noticed that on a plain `DatabaseScheduler` that fix would
111
+ have changed nothing. This package is the scheduler we wrote then. The background is in
112
+ [our engineering notes](https://theloops.live/engineering/django-celery-beat-prune).
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "django-celery-beat-prune"
7
+ version = "1.0.0"
8
+ description = "Make CELERY_BEAT_SCHEDULE authoritative for django-celery-beat: a periodic task removed from settings stops running instead of living on as a database row."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "TheLoops", email = "support@theloops.live" }]
14
+ keywords = ["django", "celery", "celery-beat", "django-celery-beat", "periodic-tasks", "scheduler"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Framework :: Django",
18
+ "Framework :: Celery",
19
+ "Operating System :: OS Independent",
20
+ "Topic :: System :: Distributed Computing",
21
+ ]
22
+ dependencies = ["django-celery-beat>=2.5", "celery>=5.3", "Django>=4.2"]
23
+
24
+ [project.optional-dependencies]
25
+ test = ["pytest>=7", "pytest-django>=4.5"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://theloops.live/engineering/django-celery-beat-prune"
29
+ Source = "https://github.com/theloops-live/django-celery-beat-prune"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
36
+ pythonpath = ["src", "."]
37
+ DJANGO_SETTINGS_MODULE = "tests.settings"
38
+ markers = ["live: starts a real celery beat process"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ """Make CELERY_BEAT_SCHEDULE authoritative for django-celery-beat.
2
+
3
+ A periodic task removed from settings stops running instead of living on as a
4
+ database row.
5
+ """
6
+
7
+ __version__ = "1.0.0"
8
+
9
+ __all__ = [
10
+ "DEFAULT_ENTRY_NAMES",
11
+ "Options",
12
+ "PruningScheduler",
13
+ "Result",
14
+ "options_for",
15
+ "prune",
16
+ "stale_names",
17
+ ]
18
+
19
+
20
+ def __getattr__(name):
21
+ # Everything is imported lazily. This package goes into INSTALLED_APPS for
22
+ # its management command, and Django imports it while the app registry is
23
+ # still loading, before django_celery_beat's models may be imported.
24
+ # Celery resolves "django_celery_beat_prune.PruningScheduler" by
25
+ # attribute, after Django is set up, which lands here.
26
+ if name == "PruningScheduler":
27
+ from .scheduler import PruningScheduler
28
+
29
+ return PruningScheduler
30
+ if name in __all__:
31
+ from . import core as _core
32
+
33
+ return getattr(_core, name)
34
+ raise AttributeError(name)
@@ -0,0 +1,140 @@
1
+ """Find and remove PeriodicTask rows that CELERY_BEAT_SCHEDULE no longer defines.
2
+
3
+ django_celery_beat's DatabaseScheduler copies every entry of the beat schedule
4
+ into the database when Beat starts, with `update_or_create`. Nothing ever
5
+ deletes, so an entry removed from settings keeps its row, stays enabled and
6
+ keeps firing. This module is the missing half: it treats the settings as the
7
+ schedule and the table as a copy of it.
8
+
9
+ Rows are deleted rather than disabled. `update_or_create` never writes
10
+ `enabled`, so a row disabled by mistake would stay disabled through every later
11
+ restart; a row deleted by mistake is recreated from settings at the next start.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import fnmatch
16
+ import logging
17
+ from dataclasses import dataclass, field
18
+ from typing import Iterable
19
+
20
+ from django_celery_beat.models import PeriodicTask, PeriodicTasks
21
+
22
+ logger = logging.getLogger("django_celery_beat_prune")
23
+
24
+ # Entries DatabaseScheduler.install_default_entries writes at every start
25
+ # without them ever being in the beat schedule. Pruning them would only have
26
+ # Beat recreate them a moment later.
27
+ DEFAULT_ENTRY_NAMES = frozenset({"celery.backend_cleanup"})
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Options:
32
+ """How pruning behaves. Read from settings by `options_for(app)`."""
33
+
34
+ keep: tuple[str, ...] = ()
35
+ """Names or shell-style patterns (`admin-*`) never pruned."""
36
+
37
+ dry_run: bool = False
38
+ """Log what would be removed and remove nothing."""
39
+
40
+ prune_one_off: bool = False
41
+ """Also remove one-off rows. Off by default: those are nearly always
42
+ created from code, for a single run, and are not meant to be in settings."""
43
+
44
+
45
+ @dataclass
46
+ class Result:
47
+ removed: list[str] = field(default_factory=list)
48
+ skipped_reason: str | None = None
49
+ dry_run: bool = False
50
+
51
+
52
+ def _setting(app, name: str, default):
53
+ """Read `name` from the Celery config, then from Django's `CELERY_<NAME>`.
54
+
55
+ A Celery app configured with `namespace="CELERY"` reads its own settings
56
+ from Django, but a key Celery does not know about is not guaranteed to be
57
+ mapped, so the Django setting is consulted directly as well.
58
+ """
59
+ value = app.conf.get(name)
60
+ if value is not None:
61
+ return value
62
+ try:
63
+ from django.conf import settings
64
+
65
+ return getattr(settings, f"CELERY_{name.upper()}", default)
66
+ except Exception: # settings not configured
67
+ return default
68
+
69
+
70
+ def options_for(app) -> Options:
71
+ keep = _setting(app, "beat_prune_keep", ()) or ()
72
+ if isinstance(keep, str):
73
+ keep = (keep,)
74
+ return Options(
75
+ keep=tuple(keep),
76
+ dry_run=bool(_setting(app, "beat_prune_dry_run", False)),
77
+ prune_one_off=bool(_setting(app, "beat_prune_one_off", False)),
78
+ )
79
+
80
+
81
+ def _kept(name: str, patterns: Iterable[str]) -> bool:
82
+ return any(name == p or fnmatch.fnmatchcase(name, p) for p in patterns)
83
+
84
+
85
+ def stale_names(app, options: Options) -> list[str] | None:
86
+ """Rows with no entry behind them, or None when it is unsafe to decide.
87
+
88
+ An empty beat schedule means settings failed to load, not that every task
89
+ was removed on purpose. Reading it literally would turn a configuration
90
+ error into a silent stop of everything scheduled, so nothing is stale then.
91
+ """
92
+ configured = set(app.conf.beat_schedule or ())
93
+ if not configured:
94
+ return None
95
+ rows = PeriodicTask.objects.exclude(name__in=configured | DEFAULT_ENTRY_NAMES)
96
+ if not options.prune_one_off:
97
+ rows = rows.exclude(one_off=True)
98
+ return sorted(n for n in rows.values_list("name", flat=True) if not _kept(n, options.keep))
99
+
100
+
101
+ def prune(app, options: Options | None = None, schedule: dict | None = None) -> Result:
102
+ """Delete stale rows; also drop them from a scheduler's in-memory schedule.
103
+
104
+ `schedule` is the dict a running scheduler already holds. Without removing
105
+ the names from it, a task just deleted could fire once more before Beat's
106
+ next full re-read of the table.
107
+ """
108
+ options = options or options_for(app)
109
+ names = stale_names(app, options)
110
+ if names is None:
111
+ logger.warning(
112
+ "Beat schedule is empty; not pruning, because deleting every "
113
+ "PeriodicTask row would stop all scheduled work"
114
+ )
115
+ return Result(skipped_reason="empty_schedule", dry_run=options.dry_run)
116
+ if not names:
117
+ return Result(dry_run=options.dry_run)
118
+
119
+ if options.dry_run:
120
+ logger.warning(
121
+ "Would remove %d periodic task(s) with no entry in the beat schedule "
122
+ "(dry run): %s",
123
+ len(names),
124
+ ", ".join(names),
125
+ )
126
+ return Result(removed=names, dry_run=True)
127
+
128
+ logger.warning(
129
+ "Removing %d periodic task(s) with no entry in the beat schedule: %s",
130
+ len(names),
131
+ ", ".join(names),
132
+ )
133
+ PeriodicTask.objects.filter(name__in=names).delete()
134
+ # A Beat running elsewhere re-reads the table only when this changes.
135
+ PeriodicTasks.update_changed()
136
+
137
+ if schedule:
138
+ for name in names:
139
+ schedule.pop(name, None)
140
+ return Result(removed=names)
@@ -0,0 +1,43 @@
1
+ from celery import current_app
2
+ from django.core.management.base import BaseCommand, CommandError
3
+
4
+ from django_celery_beat_prune.core import Options, options_for, prune
5
+
6
+
7
+ class Command(BaseCommand):
8
+ help = (
9
+ "Delete PeriodicTask rows that have no entry in CELERY_BEAT_SCHEDULE. "
10
+ "Run with --dry-run first to see what would go."
11
+ )
12
+
13
+ def add_arguments(self, parser):
14
+ parser.add_argument("--dry-run", action="store_true", help="List the rows, delete nothing.")
15
+ parser.add_argument(
16
+ "--keep",
17
+ action="append",
18
+ default=[],
19
+ metavar="PATTERN",
20
+ help="A name or shell-style pattern to keep, in addition to CELERY_BEAT_PRUNE_KEEP. Repeatable.",
21
+ )
22
+
23
+ def handle(self, *args, dry_run=False, keep=(), **options):
24
+ app = current_app
25
+ configured = options_for(app)
26
+ opts = Options(
27
+ keep=configured.keep + tuple(keep),
28
+ dry_run=dry_run or configured.dry_run,
29
+ prune_one_off=configured.prune_one_off,
30
+ )
31
+ result = prune(app, opts)
32
+ if result.skipped_reason == "empty_schedule":
33
+ raise CommandError(
34
+ "The beat schedule is empty, so nothing was pruned. Is the Celery "
35
+ "app imported (usually from your project's __init__.py)?"
36
+ )
37
+ if not result.removed:
38
+ self.stdout.write("Nothing to prune.")
39
+ return
40
+ verb = "Would remove" if result.dry_run else "Removed"
41
+ self.stdout.write(f"{verb} {len(result.removed)} periodic task(s):")
42
+ for name in result.removed:
43
+ self.stdout.write(f" {name}")
@@ -0,0 +1,20 @@
1
+ from django_celery_beat.schedulers import DatabaseScheduler
2
+
3
+ from .core import options_for, prune
4
+
5
+
6
+ class PruningScheduler(DatabaseScheduler):
7
+ """DatabaseScheduler that also removes rows the beat schedule no longer defines.
8
+
9
+ Use it in place of DatabaseScheduler::
10
+
11
+ CELERY_BEAT_SCHEDULER = "django_celery_beat_prune.PruningScheduler"
12
+
13
+ Pruning runs once, at Beat start, right after the stock scheduler has
14
+ written the settings into the table. The `enabled` flag is never touched,
15
+ so disabling a task in the admin still works as an emergency switch.
16
+ """
17
+
18
+ def setup_schedule(self):
19
+ super().setup_schedule()
20
+ prune(self.app, options_for(self.app), schedule=self._schedule)
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-celery-beat-prune
3
+ Version: 1.0.0
4
+ Summary: Make CELERY_BEAT_SCHEDULE authoritative for django-celery-beat: a periodic task removed from settings stops running instead of living on as a database row.
5
+ Author-email: TheLoops <support@theloops.live>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://theloops.live/engineering/django-celery-beat-prune
8
+ Project-URL: Source, https://github.com/theloops-live/django-celery-beat-prune
9
+ Keywords: django,celery,celery-beat,django-celery-beat,periodic-tasks,scheduler
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: Celery
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: System :: Distributed Computing
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: django-celery-beat>=2.5
19
+ Requires-Dist: celery>=5.3
20
+ Requires-Dist: Django>=4.2
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == "test"
23
+ Requires-Dist: pytest-django>=4.5; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # django-celery-beat-prune
27
+
28
+ Delete an entry from `CELERY_BEAT_SCHEDULE`, deploy, and with
29
+ [django-celery-beat](https://github.com/celery/django-celery-beat) the task
30
+ **keeps running**. `DatabaseScheduler` copies your settings into the
31
+ `PeriodicTask` table on every Beat start with `update_or_create`, and nothing
32
+ ever deletes. The row stays there and stays enabled, firing on schedule. Nothing
33
+ in the logs says so, and the deploy looks like it worked.
34
+
35
+ This package adds the missing half. Settings become the schedule, and the
36
+ table becomes a copy of it: when Beat starts, rows with no entry in
37
+ `CELERY_BEAT_SCHEDULE` are removed, and each one is named in the log.
38
+
39
+ ```python
40
+ # settings.py
41
+ CELERY_BEAT_SCHEDULER = "django_celery_beat_prune.PruningScheduler"
42
+ ```
43
+
44
+ That's the whole setup. Restart Beat, and any task you have removed from
45
+ settings stops.
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install django-celery-beat-prune
51
+ ```
52
+
53
+ Add the app if you want the management command:
54
+
55
+ ```python
56
+ INSTALLED_APPS = [
57
+ # ...
58
+ "django_celery_beat",
59
+ "django_celery_beat_prune",
60
+ ]
61
+ ```
62
+
63
+ Requires Python 3.10+, Django 4.2+, Celery 5.3+ and django-celery-beat 2.5+.
64
+ CI tests both the oldest and the newest of each.
65
+
66
+ ## What it does, and what it deliberately doesn't
67
+
68
+ - **Rows are deleted, not disabled.** `update_or_create` never writes
69
+ `enabled`. A row disabled by mistake would stay disabled through every later
70
+ restart, and that task would be silently dead. A row deleted by mistake is
71
+ recreated from settings at the next start.
72
+ - **The `enabled` flag is never touched.** Unticking *Enabled* in the admin
73
+ keeps working as the emergency switch that needs no deploy.
74
+ - **An empty schedule prunes nothing.** If `CELERY_BEAT_SCHEDULE` comes back
75
+ empty, settings almost certainly failed to load. Taken literally, an empty
76
+ schedule would delete every row and stop everything, so the package logs a
77
+ warning and leaves the table alone.
78
+ - **Celery's own `celery.backend_cleanup` is kept.** Beat recreates it at every
79
+ start anyway.
80
+ - **One-off tasks are kept by default.** Rows with `one_off=True` are
81
+ normally created from code for a single run and were never meant to be in
82
+ settings.
83
+ - **A pruned task can't fire one last time.** It is also dropped from the
84
+ schedule the running Beat already holds, so it can't fire before Beat next
85
+ re-reads the table.
86
+
87
+ ## Tasks created in the admin
88
+
89
+ If you also create periodic tasks by hand or from code, protect them by name or
90
+ by shell-style pattern:
91
+
92
+ ```python
93
+ CELERY_BEAT_PRUNE_KEEP = ["manual-*", "nightly-export"]
94
+ ```
95
+
96
+ ## Options
97
+
98
+ | Setting | Default | Meaning |
99
+ |---|---|---|
100
+ | `CELERY_BEAT_PRUNE_KEEP` | `()` | Names or patterns (`fnmatch`) never removed |
101
+ | `CELERY_BEAT_PRUNE_DRY_RUN` | `False` | Log what would be removed, remove nothing |
102
+ | `CELERY_BEAT_PRUNE_ONE_OFF` | `False` | Also remove `one_off=True` rows |
103
+
104
+ These are read from your Celery config (`beat_prune_keep`, and so on) or,
105
+ failing that, from the Django settings above.
106
+
107
+ ## Look before you prune
108
+
109
+ The first time, see what would go without restarting Beat:
110
+
111
+ ```bash
112
+ python manage.py prune_periodic_tasks --dry-run
113
+ python manage.py prune_periodic_tasks --keep "manual-*"
114
+ ```
115
+
116
+ The command needs your Celery app to be imported, which it is in the usual
117
+ layout (`from .celery import app as celery_app` in your project's
118
+ `__init__.py`).
119
+
120
+ ## Using the function directly
121
+
122
+ ```python
123
+ from django_celery_beat_prune import prune, Options
124
+
125
+ result = prune(app, Options(keep=("manual-*",), dry_run=True))
126
+ print(result.removed)
127
+ ```
128
+
129
+ ## Why this exists
130
+
131
+ We run [TheLoops](https://theloops.live), which streams pre-recorded video to
132
+ YouTube, Twitch and other platforms around the clock, and its periodic work runs
133
+ on Celery Beat. We once commented a task out of settings because it made
134
+ about 10,000 useless API calls a day. When we later moved Beat's schedule into
135
+ the database, we noticed that on a plain `DatabaseScheduler` that fix would
136
+ have changed nothing. This package is the scheduler we wrote then. The background is in
137
+ [our engineering notes](https://theloops.live/engineering/django-celery-beat-prune).
138
+
139
+ ## License
140
+
141
+ MIT
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/django_celery_beat_prune/__init__.py
5
+ src/django_celery_beat_prune/core.py
6
+ src/django_celery_beat_prune/scheduler.py
7
+ src/django_celery_beat_prune.egg-info/PKG-INFO
8
+ src/django_celery_beat_prune.egg-info/SOURCES.txt
9
+ src/django_celery_beat_prune.egg-info/dependency_links.txt
10
+ src/django_celery_beat_prune.egg-info/requires.txt
11
+ src/django_celery_beat_prune.egg-info/top_level.txt
12
+ src/django_celery_beat_prune/management/__init__.py
13
+ src/django_celery_beat_prune/management/commands/__init__.py
14
+ src/django_celery_beat_prune/management/commands/prune_periodic_tasks.py
15
+ tests/test_live_beat.py
16
+ tests/test_prune.py
@@ -0,0 +1,7 @@
1
+ django-celery-beat>=2.5
2
+ celery>=5.3
3
+ Django>=4.2
4
+
5
+ [test]
6
+ pytest>=7
7
+ pytest-django>=4.5
@@ -0,0 +1,67 @@
1
+ """A real `celery beat` process, started the way a deployment starts it.
2
+
3
+ The unit tests call setup_schedule() by hand. This one checks the part they
4
+ cannot: that Celery resolves "django_celery_beat_prune.PruningScheduler" from
5
+ the setting, after Django is set up, and that a stale row is gone once Beat
6
+ has started.
7
+ """
8
+ import os
9
+ import sqlite3
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import pytest
16
+
17
+ pytestmark = pytest.mark.live
18
+
19
+ ROOT = Path(__file__).resolve().parent.parent
20
+
21
+
22
+ def run(args, env, **kw):
23
+ return subprocess.run([sys.executable, *args], cwd=ROOT, env=env, capture_output=True, text=True, **kw)
24
+
25
+
26
+ def test_beat_removes_a_stale_row_at_start(tmp_path):
27
+ db = tmp_path / "beat.sqlite3"
28
+ env = {
29
+ **os.environ,
30
+ "DJANGO_SETTINGS_MODULE": "tests.settings",
31
+ "PRUNE_TEST_DB": str(db),
32
+ "PYTHONPATH": os.pathsep.join([str(ROOT / "src"), str(ROOT)]),
33
+ }
34
+ migrated = run(["-m", "django", "migrate", "--verbosity", "0"], env)
35
+ assert migrated.returncode == 0, migrated.stderr
36
+
37
+ seed = (
38
+ "import django; django.setup();"
39
+ "from django_celery_beat.models import IntervalSchedule, PeriodicTask;"
40
+ "i = IntervalSchedule.objects.create(every=1, period='hours');"
41
+ "PeriodicTask.objects.create(name='left-behind', task='tests.heartbeat', interval=i)"
42
+ )
43
+ seeded = run(["-c", seed], env)
44
+ assert seeded.returncode == 0, seeded.stderr
45
+
46
+ beat = subprocess.Popen(
47
+ [sys.executable, "-m", "celery", "-A", "tests.celery_app", "beat", "--loglevel", "INFO",
48
+ "--pidfile", str(tmp_path / "beat.pid")],
49
+ cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
50
+ )
51
+ try:
52
+ deadline = time.monotonic() + 30
53
+ rows = None
54
+ while time.monotonic() < deadline:
55
+ time.sleep(0.5)
56
+ with sqlite3.connect(db) as conn:
57
+ rows = {r[0] for r in conn.execute("select name from django_celery_beat_periodictask")}
58
+ if "heartbeat" in rows and "left-behind" not in rows:
59
+ break
60
+ finally:
61
+ beat.terminate()
62
+ output = beat.communicate(timeout=15)[0]
63
+
64
+ assert "PruningScheduler" in output, output
65
+ assert rows is not None and "heartbeat" in rows, output
66
+ assert "left-behind" not in rows, output
67
+ assert "left-behind" in output # named in the warning
@@ -0,0 +1,202 @@
1
+ """The schedule in the database has to stay settings-shaped.
2
+
3
+ Stock DatabaseScheduler only adds and updates rows, so what is worth testing is
4
+ the part this package adds: an entry deleted from CELERY_BEAT_SCHEDULE stops
5
+ running. The rest guards the ways pruning could go wrong - deleting Celery's
6
+ own default entry, emptying the table when settings failed to load, or eating
7
+ rows someone created on purpose.
8
+ """
9
+ import logging
10
+ from datetime import timedelta
11
+
12
+ import pytest
13
+ from celery.schedules import crontab
14
+ from django.core.management import CommandError, call_command
15
+ from django.test import override_settings
16
+ from django_celery_beat.models import ClockedSchedule, IntervalSchedule, PeriodicTask
17
+
18
+ from django_celery_beat_prune import DEFAULT_ENTRY_NAMES, Options, PruningScheduler, options_for, prune
19
+ from tests.celery_app import app
20
+
21
+ pytestmark = pytest.mark.django_db
22
+
23
+ CLEANUP = "celery.backend_cleanup"
24
+ KEPT = {"task": "tests.heartbeat", "schedule": timedelta(minutes=1)}
25
+ DROPPED = {"task": "tests.heartbeat", "schedule": timedelta(hours=6)}
26
+
27
+
28
+ @pytest.fixture
29
+ def schedule():
30
+ """Set CELERY_BEAT_SCHEDULE for the rest of the test.
31
+
32
+ Assigning to app.conf.beat_schedule looks like it works and does not:
33
+ Celery's config is a ChainMap and the Django settings layer, where
34
+ CELERY_BEAT_SCHEDULE lives, is consulted first. Overriding the setting is
35
+ also the honest test, because settings is what Beat reads.
36
+ """
37
+ overrides = []
38
+
39
+ def use(value, **extra):
40
+ override = override_settings(CELERY_BEAT_SCHEDULE=value, **extra)
41
+ override.enable()
42
+ overrides.append(override)
43
+
44
+ yield use
45
+ for override in reversed(overrides):
46
+ override.disable()
47
+
48
+
49
+ def start_beat(schedule, value, **extra):
50
+ """What Beat does at start: build the scheduler and set the schedule up."""
51
+ schedule(value, **extra)
52
+ scheduler = PruningScheduler(app=app, lazy=True)
53
+ # DatabaseScheduler registers an at-exit sync() that would touch the
54
+ # database after pytest-django has closed it; a test has nothing to sync.
55
+ scheduler._finalize.cancel()
56
+ scheduler.setup_schedule()
57
+ return scheduler
58
+
59
+
60
+ def names():
61
+ return set(PeriodicTask.objects.values_list("name", flat=True))
62
+
63
+
64
+ def add_row(name, **fields):
65
+ interval, _ = IntervalSchedule.objects.get_or_create(every=10, period=IntervalSchedule.MINUTES)
66
+ return PeriodicTask.objects.create(name=name, task="tests.heartbeat", interval=interval, **fields)
67
+
68
+
69
+ class TestStockBehaviourIsKept:
70
+ def test_every_entry_becomes_a_row(self, schedule):
71
+ start_beat(
72
+ schedule,
73
+ {
74
+ "alpha": {**KEPT, "options": {"queue": "periodic"}},
75
+ "beta": {"task": "tests.heartbeat", "schedule": crontab(hour=7, minute=7)},
76
+ },
77
+ )
78
+ assert names() == {"alpha", "beta", CLEANUP}
79
+ assert PeriodicTask.objects.get(name="alpha").queue == "periodic"
80
+
81
+ def test_starting_twice_changes_nothing(self, schedule):
82
+ start_beat(schedule, {"alpha": KEPT})
83
+ first = set(PeriodicTask.objects.values_list("id", flat=True))
84
+ start_beat(schedule, {"alpha": KEPT})
85
+ assert set(PeriodicTask.objects.values_list("id", flat=True)) == first
86
+
87
+
88
+ class TestPruning:
89
+ def test_an_entry_removed_from_settings_stops_running(self, schedule):
90
+ start_beat(schedule, {"kept": KEPT, "dropped": DROPPED})
91
+ assert "dropped" in names()
92
+
93
+ scheduler = start_beat(schedule, {"kept": KEPT})
94
+
95
+ assert names() == {"kept", CLEANUP}
96
+ # Gone from the schedule this process already holds too, so it cannot
97
+ # fire once more before Beat next re-reads the table.
98
+ assert "dropped" not in scheduler.schedule
99
+ assert "kept" in scheduler.schedule
100
+
101
+ def test_a_row_created_outside_settings_is_removed(self, schedule):
102
+ add_row("added-in-the-admin")
103
+ start_beat(schedule, {"kept": KEPT})
104
+ assert names() == {"kept", CLEANUP}
105
+
106
+ def test_celerys_own_default_entry_survives(self, schedule):
107
+ start_beat(schedule, {"kept": KEPT})
108
+ assert CLEANUP in names()
109
+ assert DEFAULT_ENTRY_NAMES == {CLEANUP}
110
+
111
+ def test_an_empty_schedule_deletes_nothing(self, schedule, caplog):
112
+ """Empty means settings failed to load, not that everything was removed."""
113
+ start_beat(schedule, {"kept": KEPT})
114
+ schedule({})
115
+ with caplog.at_level(logging.WARNING, logger="django_celery_beat_prune"):
116
+ result = prune(app)
117
+ assert result.skipped_reason == "empty_schedule"
118
+ assert names() == {"kept", CLEANUP}
119
+ assert "not pruning" in caplog.text
120
+
121
+ def test_a_disabled_entry_still_in_settings_is_left_alone(self, schedule):
122
+ """Disabling in the admin is the emergency lever that needs no deploy.
123
+ Pruning must not delete the row and quietly re-enable the task."""
124
+ start_beat(schedule, {"kept": KEPT})
125
+ PeriodicTask.objects.filter(name="kept").update(enabled=False)
126
+ start_beat(schedule, {"kept": KEPT})
127
+ assert PeriodicTask.objects.get(name="kept").enabled is False
128
+
129
+ def test_the_removal_is_logged_by_name(self, schedule, caplog):
130
+ add_row("old-report")
131
+ with caplog.at_level(logging.WARNING, logger="django_celery_beat_prune"):
132
+ start_beat(schedule, {"kept": KEPT})
133
+ assert "Removing 1 periodic task(s)" in caplog.text
134
+ assert "old-report" in caplog.text
135
+
136
+
137
+ class TestOptions:
138
+ def test_keep_accepts_names_and_patterns(self, schedule):
139
+ for name in ("admin-backup", "admin-report", "manual", "stale"):
140
+ add_row(name)
141
+ start_beat(schedule, {"kept": KEPT}, CELERY_BEAT_PRUNE_KEEP=["admin-*", "manual"])
142
+ assert names() == {"kept", CLEANUP, "admin-backup", "admin-report", "manual"}
143
+
144
+ def test_keep_as_a_single_string(self, schedule):
145
+ add_row("manual")
146
+ start_beat(schedule, {"kept": KEPT}, CELERY_BEAT_PRUNE_KEEP="manual")
147
+ assert "manual" in names()
148
+
149
+ def test_dry_run_reports_and_deletes_nothing(self, schedule, caplog):
150
+ add_row("stale")
151
+ with caplog.at_level(logging.WARNING, logger="django_celery_beat_prune"):
152
+ start_beat(schedule, {"kept": KEPT}, CELERY_BEAT_PRUNE_DRY_RUN=True)
153
+ assert "stale" in names()
154
+ assert "Would remove 1" in caplog.text
155
+
156
+ def test_one_off_rows_are_kept_by_default(self, schedule):
157
+ """One-off tasks are created from code for a single run; they were never
158
+ going to be in settings."""
159
+ clocked = ClockedSchedule.objects.create(clocked_time="2099-01-01T00:00:00Z")
160
+ PeriodicTask.objects.create(name="send-once", task="tests.heartbeat", clocked=clocked, one_off=True)
161
+ start_beat(schedule, {"kept": KEPT})
162
+ assert "send-once" in names()
163
+
164
+ def test_one_off_rows_can_be_pruned_too(self, schedule):
165
+ clocked = ClockedSchedule.objects.create(clocked_time="2099-01-01T00:00:00Z")
166
+ PeriodicTask.objects.create(name="send-once", task="tests.heartbeat", clocked=clocked, one_off=True)
167
+ start_beat(schedule, {"kept": KEPT}, CELERY_BEAT_PRUNE_ONE_OFF=True)
168
+ assert "send-once" not in names()
169
+
170
+ def test_options_default_when_nothing_is_set(self, schedule):
171
+ schedule({"kept": KEPT})
172
+ assert options_for(app) == Options()
173
+
174
+
175
+ class TestCommand:
176
+ def test_dry_run_lists_and_keeps(self, schedule, capsys):
177
+ schedule({"kept": KEPT})
178
+ add_row("stale")
179
+ call_command("prune_periodic_tasks", "--dry-run")
180
+ assert "Would remove 1 periodic task(s)" in capsys.readouterr().out
181
+ assert "stale" in names()
182
+
183
+ def test_removes_and_honours_keep(self, schedule, capsys):
184
+ schedule({"kept": KEPT})
185
+ add_row("stale")
186
+ add_row("manual")
187
+ call_command("prune_periodic_tasks", "--keep", "manual")
188
+ out = capsys.readouterr().out
189
+ assert "Removed 1 periodic task(s)" in out
190
+ assert names() == {"manual"}
191
+
192
+ def test_refuses_on_an_empty_schedule(self, schedule):
193
+ schedule({})
194
+ add_row("stale")
195
+ with pytest.raises(CommandError):
196
+ call_command("prune_periodic_tasks")
197
+ assert "stale" in names()
198
+
199
+ def test_nothing_to_prune(self, schedule, capsys):
200
+ schedule({"kept": KEPT})
201
+ call_command("prune_periodic_tasks")
202
+ assert "Nothing to prune." in capsys.readouterr().out