Skip to content

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

Add lock for Product and ProductVariant to ensure they won't be deleted before being processed (#16289) (#16529)

Krzysztof Kwaśniak4942456caf36
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 8a9b9e639c..283e3530eb 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -2,6 +2,7 @@ import datetime
from collections import defaultdict, namedtuple
from collections.abc import Iterable, Iterator
from decimal import Decimal
+from itertools import chain
from typing import TYPE_CHECKING, Callable, Optional, Union, overload
from uuid import UUID
@@ -684,6 +685,19 @@ def get_current_products_for_rules(rules: "QuerySet[PromotionRule]"):
return Product.objects.filter(Exists(variants.filter(product_id=OuterRef("id"))))
+def _create_new_rules(rules_to_add, variants_lock, rules_lock):
+ # base on what locks returned, filter out rules and variants that weren't locked
+ rules_to_add_batch = [
+ rv
+ for rv in rules_to_add
+ if rv.promotionrule_id in rules_lock and rv.productvariant_id in variants_lock
+ ]
+
+ return PromotionRule.variants.through.objects.bulk_create(
+ rules_to_add_batch, ignore_conflicts=True
+ )
+
+
def update_rule_variant_relation(
rules: QuerySet[PromotionRule], new_rules_variants: list
):
@@ -692,38 +706,62 @@ def update_rule_variant_relation(
Deletes relations, which are not valid anymore.
Adds new relations, if they don't exist already.
`new_rules_variants` is a list of PromotionRuleVariant objects.
+
+ It is important to lock the variants and rules before deleting and adding new
+ relations to avoid integrity errors. It is also important to lock the rules and
+ variants in the same order to avoid deadlocks.
"""
+ PromotionRuleVariant = PromotionRule.variants.through
+ existing_rules_variants = PromotionRuleVariant.objects.filter(
+ Exists(rules.filter(pk=OuterRef("promotionrule_id")))
+ ).all()
+ new_rule_variant_set = set(
+ (rv.promotionrule_id, rv.productvariant_id) for rv in new_rules_variants
+ )
+ existing_rule_variant_set = set(
+ (rv.promotionrule_id, rv.productvariant_id) for rv in existing_rules_variants
+ )
+ # Assign new variants to promotion rules
+ rules_variants_to_add = [
+ rv
+ for rv in new_rules_variants
+ if (rv.promotionrule_id, rv.productvariant_id) not in existing_rule_variant_set
+ ]
+
+ # Clear invalid variants assigned to promotion rules
+ rule_variant_to_delete_ids = [
+ rv
+ for rv in existing_rules_variants
+ if (rv.promotionrule_id, rv.productvariant_id) not in new_rule_variant_set
+ ]
with transaction.atomic():
- PromotionRuleVariant = PromotionRule.variants.through
- existing_rules_variants = PromotionRuleVariant.objects.filter(
- Exists(rules.filter(pk=OuterRef("promotionrule_id")))
- ).all()
- new_rule_variant_set = set(
- (rv.promotionrule_id, rv.productvariant_id) for rv in new_rules_variants
+ variants_lock = tuple(
+ ProductVariant.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(
+ id__in={
+ rv.productvariant_id
+ for rv in chain(rule_variant_to_delete_ids, rules_variants_to_add)
+ }
+ )
+ .values_list("id", flat=True)
)
- existing_rule_variant_set = set(
- (rv.promotionrule_id, rv.productvariant_id)
- for rv in existing_rules_variants
+ rules_lock = tuple(
+ PromotionRule.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(
+ id__in={
+ rv.promotionrule_id
+ for rv in chain(rule_variant_to_delete_ids, rules_variants_to_add)
+ }
+ )
+ .values_list("pk", flat=True)
)
+ PromotionRuleVariant.objects.order_by("pk").select_for_update(
+ of=("self",)
+ ).filter(id__in={rv.id for rv in rule_variant_to_delete_ids}).delete()
- # Clear invalid variants assigned to promotion rules
- rule_variant_to_delete_ids = [
- rv.id
- for rv in existing_rules_variants
- if (rv.promotionrule_id, rv.productvariant_id) not in new_rule_variant_set
- ]
- PromotionRuleVariant.objects.filter(id__in=rule_variant_to_delete_ids).delete()
-
- # Assign new variants to promotion rules
- rules_variants_to_add = [
- rv
- for rv in new_rules_variants
- if (rv.promotionrule_id, rv.productvariant_id)
- not in existing_rule_variant_set
- ]
- PromotionRuleVariant.objects.bulk_create(
- rules_variants_to_add, ignore_conflicts=True
- )
+ return _create_new_rules(rules_variants_to_add, variants_lock, rules_lock)
def create_discount_objects_for_order_promotions(
diff --git a/saleor/graphql/discount/mutations/bulk_mutations.py b/saleor/graphql/discount/mutations/bulk_mutations.py
index 935db3cd57..5d70ccdc07 100644
--- a/saleor/graphql/discount/mutations/bulk_mutations.py
+++ b/saleor/graphql/discount/mutations/bulk_mutations.py
@@ -2,7 +2,8 @@ from typing import Optional
import graphene
from django.core.exceptions import ValidationError
-from django.db.models import Exists, OuterRef, QuerySet, Subquery
+from django.db import transaction
+from django.db.models import OuterRef, Subquery
from ....discount import models
from ....discount.error_codes import DiscountErrorCode
@@ -85,14 +86,26 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
@classmethod
def bulk_action(cls, info: ResolveInfo, queryset, /):
- sale_id_to_rule = cls.get_sale_and_rules(queryset)
- sales_and_catalogue_infos = [
- (sale, cls.get_catalogue_info(sale_id_to_rule.get(sale.id)))
- for sale in queryset
- ]
- channel_to_products_map = cls.get_channel_to_products_map(queryset)
-
- queryset.delete()
+ with transaction.atomic():
+ promotions = tuple(
+ models.Promotion.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(pk__in=queryset.values_list("pk", flat=True))
+ )
+ rules = cls.get_sales(promotions)
+ sale_id_to_rule = cls.get_sale_and_rules(rules)
+ sales_and_catalogue_infos = [
+ (promotion, cls.get_catalogue_info(sale_id_to_rule.get(promotion.id)))
+ for promotion in promotions
+ ]
+ channel_to_products_map = cls.get_channel_to_products_map(rules)
+
+ models.PromotionRule.objects.order_by("pk").filter(
+ pk__in=[rule.pk for rule in rules]
+ ).delete()
+ models.Promotion.objects.order_by("pk").filter(
+ pk__in=[promotion.pk for promotion in promotions]
+ ).delete()
webhooks = get_webhooks_for_event(WebhookEventAsyncType.SALE_DELETED)
manager = get_plugin_manager_promise(info.context).get()
@@ -104,12 +117,8 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
cls.call_event(mark_products_in_channels_as_dirty, channel_to_products_map)
@classmethod
- def get_sale_and_rules(cls, qs: QuerySet[models.Promotion]):
- rules = models.PromotionRule.objects.filter(
- Exists(qs.filter(id=OuterRef("promotion_id")))
- )
- sale_id_to_rule = {rule.promotion_id: rule for rule in rules}
- return sale_id_to_rule
+ def get_sale_and_rules(cls, rules: tuple[models.PromotionRule, ...]):
+ return {rule.promotion_id: rule for rule in rules}
@classmethod
def get_catalogue_info(cls, rule: models.PromotionRule):
@@ -118,12 +127,20 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
)
@classmethod
- def get_channel_to_products_map(cls, qs: QuerySet[models.Promotion]):
- rules = models.PromotionRule.objects.filter(
- Exists(qs.filter(id=OuterRef("promotion_id")))
+ def get_channel_to_products_map(cls, rules: tuple[models.PromotionRule, ...]):
+ rules = models.PromotionRule.objects.order_by("pk").filter(
+ pk__in=[rule.pk for rule in rules]
)
return get_channel_to_products_map_from_rules(rules)
+ @classmethod
+ def get_sales(cls, promotions) -> tuple[models.PromotionRule, ...]:
+ return tuple(
+ models.PromotionRule.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(promotion_id__in=[promotion.pk for promotion in promotions])
+ )
+
class VoucherBulkDelete(ModelBulkDeleteMutation):
class Arguments:
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_bulk_delete.py
index 743247d912..a263a5091f 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_delete.py
@@ -2,6 +2,7 @@ from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models.expressions import Exists, OuterRef
from ....attribute import AttributeInputType
@@ -102,7 +103,22 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
product_variant_map[product].append(variant)
products = [product for product in queryset]
- queryset.delete()
+ with transaction.atomic():
+ variants_ids = tuple(
+ models.ProductVariant.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(product__in=products)
+ .values_list("pk", flat=True)
+ )
+ models.ProductVariant.objects.filter(pk__in=variants_ids).delete()
+ ids = tuple(
+ models.Product.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(pk__in=[product.pk for product in products])
+ .values_list("pk", flat=True)
+ )
+ models.Product.objects.filter(pk__in=ids).delete()
+
webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_DELETED)
manager = get_plugin_manager_promise(info.context).get()
for product in products:
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
index baf9b441d9..c8e51c9c83 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
@@ -2,6 +2,7 @@ from collections.abc import Iterable
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models import Exists, OuterRef, Subquery
from django.db.models.fields import IntegerField
from django.db.models.functions import Coalesce
@@ -87,43 +88,59 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
draft_order_lines_data = get_draft_order_lines_data_for_variants(pks)
- product_pks = list(
+ # we want db to perform distinct, distinct is not supported with
+ # select_for_update
+ product_pks = tuple(
models.Product.objects.filter(variants__in=pks)
.distinct()
.values_list("pk", flat=True)
)
-
- # Get cached variants with related fields to fully populate webhook payload.
- variants = list(
- models.ProductVariant.objects.filter(id__in=pks).prefetch_related(
- "channel_listings",
- "attributes__values",
- "variant_media",
+ with transaction.atomic():
+ # Get cached variants with related fields to fully populate webhook payload.
+ variants = tuple(
+ models.ProductVariant.objects.order_by("pk")
+ .select_for_update()
+ .filter(id__in=pks)
+ .prefetch_related(
+ "channel_listings",
+ "attributes__values",
+ "variant_media",
+ )
+ )
+ product_pks = tuple(
+ models.Product.objects.order_by("pk")
+ .select_for_update(of=("self",))
+ .filter(pk__in=product_pks)
+ .values_list("pk", flat=True)
)
- )
-
- cls.delete_assigned_attribute_values(pks)
- cls.delete_product_channel_listings_without_available_variants(product_pks, pks)
- response = super().perform_mutation(_root, info, ids=ids, **data)
-
- # delete order lines for deleted variants
- order_models.OrderLine.objects.filter(
- pk__in=draft_order_lines_data.line_pks
- ).delete()
- app = get_app_promise(info.context).get()
- # run order event for deleted lines
- for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
- order_events.order_line_variant_removed_event(
- order, info.context.user, app, order_lines
+ cls.delete_assigned_attribute_values(pks)
+ cls.delete_product_channel_listings_without_available_variants(
+ product_pks, pks
)
+ response = super().perform_mutation(_root, info, ids=ids, **data)
+
+ # delete order lines for deleted variants, they are ordered by Meta
+ order_models.OrderLine.objects.select_for_update(of=("self",)).filter(
+ pk__in=draft_order_lines_data.line_pks
+ ).delete()
+
+ app = get_app_promise(info.context).get()
+ # run order event for deleted lines
+ for (
+ order,
+ order_lines,
+ ) in draft_order_lines_data.order_to_lines_mapping.items():
+ order_events.order_line_variant_removed_event(
+ order, info.context.user, app, order_lines
+ )
order_pks = draft_order_lines_data.order_pks
if order_pks:
recalculate_orders_task.delay(list(order_pks))
# set new product default variant if any has been removed
- products = models.Product.objects.filter(
+ products = models.Product.objects.order_by("pk").filter(
pk__in=product_pks, default_variant__isnull=True
)
for product in products:
@@ -163,20 +180,29 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
).exclude(id__in=variant_pks)
variant_subquery = Subquery(
- queryset=variants.filter(id=OuterRef("variant_id")).values("product_id"),
+ queryset=variants.filter(id=OuterRef("variant_id"))
+ .order_by("pk")
+ .values("product_id"),
output_field=IntegerField(),
)
variant_channel_listings = models.ProductVariantChannelListing.objects.annotate(
product_id=Coalesce(variant_subquery, 0)
)
- invalid_product_channel_listings = models.ProductChannelListing.objects.filter(
- product_id__in=product_pks
- ).exclude(
- Exists(
- variant_channel_listings.filter(
- channel_id=OuterRef("channel_id"), product_id=OuterRef("product_id")
+ invalid_product_channel_listings_pks = tuple(
+ models.ProductChannelListing.objects.order_by("pk")
+ .select_for_update()
+ .filter(product_id__in=product_pks)
+ .exclude(
+ Exists(
+ variant_channel_listings.filter(
+ channel_id=OuterRef("channel_id"),
+ product_id=OuterRef("product_id"),
+ )
)
)
+ .values_list("id", flat=True)
)
- invalid_product_channel_listings.delete()
+ models.ProductChannelListing.objects.filter(
+ pk__in=invalid_product_channel_listings_pks
+ ).delete()
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
index 08db571a23..f76ceb766a 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
@@ -3,7 +3,7 @@ from typing import cast
import graphene
from django.core.exceptions import ValidationError
-from django.db.models import F
+from django.db.models import F, Subquery
from django.utils import timezone
from graphene.utils.str_converters import to_camel_case
@@ -699,8 +699,15 @@ class ProductVariantBulkUpdate(BaseMutation):
],
)
warehouse_models.Stock.objects.filter(id__in=stocks_to_remove).delete()
+ locked_ids = (
+ models.ProductVariantChannelListing.objects.filter(
+ id__in=listings_to_remove
+ )
+ .select_for_update(of=("self",))
+ .order_by("pk")
+ )
models.ProductVariantChannelListing.objects.filter(
- id__in=listings_to_remove
+ id__in=Subquery(locked_ids.values("pk"))
).delete()
@classmethod
diff --git a/saleor/graphql/product/mutations/product/product_delete.py b/saleor/graphql/product/mutations/product/product_delete.py
index 073863a381..f4a24e754c 100644
--- a/saleor/graphql/product/mutations/product/product_delete.py
+++ b/saleor/graphql/product/mutations/product/product_delete.py
@@ -46,14 +46,22 @@ class ProductDelete(ModelDeleteMutation, ModelWithExtRefMutation):
cls, _root, info: ResolveInfo, /, *, external_reference=None, id=None
):
instance = cls.get_instance(info, external_reference=external_reference, id=id)
- variants_id = list(instance.variants.all().values_list("id", flat=True))
with traced_atomic_transaction():
+ variants_id = list(
+ instance.variants.order_by("pk")
+ .select_for_update(of=("self",))
+ .all()
+ .values_list("id", flat=True)
+ )
cls.delete_assigned_attribute_values(instance)
draft_order_lines_data = get_draft_order_lines_data_for_variants(
variants_id
)
+ models.ProductVariant.objects.order_by("pk").filter(
+ pk__in=variants_id
+ ).delete()
response = super().perform_mutation(
_root, info, external_reference=external_reference, id=id
)
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 8e39116352..d94ede12a1 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -39,7 +39,7 @@ VARIANTS_UPDATE_BATCH = 500
# Results in update time ~0.2s
DISCOUNTED_PRODUCT_BATCH = 2000
# Results in update time ~2s when 600 channels exist
-PROMOTION_RULE_BATCH_SIZE = 100
+PROMOTION_RULE_BATCH_SIZE = 50
def _variants_in_batches(variants_qs):
@@ -139,7 +139,12 @@ def _get_channel_to_products_map(rule_to_variant_list):
for rule_to_variant in rule_to_variant_list:
channel_ids = rule_to_channels_map[rule_to_variant.promotionrule_id]
for channel_id in channel_ids:
- product_id = variant_id_to_product_id_map[rule_to_variant.productvariant_id]
+ try:
+ product_id = variant_id_to_product_id_map[
+ rule_to_variant.productvariant_id
+ ]
+ except KeyError:
+ continue
channel_to_products_map[channel_id].add(product_id)
return channel_to_products_map
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index 012d17e901..f2d4fe8587 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -150,10 +150,16 @@ def _create_variant_listing_promotion_rule(variant_listing_promotion_rule_to_cre
for listing in variant_listing_promotion_rule_to_create
]
# Lock PromotionRule and ProductVariantChannelListing before bulk_create
- rules = PromotionRule.objects.filter(id__in=rule_ids).select_for_update()
- variant_listings = ProductVariantChannelListing.objects.filter(
- id__in=listing_ids
- ).select_for_update()
+ rules = (
+ PromotionRule.objects.filter(id__in=rule_ids)
+ .select_for_update()
+ .order_by("pk")
+ )
+ variant_listings = (
+ ProductVariantChannelListing.objects.filter(id__in=listing_ids)
+ .select_for_update()
+ .order_by("pk")
+ )
# Do not create VariantChannelListingPromotionRule for rules that were deleted.
if len(rules) < len(rule_ids):
variant_listing_promotion_rule_to_create = [
@@ -193,7 +199,10 @@ def _get_product_to_variant_channel_listings_per_channel_map(
lambda: defaultdict(list)
)
for variant_channel_listing in variant_channel_listings.iterator():
- product_id = variant_to_product_id[variant_channel_listing.variant_id]
+ try:
+ product_id = variant_to_product_id[variant_channel_listing.variant_id]
+ except KeyError:
+ continue
price_data[product_id][variant_channel_listing.channel_id].append(
variant_channel_listing
)
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index 6c820cf0e1..03058f44d6 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -74,5 +74,4 @@ def fetch_variants_for_promotion_rules(
for variant_id in set(variants.values_list("pk", flat=True))
]
)
- update_rule_variant_relation(rules, new_rules_variants)
- return new_rules_variants
+ return update_rule_variant_relation(rules, new_rules_variants)