Skip to content

State.tasks_by_worker and State.tasks_by_type misfile or miss tasks when the first event is not the worker's #10987

Done

Description

@avanish-garg

Checklist

  • I have verified that the issue exists against the main branch of Celery.
  • This has already been asked to the discussions forum first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the main branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).
  • I have tried to reproduce the issue with pytest-celery and added the reproduction script below.

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • I have verified that the issue exists against the main branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.

Related Issues and Possible Duplicates

Related Issues

  • None. Searches for tasks_by_worker and tasks_by_type find no existing issue.

Possible Duplicates

  • None

Environment & Settings

Celery version: 5.7.0rc1 (collider), main at 2ef8265

celery report Output:

software -> celery:5.7.0rc1 (collider) kombu:5.7.0rc1 py:3.12.14
            billiard:4.3.1 py-amqp:5.4.1
platform -> system:Darwin arch:64bit
            kernel version:25.3.0 imp:CPython
loader   -> celery.loaders.default.Loader
settings -> transport:amqp results:disabled

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: N/A or Unknown
  • Minimal Celery Version: N/A or Unknown
  • Minimal Kombu Version: N/A or Unknown
  • Minimal Broker Version: N/A or Unknown
  • Minimal Result Backend Version: N/A or Unknown
  • Minimal OS and/or Kernel Version: N/A or Unknown
  • Minimal Broker Client Version: N/A or Unknown
  • Minimal Result Backend Client Version: N/A or Unknown

Python Packages

pip freeze Output:

amqp==5.4.1
billiard==4.3.1
celery @ git+https://github.com/celery/celery@2ef8265b0
click==8.5.0
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.1
kombu==5.7.0rc1
prompt-toolkit==3.0.53
python-dateutil==2.9.0.post0
six==1.17.0
typing-extensions==4.16.0
tzdata==2026.4
tzlocal==5.4.5
vine==5.1.0
wcwidth==0.9.3

Other Dependencies

Details

N/A. No broker or result backend is needed: the reproduction feeds events straight into `celery.events.state.State`.

Minimally Reproducible Test Case

Details

import time

from celery.events import Event
from celery.events.state import State


def ev(type_, **fields):
    return Event(type_, local_received=time.time(), **fields)


# (1) With task_send_sent_event=True the first event for a task is the client's
#     task-sent; the worker's events come afterwards.
s = State()
s.event(ev('task-sent', uuid='task-1', name='proj.add', args='(1, 2)', kwargs='{}',
           hostname='client@host', clock=1, timestamp=time.time()))
for i, (t, extra) in enumerate([
        ('task-received', dict(name='proj.add', args='(1, 2)', kwargs='{}')),
        ('task-started', {}),
        ('task-succeeded', dict(result='3', runtime=0.1))]):
    s.event(ev(t, uuid='task-1', hostname='worker1@host', clock=i + 2,
               timestamp=time.time(), **extra))

print('task.worker.hostname                     =', s.tasks['task-1'].worker.hostname)
print('tasks_by_worker keys                     =', sorted(s.tasks_by_worker.keys()))
print("tasks_by_worker['worker1@host']          =", [t.uuid for t in s.tasks_by_worker['worker1@host']])
print("tasks_by_worker('worker1@host') callable =", [u for u, _ in s.tasks_by_worker('worker1@host')])
print("tasks_by_worker['client@host']           =", [t.uuid for t in s.tasks_by_worker['client@host']])

# (2) First event seen has no name (task-started before task-received, or a
#     monitor attached mid-task): the task never reaches tasks_by_type.
s2 = State()
s2.event(ev('task-started', uuid='t2', hostname='worker1@host', clock=1, timestamp=time.time()))
s2.event(ev('task-received', uuid='t2', name='proj.mul', args='()', kwargs='{}',
            hostname='worker1@host', clock=2, timestamp=time.time()))
print("\ntasks_by_type('proj.mul') callable =", [u for u, _ in s2.tasks_by_type('proj.mul')])
print("tasks_by_type['proj.mul']          =", [t.uuid for t in s2.tasks_by_type['proj.mul']])

# (3) The callable form crashes for a task seen only via task-sent.
s3 = State()
s3.event(ev('task-sent', uuid='t3', name='proj.add', args='()', kwargs='{}',
            hostname='client@host', clock=1, timestamp=time.time()))
try:
    print('\ntasks_by_worker("w") =', list(s3.tasks_by_worker('w')))
except Exception as exc:
    print('\ntasks_by_worker("w") raised', type(exc).__name__, exc)

Output on main:

task.worker.hostname                     = worker1@host
tasks_by_worker keys                     = ['client@host']
tasks_by_worker['worker1@host']          = []
tasks_by_worker('worker1@host') callable = ['task-1']
tasks_by_worker['client@host']           = ['task-1']

tasks_by_type('proj.mul') callable = ['t2']
tasks_by_type['proj.mul']          = []

tasks_by_worker("w") raised AttributeError 'NoneType' object has no attribute 'hostname'

Expected: tasks_by_worker['worker1@host'] lists task-1 (as the callable does), tasks_by_type['proj.mul'] lists t2, and the callable returns an empty list instead of raising. The cause is in State.event (celery/events/state.py): both indexes are only updated if task_created, i.e. from whichever event first creates the task, even though the worker or the task name may only be known from a later event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions