Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix potential deadlock in celery task triggered by checkout.0071 migration (#16976)
Maciej Korycinski287509237561
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 83c52ff13c..d52bb7efa9 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -4,6 +4,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Optional, castfrom django.conf import settings+from django.db import transactionfrom django.utils import timezonefrom prices import Money, TaxedMoney@@ -392,20 +393,23 @@ def _fetch_checkout_prices_if_expired(checkout.price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL+ from .utils import checkout_lines_bulk_update+with allow_writer():- checkout.save(- update_fields=checkout_update_fields,- using=settings.DATABASE_CONNECTION_DEFAULT_NAME,- )- checkout.lines.bulk_update(- [line_info.line for line_info in lines],- [- "total_price_net_amount",- "total_price_gross_amount",- "tax_rate",- "undiscounted_unit_price_amount",- ],- )+ with transaction.atomic():+ checkout.save(+ update_fields=checkout_update_fields,+ using=settings.DATABASE_CONNECTION_DEFAULT_NAME,+ )+ checkout_lines_bulk_update(+ [line_info.line for line_info in lines],+ [+ "total_price_net_amount",+ "total_price_gross_amount",+ "tax_rate",+ "undiscounted_unit_price_amount",+ ],+ )return checkout_info, linesdiff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex a3b7c4e637..953db2e05a 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -28,10 +28,7 @@ from ..core.utils.url import validate_storefront_urlfrom ..discount import DiscountType, DiscountValueType, VoucherTypefrom ..discount.models import CheckoutDiscount, NotApplicable, OrderLineDiscountfrom ..discount.utils.promotion import get_sale_id-from ..discount.utils.voucher import (- increase_voucher_usage,- release_voucher_code_usage,-)+from ..discount.utils.voucher import increase_voucher_usage, release_voucher_code_usagefrom ..graphql.checkout.utils import (prepare_insufficient_stock_checkout_validation_error,)@@ -84,6 +81,7 @@ from .fetch import (from .models import Checkoutfrom .utils import (calculate_checkout_weight,+ delete_checkouts,get_checkout_metadata,get_or_create_checkout_metadata,get_voucher_for_checkout_info,@@ -1029,7 +1027,8 @@ def complete_checkout_post_payment_part(is_automatic_completion=is_automatic_completion,)# remove checkout after order is successfully created- checkout_info.checkout.delete()+ delete_checkouts([checkout_info.checkout.pk])+ checkout_info.checkout.pk = Noneexcept InsufficientStock as e:_complete_checkout_fail_handler(checkout_info,@@ -1173,9 +1172,9 @@ def _create_order_discount(order: "Order", checkout_info: "CheckoutInfo"):currency=checkout.currency,amount_value=checkout.discount_amount,voucher=checkout_info.voucher,- voucher_code=checkout_info.voucher_code.code- if checkout_info.voucher_code- else None,+ voucher_code=(+ checkout_info.voucher_code.code if checkout_info.voucher_code else None+ ),)@@ -1459,7 +1458,8 @@ def create_order_from_checkout(is_automatic_completion=is_automatic_completion,)if delete_checkout:- checkout_info.checkout.delete()+ delete_checkouts([checkout_info.checkout.pk])+ checkout_info.checkout.pk = Nonereturn orderexcept InsufficientStock:_complete_checkout_fail_handler(diff --git a/saleor/checkout/migrations/0072_propagate_line_undiscounted_unit_price.py b/saleor/checkout/migrations/0072_propagate_line_undiscounted_unit_price.pynew file mode 100644index 0000000000..92391a68a0--- /dev/null+++ b/saleor/checkout/migrations/0072_propagate_line_undiscounted_unit_price.py@@ -0,0 +1,13 @@+# Generated by Django 4.2.15 on 2024-10-23 11:43+from django.db import migrations+++# Migration used to trigger celery task with data propagation, for already released+# versions.It is only for keeping a consistency, as all data was propagated in 0071+# directly during a migration.+class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0071_propagate_line_unidscounted_unit_price"),+ ]++ operations = []diff --git a/saleor/checkout/migrations/0073_merge_20241107_1646.py b/saleor/checkout/migrations/0073_merge_20241107_1646.pynew file mode 100644index 0000000000..7be589709a--- /dev/null+++ b/saleor/checkout/migrations/0073_merge_20241107_1646.py@@ -0,0 +1,12 @@+# Generated by Django 4.2.15 on 2024-11-07 16:46++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0072_alter_checkoutline_undiscounted_unit_price_amount"),+ ("checkout", "0072_propagate_line_undiscounted_unit_price"),+ ]++ operations = []diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.pyindex f7b790256d..706dde6194 100644--- a/saleor/checkout/tasks.py+++ b/saleor/checkout/tasks.py@@ -17,6 +17,7 @@ from ..plugins.manager import get_plugins_managerfrom .complete_checkout import complete_checkoutfrom .fetch import fetch_checkout_info, fetch_checkout_linesfrom .models import Checkout, CheckoutLine+from .utils import delete_checkoutstask_logger: logging.Logger = get_task_logger(__name__)@@ -96,9 +97,9 @@ def delete_expired_checkouts(total_deleted: int = 0has_more: bool = Truefor _batch_number in range(batch_count):- ids = list(qs.values_list("pk", flat=True))+ checkout_ids = list(qs.values_list("pk", flat=True))with allow_writer():- deleted_count, _ = Checkout.objects.filter(pk__in=ids).delete()+ deleted_count = delete_checkouts(checkout_ids)total_deleted += deleted_count# Stop deleting inactive checkouts if there was no match.diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 039eb6b5a9..395805448d 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -3,6 +3,7 @@from collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional, Union, cast+from uuid import UUIDimport graphenefrom django.conf import settings@@ -116,6 +117,46 @@ def invalidate_checkout_prices(return updated_fields+def checkout_lines_bulk_update(+ lines_to_update: list["CheckoutLine"], fields_to_update: list[str]+):+ """Bulk update on CheckoutLines with lock applied on them."""+ with transaction.atomic():+ _locked_lines = list(+ CheckoutLine.objects.order_by("id")+ .select_for_update()+ .filter(id__in=[line.id for line in lines_to_update])+ .values_list("id", flat=True)+ )+ CheckoutLine.objects.bulk_update(lines_to_update, fields_to_update)+++def checkout_lines_bulk_delete(line_pks_to_delete: list[UUID]):+ """Delete CheckoutLines with lock applied on them."""+ with transaction.atomic():+ CheckoutLine.objects.filter(+ id__in=CheckoutLine.objects.order_by("id")+ .select_for_update()+ .filter(pk__in=line_pks_to_delete)+ .values_list("id", flat=True)+ ).delete()+++def delete_checkouts(checkout_pks_to_delete: list[UUID]) -> int:+ """Delete a checkouts with lock applied on them."""+ with transaction.atomic():+ CheckoutLine.objects.filter(+ id__in=CheckoutLine.objects.order_by("id")+ .select_for_update()+ .filter(checkout_id__in=checkout_pks_to_delete)+ .values_list("id", flat=True)+ ).delete()+ deleted_count, _ = Checkout.objects.filter(+ pk__in=checkout_pks_to_delete+ ).delete()+ return deleted_count++def get_user_checkout(user: User,checkout_queryset=None,@@ -286,11 +327,13 @@ def add_variants_to_checkout()if to_delete:- CheckoutLine.objects.filter(pk__in=[line.pk for line in to_delete]).delete()+ checkout_lines_bulk_delete([line.pk for line in to_delete])+if to_update:- CheckoutLine.objects.bulk_update(+ checkout_lines_bulk_update(to_update, ["quantity", "price_override", "metadata"])+if to_create:CheckoutLine.objects.bulk_create(to_create)diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 65aaeef960..7e09914716 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -417,7 +417,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(75):+ with django_assert_num_queries(80):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -435,7 +435,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(75):+ with django_assert_num_queries(80):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -567,7 +567,7 @@ def test_create_checkout_with_order_promotion(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(80):+ with django_assert_num_queries(85):response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)# then@@ -823,7 +823,7 @@ def test_update_checkout_lines_with_reservations()user_api_client.ensure_access_token()- with django_assert_num_queries(95):+ with django_assert_num_queries(103):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -837,7 +837,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(95):+ with django_assert_num_queries(103):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -1083,7 +1083,7 @@ def test_add_checkout_lines_with_reservations(user_api_client.ensure_access_token()# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(95):+ with django_assert_num_queries(100):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -1096,7 +1096,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(95):+ with django_assert_num_queries(100):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,@@ -1147,7 +1147,7 @@ def test_add_checkout_lines_catalogue_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(87):+ with django_assert_num_queries(92):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1233,7 +1233,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(87):+ with django_assert_num_queries(92):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1269,7 +1269,7 @@ def test_add_checkout_lines_order_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(90):+ with django_assert_num_queries(95):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1304,7 +1304,7 @@ def test_add_checkout_lines_gift_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(116):+ with django_assert_num_queries(121):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then