[5.x]: Catalog pricing queue lock is held until the product save commits, so parallel saves run one at a time

オープン
#4,389 コメント 3 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

@nfourtythree がすでに取り組んでいます。

2026年11月2日 から。

  • #4418 @nfourtythree による — オープン

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
48/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
mysql, php

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

repo:commerce
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 ids column 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 single php craft commerce/pricing-catalog/generate run 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 CatalogPricing jobs in Queue::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']];
  1. Save repro-import.php (below) in the project root.
  2. Start several workers at once: for i in $(seq 1 8); do php repro-import.php $i 8 150 & done; wait
  3. 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
  1. 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_TRANSACTION fires only then, and Craft's MutexTrait already relies on it. The @TODO in Product::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 from commit() after the data is already committed, so it may be better to catch and log it there.
  2. 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 call generateCatalogPrices($ids) once at the end. The EVENT_BEFORE_PUSH recipe from #3709, #3978, #4003 and #4123 no longer covers the queue-row write.
  3. 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 a storeId = NULL row (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);
     }
主要言語
PHP
スター
242
フォーク
172
平均マージ
21時間 23分
マージ済み PR(30日)
76

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

craftcms/commerce のほかの issue

craftcms/commerce の issue をすべて見る

似ている issue

PHP の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。