Repository navigation
Optimistic locking for order saves (#4398) - #4405
Draft
lukeholder wants to merge 1 commit into
Draft
lukeholder wants to merge 1 commit into
lukeholder wants to merge 1 commit into
Conversation
Contributor
There was a problem hiding this comment.
🟡 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
Increment the version for orders saved without a version · New Retry order updates after payment conflicts without resaving transactions · New Restore the instance version when a save transaction rolls back · New Add tests for stale writes, repeated saves, and rollback retries · New Preserve dateUpdated during the version-only update · New
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
saveVersioncounter to the order schema and loads it with order queries. - Checks and increments the counter during saves, throwing
StaleOrderExceptionon 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 on lines
+3872
to
+3875
| if ($isNew || $this->saveVersion === null) { | ||
| $this->saveVersion = $isNew ? 0 : $this->saveVersion; | ||
| return; | ||
| } |
| ); | ||
|
|
||
| if ($affected === 0) { | ||
| throw new StaleOrderException("Order $this->number was modified by another request since it was loaded."); |
| throw new StaleOrderException("Order $this->number was modified by another request since it was loaded."); | ||
| } | ||
|
|
||
| $this->saveVersion++; |
|
|
||
| $orderRecord->save(false); | ||
|
|
||
| $this->_incrementSaveVersion($isNew); |
Comment on lines
+3877
to
+3881
| $affected = Db::update( | ||
| Table::ORDERS, | ||
| ['saveVersion' => $this->saveVersion + 1], | ||
| ['id' => $this->id, 'saveVersion' => $this->saveVersion], | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


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 theorder-after-savemutex 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/paidStatusrevert, 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:
commerce_orders.saveVersion(unsigned int, default 0) with migration,Installand record updates. Schema version bumped to 5.8.0.0.OrderQueryselects it andOrder::$saveVersionholds the version the instance was loaded with (nullfor new orders or instances populated without it).afterSave()(inside theorder-after-savelock, inside the element save transaction) we run an atomicUPDATE commerce_orders SET saveVersion = n + 1 WHERE id = ? AND saveVersion = n. If no row matches, another request saved in between and a newStaleOrderExceptionis thrown, rolling back the whole save. On success the instance's version is incremented, so repeated saves of the same instance (e.g.updateOrderPaidInformation()thenmarkAsComplete()) keep working.I used a counter rather than
dateUpdatedbecause that has one-second resolution, and the observed races happen within the same second.Trade-offs / things to decide before merging
getCart()saves and custom code could surface errors. We may want to catchStaleOrderExceptioninCarts::getCart()andPaymentsand reload/retry once instead of failing.Db::updatewrites tocommerce_ordersbypass the counter (intended; they are not full-instance saves).afterSave, so the failing request will have written its (rolled back) data first. No data is lost thanks to the transaction.Testing
phpstan and ecs pass. Not exercised under real concurrency.
🤖 Generated with Claude Code