Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove reference cycle when query returns error. (#18549) (#18560)
Filip Owczarekb48a9c63064b
diff --git a/saleor/graphql/core/tests/garbage_collection/test_errors.py b/saleor/graphql/core/tests/garbage_collection/test_errors.pynew file mode 100644index 0000000000..5d2bbe13fc--- /dev/null+++ b/saleor/graphql/core/tests/garbage_collection/test_errors.py@@ -0,0 +1,284 @@+import gc+import json+from unittest import mock++import pytest+from django.core.serializers.json import DjangoJSONEncoder+from django.test import override_settings+from graphql.error import GraphQLError++from ....api import backend, schema+from ....tests.utils import get_graphql_content+from ....views import GraphQLView+from .utils import (+ clean_up_after_garbage_collection_test,+ disable_gc_for_garbage_collection_test,+)+++def raise_graphql_error(*args, **kwargs):+ raise GraphQLError("Exception in resolver")+++PRODUCTS_QUERY_PERMISSION_REQUIRED = """+query FetchProducts($channel: String!){+ products(first: 10, channel: $channel) {+ edges {+ node {+ id+ name+ channelListings{+ id+ }+ }+ }+ }+}+"""+++# 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_permission_error(rf, product, channel_USD):+ try:+ # given+ # Disable automatic garbage collection and set debugging flag.+ disable_gc_for_garbage_collection_test()+ # Prepare request body with GraphQL query and variables.+ variables = {"channel": channel_USD.slug}+ data = {"query": PRODUCTS_QUERY_PERMISSION_REQUIRED, "variables": variables}+ data = json.dumps(data, cls=DjangoJSONEncoder)++ # when+ # Execute the query with permission error.+ content = get_graphql_content(+ GraphQLView(backend=backend, schema=schema).handle_query(+ rf.post(path="/graphql/", data=data, content_type="application/json")+ ),+ ignore_errors=True,+ )+ # 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 == []+ # Ensure that the query returned the expected error.+ assert content["data"]["products"]["edges"][0]["node"]["name"] == product.name+ assert (+ content["errors"][0]["extensions"]["exception"]["code"]+ == "PermissionDenied"+ )+ # 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()+++PRODUCTS_QUERY = """+query FetchProducts($first: Int, $channel: String!){+ products(first: $first, channel: $channel) {+ edges {+ node {+ id+ name+ variants {+ id+ }+ }+ }+ }+}+"""+++# 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")+@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=5)+def test_query_cost_error(rf, product, channel_USD):+ try:+ # given+ # Disable automatic garbage collection and set debugging flag.+ disable_gc_for_garbage_collection_test()+ # Prepare request body with GraphQL query and variables.+ variables = {"channel": channel_USD.slug, "first": 10}+ data = {"query": PRODUCTS_QUERY, "variables": variables}+ data = json.dumps(data, cls=DjangoJSONEncoder)++ # when+ # Execute the query with cost error.+ content = get_graphql_content(+ GraphQLView(backend=backend, schema=schema).handle_query(+ rf.post(path="/graphql/", data=data, content_type="application/json")+ ),+ ignore_errors=True,+ )+ # 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 == []+ # Ensure that the query returned the expected error.+ assert (+ content["errors"][0]["extensions"]["exception"]["code"] == "QueryCostError"+ )+ # 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()+++# 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_exception_in_resolver(rf, product, channel_USD):+ try:+ # given+ # Disable automatic garbage collection and set debugging flag.+ disable_gc_for_garbage_collection_test()+ # Prepare request body with GraphQL query and variables.+ variables = {"channel": channel_USD.slug, "first": 10}+ data = {"query": PRODUCTS_QUERY, "variables": variables}+ data = json.dumps(data, cls=DjangoJSONEncoder)++ # when+ # Execute the query with GraphQLError in the resolver.+ with mock.patch(+ "saleor.graphql.product.schema.resolve_products",+ side_effect=raise_graphql_error,+ ) as _mocked_resolver:+ content = get_graphql_content(+ GraphQLView(backend=backend, schema=schema).handle_query(+ rf.post(+ path="/graphql/", data=data, content_type="application/json"+ )+ ),+ ignore_errors=True,+ )++ # 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 == []+ # Ensure that the query returned the expected error.+ assert content["errors"][0]["extensions"]["exception"]["code"] == "GraphQLError"+ # 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()+++# 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_exception_in_dataloader(rf, product, channel_USD):+ try:+ # given+ # Disable automatic garbage collection and set debugging flag.+ disable_gc_for_garbage_collection_test()+ # Prepare request body with GraphQL query and variables.+ variables = {"channel": channel_USD.slug, "first": 10}+ data = {"query": PRODUCTS_QUERY, "variables": variables}+ data = json.dumps(data, cls=DjangoJSONEncoder)++ # when+ # Execute the query with GraphQLError in the dataloader.+ with mock.patch(+ "saleor.graphql.product.schema.ChannelBySlugLoader.batch_load",+ side_effect=raise_graphql_error,+ ) as _mocked_dataloader:+ content = get_graphql_content(+ GraphQLView(backend=backend, schema=schema).handle_query(+ rf.post(+ path="/graphql/", data=data, content_type="application/json"+ )+ ),+ ignore_errors=True,+ )+ # 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 == []+ # Ensure that the query returned the expected error.+ assert content["errors"][0]["extensions"]["exception"]["code"] == "GraphQLError"+ # 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()+++STOCK_UPDATE = """+mutation ProductVariantStocksUpdate($variantId: ID!, $stocks: [StockInput!]!){+ productVariantStocksUpdate(variantId: $variantId, stocks: $stocks){+ productVariant {+ quantityAvailable+ stocks {+ id+ }+ }+ errors {+ code+ }+ }+}+"""+++# 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_input_validation_error(rf, product, channel_USD):+ try:+ # given+ # Disable automatic garbage collection and set debugging flag.+ disable_gc_for_garbage_collection_test()+ # Prepare request body with GraphQL query and variables.+ variables = {+ "variantId": "",+ "stocks": [{"warehouse": "", "quantity": 99999999999}],+ }+ data = {"query": STOCK_UPDATE, "variables": variables}+ data = json.dumps(data, cls=DjangoJSONEncoder)++ # when+ # Execute the mutation with input validation error.+ content = get_graphql_content(+ GraphQLView(backend=backend, schema=schema).handle_query(+ rf.post(path="/graphql/", data=data, content_type="application/json")+ ),+ ignore_errors=True,+ )+ # 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 == []+ # Ensure that the query returned the expected error.+ assert content["errors"][0]["extensions"]["exception"]["code"] == "GraphQLError"+ # 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/graphql/error.py b/saleor/graphql/error.pynew file mode 100644index 0000000000..256df01f86--- /dev/null+++ b/saleor/graphql/error.py@@ -0,0 +1,40 @@+from graphql.error import GraphQLError+++def clear_traceback_locals(tb):+ """Clear all locals from all connected frames.++ Similar to `clear_frames()` method of the `traceback` module but clears locals from all frames in tracebacks.+ """+ frame = tb.tb_frame+ while frame:+ try:+ frame.clear()+ except RuntimeError:+ # Ignore the exception raised if the frame is still executing.+ break+ frame = frame.f_back+++def clear_exception_locals(exception):+ # Clear locals from the exception.+ if exception.__traceback__:+ clear_traceback_locals(exception.__traceback__)+ # Clear exception stored as the `__cause__` of processed exception.+ if exception.__cause__:+ clear_exception_locals(exception.__cause__)+ # Clear exception stored as the `original_error` of processed exception.+ # This is used in `GraphQLError` from `GraphQL-Core-Legacy`.+ if isinstance(exception, GraphQLError) and hasattr(exception, "original_error"):+ clear_exception_locals(exception.original_error)+++def clear_errors(errors):+ """Clear locals from exceptions in errors.++ We can't to use the `clear_frames()` method of the `traceback` module. This function uses `tb_next` attribute+ to clear all locals from all frames in tracebacks. Errors generated by `GraphQL-Core-Legacy` don't have+ properly connected tracebacks, so we need to clear locals that go through frames.+ """+ for error in errors:+ clear_exception_locals(error)diff --git a/saleor/graphql/executor.py b/saleor/graphql/executor.pydeleted file mode 100644index ddafe3a2e9..0000000000--- a/saleor/graphql/executor.py+++ /dev/null@@ -1,23 +0,0 @@-from graphql.execution import executor--original_complete_value_catching_error = executor.complete_value_catching_error---def _patched_complete_value_catching_error(*args, **kwargs):- info = args[3]- from saleor.core.db.connection import allow_writer_in_context-- with allow_writer_in_context(info.context):- return original_complete_value_catching_error(*args, **kwargs)---def patch_executor():- """Patch `complete_value_catching_error` function to allow writer DB in mutations.-- The `complete_value_catching_error` function is called when resolving a field in- GraphQL. This patch wraps each call with `allow_writer_in_context` context manager.- This allows to use writer DB in resolvers, when they are called via mutation, while- they will still raise or log error when a resolver is run in a query.- """-- executor.complete_value_catching_error = _patched_complete_value_catching_errordiff --git a/saleor/graphql/graphql_core.py b/saleor/graphql/graphql_core.pynew file mode 100644index 0000000000..b2278b0d96--- /dev/null+++ b/saleor/graphql/graphql_core.py@@ -0,0 +1,57 @@+from graphql.execution import executor+from graphql.execution.base import ExecutionResult++original_complete_value_catching_error = executor.complete_value_catching_error+++def _patched_complete_value_catching_error(*args, **kwargs):+ info = args[3]+ from saleor.core.db.connection import allow_writer_in_context++ with allow_writer_in_context(info.context):+ return original_complete_value_catching_error(*args, **kwargs)+++def patch_executor():+ """Patch `complete_value_catching_error` function to allow writer DB in mutations.++ The `complete_value_catching_error` function is called when resolving a field in+ GraphQL. This patch wraps each call with `allow_writer_in_context` context manager.When a ValidationError is raised, the execution context does not store the error.+ This allows to use writer DB in resolvers, when they are called via mutation, while+ they will still raise or log error when a resolver is run in a query.+ """++ executor.complete_value_catching_error = _patched_complete_value_catching_error+++def __del_execution_context__(self):+ # When a `ValidationError` is raised, the execution context does not store the error.+ if hasattr(self, "errors"):+ del self.errors+++def patch_execution_context():+ """Patch `__del__` method of `ExecutionContext` to delete `errors` attribute.++ The `errors` attribute is used to store errors that occurred during the execution+ of the query. This patch ensures that the attribute is deleted when the execution+ context is deleted. This is to avoid reference cycles, as the attribute can hold+ references to objects that are no longer needed.+ """+ executor.ExecutionContext.__del__ = __del_execution_context__ # type: ignore[attr-defined]+++def __del_execution_result__(self):+ del self.errors+++def patch_execution_result():+ """Patch `__del__` method of `ExecutionResult` to delete `errors` attribute.++ The `errors` attribute is used to store errors that occurred during the execution+ of the query. This patch ensures that the attribute is deleted when the execution+ result is deleted. This is to avoid reference cycles, as the attribute can hold+ references to objects that are no longer needed.+ """++ ExecutionResult.__del__ = __del_execution_result__ # type: ignore[attr-defined]diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex affb242951..d2a1d4be2b 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -34,6 +34,7 @@ from ..webhook import observabilityfrom .api import API_PATH, schemafrom .context import clear_context, get_context_valuefrom .core.validators.query_cost import validate_query_cost+from .error import clear_errorsfrom .metrics import (record_graphql_query_cost,record_graphql_query_count,@@ -221,6 +222,9 @@ class GraphQLView(View):response["errors"] = [self.format_error(e) for e in execution_result.errors]+ # Error handling form `GraphQL-Core-Legacy` creates a multiple references cycles in+ # the error object. We need to clear them.+ clear_errors(execution_result.errors)if execution_result.invalid:status_code = 400else:diff --git a/saleor/settings.py b/saleor/settings.pyindex 70e1dcdd14..79d83ffa75 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -35,7 +35,11 @@ from .core.schedules import (initiated_checkout_automatic_completion_schedule,initiated_promotion_webhook_schedule,)-from .graphql.executor import patch_executor+from .graphql.graphql_core import (+ patch_execution_context,+ patch_execution_result,+ patch_executor,+)from .graphql.promise import patch_promisefrom .patch_local import patch_local@@ -1143,3 +1147,11 @@ patch_db()# Patch `Local` 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_local()++# Patch `ExecutionContext` 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_execution_context()++# Patch `ExecutionResult` 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_execution_result()