tornado icon indicating copy to clipboard operation
tornado copied to clipboard

Memory issue: Possible reference cycle with run_on_executor

Open peterkorodi opened this issue 7 years ago • 10 comments

Hi, I've built a simple tornado server app and run on python 3.7.2 with tornado 6.0.1:

import tornado.ioloop
import tornado.web
import gc
import sys
from concurrent.futures.thread import ThreadPoolExecutor

from tornado import gen
from tornado.concurrent import run_on_executor

executor = ThreadPoolExecutor(1)


def dump_referrers(obj):
    print(sys.getrefcount(obj))
    for i in gc.get_referrers(obj):
        print('{} {}'.format(type(i).__name__, i))


class Test(object):
    def __init__(self):
        self.l = list(range(0, 100000))

    def __del__(self):
        print('del')


class Factory(object):
    _executor = executor

    @run_on_executor(executor='_executor')
    def run(self):
        test = Test()
        return test

factory = Factory()

class MainHandler(tornado.web.RequestHandler):

    def initialize(self):
        print('Init MainHandler')

    @gen.coroutine
    def get(self):
        test = yield factory.run()
        dump_referrers(test)
        self.write('data: {}'.format(test.l))
        self.finish()
        dump_referrers(test)


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

If I call the endpoint with curl -i -X GET -H 'Content-Type: application/json' http://localhost:8888/ I got the del text on the output of the server which means the ref count of test decreases to 0 and deleted by the system. But If I call it more times. I don't have the del text anymore which means I guess there is a ref cycle which is will be deleted by the GC.

If I create a new run_on_executor_asyncio decorator and use the following code the test object always will be deleted.

import tornado.ioloop
import tornado.web
import gc
import sys
from concurrent.futures.thread import ThreadPoolExecutor
from tornado import gen
from tornado.concurrent import run_on_executor
import asyncio
import functools
from asyncio import Future
from typing import Callable, Any


def run_on_executor_asyncio(*args: Any, **kwargs: Any) -> Callable:
    def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:
        _executor = kwargs.get("executor", "executor")

        @functools.wraps(fn)
        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:
            f = getattr(self, _executor).submit(fn, self, *args, **kwargs)
            return asyncio.wrap_future(f)

        return wrapper

    if args and kwargs:
        raise ValueError("cannot combine positional and keyword args")
    if len(args) == 1:
        return run_on_executor_decorator(args[0])
    elif len(args) != 0:
        raise ValueError("expected 1 argument, got %d", len(args))
    return run_on_executor_decorator



executor = ThreadPoolExecutor(1)


def dump_referrers(obj):
    print(sys.getrefcount(obj))
    for i in gc.get_referrers(obj):
        print('{} {}'.format(type(i).__name__, i))


class Test(object):
    def __init__(self):
        self.l = list(range(0, 100000))

    def __del__(self):
        print('del')


class Factory(object):
    _executor = executor

    @run_on_executor_asyncio(executor='_executor')
    def run(self):
        test = Test()
        return test

factory = Factory()

class MainHandler(tornado.web.RequestHandler):

    def initialize(self):
        print('Init MainHandler')

    @gen.coroutine
    def get(self):
        test = yield factory.run()
        dump_referrers(test)
        self.write('data: {}'.format(test.l))
        self.finish()
        dump_referrers(test)


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

I know that the ref cycles will be removed by GC but If I call that endpoint frequently the memory usage can go up more than 1GB before the GC starts. With the second version of code I can't go up to 100MB.

Is it possible that this is a bug in the run_on_executor decorator?

peterkorodi avatar Mar 12 '19 17:03 peterkorodi

I have a similar problem but with a classic asyncio process executor.

stalkerg avatar Mar 13 '19 07:03 stalkerg

Is it possible that this is a bug in the run_on_executor decorator?

Whether a reference cycle is a bug or not is debatable, but yes, this is an issue that we generally try to fix when we notice it. We just need to add some usage of run_on_executor to maint/circlerefs/circlerefs.py and probably add try/finally blocks to clear references from stack frames when they exit.

Also note that this decorator is discouraged in new code (use IOLoop.run_in_executor instead).

bdarnell avatar Mar 19 '19 03:03 bdarnell

@bdarnell I have a same problem too.My service finally use up to 100G memory

intgogo avatar May 28 '19 06:05 intgogo

Any solutions here? Just adding a: response = yield executor.submit(concurrentOnMessage, ... ) That eventually just returns, even with only 2 threads, creates an explosive memory leak. Doing the same on on_message() does not create a memory leak. Any workarounds?

ndvbd avatar Dec 05 '22 21:12 ndvbd

@ndvbd I have no such issue now with the multiprocess executor. Also, you can avoid most Tornado-specific things nowadays, it's working very close to aiohttp.

stalkerg avatar Dec 06 '22 01:12 stalkerg

For me, the (infinite) memory leak happens when I use python 2.7.18 + tornado 5.1.1 + doing write_message on a different thread (typically with ThreadPoolExecutor). When downgrading tornado to 4.5.3 -> problem is solved.

ndvbd avatar Dec 06 '22 09:12 ndvbd

@ndvbd tornado 5.1.1 is outdated and deprecated, and EOF is the same as Python 2.7. You must migrate to Python 3.10/3.11 and Tornado 6.

stalkerg avatar Dec 07 '22 00:12 stalkerg

For me, the (infinite) memory leak happens when I use python 2.7.18 + tornado 5.1.1 + doing write_message on a different thread

Calling write_message on a different thread is not allowed (this is undefined behavior; maybe it happened to work for you in 4.5.3, but that was a fluke). Almost no tornado methods are thread-safe; see https://www.tornadoweb.org/en/stable/index.html#threads-and-wsgi. You must return from the method that you run on the executor and then write your message from the event loop thread.

@ndvbd Please stop posting on random issues; this is your last warning. If you're using a supported version of tornado, you may create a new issue where you explain exactly what you're doing and how it's not behaving the way you expect, but posting brief comments on every vaguely-related issue is not helpful to anyone.

bdarnell avatar Dec 07 '22 01:12 bdarnell

@bdarnell For me, a comment here regarding a tornado version would have extremely helped, that’s why I thought it would be good to share with others. We spent a week until we figured we should downgrade the version, and it can help others when they compare versions. On the other hand comments about deprecation of python 2.7 are not always helpful, as not always it is easily possible to migrate from 2.7 to 3, unfortunately…

ndvbd avatar Dec 07 '22 05:12 ndvbd

Thanks for the detailed report; I have a (very belated) test and solution in #3315. It happens that the cycles are in IOLoop.add_future and chain_future, not in run_on_executor itself.

bdarnell avatar Aug 22 '23 03:08 bdarnell