From cc2dbf4db5194d5347c04fc176efd0ea1cf7880c Mon Sep 17 00:00:00 2001 From: "Jens L." Date: Wed, 24 Dec 2025 01:15:45 +0100 Subject: [PATCH] core: use chunked_queryset for expired message deletion (#19028) Signed-off-by: Jens Langhammer --- authentik/core/tasks.py | 9 +++++++-- authentik/lib/utils/db.py | 7 ++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/authentik/core/tasks.py b/authentik/core/tasks.py index 01e029ecee..999c68c9c9 100644 --- a/authentik/core/tasks.py +++ b/authentik/core/tasks.py @@ -35,8 +35,13 @@ def clean_expired_models(): LOGGER.debug("Expired models", model=cls, amount=amount) self.info(f"Expired {amount} {cls._meta.verbose_name_plural}") clear_expired_cache() - Message.delete_expired() - GroupChannel.delete_expired() + for cls in [Message, GroupChannel]: + objects = cls.objects.all().filter(expires__lt=now()) + amount = objects.count() + for obj in chunked_queryset(objects): + obj.delete() + LOGGER.debug("Expired models", model=cls, amount=amount) + self.info(f"Expired {amount} {cls._meta.verbose_name_plural}") @actor(description=_("Remove temporary users created by SAML Sources.")) diff --git a/authentik/lib/utils/db.py b/authentik/lib/utils/db.py index 16687687c9..ef72d76652 100644 --- a/authentik/lib/utils/db.py +++ b/authentik/lib/utils/db.py @@ -1,16 +1,17 @@ """authentik database utilities""" import gc +from collections.abc import Generator from django.db import reset_queries -from django.db.models import QuerySet +from django.db.models import Model, QuerySet -def chunked_queryset(queryset: QuerySet, chunk_size: int = 1_000): +def chunked_queryset[T: Model](queryset: QuerySet[T], chunk_size: int = 1_000) -> Generator[T]: if not queryset.exists(): return [] - def get_chunks(qs: QuerySet): + def get_chunks(qs: QuerySet) -> Generator[QuerySet[T]]: qs = qs.order_by("pk") pks = qs.values_list("pk", flat=True) start_pk = pks[0]