Skip to content

prune_stale_started_celery_tasks

django_spire.celery.management.commands.prune_stale_started_celery_tasks

DEFAULT_THRESHOLD_SECONDS = 600 module-attribute

INSPECT_TIMEOUT_SECONDS = 5 module-attribute

logger = logging.getLogger(__name__) module-attribute

Command

Bases: BaseCommand

help = 'Resolves stale non-terminal CeleryTasks (no meta update past the threshold): syncs CeleryTasks whose backend already reached a terminal state, skips CeleryTasks still active on a worker, and marks the rest FAILURE with a StaleStarted error (worker presumed dead). Stamping is skipped entirely when no live worker answers a ping (an unacked message may still be requeued). --include-pending additionally collects stale PENDING/RECEIVED CeleryTasks: ones whose backend is terminal are synced, the rest are skipped (never stamped, since the message may still be queued or in flight).' class-attribute instance-attribute

add_arguments

Source code in django_spire/celery/management/commands/prune_stale_started_celery_tasks.py
def add_arguments(self, parser: CommandParser) -> None:
    parser.add_argument(
        '--threshold',
        type=float,
        default=DEFAULT_THRESHOLD_SECONDS,
        help=(
            'Seconds without a meta progress update before a non-terminal CeleryTask is '
            f'considered stale (default: {DEFAULT_THRESHOLD_SECONDS}).'
        ),
    )
    parser.add_argument(
        '--include-pending',
        action='store_true',
        help='Also collect stale PENDING/RECEIVED CeleryTasks (sync when the backend is '
        'terminal; never marked FAILURE).',
    )
    parser.add_argument(
        '--dry-run', action='store_true', help='Report stale CeleryTasks without updating them.'
    )

handle

Source code in django_spire/celery/management/commands/prune_stale_started_celery_tasks.py
def handle(self, *args, **options) -> None:  # noqa: ARG002
    threshold_seconds = options['threshold']
    include_pending = options['include_pending']
    cutoff_time = time.time() - threshold_seconds

    stale_celery_tasks = self._collect_stale_celery_tasks(cutoff_time, include_pending)
    if not stale_celery_tasks:
        self.stdout.write('No stale CeleryTasks found.')
        return

    sync_pks: list[int] = []
    skipped_pks: list[int] = []
    started_failure_candidates: list[int] = []
    pending_failure_candidates: list[int] = []
    verdict_buckets = {
        'sync': sync_pks,
        'pending': pending_failure_candidates,
        'failure': started_failure_candidates,
        'skip': skipped_pks,
    }
    for pk, celery_task in stale_celery_tasks.items():
        verdict_buckets[self._classify_stale(celery_task)].append(pk)

    for pk in pending_failure_candidates:
        logger.info(
            'Reaper: skipping stale queued CeleryTask %s (backend not terminal; the '
            'message may still be queued or in flight)',
            stale_celery_tasks[pk].task_id,
        )
        skipped_pks.append(pk)

    live_workers = self._live_workers() if started_failure_candidates else None
    if live_workers is not None and not live_workers:
        logger.warning(
            'Reaper: no live worker answered the ping; %d stale CeleryTask(s) will not be '
            'marked FAILURE (an unacked message may still be requeued)',
            len(started_failure_candidates),
        )

    active_task_ids = self._active_task_ids() if started_failure_candidates else None
    failed_pks: list[int] = []
    for pk in started_failure_candidates:
        if self._stamp_is_safe(stale_celery_tasks[pk], live_workers, active_task_ids):
            failed_pks.append(pk)
        else:
            skipped_pks.append(pk)

    if options['dry_run']:
        self.stdout.write(
            f'{len(sync_pks)} stale CeleryTask(s) would be synced from the backend.'
        )
        self.stdout.write(
            f'{len(skipped_pks)} stale CeleryTask(s) would be skipped (task still alive).'
        )
        self.stdout.write(f'{len(failed_pks)} stale CeleryTask(s) would be marked FAILURE.')
        return

    for pk in sync_pks:
        stale_celery_tasks[pk].services.update_from_backend()

    stamped = 0
    if failed_pks:
        stamped = (
            CeleryTask.objects.filter(pk__in=failed_pks)
            .exclude(state__in=[*states.READY_STATES, *states.EXCEPTION_STATES])
            .update(
                state=states.FAILURE,
                completed_datetime=now(),
                _result=self._stale_stamp(),
            )
        )

    self.stdout.write(
        self.style.SUCCESS(f'Synced {len(sync_pks)} stale CeleryTask(s) from the backend.')
    )
    self.stdout.write(
        self.style.SUCCESS(
            f'Skipped {len(skipped_pks)} stale CeleryTask(s) (task still alive).'
        )
    )
    self.stdout.write(self.style.SUCCESS(f'Marked {stamped} stale CeleryTask(s) as FAILURE.'))