Explicit closing cursors is required for the consistency in multithread environment
|Reported by:||nnseva||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.3|
|Severity:||Normal||Keywords:||thread, threading, cursor, close, finalization, __del__, out of sync, twisted|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Using django ORM in multithread environment causes rare (ignored) exceptions like 'ProgrammingError: (2014, "Commands out of sync; you can't run this command now")' in Cursor.__del__ method (this particular error happens when using MySQL backend).
I've met this problem using django ORM (over MySQL) together with twisted.thread.deferToThread call.
The problem happens relatively rare, but is critical for 24/7 services, because looks like causing regular memory leaks.
Deep investigating the code concerned to the exception contexts, I've found that almost no one cursor got by django ORM from the backend is closed explicitly.
I've changed the django code to implement explicit cursor closing in all found contexts. After these changes my service leaved for 12 hours of continuous working shown no one exception like this.
All changes have been made in one file, django/db/models/sql/compiler.py
Changes have been made in the following functions and methods:
- SQLCompiler.execute_sql in SINGLE and MULTI cases
- also not_modified_iter iterator (like order_modified_iter) has been added to catch iterator finalization stage
All changes are explicitly closing the cursor got from the backend after use.
The applied patch has been made for django v.1.3.1.final