id,summary,reporter,owner,description,type,status,component,version,severity,resolution,keywords,cc,stage,has_patch,needs_docs,needs_tests,needs_better_patch,easy,ui_ux 17956,Explicit closing cursors is required for the consistency in multithread environment,Vsevolod Novikov,nobody,"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 - SQLInsertCompiler.execute_sql - SQLUpdateCompiler.execute_sql - order_modified_iter - 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 ",Cleanup/optimization,closed,"Database layer (models, ORM)",1.3,Normal,duplicate,"thread, threading, cursor, close, finalization, __del__, out of sync, twisted",,Accepted,1,0,0,0,0,0