core: batch expired cache and channel record cleanup (#27587)

* core: batch expired cache and channel record cleanup

* delete more efficiently

Signed-off-by: Jens Langhammer <[email protected]>

---------

Signed-off-by: Jens Langhammer <[email protected]>
Co-authored-by: Jens Langhammer <[email protected]>
This commit is contained in:
Nuno AlvesandJens Langhammer authored and GitHub committed 2026-11-05 12:54:54 +00:00
1 parent f15be0f1e3
commit 79ef2080f0
5 files changed
+238 -14

No files matched your search

+8 -8
View File
@@ -16,7 +16,7 @@ from authentik.core.models import (
)
from authentik.lib.models import ExpiringModel
from authentik.lib.sync.models import Sync
from authentik.lib.utils.db import chunked_queryset
from authentik.lib.utils.db import chunked_queryset, delete_in_batches
from authentik.tasks.middleware import CurrentTask
LOGGER = get_logger()
@@ -32,17 +32,17 @@ def clean_expired_models():
.exclude(expiring=False)
.exclude(expiring=True, expires__gt=now())
)
amount = objects.count()
for obj in chunked_queryset(objects):
obj.expire_action()
if cls.expire_action is ExpiringModel.expire_action:
amount = delete_in_batches(objects)
else:
amount = objects.count()
for obj in chunked_queryset(objects):
obj.expire_action()
LOGGER.debug("Expired models", model=cls, amount=amount)
self.info(f"Expired {amount} {cls._meta.verbose_name_plural}")
clear_expired_cache()
for cls in [Message, GroupChannel]:
objects = cls.objects.all().filter(expires__lt=now())
amount = objects.count()
for obj in chunked_queryset(objects):
obj.delete()
amount = delete_in_batches(cls.objects.filter(expires__lt=now()))
LOGGER.debug("Expired models", model=cls, amount=amount)
self.info(f"Expired {amount} {cls._meta.verbose_name_plural}")
for cls in Sync.__subclasses__():
+34
View File
@@ -1,8 +1,13 @@
"""Test tasks"""
from datetime import timedelta
from time import mktime
from django.db import connection
from django.test.utils import CaptureQueriesContext
from django.utils.timezone import now
from django_channels_postgres.models import GroupChannel, Message
from django_postgres_cache.models import CacheEntry
from guardian.shortcuts import get_anonymous_user
from rest_framework.test import APITestCase
@@ -20,6 +25,7 @@ from authentik.core.tasks import (
clean_temporary_users,
)
from authentik.core.tests.utils import create_test_admin_user
from authentik.events.models import Event, EventAction
from authentik.lib.generators import generate_id
@@ -51,6 +57,34 @@ class TestTasks(APITestCase):
clean_expired_models.send()
self.assertFalse(Token.objects.filter(pk=token.pk).exists())
def test_clean_expired_storage(self):
"""The task deletes expired storage records while retaining live records."""
for model, fields in (
(CacheEntry, {"cache_key": "cleanup-test", "value": "value"}),
(Message, {"channel": "cleanup-test", "message": b"message"}),
(GroupChannel, {"channel": "cleanup-test", "group_key": "cleanup-test"}),
):
with self.subTest(model=model):
expired = model.objects.create(expires=now() - timedelta(hours=1), **fields)
live_fields = {**fields}
if model is CacheEntry:
live_fields["cache_key"] = "cleanup-test-live"
live = model.objects.create(expires=now() + timedelta(hours=1), **live_fields)
clean_expired_models.send()
self.assertFalse(model.objects.filter(pk=expired.pk).exists())
self.assertTrue(model.objects.filter(pk=live.pk).exists())
def test_expire_bulk(self):
"""Test that many expired objects are deleted in batches, not one query per object"""
Event.objects.all().delete()
Event.objects.bulk_create(
Event(action=EventAction.CUSTOM_PREFIX, app="test", expires=now()) for _ in range(2_500)
)
with CaptureQueriesContext(connection) as ctx:
clean_expired_models.send()
self.assertFalse(Event.objects.including_expired().exists())
self.assertLessEqual(len(ctx.captured_queries), 500)
def test_clean_temporary_users(self):
"""Test clean_temporary_users task"""
username = generate_id
+163
View File
@@ -0,0 +1,163 @@
"""PostgreSQL regression tests for bounded deletion."""
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from threading import Event
from django.db import connection, connections, transaction
from django.db.models.signals import pre_delete
from django.test import TransactionTestCase
from django.test.utils import CaptureQueriesContext
from django.utils.timezone import now
from django_channels_postgres.models import GroupChannel, Message
from django_postgres_cache.models import CacheEntry
from django_postgres_cache.tasks import clear_expired_cache
from authentik.lib.utils.db import delete_in_batches
class TestDeleteInBatches(TransactionTestCase):
"""Use committed rows and separate connections to exercise actual row locks."""
def setUp(self):
self.cutoff = now()
self.expired_at = self.cutoff - timedelta(hours=1)
self.future = self.cutoff + timedelta(hours=1)
CacheEntry.objects.all().delete()
def create_entries(self, count: int) -> None:
CacheEntry.objects.bulk_create(
[
CacheEntry(
cache_key=f"batch-test-{index:04}", value="value", expires=self.expired_at
)
for index in range(count)
]
)
def expired(self):
return CacheEntry.objects.filter(expires__lt=self.cutoff)
def test_empty(self):
self.assertEqual(delete_in_batches(self.expired()), 0)
def test_invalid_batch_size(self):
for batch_size in (0, -1):
with self.subTest(batch_size=batch_size), self.assertRaises(ValueError):
delete_in_batches(self.expired(), batch_size=batch_size)
def test_multiple_batches_preserve_unexpired(self):
self.create_entries(5)
CacheEntry.objects.create(cache_key="future", value="value", expires=self.future)
CacheEntry.objects.create(cache_key="boundary", value="value", expires=self.cutoff)
self.assertEqual(delete_in_batches(self.expired(), batch_size=2), 5)
self.assertSetEqual(
set(CacheEntry.objects.values_list("pk", flat=True)), {"future", "boundary"}
)
def test_query_count_scales_with_batches(self):
self.create_entries(25)
with CaptureQueriesContext(connection) as queries:
self.assertEqual(delete_in_batches(self.expired(), batch_size=10), 25)
deletes = [query for query in queries if query["sql"].startswith("DELETE")]
self.assertEqual(len(deletes), 3)
# Three batches plus an empty probe, including BEGIN/COMMIT per batch.
self.assertLessEqual(len(queries), 18)
def test_cache_cleanup_integration(self):
self.create_entries(1001)
CacheEntry.objects.create(cache_key="future", value="value", expires=self.future)
self.assertEqual(clear_expired_cache(), 1001)
self.assertEqual(list(CacheEntry.objects.values_list("pk", flat=True)), ["future"])
def test_channel_models(self):
for model, fields in (
(Message, {"channel": "batch-test", "message": b"message"}),
(GroupChannel, {"channel": "batch-test", "group_key": "batch-test"}),
):
with self.subTest(model=model):
model.objects.bulk_create(
[model(expires=self.expired_at, **fields) for _ in range(5)]
)
retained = model.objects.create(expires=self.future, **fields)
self.assertEqual(
delete_in_batches(
model.objects.filter(channel="batch-test", expires__lt=self.cutoff),
batch_size=2,
),
5,
)
self.assertTrue(model.objects.filter(pk=retained.pk).exists())
def test_locked_entry_is_skipped_then_cleaned(self):
self.create_entries(3)
with ThreadPoolExecutor(max_workers=1) as executor:
with transaction.atomic():
CacheEntry.objects.select_for_update().get(pk="batch-test-0000")
deleted = executor.submit(self.delete_on_other_connection).result(timeout=10)
self.assertEqual(deleted, 2)
self.assertTrue(CacheEntry.objects.filter(pk="batch-test-0000").exists())
self.assertEqual(delete_in_batches(self.expired()), 1)
def test_concurrent_refresh_survives(self):
self.create_entries(2)
with ThreadPoolExecutor(max_workers=1) as executor:
with transaction.atomic():
CacheEntry.objects.filter(pk="batch-test-0000").update(expires=self.future)
deleted = executor.submit(self.delete_on_other_connection).result(timeout=10)
self.assertEqual(deleted, 1)
self.assertEqual(delete_in_batches(self.expired()), 0)
self.assertEqual(CacheEntry.objects.get(pk="batch-test-0000").expires, self.future)
def test_concurrent_cleanups_do_not_double_count(self):
self.create_entries(4)
selected = Event()
release = Event()
def pause_first_batch(sender, instance, **kwargs):
if instance.pk == "batch-test-0000":
selected.set()
if not release.wait(timeout=10):
raise TimeoutError("Cleanup test did not release the first batch")
# Exercise Django's collector path as well as its fast-delete path.
pre_delete.connect(pause_first_batch, sender=CacheEntry)
try:
with ThreadPoolExecutor(max_workers=1) as executor:
first = executor.submit(self.delete_on_other_connection)
try:
self.assertTrue(selected.wait(timeout=10))
second_count = delete_in_batches(self.expired(), batch_size=2)
finally:
release.set()
self.assertEqual(first.result(timeout=10), 2)
self.assertEqual(second_count, 2)
finally:
pre_delete.disconnect(pause_first_batch, sender=CacheEntry)
self.assertFalse(self.expired().exists())
def test_completed_batch_survives_later_failure(self):
self.create_entries(4)
def fail_second_batch(sender, instance, **kwargs):
if instance.pk == "batch-test-0002":
raise RuntimeError("Second batch failed")
pre_delete.connect(fail_second_batch, sender=CacheEntry)
try:
with self.assertRaisesMessage(RuntimeError, "Second batch failed"):
delete_in_batches(self.expired(), batch_size=2)
finally:
pre_delete.disconnect(fail_second_batch, sender=CacheEntry)
self.assertSetEqual(
set(CacheEntry.objects.values_list("pk", flat=True)),
{"batch-test-0002", "batch-test-0003"},
)
self.assertEqual(delete_in_batches(self.expired()), 2)
def delete_on_other_connection(self) -> int:
"""Close the thread-local connection even if the test fails."""
try:
return delete_in_batches(self.expired(), batch_size=2)
finally:
connections.close_all()
+29 -2
View File
@@ -3,13 +3,13 @@
import gc
from collections.abc import Generator
from django.db import reset_queries
from django.db import reset_queries, transaction
from django.db.models import Model, QuerySet
def chunked_queryset[T: Model](queryset: QuerySet[T], chunk_size: int = 1_000) -> Generator[T]:
if not queryset.exists():
return []
return
def get_chunks(qs: QuerySet) -> Generator[QuerySet[T]]:
qs = qs.order_by("pk")
@@ -37,3 +37,30 @@ def chunked_queryset[T: Model](queryset: QuerySet[T], chunk_size: int = 1_000) -
reset_queries()
gc.collect()
yield from chunk.iterator(chunk_size=chunk_size)
def delete_in_batches[T: Model](queryset: QuerySet[T], batch_size: int = 1_000) -> int:
"""Delete matching rows in short transactions, returning the target model's count.
Call outside an enclosing transaction to release locks after each batch. Use only
for models that do not require instance-level delete/expiration hooks; Django's
deletion signals and cascades still run. Rows locked by another transaction are
skipped and may need a later cleanup run.
"""
if batch_size < 1:
raise ValueError("batch_size must be positive")
# SELECT FOR UPDATE also selects the write database when routers are configured.
queryset = queryset.select_for_update(skip_locked=True, of=("self",))
database = queryset.db
queryset = queryset.using(database)
deleted_total = 0
while True:
with transaction.atomic(using=database):
pks = list(queryset.order_by("pk").values_list("pk", flat=True)[:batch_size])
if not pks:
return deleted_total
# Hold the locks through Django's collector and DELETE so that a cache
# refresh cannot race with deletion after the expiration check.
_, counts = queryset.filter(pk__in=pks).delete()
deleted_total += counts.get(queryset.model._meta.label, 0)
@@ -1,11 +1,11 @@
from django.utils.timezone import now
from authentik.lib.utils.db import chunked_queryset
from authentik.lib.utils.db import delete_in_batches
from django_postgres_cache.models import CacheEntry
def clear_expired_cache() -> None:
def clear_expired_cache() -> int:
"""Delete unlocked expired entries and return the number removed."""
# FIXME: this is currently imported from the main project,
# do we copy it here to make it independent?
for obj in chunked_queryset(CacheEntry.objects.filter(expires__lt=now())):
obj.delete()
return delete_in_batches(CacheEntry.objects.filter(expires__lt=now()))