Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Remove reference cycle in Django DB (#17592)

Filip Owczarekdc05d6ce5dd3
diff --git a/saleor/core/db/patch.py b/saleor/core/db/patch.py
new file mode 100644
index 0000000000..7a7482084a
--- /dev/null
+++ b/saleor/core/db/patch.py
@@ -0,0 +1,32 @@
+from django.db.backends.base.validation import BaseDatabaseValidation
+from django.db.backends.postgresql.client import DatabaseClient
+from django.db.backends.postgresql.creation import DatabaseCreation
+from django.db.backends.postgresql.features import DatabaseFeatures
+from django.db.backends.postgresql.introspection import DatabaseIntrospection
+from django.db.backends.postgresql.operations import DatabaseOperations
+from django.db.utils import DatabaseErrorWrapper
+
+
+def __del_connection__(self):
+ self.connection = None
+
+
+def __del_wrapper__(self):
+ self.wrapper = None
+
+
+def patch_db():
+ """Patch `__del__` in objects to avoid memory leaks.
+
+ Those changes will remove the circular references between database objects,
+ allowing memory to be freed immediately, without the need of a deep garbage collection cycle.
+ Issue: https://code.djangoproject.com/ticket/34865
+ """
+ DatabaseClient.__del__ = __del_connection__ # type: ignore[attr-defined]
+ DatabaseCreation.__del__ = __del_connection__ # type: ignore[attr-defined]
+ DatabaseFeatures.__del__ = __del_connection__ # type: ignore[attr-defined]
+ DatabaseIntrospection.__del__ = __del_connection__ # type: ignore[attr-defined]
+ DatabaseOperations.__del__ = __del_connection__ # type: ignore[attr-defined]
+ BaseDatabaseValidation.__del__ = __del_connection__ # type: ignore[attr-defined]
+
+ DatabaseErrorWrapper.__del__ = __del_wrapper__ # type: ignore[attr-defined]
diff --git a/saleor/graphql/core/tests/garbage_collection/test_django.py b/saleor/graphql/core/tests/garbage_collection/test_django.py
new file mode 100644
index 0000000000..110388e922
--- /dev/null
+++ b/saleor/graphql/core/tests/garbage_collection/test_django.py
@@ -0,0 +1,37 @@
+import gc
+
+import pytest
+from django.db import connection
+
+from .utils import (
+ clean_up_after_garbage_collection_test,
+ disable_gc_for_garbage_collection_test,
+)
+
+
+# Group all tests that require garbage collection so that they do not run concurrently.
+# This is necessary to ensure that tests don't interfere with each other.
+# Without grouping we could receive false positive results.
[email protected]_group(name="garbage_collection")
+def test_django_connection_remove_all_reference_cycles():
+ try:
+ # given
+ # Disable automatic garbage collection and set debugging flag.
+ disable_gc_for_garbage_collection_test()
+
+ # when
+ # Create a copy of the Django connection object and close it to free resources.
+ connection.copy().close()
+
+ # Enforce garbage collection to populate the garbage list for inspection.
+ gc.collect()
+
+ # then
+ # Ensure that the garbage list is empty. The garbage list is only valid
+ # until the next collection cycle so we can only make assertions about it
+ # before re-enabling automatic collection.
+ assert gc.garbage == []
+ # Restore garbage collection settings to their original state. This should always be run to avoid interfering
+ # with other tests to ensure that code should be executed in the `finally' block.
+ finally:
+ clean_up_after_garbage_collection_test()
diff --git a/saleor/settings.py b/saleor/settings.py
index cc06de0fdd..96699d7556 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -29,6 +29,7 @@ from sentry_sdk.scrubber import DEFAULT_DENYLIST, DEFAULT_PII_DENYLIST, EventScr
from . import PatchedSubscriberExecutionContext, __version__
from .account.i18n_rules_override import i18n_rules_override
+from .core.db.patch import patch_db
from .core.languages import LANGUAGES as CORE_LANGUAGES
from .core.schedules import initiated_promotion_webhook_schedule
from .graphql.executor import patch_executor
@@ -1069,3 +1070,8 @@ patch_promise()
# Patch `_WriteBufferStream` from `gizip` to remove all references that could result in reference cycles,
# allowing memory to be freed immediately, without the need of a deep garbage collection cycle.
patch_gzip()
+
+# Patch `DatabaseClient`, `DatabaseCreation`, `DatabaseFeatures`, `DatabaseIntrospection`, `DatabaseOperations`,
+# `BaseDatabaseValidation` and `DatabaseErrorWrapper` to remove all references that could result in reference cycles,
+# allowing memory to be freed immediately, without the need of a deep garbage collection cycle.
+patch_db()