Skip to content

Fix: Infinite loop caused by calling $order->save_meta_data() during woocommerce_update_order hook #59652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 23, 2025

Conversation

prettyboymp
Copy link
Contributor

@prettyboymp prettyboymp commented Jul 14, 2025

Changes proposed in this Pull Request:

This modifies Abstract_WC_ORder_Data_Store_CPT->clear_caches() to also remove in-memory OrderCache entry for the given order.

There is common pattern in extensions to do the following:

add_action( 'woocommerce_update_order', function($order_id, $order) {
	$order = wc_get_order( $order_id );
	$order->update_meta_data( 'some_meta_key', 'some_meta_value' );
	$order->save_meta_data();
}, 10, 2 );

When this is run on an order for the first time, the meta data entry is added and saved, but ends up in an infinite loop, because of the following scenario:

  1. $order = wc_get_order( $order_id ); retrieves the previously instantiated Order instance from in-memory OrderCache,
  2. $order->save_meta_data(); Saves the changes back to the DB, but then again runs the woocommerce_update_order hook before the OrderCache entry is moved.
  3. Step 1 repeats again because the in-memory copy doesn't yet see the meta entry.

Closes WOOPLUG-4910 / #59455 .

(For Bug Fixes) Bug introduced in PR #46023 .

How to test the changes in this Pull Request:

Using the WooCommerce Testing Instructions Guide, include your detailed testing instructions:

To test that it fixes the issue with the infinite loop:

Requires object caching

  1. Enable HPOS and Enable order data caching in the datastore under WooCommerce -> Settings -> Advanced -> Features.
  2. Create an order through any means or identify an existing order.
  3. Add the following code snippet somewhere it will execute:
add_action( 'woocommerce_update_order', function($order_id, $order) {
	$order = wc_get_order( $order_id );
	$order->update_meta_data( 'some_meta_key', 'some_meta_value' );
	$order->save_meta_data();
}, 10, 2 );
  1. Go to edit the order through the admin and save it. - Note, this only works once as the original issue only occurred the first time new meta was added during the woocommerce_update_order hook. So you will need to either change the meta key you're testing with or use a new order each time.

If the problem persists, doing the above will trigger an infinite loop. Otherwise, it should save normally.

General testing -
Do some general testing around orders.

  • Make sure you can place, create, edit, and delete orders and there are no noticeable issues where incorrect information is showing.

Testing that has already taken place:

Changelog entry

  • Automatically create a changelog entry from the details below.
  • This Pull Request does not require a changelog entry. (Comment required below)
Changelog Entry Details

Significance

  • Patch
  • Minor
  • Major

Type

  • Fix - Fixes an existing bug
  • Add - Adds functionality
  • Update - Update existing functionality
  • Dev - Development related task
  • Tweak - A minor adjustment to the codebase
  • Performance - Address performance issues
  • Enhancement - Improvement to existing functionality

Message

Changelog Entry Comment

Comment

@github-actions github-actions bot added the plugin: woocommerce Issues related to the WooCommerce Core plugin. label Jul 14, 2025
@prettyboymp prettyboymp marked this pull request as ready for review July 15, 2025 12:11
@woocommercebot woocommercebot requested review from a team and kalessil and removed request for a team July 15, 2025 12:11
Copy link
Contributor

github-actions bot commented Jul 15, 2025

Testing Guidelines

Hi @kalessil ,

Apart from reviewing the code changes, please make sure to review the testing instructions (Guide) and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed.

Reminder: PR reviewers are required to document testing performed. This includes:

  • 🖼️ Screenshots or screen recordings.
  • 📝 List of functionality tested / steps followed.
  • 🌐 Site details (environment attributes such as hosting type, plugins, theme, store size, store age, and relevant settings).
  • 🔍 Any analysis performed, such as assessing potential impacts on environment attributes and other plugins, conducting performance profiling, or using LLM/AI-based analysis.

⚠️ Within the testing details you provide, please ensure that no sensitive information (such as API keys, passwords, user data, etc.) is included in this public issue.

Copy link
Contributor

coderabbitai bot commented Jul 15, 2025

📝 Walkthrough

Walkthrough

The changes relocate the logic for clearing the order cache from the order object's save() method to the data store's clear_caches() method and add cache clearing after refund updates. Additionally, the cache is cleared after saving order metadata and explicitly cleared in a test after direct database updates to refunds, ensuring consistency between cached and stored order data.

Changes

File(s) Change Summary
plugins/woocommerce/includes/abstracts/abstract-wc-order.php Removed order cache invalidation logic from the save() method of the order object.
plugins/woocommerce/includes/data-stores/abstract-wc-order-data-store-cpt.php Added order cache invalidation logic to the clear_caches() method in the order data store class.
plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableRefundDataStore.php Added call to apply changes on refund after update; no direct cache removal here but related to refund update.
plugins/woocommerce/changelog/WOOPLUG-4910-clear-order-cache-after-meta-save Added patch to clear order cache after saving order metadata.
plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php Added explicit cache removal call for refund order ID after direct DB update in a test method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WC_Order
    participant DataStore
    participant OrderCache

    User->>WC_Order: save_meta_data()
    WC_Order->>DataStore: clear_caches(order_id)
    DataStore->>OrderCache: remove(order_id)
    Note right of OrderCache: Order cache entry is cleared
Loading
sequenceDiagram
    participant RefundUpdater
    participant RefundDataStore
    participant OrderCache

    RefundUpdater->>RefundDataStore: update(refund)
    RefundDataStore->>RefundDataStore: persist_updates(refund)
    RefundDataStore->>refund: apply_changes()
    Note right of RefundDataStore: Changes applied after update
Loading

Estimated code review effort

2 (~20 minutes)


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0ef5c0c and c6790c5.

📒 Files selected for processing (3)
  • plugins/woocommerce/includes/data-stores/abstract-wc-order-data-store-cpt.php (2 hunks)
  • plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableRefundDataStore.php (1 hunks)
  • plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • plugins/woocommerce/includes/data-stores/abstract-wc-order-data-store-cpt.php
  • plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableRefundDataStore.php
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{php,js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/code-quality.mdc)

**/*.{php,js,jsx,ts,tsx}: Guard against unexpected inputs
Sanitize and validate any potentially dangerous inputs
Ensure code is backwards compatible
Write code that is readable and intuitive
Ensure code has unit or E2E tests where applicable

Files:

  • plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
**/*.{php,js,ts,jsx,tsx}

⚙️ CodeRabbit Configuration File

**/*.{php,js,ts,jsx,tsx}: Don't trust that extension developers will follow the best practices, make sure the code:

  • Guards against unexpected inputs.
  • Sanitizes and validates any potentially dangerous inputs.
  • Is backwards compatible.
  • Is readable and intuitive.
  • Has unit or E2E tests where applicable.

Files:

  • plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
🧠 Learnings (2)
📓 Common learnings
Learnt from: jorgeatorres
PR: woocommerce/woocommerce#59675
File: .github/workflows/release-bump-as-requirement.yml:48-65
Timestamp: 2025-07-15T15:39:21.856Z
Learning: In WooCommerce core repository, changelog entries for all PRs live in `plugins/woocommerce/changelog/` directory and are processed during releases, not at the repository root level.
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:83-101
Timestamp: 2025-06-17T07:07:53.443Z
Learning: In WooCommerce blocks, when porting existing code patterns that have known issues (like parseInt truncating decimal money values), maintain consistency with existing implementation rather than making isolated fixes. The preference is for systematic refactoring approaches (like broader Dinero adoption) over piecemeal changes.
Learnt from: CR
PR: woocommerce/woocommerce#0
File: .cursor/rules/generate-pr-description.mdc:0-0
Timestamp: 2025-07-21T05:22:46.417Z
Learning: Provide clear, step-by-step instructions for how to test the changes in the PR description.
Learnt from: gigitux
PR: woocommerce/woocommerce#58846
File: plugins/woocommerce/client/blocks/tests/e2e/tests/all-products/all-products.block_theme.spec.ts:41-52
Timestamp: 2025-06-16T09:20:22.981Z
Learning: In WooCommerce E2E tests, the database is reset to the initial state for each test, so there's no need to manually restore global template changes (like clearing the header template) as the test infrastructure handles cleanup automatically.
plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php (1)

Learnt from: gigitux
PR: #58846
File: plugins/woocommerce/client/blocks/tests/e2e/tests/all-products/all-products.block_theme.spec.ts:41-52
Timestamp: 2025-06-16T09:20:22.981Z
Learning: In WooCommerce E2E tests, the database is reset to the initial state for each test, so there's no need to manually restore global template changes (like clearing the header template) as the test infrastructure handles cleanup automatically.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (24)
  • GitHub Check: Blocks e2e tests 10/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 6/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Blocks e2e tests 3/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 7/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 8/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 5/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 2/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 4/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 1/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 9/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 2/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.2] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Core API tests - @woocommerce/plugin-woocommerce [api]
  • GitHub Check: Core e2e tests 1/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.2] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Lint - @woocommerce/plugin-woocommerce
  • GitHub Check: build
🔇 Additional comments (2)
plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php (2)

6-6: Good addition: Import for OrderCache class

The import of the OrderCache class is appropriate given the cache clearing logic added below. This aligns with the broader cache invalidation improvements mentioned in the PR objectives.


605-606: Proper cache invalidation after direct database updates

The explicit cache clearing using OrderCache::remove() is essential here since the code performs direct database updates to the orders table. This ensures that subsequent reads don't return stale cached data, which aligns perfectly with the PR's objective to fix infinite loop issues caused by stale cache data during order meta updates.

The pattern follows the established approach:

  1. Clear the data store's cached data via $this->sut->clear_cached_data()
  2. Clear the OrderCache via $order_cache->remove()

This dual clearing ensures both the data store cache and the OrderCache are invalidated, preventing the infinite loop scenario described in the PR.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

github-actions bot commented Jul 15, 2025

Test using WordPress Playground

The changes in this pull request can be previewed and tested using a WordPress Playground instance.
WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Test this pull request with WordPress Playground.

Note that this URL is valid for 30 days from when this comment was last updated. You can update it by closing/reopening the PR or pushing a new commit.

Copy link
Contributor

@kalessil kalessil left a comment

Choose a reason for hiding this comment

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

LGTM to me overall. @prettyboymp can you please take a look into my comments before I start manual testing?

Remove the call to clear_cache  in OrdersTableRefundDataStore, it was only the test that needed updated.
@prettyboymp prettyboymp requested a review from kalessil July 21, 2025 16:18
Copy link
Contributor

@kalessil kalessil left a comment

Choose a reason for hiding this comment

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

LGTM!

  • Testing scenario ✔️
  • Keeping the snippet in place: create an order and refund the order ✔️

@prettyboymp prettyboymp added this to the 10.1.0 milestone Jul 23, 2025
@prettyboymp prettyboymp merged commit 7376f35 into trunk Jul 23, 2025
69 of 71 checks passed
@prettyboymp prettyboymp deleted the WOOPLUG-4910/clear-order-cache-after-meta-save branch July 23, 2025 20:04
@github-actions github-actions bot modified the milestones: 10.1.0, 10.2.0 Jul 23, 2025
github-actions bot pushed a commit that referenced this pull request Jul 23, 2025
…`woocommerce_update_order` hook (#59652)

* Remove in-memory OrderCache entry when Abstract_WC_ORder_Data_Store_CPT->clear_caches() is called.

* Add changelog

* Clear caches after a refund update.

* Switch to using imports
Remove the call to clear_cache  in OrdersTableRefundDataStore, it was only the test that needed updated.
Copy link
Contributor

IMPORTANT: Merging this PR to the appropriate branches is critical to the release process and ensures that the bug does not cause regressions in the future releases.

Cherry picking was successful for release/10.1. Please merge the following PR: [Backport to release/10.1] Fix: Infinite loop caused by calling $order->save_meta_data() during woocommerce_update_order hook

prettyboymp added a commit that referenced this pull request Jul 23, 2025
…r->save_meta_data() during `woocommerce_update_order` hook (#59949)

Fix: Infinite loop caused by calling $order->save_meta_data() during `woocommerce_update_order` hook (#59652)

* Remove in-memory OrderCache entry when Abstract_WC_ORder_Data_Store_CPT->clear_caches() is called.

* Add changelog

* Clear caches after a refund update.

* Switch to using imports
Remove the call to clear_cache  in OrdersTableRefundDataStore, it was only the test that needed updated.

Co-authored-by: Michael Pretty <prettyboymp@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
plugin: woocommerce Issues related to the WooCommerce Core plugin.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants