Commit a705c1f7021 for woocommerce
commit a705c1f70218875791ebd6ae5f18bde8c00db22e
Author: Vlad Olaru <vlad.olaru@automattic.com>
Date: Wed Nov 25 14:38:24 2026 +0200
[ai] Correct inaccurate claims in the performance agent skill (#70582)
* docs(performance): Correct inaccurate claims in the performance skill
The performance skill carries a number of statements that are wrong
against current WooCommerce and WordPress code and that lead an agent
to wrong code or wrong review verdicts. Correct them in place, keeping
the existing patterns, headings, examples and conventions.
Cache priming: _prime_post_caches() does not load HPOS orders, so
wc_get_order() loops need WC_Order_Factory::get_orders(); the
get_items() exemption has two gaps (the lazy path primes the variation
but not its parent, and filter-added items are never primed); an
ID-only WP_Query primes nothing, so priming its IDs is correct; the
helper dates from WP 3.4 and its query count includes terms.
Option priming: the transient guard must also exclude wp_installing(),
matching get_transient(); site transients need the network-option
helper on multisite, which dates from WP 6.6; a missing option costs
one query until notoptions caches it, not one per call; feature-flag
keys are not in the "all autoloaded" group the same file tells agents
to skip; drop two stale line-number references.
SQL: state up front that a rewrite must return the same rows; a known
customer ID does not replace the billing-email branch (guest orders);
the lookup tables carry no post_type or post_status; the MIN/MAX
example now includes the IS NOT NULL guards its own rule requires on a
nullable column; global_unique_id is indexed.
* docs(performance): Correct MIN/MAX index and get_orders() guidance
A review of the corrected performance skill found statements that
still do not match WooCommerce, WordPress and database behavior.
Pattern H said the MIN/MAX rewrite works when WHERE and the column
share a composite index with equality or bounded-range leading keys,
and that type_status_date(type, status, date_created_gmt) serves the
orders example. With status != 'trash' that index is sorted by status
before date, so it cannot return rows in date order. Measured on MySQL
8.4 and MariaDB with 60,000 synthetic orders: each LIMIT 1 branch uses
the single-column date_created index and reads one row, the same
branch forced onto the composite index sorts 51,600 entries, and
trashing the newest 6,000 orders makes it read 6,001. With equality on
every leading column, plain MIN()/MAX() is already answered from the
index ends. The conditions, the example explanation, the table scope
note and the checklist now say this. The post_modified_gmt example
says to query each post type separately, because one ORDER BY ...
LIMIT 1 over an IN list read and sorted all 42,000 matching entries.
Cache priming: WC_Order_Factory::get_orders() reads HPOS orders in
bulk but, on post-based storage, primes the caches and then reads each
order. It is not a drop-in replacement for a wc_get_order() loop: it
drops input keys, returns a duplicate ID once, and does not return
false for a missing ID. A query with update_post_meta_cache,
update_post_term_cache or cache_results set to false returns WP_Post
objects, so the text now shows the wp_list_pluck() step before the
prime.
Option priming: the "already served from cache" claim is limited to
settings saved with autoload on. Several email, account, shipping and
advanced settings set 'autoload' => false.
Pattern G: the lookup query in DownloadsWrapper also counts variations
and unpublished products and can disagree with the fallback used
during regeneration. The text states that difference and why this
caller tolerates it, in place of calling it acceptable.
* docs(performance): Rule out prefix indexes for the MIN/MAX rewrite
Pattern H requires an index that returns rows sorted by the column,
but said nothing about indexes that store only a prefix of it. Such
an index does not sort the full value, so it cannot answer MIN()/MAX()
from its ends or serve an ORDER BY ... LIMIT 1 seek.
Core has one: meta_key_value (meta_key(50), meta_value(20)) on the
HPOS order meta table. Measured on MySQL 8.4 and MariaDB with 60,000
rows, MIN/MAX(meta_value) with an equality on meta_key read every row
for the key, and the LIMIT 1 form needed a filesort.
Condition 1 now excludes prefix indexes, and the sentence on keeping
plain MIN()/MAX() says "equality with a constant", matching the
reviewer persona.
* docs(performance): Exclude OR and GROUP BY from the MIN/MAX rewrite
Pattern H lists the predicates that stop a composite index from
returning rows sorted by the target column, but not OR. An OR of two
constant equalities on an earlier column spans two key values, like
an IN list: on the HPOS orders schema with 60,000 rows it read 35,100
index entries on MySQL 8.4 and MariaDB.
The pattern also did not say that it replaces an aggregate over the
whole result only. With GROUP BY, two LIMIT 1 seeks return one row,
not one per group.
Condition 1 now names OR, and a short note excludes grouped queries,
matching the reviewer persona.
* docs(ai): Simplify cache priming guidance
Link Store API readers directly to the order batching pattern so its
return semantics stay documented in one place. Keep the transient
examples focused on the persistent cache check WooCommerce uses when
priming options.
diff --git a/.ai/skills/woocommerce-performance/cache-priming.md b/.ai/skills/woocommerce-performance/cache-priming.md
index 0b59d3597b5..2fce60c40f4 100644
--- a/.ai/skills/woocommerce-performance/cache-priming.md
+++ b/.ai/skills/woocommerce-performance/cache-priming.md
@@ -6,7 +6,9 @@ Covers correct usage of `_prime_post_caches()` to reduce SQL query counts when l
### 1. Missing cache priming before iterating post-based objects
-**Apply when:** any `array_map` or loop fetches multiple objects by ID using `get_post()`, `wc_get_product()`, `wc_get_order()`, or any function that resolves to a `get_post()` call per item (e.g. a `format_*` helper that calls `get_post()` internally).
+**Apply when:** any `array_map` or loop fetches multiple objects by ID using `get_post()`, `wc_get_product()`, or any function that resolves to a `get_post()` call per item (e.g. a `format_*` helper that calls `get_post()` internally).
+
+**Orders are different.** `_prime_post_caches()` does not load orders stored in the HPOS tables. Load them with `WC_Order_Factory::get_orders( $order_ids )` instead of a `wc_get_order()` loop: it reads HPOS orders in bulk, and on post-based order storage it primes the post and meta caches before reading each order. It is not a drop-in replacement: it returns a list in input order (input keys are dropped), returns a duplicate ID once, and does not return `false` for a missing ID (it throws on post-based order storage and leaves a non-order entry in the list under HPOS; `$skip_invalid` fixes neither). Keep the behavior the caller relies on.
**Correct pattern:**
@@ -20,7 +22,7 @@ if ( ! empty( $ids ) ) {
The comment `// Prime caches to reduce future queries.` must always sit **inside** the `if` block, directly above the call. Do not place it before the `if`. Place the prime immediately before the loop or `array_map` that consumes the IDs. Exception: if a `do_action` call between the guard and the loop passes the IDs as arguments (e.g. `do_action( 'wc_before_products_starting_sales', $product_ids )`), move the prime before that action so hooked callbacks loading the same objects also benefit from the warmed cache. If the action does not receive the IDs, keep the prime directly above the loop.
-`_prime_post_caches()` is a WordPress internal (underscore-prefixed) that has existed since WP 4.1. The minimum supported WordPress version for WooCommerce guarantees its presence — `is_callable( '_prime_post_caches' )` guards are unnecessary and must be removed when encountered. Always wrap in `! empty()` as a readability convention; WordPress short-circuits internally before firing SQL on an empty array, so this is not a correctness requirement. The function issues a single `SELECT wp_posts.* WHERE ID IN (...)` for all non-cached IDs and a single `SELECT` for postmeta — two queries regardless of collection size, not one per ID.
+`_prime_post_caches()` is a WordPress internal (underscore-prefixed) that has existed since WP 3.4. The minimum supported WordPress version for WooCommerce guarantees its presence — `is_callable( '_prime_post_caches' )` guards are unnecessary and must be removed when encountered. Always wrap in `! empty()` as a readability convention; WordPress short-circuits internally before firing SQL on an empty array, so this is not a correctness requirement. The function issues a single `SELECT wp_posts.* WHERE ID IN (...)` for all non-cached IDs, plus batched queries for their postmeta and terms — a fixed number of queries regardless of collection size, not one per ID. Keep the default flags when priming products: `wc_get_product()` reads the `product_type` and `product_visibility` terms as well as post meta, so passing `false` for `$update_term_cache` leaves a per-product term query.
---
@@ -54,7 +56,7 @@ The normalization chain is the same regardless of which API you use to collect I
**Form A — IDs only (no loaded objects):**
-Use when you have raw variation IDs and no `WC_Product_Variation` objects yet. Read attachment meta directly from the now-warm postmeta cache. `_product_image_gallery` is stored as a comma-separated string (`"12,34,56"`) — use `explode( ',', ... )`, not `maybe_unserialize`.
+Use when you have raw variation IDs and no `WC_Product_Variation` objects yet, and the render path reads the same raw meta. A variation without its own image falls back to its parent's image in `get_image_id()`; raw `_thumbnail_id` meta does not include that fallback, so use Form B when the render path uses the product getters. Read attachment meta directly from the now-warm postmeta cache. `_product_image_gallery` is stored as a comma-separated string (`"12,34,56"`) — use `explode( ',', ... )`, not `maybe_unserialize`.
```php
if ( ! empty( $variation_ids ) ) {
@@ -111,7 +113,7 @@ if ( ! empty( $variations ) ) {
wc_get_container()->get( \Automattic\WooCommerce\Internal\Utilities\ProductUtil::class )->prime_image_caches( $variations );
```
-`WC_Product_Variation` extends `WC_Product` so variation collections are accepted directly. Use Form B inline code only when `ProductUtil` is not available in the call context (e.g. a legacy `includes/` file that cannot reach the DI container).
+`WC_Product_Variation` extends `WC_Product` so variation collections are accepted directly. Use Form B inline code only when the helper's scope does not fit, for example when only featured images are rendered.
**Scope priming to attachment IDs your code actually accesses.** Prime attachment posts only when the render path calls `get_post()`, `wp_attachment_is_image()`, `wp_get_attachment_image_src()`, or `get_the_title()` on each ID. Returning IDs as raw integers in a response array (e.g. a REST API `gallery_image_ids` field that passes IDs through without hydrating them) requires no attachment priming — the attachment `wp_posts` rows are never read.
@@ -184,7 +186,9 @@ Use `_prime_post_caches()` only when no such native argument exists on the data
2. **Lazy-load path** — `WC_Abstract_Order::get_items()` primes product post caches on first item load per order (`abstract-wc-order.php`, inside the `if ( ! isset( $this->items[ $group ] ) )` branch for `line_item` type).
-By the time an explicit `_prime_post_caches()` runs after collecting IDs from a `get_items()` loop, all product post caches are already warm on both CPT and HPOS backends.
+By the time an explicit `_prime_post_caches()` runs after collecting IDs from a `get_items()` loop, the product post caches for those items are already warm on both CPT and HPOS backends.
+
+**Two gaps to check before deleting a prime:** the lazy-load path primes the variation when an item has one, not its parent product, so code that then loads the parent of each variation still needs a batch; and items added through the `woocommerce_order_get_items` filter were never seen by either mechanism.
**Example**:
@@ -205,7 +209,7 @@ if ( ! empty( $product_ids ) ) {
}
```
-**Recognition pattern:** any block that (a) loops over orders, (b) calls `get_items()` or `get_items( 'line_item' )` inside that loop, and (c) collects `get_product_id()` / `get_variation_id()` values to feed into a subsequent `_prime_post_caches()` call. The entire collect-and-prime block is dead code and can be deleted.
+**Recognition pattern:** any block that (a) loops over orders, (b) calls `get_items()` or `get_items( 'line_item' )` inside that loop, and (c) collects `get_product_id()` / `get_variation_id()` values to feed into a subsequent `_prime_post_caches()` call. Unless one of the two gaps above applies, the entire collect-and-prime block is dead code and can be deleted.
---
@@ -215,7 +219,7 @@ if ( ! empty( $product_ids ) ) {
**Why it is wrong:** `WP_Query` automatically primes the post, meta, and term caches for every post it loads (controlled by `update_post_meta_cache` and `update_post_term_cache`, both `true` by default). Calling `_prime_post_caches()` afterward is redundant.
-Additionally, `WP_Query::query()` returns an array of `WP_Post` objects (when no `fields` argument is set), not integer IDs. `_prime_post_caches()` internally calls `intval()` on each item — `intval( WP_Post )` returns `1`, not the post ID. The function silently misbehaves.
+Additionally, `WP_Query::query()` returns an array of `WP_Post` objects (when no `fields` argument is set), not integer IDs. `_prime_post_caches()` expects integer IDs — passed `WP_Post` objects, it primes nothing.
**Do not add priming here:**
@@ -226,7 +230,7 @@ _prime_post_caches( $result );
$products = array_map( 'wc_get_product', $result );
```
-Priming is only needed when starting from a raw list of IDs not loaded through `WP_Query` — see pattern 1.
+Priming is only needed when starting from a raw list of IDs — see pattern 1. That includes IDs returned by a `'fields' => 'ids'` query, which primes no caches. A query that set `update_post_meta_cache`, `update_post_term_cache` or `cache_results` to `false` returns `WP_Post` objects but leaves that cache cold: when the code that follows reads it, prime the IDs with `_prime_post_caches( wp_list_pluck( $posts, 'ID' ) )`.
---
@@ -235,5 +239,5 @@ Priming is only needed when starting from a raw list of IDs not loaded through `
Pass `false` for the `$update_meta_cache` parameter when meta is being handled separately, to avoid double-priming:
```php
-_prime_post_caches( $order_ids, true, false ); // skip meta priming, include terms
+_prime_post_caches( $post_ids, true, false ); // skip meta priming, include terms
```
diff --git a/.ai/skills/woocommerce-performance/options-cache-priming.md b/.ai/skills/woocommerce-performance/options-cache-priming.md
index 1a3737eaa32..299c21cd864 100644
--- a/.ai/skills/woocommerce-performance/options-cache-priming.md
+++ b/.ai/skills/woocommerce-performance/options-cache-priming.md
@@ -106,7 +106,7 @@ Place the call at the end of the method that populates the registry, before any
**Anti-pattern:** Passing `_transient_*`, `_transient_timeout_*`, `_site_transient_*`, or `_site_transient_timeout_*` option names to `wp_prime_option_caches()`.
-**Why it is wrong:** When a persistent object cache is active, WordPress stores transients in the object cache under the `transient` group — not as rows in `wp_options`. `wp_prime_option_caches()` reads from the options table. On a persistent-cache site the named rows never exist, so each prime call records every transient name as a `notoptions` entry. Those entries persist indefinitely: the corresponding `wp_options` rows are never created for transients stored exclusively in the object cache, so the normal invalidation path (`add_option` / `update_option`) never fires. The `notoptions` cache grows by two entries per transient name per call (`_transient_<name>` + `_transient_timeout_<name>`). On backends where `notoptions` resolves to a single cache key read on every request (observed with sharded Redis), this growth increases per-request retrieval cost over time.
+**Why it is wrong:** When a persistent object cache is active, WordPress stores transients in the object cache under the `transient` group — not as rows in `wp_options`. `wp_prime_option_caches()` reads from the options table. On a persistent-cache site the named rows never exist, so a prime call records every transient name it has not seen before as a `notoptions` entry. Those entries persist indefinitely: the corresponding `wp_options` rows are never created for transients stored exclusively in the object cache, so the normal invalidation path (`add_option` / `update_option`) never fires. The `notoptions` cache grows by two entries per new transient name (`_transient_<name>` + `_transient_timeout_<name>`). On backends where `notoptions` resolves to a single cache key read on every request (observed with sharded Redis), this growth increases per-request retrieval cost over time.
**Correct pattern:**
@@ -121,8 +121,6 @@ if ( ! wp_using_ext_object_cache() ) {
}
```
-`wp_using_ext_object_cache()` is the same guard WordPress itself uses inside `get_transient()` and `set_transient()` to switch between the options table and the object cache. Sites without a persistent cache keep the existing batching behaviour. Sites with one already retrieve transients from the object cache directly — skipping the prime loses nothing.
-
**Mixed key list:** If the array passed to `wp_prime_option_caches()` mixes regular option names with transient names, split the call: prime the regular option names unconditionally; prime the transient names only under `! wp_using_ext_object_cache()`. Wrapping the entire call in the guard would silently drop the regular option priming on persistent-cache sites.
```php
@@ -132,7 +130,7 @@ if ( ! wp_using_ext_object_cache() ) {
}
```
-**Audit rule:** Any call to `wp_prime_option_caches()` whose key list contains names beginning with `_transient_`, `_transient_timeout_`, `_site_transient_`, or `_site_transient_timeout_` must be guarded with `! wp_using_ext_object_cache()`.
+**Audit rule:** Any call to `wp_prime_option_caches()` whose key list contains names beginning with `_transient_`, `_transient_timeout_`, `_site_transient_`, or `_site_transient_timeout_` must be guarded with `! wp_using_ext_object_cache()`. On multisite, site transients (`_site_transient_*`) are stored as network options: prime them with `wp_prime_network_option_caches()` under the same guard, not with `wp_prime_option_caches()`.
---
@@ -144,12 +142,12 @@ Always use the comment `// Prime caches to reduce future queries.` directly abov
The benefit of `wp_prime_option_caches` operates along two complementary dimensions — not binary logic:
-- **Existence**: options not yet written to the database are absent from `wp_load_alloptions()` even when flagged autoloaded. Each `get_option()` call for a missing key issues an individual SQL query. Priming batches those misses into one query upfront.
+- **Existence**: options not yet written to the database are absent from `wp_load_alloptions()` even when flagged autoloaded. The first `get_option()` call for each missing key issues an individual SQL query (later calls hit the `notoptions` cache). Priming batches those misses into one query upfront.
- **Autoload state**: non-autoloaded options are never loaded at bootstrap regardless of whether they exist. Priming is the primary mechanism to avoid per-request queries for them.
An autoloaded option that has already been saved gains nothing from priming (already in cache). The same option before it is first saved benefits from the existence check. Both dimensions apply independently — consider both when deciding whether to prime.
-For multisite contexts, use `wp_prime_network_option_caches( $network_id, $keys )` (available since WP 6.4) for network-scoped options.
+For multisite contexts, use `wp_prime_network_option_caches( $network_id, $keys )` (available since WP 6.6) for network-scoped options.
---
@@ -158,20 +156,18 @@ For multisite contexts, use `wp_prime_network_option_caches( $network_id, $keys
**WooCommerce settings API autoloads by default.** Any option registered and saved through `WC_Admin_Settings::save_fields()` is stored with `autoload = 'yes'` unless the field definition explicitly sets `'autoload' => false`. The relevant code is in `includes/admin/class-wc-admin-settings.php`:
```php
-// Line ~1035
$autoload_options[ $option_name ] = isset( $option['autoload'] ) ? (bool) $option['autoload'] : true;
-// Line ~1047
update_option( $name, $value, $autoload_options[ $name ] ? 'yes' : 'no' );
```
-WordPress loads all autoloaded options into the object cache at bootstrap via `wp_load_alloptions()`. This means that **any `get_option()` call reading a WooCommerce settings-API-registered option is already served from cache** — adding `wp_prime_option_caches` there is a no-op.
+WordPress loads all autoloaded options into the object cache at bootstrap via `wp_load_alloptions()`. This means that **any `get_option()` call reading a WooCommerce settings-API option that has been saved with autoload on is already served from cache** — adding `wp_prime_option_caches` there is a no-op. Options whose field sets `'autoload' => false` (several email, account, shipping and advanced settings do) are not loaded at bootstrap and can still benefit from priming.
### False-positive patterns — do NOT add priming
High `get_option()` concentration alone is **not** a signal. These are common false positives:
- **Endpoint options** — `woocommerce_checkout_pay_endpoint`, `woocommerce_myaccount_*_endpoint`, etc. All autoloaded via settings API.
-- **Feature flags and toggles** — `woocommerce_enable_ajax_add_to_cart`, `woocommerce_enable_checkout_login_reminder`, `woocommerce_tax_display_cart`, etc. All autoloaded.
+- **Settings toggles** — `woocommerce_enable_ajax_add_to_cart`, `woocommerce_enable_checkout_login_reminder`, `woocommerce_tax_display_cart`, etc. All autoloaded. (The `woocommerce_feature_{id}_enabled` keys are not in this group: they may not exist yet and are covered by pattern 4.)
- **General store settings** — currency, weight unit, address fields, etc. All autoloaded.
### The `*_settings` per-entity pattern
diff --git a/.ai/skills/woocommerce-performance/sql-query-patterns.md b/.ai/skills/woocommerce-performance/sql-query-patterns.md
index 1ffe36d9a23..de12aa53c19 100644
--- a/.ai/skills/woocommerce-performance/sql-query-patterns.md
+++ b/.ai/skills/woocommerce-performance/sql-query-patterns.md
@@ -2,6 +2,8 @@
**When to use:** Writing or reviewing any SQL query in WooCommerce PHP code — joins, aggregates, meta lookups, or range queries. Apply proactively when generating new code, or flag violations when reviewing.
+**Before rewriting a query, pin down what it must return.** A faster query that returns different rows is a bug, not an optimization: keep the same eligible rows (post type, status, visibility), the same handling of duplicates and NULLs, and the same result for empty input. HPOS and posts order storage use different tables and indexes, so check both paths.
+
---
## Cross-cutting: safe `IN (...)` list construction
@@ -35,7 +37,7 @@ $sql = $wpdb->prepare( "WHERE stock_status IN ($placeholders)", ...$values );
**Only join `wp_posts` when you need a column from it.**
-When a query receives `$product_ids` from an upstream `WP_Query` that explicitly enforced both `post_type='product'` **and** `post_status='publish'`, the `wp_posts` join adds no new filtering. A `WP_Query` result qualifies; a raw ID list from user input or a query that only enforced one of the two constraints does not.
+When a query receives `$product_ids` from an upstream `WP_Query` that explicitly enforced both `post_type='product'` **and** `post_status='publish'`, the `wp_posts` join adds no new filtering. A `WP_Query` result used as returned qualifies; a raw ID list from user input, a query that only enforced one of the two constraints, or a list that filters or other code can add IDs to does not.
| You need from `wp_posts` | Join required? |
|----------------------------------------------------------------------------|----------------------------------------------|
@@ -157,7 +159,7 @@ foreach ( $rows as $row ) {
## Pattern E — OR across heterogeneous indexed columns (flag this)
-An `OR` condition that spans two different indexed columns forces an `index_merge sort_union` — the optimizer scans each index separately and merges the result sets. This is often worse than a single index range scan.
+An `OR` condition that spans two different indexed columns is typically resolved with an `index_merge sort_union` — the optimizer scans each index separately and merges the result sets. This is often worse than a single index range scan.
```sql
-- index_merge sort_union on billing_email + customer_id_status indexes:
@@ -167,15 +169,15 @@ WHERE status IN ('wc-processing', 'wc-completed')
**Fix — check the selective branch first, avoid the OR in the best case:**
-When one branch is strictly more selective (e.g. `customer_id` is a resolved integer vs. `billing_email` fallback), evaluate that branch first at the PHP level and only construct the OR fallback when the best-case branch cannot be used:
+When one branch is strictly more selective (e.g. `customer_id` is a resolved integer vs. `billing_email` fallback), evaluate that branch first at the PHP level and only construct the OR fallback when the best-case branch cannot be used. Only drop a branch that cannot change the result: in `wc_customer_bought_product()` a known `customer_id` does not replace the `billing_email` branch, because guest orders placed with the same email carry no customer ID.
```sql
--- Best case: customer_id known → single range on customer_id_status (covering index,
--- no row data fetched, ~6ms)
+-- Best case: customer_id is the only identity to match → single range on
+-- customer_id_status (covering index, no row data fetched, ~6ms)
WHERE status IN ('wc-processing', 'wc-completed')
AND customer_id = 1
--- Parity (customer_id unavailable): same index_merge as before, but now the more
+-- Parity (both identities needed): same index_merge as before, but now the more
-- selective index (customer_id_status) is listed first, which improves merge order
WHERE status IN ('wc-processing', 'wc-completed')
AND ( customer_id = 1 OR billing_email IN ('user@example.com') )
@@ -210,7 +212,7 @@ WHERE ( meta_key = '_customer_user' AND meta_value = '1' )
**Bonus — decouple multi-fan joins via subquery:**
-When the postmeta result set drives a join into a second fan-out table (e.g. `order_items → order_itemmeta`), a flat JOIN multiplies the fans: `postmeta_rows × itemmeta_rows`. Restructure the postmeta side as a subquery to force semijoin materialization (`Start/End temporary`) and prevent fan multiplication:
+When the postmeta result set drives a join into a second fan-out table (e.g. `order_items → order_itemmeta`), a flat JOIN multiplies the fans: `postmeta_rows × itemmeta_rows`. Restructure the postmeta side as a subquery so the optimizer can evaluate it as a semijoin (`Start/End temporary`) and prevent fan multiplication:
```sql
-- Flat join: postmeta fan × itemmeta fan multiply
@@ -243,17 +245,17 @@ WHERE items.order_id IN (
## Pattern G — Prefer WooCommerce lookup tables over posts+postmeta join
-WooCommerce maintains two dedicated lookup tables with pre-aggregated product data and narrow, indexed rows. When the required data exists there, drop the `wp_posts + wp_postmeta` join entirely.
+WooCommerce maintains two dedicated lookup tables with pre-aggregated product data and narrow, indexed rows. When the required data exists there, drop the `wp_posts + wp_postmeta` join entirely. The lookup tables have no `post_type` or `post_status` columns: when the result must be limited to published products, keep that filter (a `wp_posts` join, or IDs that were already filtered).
### `wc_product_meta_lookup` — product scalars
-Stores one row per product. Available columns and indexes:
+Stores one row per product and per variation. Available columns and indexes:
```sql
-- Columns (all indexed unless noted):
product_id BIGINT PK
sku VARCHAR(100) INDEX sku(50)
-global_unique_id VARCHAR(100) (no index)
+global_unique_id VARCHAR(100) INDEX global_unique_id(50)
virtual TINYINT(1) INDEX virtual
downloadable TINYINT(1) INDEX downloadable
min_price DECIMAL(19,4) INDEX min_max_price(min_price, max_price)
@@ -285,6 +287,8 @@ LIMIT 1
SELECT product_id FROM wp_wc_product_meta_lookup WHERE downloadable = 1 LIMIT 1
```
+The "after" query no longer checks `post_type` or `post_status`, so it also counts variations and products that are not published, and it can disagree with the "before" query that still runs while the lookup table regenerates. `DownloadsWrapper` tolerates that because the value only sets a CSS class in the editor preview; a query that must return published products has to keep the filter.
+
**Canonical example:** `DownloadsWrapper` in `src/Blocks/BlockTypes/OrderConfirmation/DownloadsWrapper.php`; `FilterData::get_stock_status_counts` in `src/Internal/ProductFilters/FilterData.php`.
### `wc_product_attributes_lookup` — product-term relationships
@@ -319,15 +323,17 @@ if ( 'yes' === get_option( 'woocommerce_attribute_lookup_enabled' ) ) {
## Pattern H — `MIN/MAX` full scan → `UNION ALL + LIMIT 1`
-`SELECT MIN(col), MAX(col) FROM table WHERE ...` requires a full index scan of all matching rows. When the column is covered by a sorted composite index, the min and max can each be found in a single seek by reading one row from each end.
+`SELECT MIN(col), MAX(col) FROM table WHERE ...` reads every matching row when the optimizer cannot jump to the ends of an index. When an index returns the rows sorted by the column, the min and max can each be found by reading from one end of it.
**When it applies:** All three conditions must hold:
-1. The WHERE predicates on the leading index columns are equality constraints (`col = const`) or bounded ranges that the optimizer can resolve as a contiguous index segment.
-2. The ORDER BY column is the trailing key of that same index.
+1. An index returns the rows already sorted by the ORDER BY column: either an index that starts with that column, or a composite index where every column before it has an equality predicate (`col = const`). A range, `IN (...)`, `OR` or `!=` on an earlier column does not qualify, because the index is then sorted by that column first. An index that stores only a prefix of a column, such as `meta_key_value (meta_key(50), meta_value(20))` on the HPOS order meta table, does not qualify either: it does not sort the full value.
+2. Few rows at each end of that index fail the remaining WHERE predicates. Each failing row is read and skipped before the first qualifying one.
3. `LIMIT 1` stops the scan after the first qualifying row.
-The `type_status_date(type, status, date_created_gmt)` index satisfies all three conditions: `type = 'shop_order'` is an equality (const), `status != 'trash'` is a bounded range the optimizer walks within the index, and `date_created_gmt` is the trailing key read directionally. `LIMIT 1` stops after the first row in each direction.
+When every WHERE predicate is an equality with a constant on the leading columns of a composite index that has the column next, keep the plain `MIN()` / `MAX()`: MySQL and MariaDB already answer it from the index ends (`EXPLAIN` shows `Select tables optimized away`).
+
+The example below does not use `type_status_date(type, status, date_created_gmt)`: `status != 'trash'` is not an equality, so that index is sorted by status before date. The optimizer walks the single-column `date_created(date_created_gmt)` index from each end and checks `type` and `status` on each row. That reads one row per branch when the oldest and newest rows are orders that are not trashed, and one more for every refund or trashed order it has to skip first — confirm with `EXPLAIN`.
```sql
-- Full scan: 51,831 rows examined, ~66ms avg
@@ -339,20 +345,22 @@ WHERE type = 'shop_order' AND status != 'trash'
SELECT MIN(date_created_gmt), MAX(date_created_gmt)
FROM (
( SELECT date_created_gmt FROM wp_wc_orders
- WHERE type = 'shop_order' AND status != 'trash'
+ WHERE type = 'shop_order' AND status != 'trash' AND date_created_gmt IS NOT NULL
ORDER BY date_created_gmt DESC LIMIT 1 )
UNION ALL
( SELECT date_created_gmt FROM wp_wc_orders
- WHERE type = 'shop_order' AND status != 'trash'
+ WHERE type = 'shop_order' AND status != 'trash' AND date_created_gmt IS NOT NULL
ORDER BY date_created_gmt ASC LIMIT 1 )
) d
```
-**NULL handling:** `MIN()` / `MAX()` ignore NULLs; `ORDER BY col ASC LIMIT 1` returns NULL first (MySQL sorts NULLs before values in ASC). On a nullable column the two approaches produce different results. Pattern H is only safe when the column is `NOT NULL`, or when both UNION branches add `AND col IS NOT NULL`.
+**NULL handling:** `MIN()` / `MAX()` ignore NULLs; `ORDER BY col ASC LIMIT 1` returns NULL first (MySQL sorts NULLs before values in ASC). On a nullable column the two approaches produce different results. Pattern H is only safe when the column is `NOT NULL`, or when both UNION branches add `AND col IS NOT NULL` (as above: `date_created_gmt` is nullable).
+
+**Grouped queries:** Pattern H does not apply to a query with `GROUP BY`: the two seeks return one row, not one per group.
-**If the required index does not exist:** Adding it is a prerequisite, not a reason to skip the pattern. Evaluate whether the index maintenance cost is justified (it usually is for high-read, low-write tables like `wp_wc_orders`). For example, `SELECT MAX(post_modified_gmt) FROM wp_posts WHERE post_type IN ('product', 'product_variation')` is a Pattern H candidate, but `post_modified_gmt` has no standard WordPress index — the optimization requires first adding `(post_type, post_modified_gmt)`.
+**If the required index does not exist:** Adding it is a prerequisite, not a reason to skip the pattern. Evaluate whether the index's write, storage, and migration cost is justified before adding it. For example, `SELECT MAX(post_modified_gmt) FROM wp_posts WHERE post_type IN ('product', 'product_variation')` is a Pattern H candidate, but `post_modified_gmt` has no standard WordPress index — the optimization requires first adding `(post_type, post_modified_gmt)`. The `IN (...)` list is not an equality, so one `ORDER BY post_modified_gmt DESC LIMIT 1` over both types still reads and sorts every matching row: query each post type separately (`WHERE post_type = 'product'`, then `'product_variation'`) and take the larger result.
-**Table scope:** The pattern applies to any table with a suitable composite index — not only `wp_wc_orders`. When HPOS is disabled, orders reside in `wp_posts` with index `type_status_date(post_type, post_status, post_date)` — a different trailing key than `wp_wc_orders`. Always verify the target table's actual index covers the WHERE + ORDER BY columns before applying the rewrite.
+**Table scope:** The pattern applies to any table with a suitable index — not only `wp_wc_orders`. When HPOS is disabled, orders reside in `wp_posts` with index `type_status_date(post_type, post_status, post_date, ID)` and no index that starts with `post_date`, so the `status != 'trash'` example above has no cheap seek there. Always check the target table's actual indexes against condition 1 before applying the rewrite.
**Canonical example:** `ListTable` in `src/Internal/Admin/Orders/ListTable.php`.
@@ -366,10 +374,10 @@ When writing or reviewing a SQL query:
- [ ] Is `wp_term_relationships` joined without constraining `term_taxonomy_id`? Fan-out risk. (Pattern C)
- [ ] Are there N queries in a loop with a different parameter each time? Collapse with `GROUP BY`. (Pattern D)
- [ ] Is the narrowest table driving the query? Prefer `wp_term_taxonomy` / `wp_terms` (small) over `wp_posts` / `wp_term_relationships` (large). (Pattern A)
-- [ ] Does a `WHERE` clause use `OR` across two different indexed columns? Check the more selective branch first at the PHP level. (Pattern E)
+- [ ] Does a `WHERE` clause use `OR` across two different indexed columns? Check the more selective branch first at the PHP level, without dropping a branch the result needs. (Pattern E)
- [ ] Does a `WHERE` clause combine `meta_key IN (...) AND meta_value IN (...)`? Split into per-key conditions. (Pattern F)
- [ ] Are two fan-out tables joined flat (multiplying rows)? Decouple one side as a subquery. (Pattern F)
-- [ ] Does a `wp_posts + wp_postmeta` join fetch data available in `wc_product_meta_lookup`? Use the lookup table if the regeneration guard passes. (Pattern G)
+- [ ] Does a `wp_posts + wp_postmeta` join fetch data available in `wc_product_meta_lookup`? Use the lookup table if the regeneration guard passes, keeping any `post_status` filter the result needs. (Pattern G)
- [ ] Does any dynamic `IN (...)` list guard against empty input and sanitize values? (Cross-cutting)
-- [ ] Does the query compute `MIN(col)` or `MAX(col)` over a large indexed table? Use `UNION ALL + LIMIT 1` if WHERE + ORDER BY share a composite index and the column is `NOT NULL` (or both branches add `AND col IS NOT NULL`). (Pattern H)
+- [ ] Does the query compute `MIN(col)` or `MAX(col)` over a large indexed table? Use `UNION ALL + LIMIT 1` if an index returns the rows sorted by that column, few rows at its ends fail the WHERE, and the column is `NOT NULL` (or both branches add `AND col IS NOT NULL`). Keep plain `MIN` / `MAX` when every predicate is an equality on the index's leading columns. (Pattern H)
- [ ] After applying any optimization, verify the execution plan changed as expected with `EXPLAIN` — check `type`, `key`, `rows`, and `Extra` columns before and after.
diff --git a/.ai/skills/woocommerce-store-api/performance.md b/.ai/skills/woocommerce-store-api/performance.md
index ac70f282827..de02c9dbe91 100644
--- a/.ai/skills/woocommerce-store-api/performance.md
+++ b/.ai/skills/woocommerce-store-api/performance.md
@@ -4,10 +4,10 @@ This file is a thin wrapper over the `woocommerce-performance` skill, framed for
## When this matters
-Any schema that serialises a **collection** of post-based objects (products, orders, attachments) is a candidate for cache priming. Store API list responses are the most common case:
+Any schema that serialises a **collection** of products or attachments is a candidate for post cache priming (for orders, see [pattern 1 in the performance skill](../woocommerce-performance/cache-priming.md#1-missing-cache-priming-before-iterating-post-based-objects)). Store API list responses are the most common case:
- `GET /cart` returns N cart line items, each loaded via `wc_get_product()`.
-- Any future route returning a collection of products, orders, or attachment-backed resources — each item loaded individually inside the per-item loop.
+- Any future route returning a collection of products or attachment-backed resources — each item loaded individually inside the per-item loop.
Without priming, each per-item lookup hits the database individually — classic N+1.