Repository navigation
Memory leak with asyncpg, for SQLAlchemy generic functions #272
Description
Summary
The postgres backend includes a cache for result processors, which makes the library to leak memory when some specific SQLAlchemy generic functions are used.
Description
The _result_processors dictionary is used as a global cache:
databases/databases/backends/postgres.py
Line 19 in 8cd5514
| _result_processors = {} # type: dict |
Every time a record is accessed, the Record.__getitem__ method is called, and that's where the cache is filled, considering the data type of the accessed field (e.g. Integer(), Date()...). Let's take into account that the keys for this cache are instances for any of these SQLAlchemy types.
databases/databases/backends/postgres.py
Lines 123 to 127 in 8cd5514
| try: | |
| processor = _result_processors[datatype] | |
| except KeyError: | |
| processor = datatype.result_processor(self._dialect, None) | |
| _result_processors[datatype] = processor |
So, for this cache to be successfully used, we need type instances that are reused during the application lifetime. That's how SQLAlchemy works, when defining tables and their columns.
However, SQLAlchemy also provides other SQL functions that don't work in this same way. Specifically, any function that inherits from GenericFunction but does not inherit from ReturnTypeFromArgs.
This is because the ReturnTypeFromArgs constructor reuses the type of the column it wraps: https://github.com/sqlalchemy/sqlalchemy/blob/6eda3aa8c5f58e415a49ac8dc73eb8608f4be306/lib/sqlalchemy/sql/functions.py#L840
But the GenericFunction constructor initializes a new data type every time it's called (unless an instantiated type is provided, something not common in this scenario: https://github.com/sqlalchemy/sqlalchemy/blob/6eda3aa8c5f58e415a49ac8dc73eb8608f4be306/lib/sqlalchemy/sql/functions.py#L796-L798
As a new type is initialized every time, it's added to the _result_processors dictionary, which keeps growing and leaking memory, with entries that won't be reused for these particular type instances.
Test case
This is a simple test case I built to reproduce the issue. It includes functions that leak memory as part of the test_functions_with_memory_leak test case parametrization, and functions that do not leak memory (because of being subclasses of ReturnTypeFromArgs) as part of the test_functions_without_memory_leak test case parametrization.
Requirements:
databases[postgresql]==0.4.1
pytest
pytest-asyncio
Test cases:
import asyncio
from databases import Database
from databases.backends.postgres import _result_processors
import pytest
from sqlalchemy import column, func, select, table
SCORES_TABLE = table('HighScores', column('id'), column('name'), column('score'))
@pytest.fixture(scope='session')
def event_loop():
"""Needed to have Session-scoped fixtures."""
return asyncio.new_event_loop()
@pytest.fixture(scope='session', autouse=True)
async def db():
"""Create a database instance, and connect to it."""
database = Database('postgresql://postgres:postgres@localhost/db')
await database.connect()
await database.execute(
query="""
CREATE TABLE IF NOT EXISTS "HighScores"
(id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)
""",
)
await database.execute(
query="""
INSERT INTO "HighScores" (id, name, score)
VALUES (1, 'TEST', 1000)
ON CONFLICT DO NOTHING
""",
)
yield database
await database.disconnect()
@pytest.fixture(autouse=True)
async def clean_result_processors():
"""After each test, clean the `_result_processors` internal dictionary."""
yield
_result_processors.clear()
@pytest.mark.asyncio
@pytest.mark.parametrize('query_func', (
lambda: select([func.count()]).select_from(SCORES_TABLE),
lambda: select([func.concat(SCORES_TABLE.c.name, SCORES_TABLE.c.name)]).select_from(SCORES_TABLE),
lambda: select([func.current_date()]),
lambda: select([func.now()]),
))
async def test_functions_with_memory_leak(query_func, db):
"""This test is parametrized with some of the SQLAlchemy functions that generate the memory leak."""
for _ in range(100):
query = query_func()
record = await db.fetch_one(query=query)
# Access record fields, to trigger Record.__getitem__
[record[item] for item in record._row.keys()]
assert len(_result_processors) == len(record._row)
@pytest.mark.asyncio
@pytest.mark.parametrize('query_func', (
lambda: select([func.sum(SCORES_TABLE.c.score)]).select_from(SCORES_TABLE),
lambda: select([func.min(SCORES_TABLE.c.score)]).select_from(SCORES_TABLE),
lambda: select([func.max(SCORES_TABLE.c.score)]).select_from(SCORES_TABLE),
lambda: select([func.coalesce(SCORES_TABLE.c.score, 0)]).select_from(SCORES_TABLE),
))
async def test_functions_without_memory_leak(query_func, db):
"""This test is parametrized with some of the SQLAlchemy functions that do not generate the memory leak."""
for _ in range(100):
query = query_func()
record = await db.fetch_one(query=query)
# Access record fields, to trigger Record.__getitem__
[record[item] for item in record._row.keys()]
assert len(_result_processors) == len(record._row)
Activity
vmarkovtsev commentedon Dec 9, 2020
Thanks @adamantike for such a great investigation. I feel that blacklisting such generic functions from the cache will be sufficient to resolve this problem. Would you mind PR-ing that together with the test case you've engineered, given that you know all the details?
adamantike commentedon Dec 10, 2020
So, I kept investigating, and found a few more details that are relevant to find the proper solution for this issue:
Blacklisting these functions is an option, but it comes with a few drawbacks:
type, that function will never make use of the cache (as there's no simple way to differentiate the two scenarios from outside of SQLAlchemy code), which would negatively affect performance for existing users (if there's any), and releasing a patch version could be harder without the proper warning.The second option could be to convert the
_result_processorsmap into a LRU cache, with a big enough maximum size. We wouldn't fix the leak, but we would be sure that it can consume up to that maximum size, so we can forget about tracking down new use cases that can potentially generate dynamically generated data types in SQLAlchemy. However, users that are experiencing this issue will have this LRU cache invalidating their valid entries regularly, so performance would be also affected once in a while.After learning a bit more about the
databasescodebase, I wondered how something as beneficial for performance is not already built-in in SQLAlchemy. It makes sense to delegate this problem to the underlying library, right? So, actually, I found SQLAlchemy can already handle this, in a better way: by using aWeakKeyDictionary. https://github.com/sqlalchemy/sqlalchemy/blob/a15aeba4fb22503c1eb235fdc2e7a574136ca7dc/lib/sqlalchemy/engine/default.py#L321-L323. With this, we can remove the caching layer from this library, and entirely rely on SQLAlchemy. Dropping_result_processorsshould be safe as it's part of the internal API. The only issue with this solution is that we rely on an internal API from SQLAlchemy.I'll file a PR for option 3, which also makes my tests irrelevant as we would just use SQLAlchemy for the caching!
Fix memory leak with asyncpg, for SQLAlchemy generic functions (#273)
adamantike commentedon Mar 13, 2021
In case someone else is experiencing this issue, there is a simple hotfix, until a version newer than
0.4.1gets released: just clean up thedatabases.backends.postgres._result_processorsdictionary periodically.For example, this is how we're doing it in a FastAPI application, using a request middleware: