Make WordPress Core

Opened 5 months ago

Last modified 11 days ago

#65485 new enhancement

Performance: Avoid redundant cache invalidation in wp_insert_* functions when processing meta_input

Reported by: spacedmonkey Owned by:
Priority: normal Milestone: Awaiting Review
Component: Cache API Version:
Severity: normal Keywords: good-first-bug has-patch has-unit-tests
Cc: Focuses: performance

Description

The Problem

Functions like wp_insert_post(), wp_insert_comment(), wp_insert_site(), and wp_insert_user() accept a meta_input parameter (or equivalent) to create or update multiple pieces of meta data at once via a foreach loop.

However, Core hooks the cache invalidation function wp_cache_set_posts_last_changed (and its equivalents for users, comments, and sites) directly to the meta action hooks:

<?php
add_action( 'added_post_meta', 'wp_cache_set_posts_last_changed' );
add_action( 'updated_post_meta', 'wp_cache_set_posts_last_changed' );
add_action( 'deleted_post_meta', 'wp_cache_set_posts_last_changed' );

Because these are fired on every individual meta update, passing an array of 5 meta keys results in the cache being invalidated 5 consecutive times during a single insertion process. This is highly redundant and wasteful. Furthermore, wp_insert_post() already calls clean_post_cache() at the end of its execution, which inherently handles the necessary cache clearing.

The Proposed Solution

To optimize database and object cache performance, we should temporarily unhook the _last_changed cache invalidation callbacks before iterating through the meta_input loop, and re-hook them immediately after the loop finishes.

For example, in wp_insert_post():

<?php
// Temporarily unhook to prevent redundant cache invalidation per meta key
$has_action = remove_action( 'updated_post_meta', 'wp_cache_set_posts_last_changed' );

foreach ( $meta_input as $meta_key => $meta_value ) {
    update_post_meta( $post_id, $meta_key, $meta_value );
}

// Re-hook after the loop completes
if ( $has_action ) {
    add_action( 'updated_post_meta', 'wp_cache_set_posts_last_changed' );
}

Scope of Impact

This optimization pattern should be applied across all major wp_insert_* functions that handle bulk meta input loops:

  • wp_insert_post()
  • wp_insert_comment()
  • wp_insert_user()
  • wp_insert_site()

By preventing these redundant internal cache sets, we can noticeably reduce object cache overhead during bulk creation/import processes.

Change History (4)

This ticket was mentioned in ​PR #12244 on ​WordPress/wordpress-develop by ​@micahele.


5 months ago
#1

  • Keywords has-patch has-unit-tests added

## Summary

Fixes #65485.

When inserting posts, comments, or users with multiple meta entries via meta_input or comment_meta, the wp_cache_set_*_last_changed() callback (hooked to added_*_meta/updated_*_meta) fired once per meta key, causing N redundant cache writes for N meta entries.

For example, inserting a post with 5 meta_input entries triggered 5 redundant last_changed cache writes during the meta loop — even though wp_insert_post() already calls clean_post_cache() at the end, which invalidates the cache once.

## The fix

Temporarily suspends the per-key _last_changed callback during the bulk meta loop and restores it afterward. The parent functions (clean_post_cache(), etc.) already invalidate the cache once at the end of the insertion, so no explicit re-trigger is needed.

### Affected functions

  • wp_insert_post() — meta_input loop
  • wp_insert_comment() and wp_update_comment() — comment_meta loops
  • wp_insert_user() — meta loops (both add and update branches)

## Testing

### Reproduction (before fix)

POST: posts last_changed writes = 5 (for 5 meta_input entries)
COMMENT: comment last_changed writes = 5 (for 5 comment_meta entries)
USER: users last_changed writes = 18 (for 5 meta_input entries + role meta)

### After fix

POST: posts last_changed writes = 3 (clean_post_cache + 2 single _pingme/_encloseme adds after loop)
COMMENT: comment last_changed writes = 1
USER: users last_changed writes = 6 (role-setting + contact-method meta outside loop)

The redundant per-key invalidations during the bulk loops are eliminated. Remaining writes are from legitimate single meta operations outside the loop.

### Test suite

  • New test: Tests_Cache_RedundantMetaInvalidation (5 tests) — passes with fix, fails without it
  • Existing tests pass with 0 regressions:
    • Post/Meta: 527 tests
    • Comment: 547 tests
    • User: 1341 tests
    • Cache: 92 tests
  • PHP lint and WordPress coding standards: clean

## How to test

npm run test:php -- --filter Tests_Cache_RedundantMetaInvalidation

This ticket was mentioned in ​PR #14553 on ​WordPress/wordpress-develop by ​@ShaneRounce.


3 weeks ago
#2

I have added regression coverage for queries made from post and comment metadata callbacks. The tests also check comment-query freshness after insertion and preservation of an intentionally removed invalidation callback.

These complement MicahelE's optimisation in ​https://github.com/WordPress/wordpress-develop/pull/12244. All four checks pass on current Core. With that patch applied, three return stale query results. The optimisation itself is not included in this contribution.

Validation: the affected comment and post-insertion suites pass with 162 tests and 444 assertions. PHP syntax, WordPress coding standards and diff checks pass. The comparison uses the default object cache on single-site Core, not Redis or multisite.

Commit: ​https://github.com/AceMedia/wordpress-develop/commit/ff8b44a8528cf8cff918e82b1faeba084bc822be

AI assistance: Codex helped me investigate the issue, prepare the tests and run the checks. I have reviewed the code myself. The recorded test runs were executed by Codex.

#3 @lancewillett
11 days ago

In 65114:

Tests: Guard query freshness during metadata insertion.

Verify that post and comment metadata observers see newly added metadata, and that comment queries remain fresh after insertion. Preserve an intentionally removed comment-cache invalidation callback.

Developed in: ​https://github.com/WordPress/wordpress-develop/pull/14553

Props shanerounce, huzaifaalmesbah.
See #65485.

Note: See TracTickets for help on using tickets.