Skip to content

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

Unify the lock logic for allocations and stocks (#17129)

Maciej Korycinskiaba4e2edd386
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index f572d024f8..e76948aa9f 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -45,6 +45,7 @@ from ....permission.enums import OrderPermissions
from ....product.models import ProductVariant
from ....shipping.models import ShippingMethod, ShippingMethodChannelListing
from ....tax.models import TaxClass
+from ....warehouse.management import stock_bulk_update
from ....warehouse.models import Stock, Warehouse
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
@@ -2266,7 +2267,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
)
FulfillmentLine.objects.bulk_create(fulfillment_lines)
- Stock.objects.bulk_update(stocks, ["quantity"])
+ stock_bulk_update(stocks, ["quantity"])
transactions: list[TransactionItem] = sum(
[
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 7bcc086711..af88048052 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
@@ -13,6 +13,7 @@ from ....permission.enums import ProductPermissions
from ....product import models
from ....product.error_codes import ProductErrorCode, ProductVariantBulkErrorCode
from ....warehouse import models as warehouse_models
+from ....warehouse.management import delete_stocks, stock_bulk_update
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...attribute.utils import AttributeAssignmentMixin
@@ -689,7 +690,9 @@ class ProductVariantBulkUpdate(BaseMutation):
warehouse_models.Stock.objects.bulk_create(
stocks_to_create, ignore_conflicts=True
)
- warehouse_models.Stock.objects.bulk_update(stocks_to_update, ["quantity"])
+ if stocks_to_update:
+ stock_bulk_update(stocks_to_update, ["quantity"])
+
models.ProductVariantChannelListing.objects.bulk_create(listings_to_create)
models.ProductVariantChannelListing.objects.bulk_update(
listings_to_update,
@@ -700,7 +703,9 @@ class ProductVariantBulkUpdate(BaseMutation):
"preorder_quantity_threshold",
],
)
- warehouse_models.Stock.objects.filter(id__in=stocks_to_remove).delete()
+ if stocks_to_remove:
+ delete_stocks(stocks_to_remove)
+
locked_ids = (
models.ProductVariantChannelListing.objects.filter(
id__in=listings_to_remove
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py
index 9a14165fc3..b515a1158d 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_delete.py
@@ -5,6 +5,7 @@ from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductPermissions
from ....product import models
from ....warehouse import models as warehouse_models
+from ....warehouse.management import delete_stocks
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...channel import ChannelContext
@@ -80,8 +81,7 @@ class ProductVariantStocksDelete(BaseMutation):
cls.call_event(
manager.product_variant_out_of_stock, stock, webhooks=webhooks
)
-
- stocks_to_delete.delete()
+ delete_stocks([stock.id for stock in stocks_to_delete])
StocksByProductVariantIdLoader(info.context).clear(variant.id)
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
index 7a610b1dd0..94173e7b7d 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
@@ -7,6 +7,7 @@ from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductPermissions
from ....product import models
from ....warehouse import models as warehouse_models
+from ....warehouse.management import stock_bulk_update
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...channel import ChannelContext
@@ -129,4 +130,4 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
webhooks=webhooks_stock_update,
)
- warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])
+ stock_bulk_update(stocks, ["quantity"])
diff --git a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py
index 893040c49b..75c83aa394 100644
--- a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py
+++ b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py
@@ -8,6 +8,7 @@ from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductPermissions
from ....warehouse import models
from ....warehouse.error_codes import StockBulkUpdateErrorCode
+from ....warehouse.management import stock_qs_select_for_update
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
@@ -361,7 +362,7 @@ class StockBulkUpdate(BaseMutation):
variant_lookup = Q(product_variant__external_reference__in=variants)
stocks = (
- models.Stock.objects.select_for_update()
+ stock_qs_select_for_update()
.filter(warehouse_lookup & variant_lookup)
.annotate(
variant_external_reference=F("product_variant__external_reference"),
@@ -382,6 +383,8 @@ class StockBulkUpdate(BaseMutation):
for stock_data in instances_data_with_errors_list
if stock_data["instance"] and stock_data.get("quantity_updated")
]
+
+ # Stocks are locked in `get_stocks`
models.Stock.objects.bulk_update(stocks_to_update, fields=["quantity"])
return stocks_to_update
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index c7fad090ad..11c629eaf6 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -43,6 +43,57 @@ class StockData(NamedTuple):
quantity: int
+def stock_select_for_update_for_existing_qs(qs):
+ return qs.order_by("pk").select_for_update(of=(["self"]))
+
+
+def stock_qs_select_for_update():
+ return stock_select_for_update_for_existing_qs(Stock.objects.all())
+
+
+def delete_stocks(stock_pks_to_delete: list[int]):
+ with transaction.atomic():
+ return Stock.objects.filter(
+ id__in=Stock.objects.order_by("pk")
+ .select_for_update(of=["self"])
+ .values_list("pk", flat=True)
+ .filter(id__in=stock_pks_to_delete)
+ ).delete()
+
+
+def stock_bulk_update(stocks: list[Stock], fields_to_update: list[str]):
+ with transaction.atomic():
+ _locked_stocks = list(
+ stock_qs_select_for_update()
+ .filter(id__in=[stock.id for stock in stocks])
+ .values_list("id", flat=True)
+ )
+ Stock.objects.bulk_update(stocks, fields_to_update)
+
+
+def allocation_with_stock_qs_select_for_update():
+ return (
+ Allocation.objects.select_related("stock")
+ .select_for_update(
+ of=(
+ "self",
+ "stock",
+ )
+ )
+ .order_by("stock__pk")
+ )
+
+
+def delete_allocations(allocation_pks_to_delete: list[int]):
+ with transaction.atomic():
+ return Allocation.objects.filter(
+ id__in=Allocation.objects.order_by("stock_id")
+ .select_for_update(of=["self"])
+ .values_list("pk", flat=True)
+ .filter(id__in=allocation_pks_to_delete)
+ ).delete()
+
+
@traced_atomic_transaction()
def allocate_stocks(
order_lines_info: list["OrderLineInfo"],
@@ -86,9 +137,8 @@ def allocate_stocks(
)
stocks = list(
- stocks.select_for_update(of=("self",))
+ stock_select_for_update_for_existing_qs(stocks)
.filter(**filter_lookup)
- .order_by("pk")
.values("id", "product_variant", "pk", "quantity", "warehouse_id")
)
stocks_id = (stock.pop("id") for stock in stocks)
@@ -290,16 +340,8 @@ def deallocate_stock(order_lines_data: list["OrderLineInfo"], manager: PluginsMa
raise an exception.
"""
lines = [line_info.line for line_info in order_lines_data]
- lines_allocations = (
- Allocation.objects.filter(order_line__in=lines)
- .select_related("stock")
- .select_for_update(
- of=(
- "self",
- "stock",
- )
- )
- .order_by("stock__pk")
+ lines_allocations = allocation_with_stock_qs_select_for_update().filter(
+ order_line__in=lines
)
line_to_allocations: dict[UUID, list[Allocation]] = defaultdict(list)
@@ -381,7 +423,7 @@ def increase_stock(
"""
assert order_line.variant
stock = (
- Stock.objects.select_for_update(of=("self",))
+ stock_qs_select_for_update()
.filter(warehouse=warehouse, product_variant=order_line.variant)
.first()
)
@@ -411,10 +453,11 @@ def increase_allocations(
"""Increase allocation for order lines with appropriate quantity."""
line_pks = [info.line.pk for info in lines_info]
allocations = list(
- Allocation.objects.filter(order_line__in=line_pks)
- .select_related("stock", "order_line")
- .select_for_update(of=("self", "stock"))
+ allocation_with_stock_qs_select_for_update()
+ .select_related("order_line")
+ .filter(order_line__in=line_pks)
)
+
# evaluate allocations query to trigger select_for_update lock
allocation_pks_to_delete = [alloc.pk for alloc in allocations]
allocation_quantity_map: dict[UUID, list] = defaultdict(list)
@@ -478,16 +521,15 @@ def decrease_stock(
try:
deallocate_stock(order_lines_info, manager)
except AllocationError as exc:
- Allocation.objects.filter(order_line__in=exc.order_lines).update(
- quantity_allocated=0
- )
+ Allocation.objects.order_by("stock_id").filter(
+ order_line__in=exc.order_lines
+ ).update(quantity_allocated=0)
stocks = (
- Stock.objects.select_for_update(of=("self",))
+ stock_qs_select_for_update()
.filter(product_variant__in=variants)
.filter(warehouse_id__in=warehouse_pks)
.select_related("product_variant", "warehouse")
- .order_by("pk")
)
variant_and_warehouse_to_stock: dict[int, dict[UUID, Stock]] = defaultdict(dict)
@@ -599,9 +641,9 @@ def get_order_lines_with_track_inventory(
def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
"""Remove all allocations for given order."""
lines = OrderLine.objects.filter(order_id=order.id)
- allocations = Allocation.objects.filter(
+ allocations = allocation_with_stock_qs_select_for_update().filter(
Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0
- ).select_related("stock")
+ )
stocks_to_update = []
for alloc in allocations:
@@ -609,7 +651,10 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated
stocks_to_update.append(stock)
- for allocation in allocations.annotate_stock_available_quantity():
+ allocations_for_back_in_stock = Allocation.objects.filter(
+ id__in=[allocation.id for allocation in allocations]
+ )
+ for allocation in allocations_for_back_in_stock.annotate_stock_available_quantity():
if allocation.stock_available_quantity <= 0:
transaction.on_commit(
lambda: manager.product_variant_back_in_stock(allocation.stock)
@@ -623,9 +668,9 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
def deallocate_stock_for_orders(orders_id, manager: PluginsManager):
"""Remove all allocations for given order."""
lines = OrderLine.objects.filter(order_id__in=orders_id)
- allocations = Allocation.objects.filter(
+ allocations = allocation_with_stock_qs_select_for_update().filter(
Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0
- ).select_related("stock")
+ )
stocks_to_update = []
for alloc in allocations:
@@ -633,7 +678,10 @@ def deallocate_stock_for_orders(orders_id, manager: PluginsManager):
stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated
stocks_to_update.append(stock)
- for allocation in allocations.annotate_stock_available_quantity():
+ allocations_for_back_in_stock = Allocation.objects.filter(
+ id__in=[allocation.id for allocation in allocations]
+ )
+ for allocation in allocations_for_back_in_stock.annotate_stock_available_quantity():
if allocation.stock_available_quantity <= 0:
transaction.on_commit(
lambda: manager.product_variant_back_in_stock(allocation.stock)
@@ -903,7 +951,7 @@ def _get_stock_for_preorder_allocation(
raise PreorderAllocationError(preorder_allocation.order_line)
stock = list(
- Stock.objects.select_for_update(of=("self",)).filter(
+ stock_qs_select_for_update().filter(
warehouse=warehouse, product_variant=product_variant
)
)
diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.py
index 101a024c07..2be463f45c 100644
--- a/saleor/warehouse/reservations.py
+++ b/saleor/warehouse/reservations.py
@@ -11,8 +11,8 @@ from django.utils import timezone
from ..core.exceptions import InsufficientStock, InsufficientStockData
from ..core.tracing import traced_atomic_transaction
from ..product.models import ProductVariant, ProductVariantChannelListing
-from .management import sort_stocks
-from .models import Allocation, PreorderReservation, Reservation, Stock
+from .management import sort_stocks, stock_qs_select_for_update
+from .models import Allocation, PreorderReservation, Reservation
if TYPE_CHECKING:
from ..channel.models import Channel
@@ -106,7 +106,7 @@ def reserve_stocks(
return
stocks = list(
- Stock.objects.select_for_update(of=("self",))
+ stock_qs_select_for_update()
.get_variants_stocks_for_country(country_code, channel.slug, variants)
.order_by("pk")
.values("id", "product_variant", "pk", "quantity", "warehouse_id")
diff --git a/saleor/warehouse/tasks.py b/saleor/warehouse/tasks.py
index d7dd27b9cf..35683c224c 100644
--- a/saleor/warehouse/tasks.py
+++ b/saleor/warehouse/tasks.py
@@ -5,6 +5,7 @@ from django.utils import timezone
from ..celeryconf import app
from ..core.db.connection import allow_writer
+from .management import delete_allocations, stock_bulk_update
from .models import Allocation, PreorderReservation, Reservation, Stock
task_logger = get_task_logger(__name__)
@@ -13,7 +14,10 @@ task_logger = get_task_logger(__name__)
@app.task
@allow_writer()
def delete_empty_allocations_task():
- count, _ = Allocation.objects.filter(quantity_allocated=0).delete()
+ ids_to_delete = list(
+ Allocation.objects.filter(quantity_allocated=0).values_list("id", flat=True)
+ )
+ count, _ = delete_allocations(ids_to_delete)
if count:
task_logger.debug("Removed %s allocations", count)
@@ -56,7 +60,8 @@ def update_stocks_quantity_allocated_task():
mismatched_stock.quantity_allocated = allocations_allocated
stocks_to_update.append(mismatched_stock)
- Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+ stock_bulk_update(stocks_to_update, ["quantity_allocated"])
+
task_logger.info(
"Finished updating quantity_allocated on stocks, %d were corrected.",
len(stocks_to_update),
diff --git a/saleor/warehouse/tests/test_tasks.py b/saleor/warehouse/tests/test_tasks.py
index ed4b4af59f..61ee57cc06 100644
--- a/saleor/warehouse/tests/test_tasks.py
+++ b/saleor/warehouse/tests/test_tasks.py
@@ -3,13 +3,28 @@ import datetime
import pytest
from django.utils import timezone
-from ..models import PreorderReservation, Reservation
+from ..models import Allocation, PreorderReservation, Reservation
from ..tasks import (
+ delete_empty_allocations_task,
delete_expired_reservations_task,
update_stocks_quantity_allocated_task,
)
+def test_delete_empty_allocations_task(allocations):
+ # given
+ allocation = allocations[0]
+ allocation.quantity_allocated = 0
+ allocation.save()
+
+ # when
+ delete_empty_allocations_task()
+
+ # then
+ assert Allocation.objects.count() == len(allocations) - 1
+ assert not Allocation.objects.filter(id=allocation.id).exists()
+
+
def test_delete_expired_reservations_task_deletes_expired_stock_reservations(
checkout_line_with_reservation_in_many_stocks,
):