Skip to content

Optimistic locking for order saves (#4398) - #4405

Draft
lukeholder wants to merge 1 commit into
5.8from
feature/5.8-order-optimistic-locking
Draft

lukeholder wants to merge 1 commit into
5.8from
feature/5.8-order-optimistic-locking

Conversation

@lukeholder

Copy link
Copy Markdown
Member

Follow-up to #4404 (which fixes the symptoms on 5.x). Relates to #4398.

Problem

Order::afterSave() writes the whole order from the in-memory instance. Nothing checks that the instance is still current, and the order-after-save mutex only serialises saves. If request A loads an order, request B saves it (e.g. completes it, or recalculates and replaces its adjustments), and A then saves its older copy, A silently overwrites B: isCompleted/orderStatusId/paidStatus revert, and A's stale adjustment IDs lead to B's adjustments being deleted. #4404 guards the specific known cases (completed -> incomplete, adjustment cleanup, getCart()), but any other stale writer (custom code, plugins, the CP) still has the general problem.

Approach

Classic optimistic locking with a version counter:

  • New commerce_orders.saveVersion (unsigned int, default 0) with migration, Install and record updates. Schema version bumped to 5.8.0.0.
  • OrderQuery selects it and Order::$saveVersion holds the version the instance was loaded with (null for new orders or instances populated without it).
  • In afterSave() (inside the order-after-save lock, inside the element save transaction) we run an atomic UPDATE commerce_orders SET saveVersion = n + 1 WHERE id = ? AND saveVersion = n. If no row matches, another request saved in between and a new StaleOrderException is thrown, rolling back the whole save. On success the instance's version is incremented, so repeated saves of the same instance (e.g. updateOrderPaidInformation() then markAsComplete()) keep working.

I used a counter rather than dateUpdated because that has one-second resolution, and the observed races happen within the same second.

Trade-offs / things to decide before merging

  • Behaviour change: a stale save now throws instead of silently winning. Callers that hold an order across a long operation and then save it can start failing. For webhooks this is mostly benign (the gateway retries and loads fresh data), but front-end getCart() saves and custom code could surface errors. We may want to catch StaleOrderException in Carts::getCart() and Payments and reload/retry once instead of failing.
  • Does not merge changes; it only rejects the stale write. A reload-and-retry helper would be a natural follow-up.
  • Direct Db::update writes to commerce_orders bypass the counter (intended; they are not full-instance saves).
  • Only checked in afterSave, so the failing request will have written its (rolled back) data first. No data is lost thanks to the transaction.
  • No tests yet. This needs a test that loads two instances of one order, saves one, then expects the second to throw, plus coverage of the same-instance double save.
  • Needs a changelog entry once the version is settled.

Testing

phpstan and ecs pass. Not exercised under real concurrency.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Optimistic locking can still allow stale overwrites after unversioned saves or rollbacks, while conflicts following successful captures or refunds leave order payment information unapplied.

5 open issues
What changed in this PR

Adds version-based optimistic locking to order saves, extending the targeted protections in #4404 to address stale order overwrites reported in #4398.

Changes:

  • Adds a saveVersion counter to the order schema and loads it with order queries.
  • Checks and increments the counter during saves, throwing StaleOrderException on conflicts.
  • Updates installation and migration support and bumps the schema version to 5.8.0.0.
File Description
src/​records/​Order.php Documents the order record’s version field.
src/​Plugin.php Bumps the schema version.
src/​migrations/​m261102_000000_add_save_version_to_orders.php Adds the counter to existing installations.
src/​migrations/​Install.php Includes the counter in new installations.
src/​errors/​StaleOrderException.php Defines the stale-save exception.
src/​elements/​Order.php Tracks the loaded version and checks for save conflicts.
src/​elements/​db/​OrderQuery.php Selects the version when loading orders.

Review effort: Balanced

Comment thread src/elements/Order.php
Comment on lines +3872 to +3875
if ($isNew || $this->saveVersion === null) {
$this->saveVersion = $isNew ? 0 : $this->saveVersion;
return;
}
Comment thread src/elements/Order.php
);

if ($affected === 0) {
throw new StaleOrderException("Order $this->number was modified by another request since it was loaded.");
Comment thread src/elements/Order.php
throw new StaleOrderException("Order $this->number was modified by another request since it was loaded.");
}

$this->saveVersion++;
Comment thread src/elements/Order.php

$orderRecord->save(false);

$this->_incrementSaveVersion($isNew);
Comment thread src/elements/Order.php
Comment on lines +3877 to +3881
$affected = Db::update(
Table::ORDERS,
['saveVersion' => $this->saveVersion + 1],
['id' => $this->id, 'saveVersion' => $this->saveVersion],
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants