Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: close sqla connections when unloading profile #5728

Merged
merged 1 commit into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions aiida/storage/psql_dos/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# pylint: disable=missing-function-docstring
from contextlib import contextmanager, nullcontext
import functools
import gc
import pathlib
from typing import TYPE_CHECKING, Iterator, List, Optional, Sequence, Set, Union

Expand Down Expand Up @@ -144,6 +145,10 @@ def close(self) -> None:
self._session_factory.close()
self._session_factory = None

# Without this, sqlalchemy keeps a weakref to a session
# in sqlalchemy.orm.session._sessions
gc.collect()

def _clear(self, recreate_user: bool = True) -> None:
from aiida.storage.psql_dos.models.settings import DbSetting
from aiida.storage.psql_dos.models.user import DbUser
Expand Down
21 changes: 21 additions & 0 deletions tests/storage/psql_dos/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,24 @@ def mock_get_info(self, detailed=False, **kwargs): # pylint: disable=unused-arg
assert 'extra_value' in repository_info_out
assert repository_info_out['value'] == 42
assert repository_info_out['extra_value'] == 0


@pytest.mark.usefixtures('aiida_profile_clean')
def test_unload_profile():
"""Test that unloading the profile closes all sqla sessions.

This is a regression test for #5506.
"""
from sqlalchemy.orm.session import _sessions # pylint: disable=import-outside-toplevel

# Just running the test suite itself should have opened at least one session
assert len(_sessions) != 0, str(_sessions)

manager = get_manager()
profile_name = manager.get_profile().name

try:
manager.unload_profile()
assert len(_sessions) == 0, str(_sessions)
finally:
manager.load_profile(profile_name)