Skip to content

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

Fix race condition during price recalculation (#18115) (#18133)

Filip Owczarek89a7023ded45
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 1afb16e0cb..f4653344cc 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -8,7 +8,6 @@ from django.db import transaction
from django.utils import timezone
from prices import Money, TaxedMoney
-from ..checkout import CheckoutAuthorizeStatus, base_calculations
from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.taxes import (
@@ -31,7 +30,9 @@ from ..tax.utils import (
get_tax_calculation_strategy_for_checkout,
normalize_tax_rate_for_db,
)
+from . import CheckoutAuthorizeStatus, base_calculations
from .fetch import find_checkout_line_info
+from .lock_objects import checkout_qs_select_for_update
from .models import Checkout
from .payment_utils import update_checkout_payment_statuses
@@ -442,45 +443,60 @@ def _fetch_checkout_prices_if_expired(
# tax from the original gross prices.
_remove_tax(checkout, lines)
- checkout_update_fields = [
- "voucher_code",
- "total_net_amount",
- "total_gross_amount",
- "subtotal_net_amount",
- "subtotal_gross_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "undiscounted_base_shipping_price_amount",
- "shipping_tax_rate",
- "translated_discount_name",
- "discount_amount",
- "discount_name",
- "currency",
- "last_change",
- "price_expiration",
- "tax_error",
- ]
-
checkout.price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL
- from .utils import checkout_lines_bulk_update
-
with allow_writer():
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",
- "prior_unit_price_amount",
- ],
- )
+ try:
+ locked_checkout = (
+ checkout_qs_select_for_update()
+ .only("last_change")
+ .get(token=checkout.token)
+ )
+ except Checkout.DoesNotExist:
+ # Checkout was removed or converted to a order. Return data without saving.
+ return checkout_info, lines
+
+ # Check whether the checkout has been modified during the recalculation process by another process.
+ # If so, we should skip saving. The same applies if the checkout has been removed. This is important
+ # to avoid overwriting changes made by the other requests. Skipping the save function does not affect
+ # the query response because it returns the adjusted checkout and line info objects.
+ if checkout.last_change == locked_checkout.last_change:
+ checkout_update_fields = [
+ "voucher_code",
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "undiscounted_base_shipping_price_amount",
+ "shipping_tax_rate",
+ "translated_discount_name",
+ "discount_amount",
+ "discount_name",
+ "currency",
+ "last_change",
+ "price_expiration",
+ "tax_error",
+ ]
+
+ from .utils import checkout_lines_bulk_update
+
+ 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",
+ "prior_unit_price_amount",
+ ],
+ )
return checkout_info, lines
diff --git a/saleor/checkout/tests/fixtures/checkout_with_prices.py b/saleor/checkout/tests/fixtures/checkout_with_prices.py
index a0e01019ad..32da626efd 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_prices.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_prices.py
@@ -22,7 +22,9 @@ def checkout_with_prices(
):
# Need to save shipping_method before fetching checkout info.
checkout_with_items.shipping_method = shipping_method
- checkout_with_items.save(update_fields=["shipping_method"])
+ country_code = address_other_country.country.code
+ checkout_with_items.set_country(country_code, commit=False)
+ checkout_with_items.save(update_fields=["shipping_method", "country"])
manager = get_plugins_manager(allow_replica=False)
lines = checkout_with_items.lines.all()
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index e25d73bc50..e7f60c3d1e 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -3,17 +3,13 @@ from typing import Literal
from unittest.mock import Mock, patch
import pytest
+from django.db.models import F
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
from graphene import Node
from prices import Money, TaxedMoney
-from ...checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
-from ...checkout.utils import (
- add_promo_code_to_checkout,
- assign_external_shipping_to_checkout,
-)
from ...core.prices import quantize_price
from ...core.taxes import (
TaxData,
@@ -33,6 +29,8 @@ from ...product.models import ProductVariantChannelListing
from ...shipping.interface import ShippingMethodData
from ...tax import TaxCalculationStrategy
from ...tax.calculations.checkout import update_checkout_prices_with_flat_rates
+from ...tests import race_condition
+from .. import CheckoutAuthorizeStatus, CheckoutChargeStatus
from ..base_calculations import (
base_checkout_delivery_price,
calculate_base_line_total_price,
@@ -45,6 +43,11 @@ from ..calculations import (
logger,
)
from ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_lines
+from ..models import Checkout
+from ..utils import (
+ add_promo_code_to_checkout,
+ assign_external_shipping_to_checkout,
+)
@pytest.fixture
@@ -1300,3 +1303,105 @@ def test_fetch_checkout_data_updates_status_for_zero_amount_checkout_with_lines(
checkout_with_item_total_0.refresh_from_db()
assert checkout_with_item_total_0.authorize_status == CheckoutAuthorizeStatus.FULL
assert checkout_with_item_total_0.charge_status == CheckoutChargeStatus.FULL
+
+
+def test_fetch_checkout_data_checkout_removed_before_save(
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ currency = checkout.currency
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
+ start_total_price = checkout.total
+ lines = list(checkout.lines.all())
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines_info, _ = fetch_checkout_lines(checkout)
+ fetch_kwargs = {
+ "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
+ "manager": manager,
+ "lines": lines_info,
+ "address": checkout.shipping_address,
+ }
+
+ # when
+ def delete_checkout(*args, **kwargs):
+ # Simulate checkout deletion. We can't run `delete()` on `checkout_with_prices`, because
+ # it's would pass `checkout` without `pk` to `checkout_info`.
+ Checkout.objects.filter(pk=checkout.pk).delete()
+
+ with race_condition.RunAfter(
+ "saleor.checkout.calculations._calculate_and_add_tax", delete_checkout
+ ):
+ result_checkout_info, result_lines_info = fetch_checkout_data(**fetch_kwargs)
+
+ # then
+ # Check if checkout was deleted.
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ # Check if prices are recalculated and returned in info objects.
+ assert start_total_price != result_checkout_info.checkout.total
+ assert result_checkout_info.checkout.total is not None
+ assert result_checkout_info.checkout.total > zero_taxed_money(currency)
+
+ for line, result_line in zip(lines, result_lines_info, strict=True):
+ assert line.total_price != result_line.line.total_price
+ assert result_line.line.total_price is not None
+ assert result_line.line.total_price > zero_taxed_money(currency)
+
+
+def test_fetch_checkout_data_checkout_updated_during_price_recalculation(
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ currency = checkout.currency
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration", "last_change"])
+ checkout.refresh_from_db()
+ total_price_before_recalculation = checkout.total
+ last_change_before_recalculation = checkout.last_change
+ lines = list(checkout.lines.all())
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines_info, _ = fetch_checkout_lines(checkout)
+ fetch_kwargs = {
+ "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
+ "manager": manager,
+ "lines": lines_info,
+ "address": checkout.shipping_address,
+ }
+ expected_email = "[email protected]"
+
+ # when
+ def modify_checkout(*args, **kwargs):
+ checkout_to_modify = Checkout.objects.get(pk=checkout.pk)
+ checkout_to_modify.lines.update(quantity=F("quantity") + 1)
+ checkout_to_modify.email = expected_email
+ checkout_to_modify.save(update_fields=["email", "last_change"])
+
+ with race_condition.RunAfter(
+ "saleor.checkout.calculations._calculate_and_add_tax", modify_checkout
+ ):
+ result_checkout_info, result_lines_info = fetch_checkout_data(**fetch_kwargs)
+
+ # then
+ # Check if prices are recalculated and returned in info objects.
+ assert result_checkout_info.checkout.total != total_price_before_recalculation
+ assert result_checkout_info.checkout.total is not None
+ assert result_checkout_info.checkout.total > zero_taxed_money(currency)
+
+ for line, result_line in zip(lines, result_lines_info, strict=True):
+ assert line.total_price != result_line.line.total_price
+ assert result_line.line.total_price is not None
+ assert result_line.line.total_price > zero_taxed_money(currency)
+ assert result_line.line.quantity == line.quantity
+
+ # Check if database contains updated checkout by other requests.
+ checkout.refresh_from_db()
+ assert checkout.last_change > last_change_before_recalculation
+ assert checkout.email == expected_email
+ for old_line, new_line in zip(lines, checkout.lines.all(), strict=True):
+ assert old_line.quantity + 1 == new_line.quantity
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index c4d8184651..f5c9e1274a 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -422,7 +422,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(83):
+ with django_assert_num_queries(84):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -440,7 +440,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(83):
+ with django_assert_num_queries(84):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -572,7 +572,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(89):
+ with django_assert_num_queries(90):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -828,7 +828,7 @@ def test_update_checkout_lines_with_reservations(
)
user_api_client.ensure_access_token()
- with django_assert_num_queries(105):
+ with django_assert_num_queries(106):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -842,7 +842,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(105):
+ with django_assert_num_queries(106):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -1103,7 +1103,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(102):
+ with django_assert_num_queries(103):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1116,7 +1116,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(102):
+ with django_assert_num_queries(103):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1167,7 +1167,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(93):
+ with django_assert_num_queries(94):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1253,7 +1253,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(93):
+ with django_assert_num_queries(94):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1289,7 +1289,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(99):
+ with django_assert_num_queries(100):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1324,7 +1324,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(126):
+ with django_assert_num_queries(127):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 79bab72ecb..c403074a12 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -9,6 +9,10 @@ from django.test import override_settings
from django.utils import timezone
from .....checkout.actions import call_checkout_info_event
+from .....checkout.calculations import (
+ _calculate_and_add_tax,
+ fetch_checkout_data,
+)
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
@@ -22,6 +26,7 @@ from .....core.models import EventDelivery
from .....discount import RewardValueType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
+from .....tests import race_condition
from .....warehouse.models import Reservation, Stock
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from .....webhook.transport.asynchronous.transport import send_webhook_request_async
@@ -1914,3 +1919,57 @@ def test_checkout_lines_update_with_new_metadata_merge_old(
assert line.metadata["new_key"] == "new_value"
assert line.variant == variant
+
+
+ "saleor.checkout.calculations._calculate_and_add_tax",
+ wraps=_calculate_and_add_tax,
+)
+ "saleor.checkout.calculations.fetch_checkout_data",
+ wraps=fetch_checkout_data,
+)
+def test_checkout_lines_update_checkout_updated_during_price_recalculation(
+ mock_fetch_checkout_data,
+ mock_calculate_and_add_tax,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ expected_email = "[email protected]"
+ checkout = checkout_with_prices
+ line = checkout.lines.first()
+ variant = line.variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ }
+
+ # when
+ def modify_checkout(*args, **kwargs):
+ checkout_to_modify = Checkout.objects.get(pk=checkout.pk)
+ checkout_to_modify.email = expected_email
+ checkout_to_modify.save(update_fields=["email", "last_change"])
+
+ with race_condition.RunAfter(
+ "saleor.checkout.calculations._calculate_and_add_tax", modify_checkout
+ ):
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+
+ # Ensure that the checkout prices recalculation was triggered more than one time.
+ assert mock_fetch_checkout_data.call_count > 1
+
+ # Ensure that the checkout price are recalculated only one time
+ assert mock_calculate_and_add_tax.call_count == 1
+
+ checkout.refresh_from_db()
+ assert checkout.email == expected_email
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 92b4c845f2..a7fe64ba63 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -5,6 +5,7 @@ from unittest import mock
import graphene
import pytest
from django.core.exceptions import ValidationError
+from django.db.models import F
from django.test import override_settings
from django.utils import timezone
from django.utils.dateparse import parse_datetime
@@ -13,13 +14,18 @@ from measurement.measures import Weight
from prices import Money
from ....checkout import base_calculations, calculations
-from ....checkout.calculations import _fetch_checkout_prices_if_expired
+from ....checkout.calculations import (
+ _calculate_and_add_tax,
+ _fetch_checkout_prices_if_expired,
+ fetch_checkout_data,
+)
from ....checkout.checkout_cleaner import (
clean_checkout_payment,
clean_checkout_shipping,
)
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.models import Checkout
from ....checkout.utils import (
PRIVATE_META_APP_SHIPPING_ID,
add_variant_to_checkout,
@@ -1843,6 +1849,7 @@ query getCheckout($id: ID) {
lines {
id
isGift
+ quantity
variant {
id
pricing {
@@ -2856,6 +2863,72 @@ def test_checkout_display_gross_prices_use_default(user_api_client, checkout_wit
assert data["displayGrossPrices"] == tax_config.display_gross_prices
+ "saleor.checkout.calculations._calculate_and_add_tax",
+ wraps=_calculate_and_add_tax,
+)
+ "saleor.checkout.calculations.fetch_checkout_data",
+ wraps=fetch_checkout_data,
+)
+def test_checkout_prices_with_checkout_updated_during_price_recalculation(
+ mock_fetch_checkout_data,
+ mock_calculate_and_add_tax,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ expected_email = "[email protected]"
+ checkout = checkout_with_prices
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ }
+ total_before_recalculation = checkout.total
+ lines_before_recalculation = list(checkout.lines.all())
+
+ # when
+ def modify_checkout(*args, **kwargs):
+ with allow_writer():
+ checkout_to_modify = Checkout.objects.get(pk=checkout.pk)
+ checkout_to_modify.lines.update(quantity=F("quantity") + 1)
+ checkout_to_modify.email = expected_email
+ checkout_to_modify.save(update_fields=["email", "last_change"])
+
+ with race_condition.RunAfter(
+ "saleor.checkout.calculations._calculate_and_add_tax", modify_checkout
+ ):
+ response = user_api_client.post_graphql(QUERY_CHECKOUT_PRICES, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+
+ # Ensure that the checkout prices recalculation was triggered more than one time
+ assert mock_fetch_checkout_data.call_count > 1
+
+ # Ensure that the checkout price are recalculated only one time
+ assert mock_calculate_and_add_tax.call_count == 1
+
+ checkout.refresh_from_db()
+ assert checkout.email == expected_email
+
+ # Confirm that total price hasn't changed in database due to recalculation
+ assert checkout.total == total_before_recalculation
+ # Confirm that total price has changed in query response due to recalculation
+ assert (
+ data["totalPrice"]["gross"]["amount"] != total_before_recalculation.gross.amount
+ )
+
+ for line_before_recalculation, result_line, line in zip(
+ lines_before_recalculation, data["lines"], checkout.lines.all(), strict=True
+ ):
+ # Confirm that returned line quantities are same as before simulated update was applied to the database
+ assert line_before_recalculation.quantity == result_line["quantity"]
+ # Confirm that line quantities have been updated in database
+ assert line_before_recalculation.quantity + 1 == line.quantity
+
+
def test_checkout_display_gross_prices_use_country_exception(
user_api_client, checkout_with_item
):