Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Memory leak with asyncpg, for SQLAlchemy generic functions #272

Closed

Description

@adamantike

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:

_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.

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

  1. vmarkovtsev commented on Dec 9, 2020

    @vmarkovtsev
    Contributor

    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?

  2. adamantike commented on Dec 10, 2020

    @adamantike
    ContributorAuthor

    So, I kept investigating, and found a few more details that are relevant to find the proper solution for this issue:

    1. Blacklisting these functions is an option, but it comes with a few drawbacks:

      • If the user actually uses one of these functions, but with a previously initialized 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.
      • Also, I'm not completely familiar with SQLAlchemy internals and any other use cases that could generate this same memory leak; so we would need to rely on other users from realizing they are experiencing this same leak, and tracking down which new condition we should add to the blacklist.
    2. The second option could be to convert the _result_processors map 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.

    3. After learning a bit more about the databases codebase, 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 a WeakKeyDictionary. 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_processors should 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!

  3. added a commit that references this issue on Dec 10, 2020
    05a52cd
  4. adamantike commented on Mar 13, 2021

    @adamantike
    ContributorAuthor

    In case someone else is experiencing this issue, there is a simple hotfix, until a version newer than 0.4.1 gets released: just clean up the databases.backends.postgres._result_processors dictionary periodically.

    For example, this is how we're doing it in a FastAPI application, using a request middleware:

    from typing import Any, Callable
    
    import databases
    from fastapi import Request
    from packaging import version
    
    if version.parse(databases.__version__) <= version.parse('0.4.1'):
        # Patch memory leak present in `databases` package, up until version 0.4.1.
        # Issue fixed in https://github.com/encode/databases/pull/273.
        # TODO: Remove this patch when a new `databases` version is released.
        from databases.backends.postgres import _result_processors
    
        @app.middleware("http")
        async def patch_databases_memory_leak(request: Request, call_next: Callable[[Request], Any]) -> Any:
            if len(_result_processors) > 10000:
                _result_processors.clear()
            return await call_next(request)
    
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