[5.x]: Catalog pricing queue lock is held until the product save commits, so parallel saves run one at a time
Maintainer thường phản hồi trong vòng 1 ngày
Đánh giá
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức phù hợp với người mới
- 48/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Khá rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- mysql, php
- Lĩnh vực
- backend, databases, performance
Hướng nghiên cứu
Read src/services/CatalogPricing.php and the Product::afterPropagate() TODO mentioned in the report; the issue also points to Connection::EVENT_COMMIT_TRANSACTION and Connection::EVENT_ROLLBACK_TRANSACTION. Start by tracing how _queueCatalogPricingIds() acquires and releases the mutex during an element save. Done means parallel product saves no longer serialize or fail on the mutex timeout, with queue work deferred until the outermost transaction commits.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
What happened?
Description
Since 5.7.0, every purchasable save calls CatalogPricing::createCatalogPricingJob() from afterPropagate(). That takes the global catalogpricingqueue mutex (5 s timeout) and merges the IDs into the single unreserved commerce_catalogpricing_queue row.
This runs inside the element-save transaction, so the release() in _queueCatalogPricingIds() doesn't release anything: craft\mutex\MutexTrait queues the release until the outermost transaction commits. The lock stays held for the rest of the product save: every remaining variant, search index updates, relations, revisions and other plugins' save handlers.
So parallel product saves (import workers, webhook requests, a CP save during an import) run one at a time. A save that waits more than 5 s throws RuntimeException: Unable to acquire the catalog pricing queue mutex. and the whole product rolls back.
We hit this importing a ~340k-SKU dropship feed (Commerce 5.7.6, Craft 5.11, MySQL 8.0, READ COMMITTED):
- 8 import workers were no faster than 4. One worker with no plugin listeners had no timeouts.
- One 13-hour run logged 48,172 mutex timeouts, and each one was a rolled-back product save that had to be retried.
- The pending row's
idscolumn grew to 988 KB at 154k variants and is rewritten on every save. - After importing 312k variants there were 343,680 "Generating catalog pricing" jobs. A 20-variant product queues 21: one for each variant's
afterPropagate()and one for the product's. A singlephp craft commerce/pricing-catalog/generaterun regenerated all 312,257 prices in 4.7 s.
Related issues that describe something different:
- #3709, #3978 and #4123 are about the job count. The workaround suggested there (cancel
CatalogPricingjobs inQueue::EVENT_BEFORE_PUSH) hasn't helped since 5.7.0, because the mutex and the queue-row write happen before the push. The table below shows this. - #4003 and #4141 are deadlocks inside
generateCatalogPrices(). - The open PR #4360 targets the same error. See "Tested with #4360" below.
Steps to reproduce
Fresh install: Craft 5.11.5.1, Commerce 5.7.6, MySQL 8.0.45, PHP 8.3, the default store, and one product type with handle repro and no custom fields. config/db.php sets READ COMMITTED, as in our import:
return ['attributes' => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED']];
- Save
repro-import.php(below) in the project root. - Start several workers at once:
for i in $(seq 1 8); do php repro-import.php $i 8 150 & done; wait - While they run, check
SELECT ID, STATE, TIME, LEFT(INFO, 80) FROM information_schema.PROCESSLIST WHERE INFO LIKE 'SELECT GET_LOCK%';
repro-import.php
<?php
// php repro-import.php <worker> <products> [variantsPerProduct=20] [--suppress-job]
// --suppress-job applies the EVENT_BEFORE_PUSH workaround from #3709/#3978/#4003/#4123.
use craft\commerce\elements\Product;
use craft\commerce\elements\Variant;
use craft\commerce\Plugin as Commerce;
use craft\commerce\queue\jobs\CatalogPricing as CatalogPricingJob;
use yii\base\Event;
use yii\queue\PushEvent;
use yii\queue\Queue;
require __DIR__ . '/bootstrap.php';
$app = require CRAFT_VENDOR_PATH . '/craftcms/cms/bootstrap/console.php';
$worker = (int)($argv[1] ?? 1);
$products = (int)($argv[2] ?? 20);
$variantsPer = (int)($argv[3] ?? 20);
$suppressJob = in_array('--suppress-job', $argv, true);
if ($suppressJob) {
Event::on(Queue::class, Queue::EVENT_BEFORE_PUSH, function(PushEvent $event) {
if ($event->job instanceof CatalogPricingJob) {
$event->handled = true;
}
});
}
$type = Commerce::getInstance()->getProductTypes()->getProductTypeByHandle('repro');
$run = $worker . '-' . substr(uniqid(), -6);
$stats = ['saved' => 0, 'mutexTimeouts' => 0, 'otherErrors' => 0];
$times = [];
$t0 = microtime(true);
for ($i = 1; $i <= $products; $i++) {
$product = new Product(['typeId' => $type->id, 'title' => "Repro $run-$i", 'slug' => "repro-$run-$i"]);
$variants = [];
for ($v = 1; $v <= $variantsPer; $v++) {
$variant = new Variant(['sku' => "R-$run-$i-$v", 'basePrice' => 10 + $v, 'title' => "Variant $v"]);
$variant->setPrimaryOwner($product);
$variant->setOwner($product);
$variants[] = $variant;
}
$product->setVariants($variants);
$product->setDirtyAttributes(['variants']);
$ts = microtime(true);
try {
if (Craft::$app->getElements()->saveElement($product)) {
$stats['saved']++;
} else {
$stats['otherErrors']++;
}
} catch (Throwable $e) {
str_contains($e->getMessage(), 'catalog pricing queue mutex') ? $stats['mutexTimeouts']++ : $stats['otherErrors']++;
Craft::$app->getDb()->close();
}
$times[] = microtime(true) - $ts;
}
echo json_encode(['worker' => $worker, 'elapsed' => round(microtime(true) - $t0, 1),
'avgSave' => round(array_sum($times) / count($times), 2)] + $stats), "\n";
Results on a laptop with local MySQL. Each row is a fresh run with the pricing queue emptied first. Wall time is the slowest worker.
| Code | Workers × products × variants | Wall time | Products saved | Mutex timeouts | Jobs queued | Products/s |
|---|---|---|---|---|---|---|
| 5.7.6 | 1 × 30 × 20 | 3.3 s | 30 | 0 | 630 | 9.1 |
| 5.7.6 | 4 × 30 × 20 | 12.6 s | 120 | 0 | 2,520 | 9.5 |
| 5.7.6 | 8 × 30 × 20 | 29.4 s | 240 | 0 | 5,040 | 8.2 |
| 5.7.6 | 1 × 8 × 150 | 6.0 s | 8 | 0 | 1,208 | 1.3 |
| 5.7.6 | 8 × 8 × 150 | 44.0 s | 44 of 64 | 20 | 6,644 | 1.0 |
5.7.6 + EVENT_BEFORE_PUSH workaround |
8 × 8 × 150 | 42.6 s | 45 of 64 | 19 | 0 | 1.1 |
| 5.7.6 + #4360 | 8 × 8 × 150 | 75.2 s | 64 | 0 | 8 | 0.9 |
| 5.7.6 + deferred write (diff below) | 1 × 8 × 150 | 7.1 s | 8 | 0 | 8 | 1.1 |
| 5.7.6 + deferred write | 8 × 8 × 150 | 11.2 s | 64 | 0 | 64 | 5.7 |
| 5.7.6 + deferred write | 8 × 30 × 20 | 6.0 s | 240 | 0 | 240 | 40 |
On 5.7.6, adding workers adds no throughput. In the 8 × 30 × 20 run we sampled performance_schema.metadata_locks every 0.5 s. In 45 of the 52 samples, 7 of the 8 connections were waiting on the catalogpricingqueue user lock while the eighth held it. A processlist sample from the 8 × 8 × 150 run:
STATE TIME INFO
User lock 4 SELECT GET_LOCK(SUBSTRING(CONCAT('commerce-pricing-repro--dev', '97a966792e81feb6880a444dff516635a6c7d5eb'), 1, 64), 5) ...
User lock 4 SELECT GET_LOCK(SUBSTRING(CONCAT('commerce-pricing-repro--dev', '97a966792e81feb6880a444dff516635a6c7d5eb'), 1, 64), 5) ...
User lock 3 SELECT GET_LOCK(...)
...
(97a96679… is sha1('catalogpricingqueue').) This script shows that the lock outlives createCatalogPricingJob() and is held until commit:
$lockName = substr(Craft::$app->getEnvId() . sha1('catalogpricingqueue'), 0, 64);
$db = Craft::$app->getDb();
$other = new PDO($db->dsn, $db->username, $db->password); // second connection, outside the transaction
$isUsed = fn() => $other->query('SELECT IS_USED_LOCK(' . $other->quote($lockName) . ')')->fetchColumn() ?: 'free';
$tx = $db->beginTransaction();
Commerce::getInstance()->getCatalogPricing()->createCatalogPricingJob(['purchasableIds' => [$someVariantId], 'storeId' => 1]);
echo $isUsed(), "\n"; sleep(2); echo $isUsed(), "\n";
$tx->commit();
echo $isUsed(), "\n";
66319 <- inside the transaction, after createCatalogPricingJob() returned
66319 <- 2 s later, still inside the transaction
free <- after commit
Expected behavior
Product saves in separate processes run in parallel. A bookkeeping write to the pricing queue doesn't decide whether a product save succeeds.
Actual behavior
All product saves wait on one global lock that is held for each whole save transaction. Any save that waits longer than 5 s throws, and the whole product rolls back.
Tested with #4360
We applied #4360 (head dc0611de) to 5.7.6 and ran the same test. It removes the exception and cuts the job count (8 jobs instead of 6,644), and we'd like to see it merged. Inside an element save, though, its compare-and-swap UPDATE commerce_catalogpricing_queue takes an InnoDB row lock that is also held until commit, so the saves still wait for each other. 8 workers took 75 s for 64 products, against 6.2 s for 8 products with one worker. 830 processlist samples showed UPDATE commerce_catalogpricing_queue … waiting on the row lock, with single waits of up to 11 s. With larger products or more workers these waits would run into innodb_lock_wait_timeout (50 s by default).
Suggestions
- Don't write to the shared queue row inside the element-save transaction. Collect the IDs in memory, then write them and push one job when the outermost transaction commits.
Connection::EVENT_COMMIT_TRANSACTIONfires only then, and Craft'sMutexTraitalready relies on it. The@TODOinProduct::afterPropagate()describes the same idea. Our prototype on 5.7.6 (about 60 lines, diff below) produced the "deferred write" rows above: 0 timeouts, one job per product, and 8 workers about 5× faster than on 5.7.6. It works alongside #4360, since that PR's merge would then run after commit, outside any long transaction. One open question: an exception thrown in the commit handler surfaces fromcommit()after the data is already committed, so it may be better to catch and log it there. - A supported way to pause per-save queueing during bulk imports, for example
CatalogPricing::withoutQueueing(callable $fn)or a cancellable event before the IDs are queued. An importer could then callgenerateCatalogPrices($ids)once at the end. TheEVENT_BEFORE_PUSHrecipe from #3709, #3978, #4003 and #4123 no longer covers the queue-row write. - Smaller: a new product queues the same IDs twice. Variants pass their store ID, but
Product::afterPropagate()passes$this->storeId, which is still null on a new product. So every new product also adds all its variants to astoreId = NULLrow (all stores). In the repro the two rows always held the same IDs.
Prototype: defer the queue write until the outermost commit (5.7.6)
--- a/src/services/CatalogPricing.php
+++ b/src/services/CatalogPricing.php
@@ -30,6 +30,7 @@
use Illuminate\Support\Collection;
use yii\base\Component;
use yii\base\InvalidConfigException;
+use yii\db\Connection;
use yii\db\Exception;
use yii\db\Expression;
use yii\queue\Queue;
@@ -42,6 +43,23 @@
*/
class CatalogPricing extends Component
{
+ /**
+ * @var array<string, array{storeId: ?int, type: string, ids: ?int[]}> IDs queued inside the current
+ * DB transaction, written to the queue table once the outermost transaction commits.
+ */
+ private array $_deferred = [];
+
+ private int $_deferredPriority = 100;
+
+ public function init(): void
+ {
+ parent::init();
+
+ $db = Craft::$app->getDb();
+ $db->on(Connection::EVENT_COMMIT_TRANSACTION, fn() => $this->_flushDeferred());
+ $db->on(Connection::EVENT_ROLLBACK_TRANSACTION, fn() => $this->_deferred = []);
+ }
+
/**
* @var array|null
*/
@@ -516,15 +534,54 @@
// Queue purchasable-based and rule-based work into separate rows so they are never cross-contaminated.
// Catalog pricing rules determine which purchasables are relevant, so the two must be processed independently.
+ $queue = [];
if (!empty($purchasableIds) || ($purchasableIds === null && empty($catalogPricingRuleIds))) {
// Specific purchasable IDs: these will be regenerated against all applicable rules
- $this->_queueCatalogPricingIds($storeId, CatalogPricingQueueRecord::TYPE_PURCHASABLE, $purchasableIds);
+ $queue[] = [$storeId, CatalogPricingQueueRecord::TYPE_PURCHASABLE, $purchasableIds];
}
if (!empty($catalogPricingRuleIds)) {
- $this->_queueCatalogPricingIds($storeId, CatalogPricingQueueRecord::TYPE_RULE, $catalogPricingRuleIds);
+ $queue[] = [$storeId, CatalogPricingQueueRecord::TYPE_RULE, $catalogPricingRuleIds];
}
+ // Inside a transaction (an element save), collect the IDs and touch the shared queue row
+ // only after the outermost commit, so the row lock is never held for the whole save.
+ if (Craft::$app->getDb()->getTransaction() !== null) {
+ foreach ($queue as [$storeId, $type, $ids]) {
+ $key = $storeId . '|' . $type;
+ $pending = $this->_deferred[$key]['ids'] ?? [];
+ $this->_deferred[$key] = [
+ 'storeId' => $storeId,
+ 'type' => $type,
+ 'ids' => ($pending === null || $ids === null) ? null : array_merge($pending, $ids),
+ ];
+ }
+ $this->_deferredPriority = min($this->_deferredPriority, $priority);
+ return;
+ }
+
+ foreach ($queue as [$storeId, $type, $ids]) {
+ $this->_queueCatalogPricingIds($storeId, $type, $ids);
+ }
+
+ QueueHelper::push(Craft::createObject(CatalogPricingJob::class), $priority);
+ }
+
+ private function _flushDeferred(): void
+ {
+ if ($this->_deferred === []) {
+ return;
+ }
+
+ $deferred = $this->_deferred;
+ $priority = $this->_deferredPriority;
+ $this->_deferred = [];
+ $this->_deferredPriority = 100;
+
+ foreach ($deferred as $item) {
+ $this->_queueCatalogPricingIds($item['storeId'], $item['type'], $this->_normalizeIds($item['ids']));
+ }
+
QueueHelper::push(Craft::createObject(CatalogPricingJob::class), $priority);
}
- Ngôn ngữ chính
- PHP
- Star
- 242
- Fork
- 172
- Merge trung bình
- 21 giờ 23 phút
- Pull request đã merge (30 ngày)
- 76
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Không có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của craftcms/commerce
-
[5.x]: `getInventoryLevel()` reads every inventory transaction of the location to return one itemĐang mởbug commerce5 Craft Commerce repo:commerce
Độ khó 4/5 1-2 ngày Mức phù hợp với người mới 55/100
craftcms/commerce#4494 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[6.x]: Commerce can't boot without `craftcms/yii2-adapter`Có thể làm lại được @lukeholder đã nhận 30 ngày trước và không có pull request nào đang mở. Đang mởrepo:commerce
Độ khó 4/5 3-5 ngày Mức phù hợp với người mới 45/100
craftcms/commerce#4402 · 2 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
bug commerce5 Craft Commerce
Độ khó 5/5 Hơn một tuần Mức phù hợp với người mới 25/100
craftcms/commerce#4264 · 4 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
💡 enhancement commerce5 Craft Commerce
Độ khó 4/5 3-5 ngày Mức phù hợp với người mới 35/100
craftcms/commerce#4156 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[4.x]: Multiple empty carts when refreshing fast with autoSetNewCartAddresses settingCó thể làm lại được @lukeholder đã nhận 596 ngày trước và không có pull request nào đang mở. Đang mởbug commerce4 Craft Commerce
craftcms/commerce#3973 · 6 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của craftcms/commerce
Issue tương tự
-
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 86/100
Automattic/static-site-importer#3462 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Document lexicon.default.userconfig and lexicon.default.userconfig.enforced in config.sample.phpĐang mởenhancement feature: settings good first issue
Độ khó 1/5 1-3 giờ Mức phù hợp với người mới 88/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
nextcloud/integration_openai#480 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
Maintainer thường phản hồi trong vòng 1 ngày
-
a11y
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
omeka/plugin-Contribution#84 ·