Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix DB locks - never-evaluated `select_for_update` querysets (#19615)
Przemysław Ładad7fe298a4752
diff --git a/AGENTS.md b/AGENTS.mdindex d1f59caa0d..115f2a6de3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -369,6 +369,27 @@ def my_model_qs_select_for_update() -> QuerySet[MyModel]:return MyModel.objects.order_by("pk").select_for_update(of=["self"])```+### select_for_update pitfalls++1. Querysets are lazy - an unevaluated lock queryset runs no SQL, so no lock is+ taken and it fails silently. Force evaluation inside the transaction with+ `list(...)`, `.get()`/`.first()`, or use it as an `__in` subquery of the write.++ ```python+ with transaction.atomic():+ # Bad: lazy - no lock+ _locked = model_qs_select_for_update().filter(pk__in=pks)+ # Good: rows locked, only pks fetched+ _locked = list(+ model_qs_select_for_update().filter(pk__in=pks).values_list("pk", flat=True)+ )+ Model.objects.bulk_update(objs, ["field"])+ ```++2. Test the lock with the `assert_locks_rows_before_write` fixture+ (`saleor/tests/fixtures.py`) - it captures the block's queries and asserts an+ ordered `FOR UPDATE` query is emitted before the `UPDATE`.+## Database TransactionsWrap related operations in transactions using `traced_atomic_transaction`:diff --git a/saleor/attribute/lock_objects.py b/saleor/attribute/lock_objects.pyindex 0361872920..0a563bd33a 100644--- a/saleor/attribute/lock_objects.py+++ b/saleor/attribute/lock_objects.py@@ -4,6 +4,8 @@ from .models.base import Attribute, AttributeValuedef attribute_value_qs_select_for_update() -> QuerySet[AttributeValue]:+ # Matching lock order (sort_order, pk) of `perform_reordering` to avoid deadlocks.+ # TODO: switch to a stable pk-only ordering together with the reordering logic.return AttributeValue.objects.order_by("sort_order", "pk").select_for_update(of=(["self"]))diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.pyindex dd8354e74d..0e3db729e5 100644--- a/saleor/attribute/models/base.py+++ b/saleor/attribute/models/base.py@@ -364,10 +364,10 @@ class AttributeValueManager(models.Manager):from ..lock_objects import attribute_value_qs_select_for_updatewith transaction.atomic():- _locked_qs = (+ _locked_ids = list(attribute_value_qs_select_for_update().filter(pk__in=[obj.pk for obj in objects_to_be_updated])- .select_for_update(of=(["self"]))+ .values_list("pk", flat=True))self.bulk_update(objects_to_be_updated,diff --git a/saleor/attribute/tests/models/test_base.py b/saleor/attribute/tests/models/test_base.pyindex d3abef2dd9..d12d5460d1 100644--- a/saleor/attribute/tests/models/test_base.py+++ b/saleor/attribute/tests/models/test_base.py@@ -146,3 +146,33 @@ def test_max_sort_order_0_when_deleting_attribute_value_with_sort_order_0():assert attribute.max_sort_order == 0value2.refresh_from_db()assert value2.sort_order == 0+++def test_bulk_update_or_create_locks_rows_before_update(assert_locks_rows_before_write):+ # given+ attribute = Attribute.objects.create(+ slug="test-slug",+ name="test name",+ type=AttributeType.PRODUCT_TYPE,+ )+ value = AttributeValue.objects.create(+ attribute=attribute, name="value", slug="value"+ )+ new_name = "updated name"++ # when+ with assert_locks_rows_before_write():+ results = AttributeValue.objects.bulk_update_or_create(+ [+ {+ "attribute": attribute,+ "slug": value.slug,+ "defaults": {"name": new_name},+ }+ ]+ )++ # then+ value.refresh_from_db(fields=("name",))+ assert value.name == new_name+ assert results == [value]diff --git a/saleor/checkout/lock_objects.py b/saleor/checkout/lock_objects.pyindex 4c12ae6dbc..253fda1327 100644--- a/saleor/checkout/lock_objects.py+++ b/saleor/checkout/lock_objects.py@@ -4,8 +4,8 @@ from .models import Checkout, CheckoutLinedef checkout_qs_select_for_update() -> QuerySet[Checkout]:- return Checkout.objects.order_by("pk").select_for_update(of=(["self"]))+ return Checkout.objects.order_by("pk").select_for_update(of=["self"])def checkout_lines_qs_select_for_update() -> QuerySet[CheckoutLine]:- return CheckoutLine.objects.order_by("pk").select_for_update(of=(["self"]))+ return CheckoutLine.objects.order_by("pk").select_for_update(of=["self"])diff --git a/saleor/checkout/search/indexing.py b/saleor/checkout/search/indexing.pyindex 681cedd47f..22e345e97f 100644--- a/saleor/checkout/search/indexing.py+++ b/saleor/checkout/search/indexing.py@@ -49,7 +49,7 @@ def update_checkouts_search_vector(checkouts: list["Checkout"]):with transaction.atomic():with allow_writer():- _locked_checkouts = (+ _locked_checkouts = list(checkout_qs_select_for_update().filter(pk__in=[checkout.pk for checkout in checkouts]).values_list("pk", flat=True)diff --git a/saleor/checkout/tests/test_search_indexing.py b/saleor/checkout/tests/test_search_indexing.pyindex cc72b0aaaf..838885aba8 100644--- a/saleor/checkout/tests/test_search_indexing.py+++ b/saleor/checkout/tests/test_search_indexing.py@@ -143,26 +143,27 @@ def test_update_checkouts_search_vector_constant_queries(checkout_list = checkout_list_with_relations# when & then- # Expected query breakdown (14 total):+ # Expected query breakdown (15 total):# First transaction block:- # 1. Select for update (filter dirty checkouts)- # 2. Update search_index_dirty flag+ # 1. Transaction savepoint+ # 2. Update search_index_dirty flag (locks via inlined FOR UPDATE subquery)+ # 3. Release savepoint# Load checkout data:- # 3. Load users (1 query)- # 4. Load addresses (1 query)- # 5. Load payments (1 query)- # 6. Load checkout lines (1 query)- # 7. Load transactions (1 query)- # 8. Load product variants (1 query)- # 9. Load products (1 query)- # 10. Load transaction events (1 query)+ # 4. Load users (1 query)+ # 5. Load addresses (1 query)+ # 6. Load payments (1 query)+ # 7. Load checkout lines (1 query)+ # 8. Load transactions (1 query)+ # 9. Load product variants (1 query)+ # 10. Load products (1 query)+ # 11. Load transaction events (1 query)# Second transaction block:- # 11. Transaction savepoint- # 12. Select for update (lock checkouts)- # 13. Bulk update search vectors- # 14. Release savepoint+ # 12. Transaction savepoint+ # 13. Select for update (lock checkouts)+ # 14. Bulk update search vectors+ # 15. Release savepoint- expected_queries = 14+ expected_queries = 15with django_assert_num_queries(expected_queries):update_checkouts_search_vector(checkout_list[: len(checkout_list) - 1])with django_assert_num_queries(expected_queries):@@ -708,3 +709,21 @@ def test_update_checkouts_search_vector_resets_flag_on_load_data_exception(checkout.refresh_from_db()assert checkout.search_index_dirty is Trueassert not checkout.search_vector+++def test_update_checkouts_search_vector_locks_rows_before_write(+ checkout_with_item, assert_locks_rows_before_write+):+ # given+ assert not checkout_with_item.search_vector++ # when+ # patch out set_search_index_dirty - it emits its own locked UPDATE and is+ # tested separately; here we only verify the search vector write phase.+ with patch("saleor.checkout.search.indexing.set_search_index_dirty"):+ with assert_locks_rows_before_write():+ update_checkouts_search_vector([checkout_with_item])++ # then+ checkout_with_item.refresh_from_db(fields=("search_vector",))+ assert checkout_with_item.search_vectordiff --git a/saleor/page/lock_objects.py b/saleor/page/lock_objects.pyindex 524b7cd821..12d44516d7 100644--- a/saleor/page/lock_objects.py+++ b/saleor/page/lock_objects.py@@ -4,4 +4,4 @@ from .models import Pagedef page_qs_select_for_update() -> QuerySet[Page]:- return Page.objects.order_by("pk").select_for_update(of=(["self"]))+ return Page.objects.order_by("pk").select_for_update(of=["self"])diff --git a/saleor/page/search.py b/saleor/page/search.pyindex 311e5cef5d..dc2a04f671 100644--- a/saleor/page/search.py+++ b/saleor/page/search.py@@ -48,7 +48,7 @@ def update_pages_search_vector(# Save updateswith transaction.atomic():- _locked_pages = (+ _locked_pages = list(page_qs_select_for_update().filter(id__in=[page.id for page in pages]).values_list("id", flat=True)diff --git a/saleor/page/tests/test_search.py b/saleor/page/tests/test_search.pyindex 17b0b96e07..8e3ab7d85b 100644--- a/saleor/page/tests/test_search.py+++ b/saleor/page/tests/test_search.py@@ -23,6 +23,14 @@ def test_update_pages_search_vector_multiple_pages(page_list):assert page.search_index_dirty is False+def test_update_pages_search_vector_locks_rows_before_write(+ page_list, assert_locks_rows_before_write+):+ # when/then+ with assert_locks_rows_before_write():+ update_pages_search_vector(page_list)++def test_update_pages_search_vector_empty_list(db):"""Test updating search vector with empty page IDs list."""# given@@ -94,19 +102,20 @@ def test_update_pages_search_vector_constant_queries(page_list = page_list_with_attributes# when & then- # Expected query breakdown (10 total):+ # Expected query breakdown (11 total):# 1. Load page types (1 query)- # 2. Load page data for select_for_update (1 query)+ # 2. Load page data (1 query)# 3. Load page-attribute relationships (1 query)# 4. Load attributes (1 query)# 5. Load attribute value assignments - batched (1 query)# 6. Load attribute values - batched (1 query)# 7. Load reference page titles (1 query)# 8. Transaction savepoint (1 query)- # 9. Bulk update (1 query)- # 10. Release savepoint (1 query)+ # 9. Lock pages with select_for_update (1 query)+ # 10. Bulk update (1 query)+ # 11. Release savepoint (1 query)- expected_queries = 10+ expected_queries = 11with django_assert_num_queries(expected_queries): # Expected number of queriesupdate_pages_search_vector(page_list[: len(page_list) - 1])with django_assert_num_queries(diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f8887f3f04..db6c890d7e 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -164,6 +164,39 @@ def assert_max_num_queries(capture_queries):return partial(capture_queries, exact=False)+def assert_locks_rows_before_write(capture_queries):+ """Assert that the wrapped block locks rows before writing them.++ Verifies the emitted SQL contains exactly one `SELECT ... FOR UPDATE` with a+ deterministic `ORDER BY` (concurrent lockers acquiring rows in the same+ order is what prevents deadlocks between them), followed by exactly one+ `UPDATE`. Asserting on SQL is deliberate, as a missing lock is hard to+ detect with a behavioral test.+ """++ @contextmanager+ def _assert_locks_rows_before_write():+ with capture_queries() as ctx:+ yield++ lock_and_update_queries = [+ query["sql"]+ for query in ctx.captured_queries+ if "FOR UPDATE" in query["sql"] or query["sql"].startswith("UPDATE")+ ]+ assert len(lock_and_update_queries) == 2, (+ "expected exactly one lock SELECT and one UPDATE query, got: "+ f"{lock_and_update_queries}"+ )+ lock_query, update_query = lock_and_update_queries+ assert "FOR UPDATE" in lock_query, "rows were not locked before the write"+ assert "ORDER BY" in lock_query, "the lock query has no deterministic order"+ assert update_query.startswith("UPDATE")++ return _assert_locks_rows_before_write++@pytest.fixturedef address(db): # pylint: disable=W0613return Address.objects.create(