Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix memory leak for cached states (#18944)
Iga Karbowiak22a30bf2e4cc
diff --git a/saleor/graphql/context.py b/saleor/graphql/context.pyindex 05176c3748..581d918e70 100644--- a/saleor/graphql/context.py+++ b/saleor/graphql/context.py@@ -27,10 +27,40 @@ def get_context_value(request: HttpRequest) -> SaleorContext:def clear_context(context: SaleorContext):+ _clear_dataloaders_fields_cache(context)context.dataloaders.clear()del context.user+def _clear_dataloaders_fields_cache(context: SaleorContext):+ """Clear Django model fields_cache on all cached dataloader values.++ Django's OneToOneField descriptors create bidirectional caches in+ _state.fields_cache (e.g. Site ↔ SiteSettings), forming reference cycles+ that survive after dataloaders are cleared. Breaking these caches here+ prevents the cycles from leaking into garbage collection.++ How it works:+ - `_promise_cache` is an internal dict on the `promise` library's DataLoader+ (BaseLoader). It maps loader keys to Promise objects — this is where the+ dataloader stores its cached results.+ - Each value in `_promise_cache` is a Promise, not the actual model instance.+ `.get()` extracts the resolved value. By the time `clear_context` runs (in+ the `finally` block after GraphQL execution), all promises are already+ resolved — no additional DB queries are triggered here.+ - Rejected promises (failed DB queries) raise on `.get()`, so we skip them+ via try/except since there is no model instance to clean up.+ """+ for loader in context.dataloaders.values():+ for promise in getattr(loader, "_promise_cache", {}).values():+ try:+ value = promise.get()+ except Exception:+ continue+ if hasattr(value, "_state"):+ value._state.fields_cache.clear()++class RequestWithUser(HttpRequest):_cached_user: User | Noneapp: App | Nonediff --git a/saleor/graphql/core/tests/garbage_collection/test_saleor_context.py b/saleor/graphql/core/tests/garbage_collection/test_saleor_context.pyindex 2ea239413d..3b9b3e05b8 100644--- a/saleor/graphql/core/tests/garbage_collection/test_saleor_context.py+++ b/saleor/graphql/core/tests/garbage_collection/test_saleor_context.py@@ -13,7 +13,7 @@ from .utils import (disable_gc_for_garbage_collection_test,)-PRODUCTS_QUERY = """+ME_QUERY = """{me {@@ -21,6 +21,14 @@ PRODUCTS_QUERY = """}"""+SHOP_DESCRIPTION_QUERY = """+{+ shop {+ description+ }+}+"""+# 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.@@ -32,7 +40,7 @@ def test_query_remove_SaleorContext_memory_cycles(rf, staff_user):# Disable automatic garbage collection and set debugging flag.disable_gc_for_garbage_collection_test()# Prepare request body with GraphQL query.- data = {"query": PRODUCTS_QUERY}+ data = {"query": ME_QUERY}data = json.dumps(data, cls=DjangoJSONEncoder)jwt_token = create_access_token(staff_user)@@ -63,3 +71,33 @@ def test_query_remove_SaleorContext_memory_cycles(rf, staff_user):# with other tests to ensure that code should be executed in the `finally' block.finally:clean_up_after_garbage_collection_test()++[email protected]_group(name="garbage_collection")+def test_query_with_site_settings_no_memory_cycles(rf, site_settings):+ # Verify that queries accessing site.settings via load_site_callback+ # do not leave Django OneToOneField bidirectional cache cycles.+ try:+ # given+ disable_gc_for_garbage_collection_test()+ data = {"query": SHOP_DESCRIPTION_QUERY}+ data = json.dumps(data, cls=DjangoJSONEncoder)++ # when+ content = get_graphql_content(+ GraphQLView(backend=backend, schema=schema).handle_query(+ rf.post(+ path="/graphql/",+ data=data,+ content_type="application/json",+ )+ ),+ ignore_errors=True,+ )+ gc.collect()++ # then+ assert gc.garbage == []+ assert content["data"]["shop"]["description"] is not None+ finally:+ clean_up_after_garbage_collection_test()