Skip to main content

Python: Debugging Memory Leaks

I wrote a simple tool that could take Web logs and replay them against a server in "real time". I was performance testing my Web app over the course of a day by hitting it with many days worth of Web logs at the same time.

By monitoring top, I found out that it was leaking memory. I was excited to try out Guppy, but it didn't help. Neither did playing around with the gc module. I had too many objects coming and going to make sense of it all.

Hence, I fell back to a simple process of elimination. Divide-and-conquer! I would make a change to the code, then I would exercise the code in a loop and monitor the output from top for ever-increasing memory usage.

Several hours later, I was able to nail it down to this simple repro:
# This program leaks memory rather quickly.  Removing the charset
# parameter fixes it.

import MySQLdb
import sys


while True:
connection = MySQLdb.connect(user='user', passwd='password',
host='localhost', db='development',
charset='utf8')
try:
cursor = connection.cursor()
cursor.execute('select * from mytable where false')
sys.stdout.write('.')
sys.stdout.flush()
finally:
connection.close()
It makes sense that if the memory leak is at the C level, I might not be able to find it with Python-level tools. I'll go hunting tomorrow to see if the MySQLdb team has already fixed it, and if not, I'll submit a bug.

Comments

Anonymous said…
That's why you access mysql via the protocol, not the 47MB client library. 8^)
Anonymous said…
Just a quick question - does cursor.execute() return something that needs cleaning up like connection in your example?
Anonymous said…
I can confirm memory leaks in Python programs can be hard to find and fix. When I was doing memory leak hunting in M2Crypto, I got some help from pje (how to use weakref). I also used the gc to catch some bugs, but many bugs were in the C layer for which I needed Valgrind. Even with all the instructions on how to suppress some errors, Valgrind produced a lot of false positives, and it isn't the easiest of things to use.

When I was debugging Chandler, I also tried to use Heapy, PySizer, and a nice frontend I built just for Chandler which took information from gc etc. I also found a commercial tool called Python Memory Validator which actually helped me find one bug in Chandler. I found one bug in the Python Memory Validator and the company was quick to fix it. They provide free evaluation if you want to try it out.

And just now as I was doing some searches I found muppy. Don't know anything more about it.

Still the bottom line is that none of the tools I have used were easy to use. There is definitely room for a good, simple memory debugger for Python.
jjinux said…
> That's why you access mysql via the protocol, not the 47MB client library. 8^)

Ah, if only MySQL had a clean, well documented interface, eh? It'd be great to have a pure-Python, asynchronous driver.
jjinux said…
> Just a quick question - does cursor.execute() return something that needs cleaning up like connection in your example?

You can call cursor.fetchall(), but you shouldn't need to.
jjinux said…
Thanks for the tips, Heikki.
jjinux said…
I can repro the bug with MySQLdb from svn. I just filed a bug:

http://sourceforge.net/tracker/index.php?func=detail&aid=2125250&group_id=22307&atid=374932
jjinux said…
Duh, it looks like this has already been fixed in trunk. I was running it wrong earlier. It definitely leaks in 1.2.2, but it does not appear to leak in trunk. Closing and marking as invalid.
jjinux said…
If anyone cares, here's how I updated my box:

apt-get install libmysqlclient15-dev libmysql++-dev python-dev:
+zlib1g-dev
+libmysql++2c2a
+python2.5-dev
cd
svn co https://mysql-python.svn.sourceforge.net/svnroot/mysql-python/trunk mysql-python
cd mysql-python/MySQLdb
python setup.py build
python setup.py bdist_egg
sudo easy_install --always-unzip dist/MySQL_python-1.3.0-py2.5-*.egg
cd ../..
rm -rf mysql-python/
jjinux said…
Ugh, the version on trunk doesn't actually know how to return unicode objects if I set charset='utf8'. It's like it's ignoring that. If I leave that out, the old version doesn't leak either! ;)
Anonymous said…
I'm getting a similar leak, and using charset UTF8. You seem to be saying that neither solution (svn, or leaving out charset) supports unicode.. is this correct? I need unicode in my app - do you know of any way of fixing the leak and using unicode?

Thanks!
mike bayer said…
I think its important to note that the memory leak here goes away if the use_unicode=0 flag is set. This also causes MySQLdb to return plain bytestrings instead of Python unicode objects, but a SQL abstraction layer such as SQLAlchemy handles the conversion of bytestring to unicode object in a more finely-controllable way. So the very common setting of charset=utf8&use_unicode=0 in conjunction with an abstraction layer which handles the unicode conversion is the way to go.
Anonymous said…
I do not know, I do anything to avoid using mysql if I can, in favour of better ACID comliant DBMSs.

I enjoyed reading your blog.
jjinux said…
Joe, I need unicode. I can't find any way around this problem. If you want Unicode, then you're stuck with a memory leak. My approach is to use cron to restart the app once or twice a day :( Eventually, I might switch to managing encodings manually.

==

Mike, hello! I prefer SQLAlchemy when I have a little bit of really complex data, but I prefer straight SQL when I have a ton of really simple data. Cheers!

==

anonymous, thanks for reading!

Popular posts from this blog

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from