← Back to DAGDA | Support | Source: https://github.com/GrahamDumpleton/mod_wsgi/issues/43
Skip to content

Calling PyCG_Collect before destroying sub interpreter. #43

Closed

Description

@GrahamDumpleton

See:

http://emptysqua.re/blog/a-normal-accident-in-python-and-mod-wsgi/

The Python internals does not itself trigger garbage collection before destroying a sub interpreter.

In face value this appears to be wrong and it should.

Look at triggering it explicitly in mod_wsgi.

Activity

  1. GrahamDumpleton commented on Nov 1, 2014

    @GrahamDumpleton
    OwnerAuthor

    Test code is:

    class C(object):
        pass
    
    class Pool(object):
        def __del__(self):
            print('del')
            list()
    
    C.pool = Pool()
    

    Put this in a WSGI script file which is executed in context of a sub interpreter.

    Simply adding PyGC_Collect() call before PyEnd_Interpreter() doesn't solve the problem.

    There looks to be a bigger problem in the Python interpreter shutdown itself as __del__() methods of objects created in a sub interpreter should not be getting called when the main interpreter is being shutdown.

  2. GrahamDumpleton commented on Nov 1, 2014

    @GrahamDumpleton
    OwnerAuthor

    This is seriously obscure bug in Python.

    Use test:

    class C(object):
        pass
    
    class Pool(object):
        def __init__(self):
            self.myimport = __import__
        def __del__(self):
            mod_wsgi = self.myimport('mod_wsgi')
            print('del in %r' % mod_wsgi.application_group)
            list()
    
    import mod_wsgi
    print('init %r' % mod_wsgi.application_group)
    
    C.pool = Pool()
    

    When run as test, one gets:

    init 'xxx'
    del in ''
    Exception TypeError: "'NoneType' object is not callable" in <bound method Pool.__del__ of <__wsgi__.Pool object at 0x10fe72150>> ignored
    

    So the test confirms that the __del__() was called in the wrong interpreter context.

  3. pitrou commented on Jul 3, 2015

    @pitrou

    It's not a bug in Python, it just shows that subinterpreters are much less isolated from each other than people may assume. The GC is a global operation, it operates on the whole object graph: there is no distinct per-interpreter subgraph to operate on.

    If you really depend on destructors being called from the "right" subinterpreter, then you should strive to avoid reference cycles (using weakrefs is a way to do so).

  4. rbtcollins commented on Jan 21, 2018

    @rbtcollins

    So there's a couple of separate things here. One is as @pitrou says, subinterpreters share a lot of machinery - malloc arenas, the GIL, and so on. Or they used to, I haven't tracked all the recent changes.

    Secondly, __del__ doesn't usually do what people want it to do: Python does not guarantee calling del at all, ever. https://docs.python.org/3/reference/datamodel.html#object.__del__ - note the two specific cases: if the reference count does not hit zero, __del__ is not called (cycle breaking is one way that we try to call __del__ - but cannot guarantee we will. Secondly interpreter shutdown does not guarantee calling __del__ at all, and I'd expect subinterpreter shutdown to equally have no guarantee there - both because of the shared memory model and because of the requirement that shutdown actually, you know, shutdown: blocking forever until the ref count hits 0 would be a great way to not shutdown.

    As for the issue you are encountering, doing a GC before subinterpreter shutdown is irrelevant to this issue: the underlying sequence of interactions is this:

    1. there is a live reference to pool (mod.Pool)
    2. that reference gets cleared when the module globals are cleared (now we have mod.Pool = None)
    3. Pool has a refcount > 0 so it is not freed by step 2
    4. builtins.list has been cleared at the same time (either before or after, doesn't matter right now)
    5. sometime later gc runs which leads to Pool being freed and __del__ running. But list is not a valid symbol anymore, so boom.

    If we do a GC before step 2, it has no effect and rightly so.
    If we do a GC after step 4, it only moves the error to 'right now' rather than whenever GC would have occured on its own.

    How can you fix this permanently?

    1. Well the Pool code has to be written such that __del__ works when:
    • no module globals in any module have a value: Specifically, nothing in the current module, and nothing in builtins, can be depended on.
    1. To avoid Pool hanging around, it must have exactly one reference to it - the module reference. It cannot have a self reference or anything in it refering to it.

    NB: If builtins.list is cleared before step 2, then even if Pool is freed immediately the module globals are cleared, the code would still error - because the list function is set to None. So all things needed in the __del__ should be captured in a closure of some sort - e.g. on the instance

    From mod_wsgi's perspective, you could abstract this and offer an object with the following semantics:

    • created before any user code
    • guaranteed (unless the user does something against the rules) to have exactly one reference and to be freed when the module globals are zeroed on
    • holds references to anything that should be freed at mod_wsgi shutdown: so rather than module.pool or whatever, people would say 'thisspecialobject.pool = whatever'.

    Folk would still have to be careful of any use of globals in __del__ of course.

  5. pitrou commented on Jan 21, 2018

    @pitrou

    You can also use weakref.finalize, which will register an atexit handler for the finalizer to be called. In Python 3.7, atexit handlers are per-interpreter so it should work as you expect.

  6. pitrou commented on Jan 21, 2018

    @pitrou
  7. GrahamDumpleton commented on Jan 21, 2018

    @GrahamDumpleton
    OwnerAuthor

    FWIW, mod_wsgi has implemented itself calling of atexit callbacks in sub interpreters prior to destruction of sub interpreters for all Python versions for a very long time. So if workarounds for this problem in underlying CPython can be implemented on top of atexit then that can be used. Based on my experience and attitudes I have seen by module authors in the past around other issues which cause their modules not to work in sub interpreters, I expect no one to actually implement any such workaround just so their code works in sub interpreters. It is such a niche use case they will not bother.

    In practice the only real solution for this is to not use sub interpreters at all. As long as people follow the current best practice recommendation when using mod_wsgi of using daemon mode, running each WSGI application in a separate daemon process group, and forcing the use of the first interpreter context, they will avoid as much as they can the various issues with sub interpreters.

    I am going to close this as there isn't anything more mod_wsgi can do about it given that it is due to how CPython itself works and the limitations on sub interpreters. The idea that mod_wsgi implement some special object to be used by code authors to deal with this case would be a waste of time as it would never be used.

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions