Skip to content

KeyValueStoreBackend: assumes chord's group result exists #1094

Closed

Description

@bpowers

During a time of (very) high DB load on our slow Amazon RDS mysql
database, we began seeing these errors in our celery worker logs:

INTERNAL ERROR: TypeError("object of type 'NoneType' has no len()",)
Traceback (most recent call last):
  File ".../celery/task/trace.py", line 266, in trace_task
    on_chord_part_return(task)
  File ".../celery/backends/base.py", line 475, in on_chord_part_return
    if val >= len(deps):
TypeError: object of type 'NoneType' has no len()

The errors were in the logs, but not logged in sentry (I guess they're
too low in the stack for the django/raven handler? IDK).

GroupResult.restore calls backend.restore_group, and the result of
this call (deps) is used as a list in
KeyValueStoreBackend.on_chord_part_return on
celery/backends/base.py:475. However, if the group result has expired
or otherwise disappeared from the backend (in our case redis),
_restore_group will return None. I think the correct thing to do in this case
is to simply return.

I've a patch here to do so:
bpowers@e852409

feel free to apply to your tree or I can submit a pull request if it looks good, otherwise we can discuss here :)

Activity

  1. bpowers commented on Nov 29, 2012

    @bpowers
    ContributorAuthor

    After talking with some colleagues here at SocialCode, we're not convinced that the chord takes over 3 hours (which is what we have the expire time set to), so maybe this is a symptom of another bug.

  2. bpowers commented on Nov 29, 2012

    @bpowers
    ContributorAuthor

    Other clues are that after we get these errors, the queue builds up and stops being processed. Maybe because these low-level exceptions kill the greenlet (we're using the gevent worker class) they're running on, eventually leaving no greenlets to process the queue?

    When we run redis-cli MONITOR we get this result:
    https://gist.github.com/0a11797e13856067ef77

    So - the normal celeryev heartbeat/status stuff and kombu.transport.redis's QoS.restore_visible() function, thats it. I don't know kombu/celery enough to know exactly whats going on there, but maybe that helps

  3. ask commented on Dec 3, 2012

    @ask
    Contributor

    Using 3.0 branch I tried adding raise TypeError to KeyValueStoreBackend.on_chord_part_return, and starting the worker with -P gevent -c1, and it does not crash the greenthread.

    So maybe something else is going on, though definitely the chord shouldn't crash because of a missing group result, so that needs to be fixed.

    We must decide on how chords handle errors, currently it will actually forward the exception to the chord callback,
    which may not be serializable when using json. One possible solution is adding a dedicated errback.

    I really need more information for this bug though, like if the group result key really does expire or not

  4. jbeard565 commented on Feb 23, 2013

    @jbeard565

    I get the same error with a trivial example app just by trying to use the pylibmc cache backend. I'm only getting started, so the entire app is just pieces I copied out of the various docs. I believe any use of chord while using a cache backend will result in the same error as above.

    Before configuring the pylibmc backend, I was using rabbitmq on the backend, and this particular issue never happened. (There were different issues that led me to try using memcached, which brought me here).

    Like bpowers (above), I experimented with a local change to on_chord_part_return, and determined that the null is coming from GroupResult.restore(), but in my case (using memcached) it is ALWAYS None.

    [2013-02-23 01:21:08,591: CRITICAL/MainProcess] Task tasks.mathTasks.add[1e348bf1-dfd5-4e00-bd80-a47bb8d1a591] INTERNAL ERROR: TypeError("object of type 'NoneType' has no len()",)
    Traceback (most recent call last):
    File "/usr/local/lib/python2.7/site-packages/celery/task/trace.py", line 272, in trace_task
    on_chord_part_return(task)
    File "/usr/local/lib/python2.7/site-packages/celery/backends/base.py", line 496, in on_chord_part_return
    if val >= len(deps):
    TypeError: object of type 'NoneType' has no len()

    ---[ here's my celery report output / #### to protect the innocent ] -----------
    [test@####] PYTHONPATH=hello/src/ celery -A tasks.taskMaster report

    software -> celery:3.0.15 (Chiastic Slide) kombu:2.5.6 py:2.7.3
    billiard:2.7.3.21 librabbitmq:1.0.1
    platform -> system:Linux arch:64bit, ELF imp:CPython
    loader -> celery.loaders.app.AppLoader
    settings -> transport:librabbitmq results:cache

    BROKER_URL: 'amqp://someuser:somepass@####.com/testvhost'
    CELERY_CACHE_BACKEND: 'pylibmc://####.com:11211;####:11211;####:11211'
    CELERY_IMPORTS: ['tasks.stringTasks', 'tasks.mathTasks']
    CELERY_RESULT_BACKEND: 'cache'
    CELERY_TASK_RESULT_EXPIRES: 3600

    --jeff

    seems to be the same issue as #1052 (above)

  5. added a commit that references this issue on Mar 5, 2013
    5b3eef5
  6. ask commented on Mar 5, 2013

    @ask
    Contributor

    Closed by 5b3eef5

  7. dnathe4th commented on Apr 3, 2013

    @dnathe4th

    Unfortunately I'm still seeing this in 3.0.17

    Traceback (most recent call last):
    
    File "XXXXXXX/current/local/lib/python2.7/site-packages/celery-3.0.17-py2.7.egg/celery/task/trace.py", line 272, in trace_task
      on_chord_part_return(task)
    File "XXXXXXX/current/local/lib/python2.7/site-packages/celery-3.0.17-py2.7.egg/celery/backends/base.py", line 498, in on_chord_part_return
      if val >= len(deps):
    TypeError: object of type ‘NoneType’ has no len()

    Similar symptoms as described above, workers seem to die under high load / high volume / large unprocessed queue. At first we also thought it was a key expiring (we've got the redis backend as well), but I would have assumed the last update would have fixed that.

    What else can I provide to help troubleshooting?

  8. zhxgigi commented on Apr 10, 2013

    @zhxgigi

    @ask @dnathe4th, this problems also happened in 3.0.16:

    [2013-04-10 02:47:11,530: WARNING/PoolWorker-9] /usr/local/lib/python2.7/dist-packages/celery/task/trace.py:336: RuntimeWarning:       Exception raised outside body: TypeError("object of type 'NoneType' has no len()",):
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/celery/task/trace.py", line 272, in trace_task
        on_chord_part_return(task)
      File "/usr/local/lib/python2.7/dist-packages/celery/backends/base.py", line 497, in on_chord_part_return
        if val >= len(deps):
    TypeError: {'exc_message': "object of type 'NoneType' has no len()", 'exc_type': 'TypeError'}
    
      exc, exc_info.traceback)))
    [2013-04-10 02:47:11,532: CRITICAL/MainProcess] Task XXX.XXX.XXX[a0593def-ea6c-4a31-b0d6-6c300a9a2df2] INTERNAL ERROR:    {'exc_message': "object of type 'NoneType' has no len()", 'exc_type': 'TypeError'}
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/celery/task/trace.py", line 272, in trace_task
        on_chord_part_return(task)
      File "/usr/local/lib/python2.7/dist-packages/celery/backends/base.py", line 497, in on_chord_part_return
        if val >= len(deps):
    TypeError: {'exc_message': "object of type 'NoneType' has no len()", 'exc_type': 'TypeError'}       

    here is out task like:
    chain(group(task1, task2,...,taskN),dummy, group(t1,t2,tN), task, task),

    we have 12 processes on one worker, and about 30 tasks in the redis queue at one time, and 3 of 30 tasks failed on above exceptions, and the other success.

  9. erikcw commented on Jul 5, 2013

    @erikcw

    @ask This ticket should be reopened.

    I'm having the same problem under 3.0.20.

    Traceback (most recent call last):
      File "/Users/erik/.virtualenvs/retargeting/lib/python2.7/site-packages/celery/task/trace.py", line 277, in trace_task
        on_chord_part_return(task)
      File "/Users/erik/.virtualenvs/retargeting/lib/python2.7/site-packages/celery/backends/base.py", line 503, in on_chord_part_return
        if val >= len(deps):
    TypeError: object of type 'NoneType' has no len()
    

    Redis Broker and Redis Backend. CELERY_TASK_RESULT_EXPIRES set to 12 hours.

    Task (with chord) should take about 5-10 minutes to run.

    This tasks imports a large report from an API into our database. Instead of processing it all in one task, a chord is used to break up the task so that the celery worker isn't monopolized and and other tasks can be processed between rows.

    process_report downloads the report, then creates a celery group with a subtask (process_each_row) to process each row of the report (5-6 seconds to process each row). A celery chain is used to combine this group with a final subtask that verifies the import results and marks the job as completed in the database (finsh_processing_report).

    Tasks:

    @task(max_retries=10, rate_limit="12/h")
    def process_report(pk, reprocess_import=False):
        """
        Import the report into the database.  Since this can take several minutes, we are rate limiting it to 12 per hour or 1 every 5 minutes.
        """
        feed_status = FeedStatus.objects.get(pk=pk)
    
        key = "lock:process_report:{0}".format(feed_status.pk)
        lock = get_redis().lock(key, timeout=60*60)
        have_lock = lock.acquire(False)
        if not have_lock:
            logger.info("Could not acquire lock.  Requeue later. {0} (report_id {1})".format(repr(feed_status), feed_status.report_id))
            # could also have the task retry -- but the sweeper task will start a new task so it is redundant.
            return
        if feed_status.report_finished_processing_at and not reprocess_import:
            # report already processed -- skip task.
            logger.info("Already processed {0} (report_id {1})".format(repr(feed_status), feed_status.report_id))
            return "Already Processed"
        # since we are using subtasks, this lock is superceded by the lock at the top of the task
        with global_lock("lock::import_report", 60*30, process_report):
            logger.info("Check job status for {0} (report_id {1})".format(repr(feed_status), feed_status.report_id))
            anx = api.APIClient()
            resp = anx.report_service.report_job_status(feed_status.report_id)
            if resp['response']['execution_status'] == 'ready':
                with transaction.commit_on_success():
                    feed_status.report_ready_at = timezone.now()
                    feed_status.save()
                report_row_count = int(resp['response']['report']['row_count'])
                if report_row_count > 0:
                    resp = anx.report_service.download_report(feed_status.report_id)
                    #feed_status.import_report(resp.iter_lines())
                    task_group = group(process_report_row.si(feed_status.pk, row) for row in feed_status.prep_csv(resp.iter_lines()))
                    ar = chain(task_group, finsh_processing_report.si(feed_status.pk, report_row_count)).delay()
                    logger.info("Report import task chain started.  Task_id: {2}. {0} (report_id {1})".format(repr(feed_status), feed_status.report_id, ar.task_id))
                    return ar.task_id
                else:
                    logger.info("Report had 0 rows. {0} (report_id {1})".format(repr(feed_status), feed_status.report_id))
                    finsh_processing_report(feed_status.pk, report_row_count)
                    return
            else:
                logger.info("Report not ready for download ({2}). {0} (report_id {1})".format(repr(feed_status), feed_status.report_id, resp['response']['execution_status']))
                return process_report.apply_async((feed_status.pk,), countdown=60)
    
    
    @task
    def process_report_row(pk, row):
        feed_status = FeedStatus.objects.get(pk=pk)
        feed_status.process_report_row(row)
    
    @task
    def finsh_processing_report(pk, expected_row_count):
        feed_status = FeedStatus.objects.get(pk=pk)
        row_count = feed_status.factmetrics_set.count()
        assert row_count == expected_row_count, "Report didn't finish processing correctly.  Row counts do not match ({0} != {1})".format(row_count, expected_row_count)
        feed_status.report_finished_processing_at = timezone.now()
        feed_status.save()
        # this isn't stricly necessary, since the lock will TTL on redis anyway.  Just housekeeping.
        key = "lock:process_report:{0}".format(feed_status.pk)
        lock = get_redis().lock(key, timeout=60*60)
        try:
            lock.release()
        except ValueError:
            pass
  10. erikcw commented on Jul 5, 2013

    @erikcw

    Just tested on 3.0.21. Also still an issue.

  11. reopened this on Jul 5, 2013
  12. ask commented on Jul 5, 2013

    @ask
    Contributor

    Thank you, will investigate

  13. zhxgigi commented on Jul 9, 2013

    @zhxgigi

    @ask, I hit this again with celery==3.0.17,
    task chain like: task->group(tasks)->task
    After quick investigate, I think:

    • one of group task execute very slow and exceed task timeout.
    • Celery re-publish t1 as t2,
    • t1 is done, and clear the chord counter.
    • t2 is done but failed on process the counter.

    It seems related to CELERY_TASK_RESULT_EXPIRES and BROKER_TRANSPORT_OPTIONS items, to me it's hard to say it's an issue or improper configuration.

  14. jeffp123 commented on Jul 15, 2013

    @jeffp123

    I came to this page after experiencing the same error. I think it might have something to do with grouping tasks that have "ignore_result=False", in my case anyway. I have not done enough testing to conclude this, but it is something to consider.

  15. maspwr commented on Sep 5, 2013

    @maspwr

    We are using Redis as a broker and result backend. We too are experiencing the TypeError: object of type 'NoneType' has no len() errors. I haven't tracked down the exact circumstances under which it occurs yet, but it is happening very frequently.

    The particular task generating the error is part of a chord. Are there known cases where a chord's group can be deleted while some tasks are still executing?

  16. EnTeQuAk commented on Sep 12, 2013

    @EnTeQuAk

    Hey,

    so we stumbled on this issue yesterday and might have found out the infrastructural reasons for this. Our setup was as follows:

    Two celery workers on two different machines, connected via RabbitMQ with Redis as the result backend. Redis, unfortunately, were running on each of the worker-machine and each worker was pointing to it's own local redis server as the result backend. We got the above error reproduced with this setup perfectly fine. Once we got pointing the workers to a central Redis server for the results the problem just went away.

    Could it be, that the chord somehow evaluates the results of each task but since some of the tasks might actually be executed by a different worker on a different machine, using a different result backend, it can't evaluate the results since it has no access to it.

    At least that's what we have seen.

  17. ask commented on Oct 23, 2013

    @ask
    Contributor

    The above change (d5fa635) should fix this issue, and I also added another change
    so that an error is set on the callback if retrieving the group result raises. Sadly I managed to commit that other change together with another change, but the relevant lines are here: https://github.com/celery/celery/blob/master/celery/backends/base.py#L466-L473

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions