Commit 65b03fba509 for woocommerce
commit 65b03fba50901683c9e8682db6b907fa7b862234
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date: Tue Nov 24 21:22:18 2026 +0100
Agent readiness: keep rows saved during an abandoned scan, recheck UCP after enabling, exact Connect hosts (#71360)
* Agent readiness: keep rows saved during an abandoned scan, recheck UCP after enabling, exact Connect hosts
- An abandoned scan (gave up, cancelled or replaced) now keeps the rows a
product save wrote while it ran, as a finished scan already does, and
only clears products that have rows.
- Turning UCP on checks the required conditions again after writing the
discovery file, so a failed write answers needs attention, not active,
and AI shopping doesn't say AI assistants can now shop the store.
- The Connect to WordPress.com redirect is allowed only to wordpress.com
and jetpack.wordpress.com, and never with a backslash or whitespace.
Fixes WOOAIRR-884, WOOAIRR-797, WOO6-721.
* Keep failure rows a save writes while scan cleanup runs.
The write time is checked in the delete, so a save that commits after the old freshness snapshot is not removed.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Record a failure-row write before changing the rows.
Cleanup that runs during a save then keeps those rows, and the direct delete still flushes the product meta cache.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Agent readiness: test the needs attention switch with unsaved fields, and the reload URL
* Agent readiness: clear the meta caches after the cleanup delete without firing deleted_post_meta, and test a save during cleanup and past one chunk
The direct delete no longer fires deleted_post_meta by hand with no meta
ids. It clears what that hook's WooCommerce listener would, each
product's WooCommerce meta cache, as well as WordPress's meta cache.
New tests cover cleanup running while a save writes its rows, cleanup of
more products than one delete takes, and reading the rows through the
product after cleanup.
* Agent readiness: clean the post cache after the cleanup delete, so cached queries and products drop the rows
Clearing only the meta caches left two caches the meta hooks would have
cleared: cached post queries such as the Products list filter, and the
cached product with product instance caching on. clean_post_cache() clears
both, for chunks that deleted rows.
* Agent readiness: after the cleanup delete, clear what the deleted_post_meta listeners would, also while cache invalidation is suspended
clean_post_cache() returns early while invalidation is suspended, while the
meta API's listeners still run. The cleanup now clears the meta cache and
bumps posts last changed once per chunk, and clears each product's
WooCommerce meta cache and cached product, without loading the posts.
---------
diff --git a/plugins/woocommerce/changelog/fix-agent-readiness-airr-findings b/plugins/woocommerce/changelog/fix-agent-readiness-airr-findings
new file mode 100644
index 00000000000..e48d05df1d8
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-agent-readiness-airr-findings
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Fix AI shopping health scan cleanup, UCP switch status and Connect redirect check; unreleased feature.
+
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/ai-shopping.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/ai-shopping.tsx
index 4505f119063..ce02dfaa258 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/ai-shopping.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/ai-shopping.tsx
@@ -214,7 +214,10 @@ export default function AiShopping( { view }: { view: ShoppingView } ) {
setValues( ( current ) => ( { ...current, enabled: enable } ) );
setBusy( true );
try {
- const response = await apiFetch< { enabled: boolean } >( {
+ const response = await apiFetch< {
+ enabled: boolean;
+ status?: string;
+ } >( {
path: ucp.path,
method: 'POST',
data: { enabled: enable },
@@ -223,17 +226,26 @@ export default function AiShopping( { view }: { view: ShoppingView } ) {
...current,
enabled: response.enabled,
} ) );
- const done = response.enabled ? ucp.turned_on : ucp.turned_off;
+ // On, but a required check failed (such as the UCP address not loading): no
+ // "can now shop" message; the page shows Needs attention and the step to fix.
+ let done = response.enabled ? ucp.turned_on : ucp.turned_off;
+ if ( response.status === 'needs_attention' ) {
+ done = '';
+ }
// The checklist and the other cards depend on the switch, so the page reloads,
// unless that would lose unsaved fields.
if ( dirtyRef.current ) {
- showSnackbar( done );
+ if ( done ) {
+ showSnackbar( done );
+ }
say( ucp.unsaved );
setBusy( false );
return;
}
try {
- window.sessionStorage.setItem( SNACKBAR_KEY, done );
+ if ( done ) {
+ window.sessionStorage.setItem( SNACKBAR_KEY, done );
+ }
} catch {}
// Not reload(): after Save, that would post the settings form again.
window.location.assign(
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/test/ai-shopping.test.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/test/ai-shopping.test.tsx
index 5cd2a396c12..54adad543a3 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/test/ai-shopping.test.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/test/ai-shopping.test.tsx
@@ -452,6 +452,54 @@ describe( 'AiShopping', () => {
expect( mockCreateSuccessNotice ).not.toHaveBeenCalled();
} );
+ it( 'does not say AI assistants can shop the store when it turns on but needs attention', async () => {
+ mockedFetch.mockResolvedValue( {
+ enabled: true,
+ status: 'needs_attention',
+ } );
+ renderPage( view( { ucp: { ...view().ucp, blocked: false } } ) );
+
+ fireEvent.click( toggle() );
+ await waitFor( () => expect( mockedFetch ).toHaveBeenCalled() );
+ await screen.findByRole( 'checkbox', { name: /Allow AI assistants/ } );
+
+ expect( window.location.assign ).toHaveBeenCalledWith(
+ 'https://example.com/wp-admin/admin.php?page=wc-settings'
+ );
+ expect(
+ window.sessionStorage.getItem( 'wc-ai-shopping-snackbar' )
+ ).toBeNull();
+ expect( mockCreateSuccessNotice ).not.toHaveBeenCalled();
+ } );
+
+ it( 'with unsaved fields, does not say AI assistants can shop the store when it turns on but needs attention, and says to save', async () => {
+ mockedFetch.mockResolvedValue( {
+ enabled: true,
+ status: 'needs_attention',
+ } );
+ renderPage( view( { ucp: { ...view().ucp, blocked: false } } ) );
+ fireEvent.change(
+ screen.getByRole( 'combobox', {
+ name: 'Refund and returns policy',
+ } ),
+ { target: { value: '12' } }
+ );
+
+ fireEvent.click( toggle() );
+ await waitFor( () => expect( mockedFetch ).toHaveBeenCalled() );
+ await screen.findByRole( 'checkbox', { name: /Allow AI assistants/ } );
+
+ expect( window.location.assign ).not.toHaveBeenCalled();
+ expect( toggle() ).toBeChecked();
+ expect( mockCreateSuccessNotice ).not.toHaveBeenCalled();
+ expect(
+ window.sessionStorage.getItem( 'wc-ai-shopping-snackbar' )
+ ).toBeNull();
+ expect(
+ screen.getByText( 'Save your changes to see the updated status.' )
+ ).toBeInTheDocument();
+ } );
+
it( 'shows the switch’s snackbar on the page that loads after it saves, once', () => {
window.sessionStorage.setItem(
'wc-ai-shopping-snackbar',
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
index 54bf15e27a1..66bbc12e474 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
@@ -686,6 +686,7 @@ class AgentReadiness {
/**
* End a scan without storing a report. Removes failure rows it wrote for products the
* previous report never covered, so the Products list stays aligned with that report.
+ * Rows a save wrote while the scan ran stay, as when a scan finishes.
* A scan whose report is already stored only finishes that cleanup.
*
* @param array{id?:string,ids?:array<int,int>,had_rows?:array<int,int>,tested?:array<int,int>,rows_as_of?:float} $state Scan progress.
@@ -700,9 +701,11 @@ class AgentReadiness {
}
$had_rows = array_map( 'intval', (array) ( $state['had_rows'] ?? array() ) );
$ids = array_map( 'intval', (array) ( $state['ids'] ?? array() ) );
- foreach ( array_diff( $ids, $had_rows ) as $product_id ) {
- ProductFailures::forget( $product_id );
- }
+ // Only products that have rows now: a scan can list thousands that never got any.
+ ProductFailures::forget_unless_written_since(
+ array_values( array_intersect( array_diff( $ids, $had_rows ), ProductFailures::stored_product_ids() ) ),
+ isset( $state['rows_as_of'] ) ? (float) $state['rows_as_of'] : null
+ );
delete_option( self::SCAN_OPTION );
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php
index 03d59ac8222..a20bd6aff8b 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php
@@ -130,7 +130,7 @@ class AgenticCommerceSettings implements RegisterHooksInterface {
wp_die( esc_html__( 'Sorry, you are not allowed to connect this store.', 'woocommerce' ), 403 );
}
check_admin_referer( self::CONNECT_ACTION );
- // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- wordpress_com_https_url() allows only https on wordpress.com.
+ // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- wordpress_com_https_url() allows only https on wordpress.com and jetpack.wordpress.com.
wp_redirect( self::connect_redirect() );
exit;
}
@@ -163,7 +163,8 @@ class AgenticCommerceSettings implements RegisterHooksInterface {
}
/**
- * An https WordPress.com URL with a lowercased scheme, or an empty string.
+ * An https URL on wordpress.com or jetpack.wordpress.com, the hosts Jetpack sends users to for the
+ * connection, with a lowercased scheme, or an empty string.
*
* @since 11.4.0
*
@@ -171,6 +172,10 @@ class AgenticCommerceSettings implements RegisterHooksInterface {
* @return string
*/
public static function wordpress_com_https_url( string $url ): string {
+ // Browsers read a backslash as a slash, so a host PHP parses as on wordpress.com could lead elsewhere.
+ if ( 1 === preg_match( '/[\\\\\s]/', $url ) ) {
+ return '';
+ }
$parts = wp_parse_url( $url );
if ( ! is_array( $parts ) || isset( $parts['user'] ) || isset( $parts['pass'] ) ) {
return '';
@@ -178,9 +183,7 @@ class AgenticCommerceSettings implements RegisterHooksInterface {
$raw_scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : '';
$scheme = strtolower( $raw_scheme );
$host = strtolower( (string) ( $parts['host'] ?? '' ) );
- $suffix = '.wordpress.com';
- $on_wp = 'wordpress.com' === $host || ( strlen( $host ) > strlen( $suffix ) && substr( $host, -strlen( $suffix ) ) === $suffix );
- if ( 'https' !== $scheme || ! $on_wp ) {
+ if ( 'https' !== $scheme || ! in_array( $host, array( 'wordpress.com', 'jetpack.wordpress.com' ), true ) ) {
return '';
}
return 'https' . substr( $url, strlen( $raw_scheme ) );
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php
index 475ee8bd8f3..873e44f041b 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php
@@ -3,6 +3,8 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\AgentReadiness;
+use Automattic\WooCommerce\Internal\Caches\ProductCache;
+
defined( 'ABSPATH' ) || exit;
/**
@@ -22,6 +24,11 @@ class ProductFailures {
*/
public const WRITTEN_META = '_wc_agent_readiness_written_at';
+ /**
+ * Products per cleanup delete statement.
+ */
+ public const CLEANUP_CHUNK = 100;
+
/**
* The value every checked product has, passing or not.
*/
@@ -49,9 +56,7 @@ class ProductFailures {
*
* @param int $product_id Product id.
* @param array<string, array<string, array{field:string,effect:string}>> $failures Channel map of each failed check, by check id.
- * @param bool $mark_written Whether to record the write time. A save does, so a scan
- * in progress keeps its rows. The scan's own writes don't:
- * keep_only() reads the time only for products the scan did not test.
+ * @param bool $mark_written Whether to record the write time. A save does, so cleanup keeps its rows. The scan's own writes don't, so they can be removed.
*/
public static function store( int $product_id, array $failures, bool $mark_written = true ): void {
$values = array_merge( array( self::CHECKED ), array_map( 'strval', array_keys( $failures ) ) );
@@ -61,6 +66,10 @@ class ProductFailures {
}
}
unset( self::$counts[ get_current_blog_id() ] );
+ if ( $mark_written ) {
+ // Before the rows change. Cleanup that runs during this save then sees a current write and keeps the rows.
+ update_post_meta( $product_id, self::WRITTEN_META, sprintf( '%.6F', microtime( true ) ) );
+ }
$stored = self::stored( $product_id );
foreach ( array_diff( $stored, $values ) as $value ) {
delete_post_meta( $product_id, self::META_KEY, $value );
@@ -68,10 +77,6 @@ class ProductFailures {
foreach ( array_diff( $values, $stored ) as $value ) {
add_post_meta( $product_id, self::META_KEY, $value );
}
- if ( $mark_written ) {
- // Same values still count as a new write, so a save during a scan is not treated as the old rows.
- update_post_meta( $product_id, self::WRITTEN_META, sprintf( '%.6F', microtime( true ) ) );
- }
}
/**
@@ -130,26 +135,66 @@ class ProductFailures {
if ( array() === $drop ) {
return;
}
- $fresh = null === $written_after ? array() : array_fill_keys( self::ids_written_since( $written_after ), true );
- foreach ( $drop as $product_id ) {
- if ( isset( $fresh[ $product_id ] ) ) {
- continue;
- }
- self::forget( $product_id );
- }
+ self::forget_unless_written_since( $drop, $written_after );
}
/**
- * Products whose rows were written at or after a scan started.
+ * Remove the rows of these products, except rows whose write time is at or after $written_after.
*
- * @param float $after Unix time.
- * @return array<int, int>
+ * The write time is checked in the delete. A list of fresh ids read earlier would miss a save that commits before the loop reaches that product.
+ *
+ * @param array<int, int> $product_ids Product ids.
+ * @param float|null $written_after Unix time the scan started, or null to remove them all.
*/
- private static function ids_written_since( float $after ): array {
+ public static function forget_unless_written_since( array $product_ids, ?float $written_after ): void {
+ $product_ids = array_values( array_unique( array_filter( array_map( 'absint', $product_ids ) ) ) );
+ if ( array() === $product_ids ) {
+ return;
+ }
+ if ( null === $written_after ) {
+ foreach ( $product_ids as $product_id ) {
+ self::forget( $product_id );
+ }
+ return;
+ }
+ unset( self::$counts[ get_current_blog_id() ] );
global $wpdb;
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One read of write times, which are not cached with the check rows.
- $ids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND CAST(meta_value AS DECIMAL(16,6)) >= %f", self::WRITTEN_META, $after ) );
- return array_map( 'intval', (array) $ids );
+ // A scan can name thousands of products. Each statement stays small, and each one decides from the write time it sees.
+ foreach ( array_chunk( $product_ids, self::CLEANUP_CHUNK ) as $chunk ) {
+ $ids = implode( ',', $chunk );
+ // $ids are absint. The write time is in this delete, so a save that commits after a separate read is not removed.
+ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ $deleted = $wpdb->query(
+ $wpdb->prepare(
+ "DELETE pm FROM {$wpdb->postmeta} AS pm
+ LEFT JOIN {$wpdb->postmeta} AS fresh
+ ON fresh.post_id = pm.post_id
+ AND fresh.meta_key = %s
+ AND CAST(fresh.meta_value AS DECIMAL(16,6)) >= %f
+ WHERE pm.post_id IN ($ids)
+ AND pm.meta_key IN (%s, %s)
+ AND fresh.meta_id IS NULL",
+ self::WRITTEN_META,
+ $written_after,
+ self::META_KEY,
+ self::WRITTEN_META
+ )
+ );
+ // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ if ( ! $deleted ) {
+ continue;
+ }
+ // The delete bypasses the meta API, so clear what its deleted_post_meta listeners would, also while
+ // cache invalidation is suspended: the meta cache, cached post queries like the Products list filter,
+ // WooCommerce's product meta cache and the cached product (product instance caching).
+ wp_cache_delete_multiple( $chunk, 'post_meta' );
+ wp_cache_set_posts_last_changed();
+ $product_cache = wc_get_container()->get( ProductCache::class );
+ foreach ( $chunk as $product_id ) {
+ \WC_Cache_Helper::invalidate_cache_group( 'object_' . $product_id );
+ $product_cache->remove( $product_id );
+ }
+ }
}
/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index 1ef629882e2..ba5b8607df1 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -209,7 +209,7 @@ WooCommerce > Settings > AI tools (`AgenticCommerceSettings`, `AgenticCommerceSe
AI shopping has one card per part:
-- The UCP switch, first, with Learn how it works. It saves on its own through `POST wc/v3/agent-readiness/ucp` (`{ "enabled": true }`). A failing required check keeps it from being turned on, and that POST answers 409; turning it off still works. After it changes, a snackbar says "AI assistants can now shop your store." or "AI assistants can no longer shop your store." The page reloads after it changes and shows the snackbar, unless a policy field has unsaved changes; then the snackbar shows at once and it asks to save them. In coming soon mode the card has a warning notice that agents can't shop the store yet, with Change store visibility.
+- The UCP switch, first, with Learn how it works. It saves on its own through `POST wc/v3/agent-readiness/ucp` (`{ "enabled": true }`). A failing required check keeps it from being turned on, and that POST answers 409; turning it off still works. Turning it on writes the discovery file under Plain permalinks and checks again, so a failed write leaves it on with `needs_attention` and `ucp_discovery` failing. After it changes, a snackbar says "AI assistants can now shop your store." or "AI assistants can no longer shop your store.", except when it turns on with `needs_attention`: then the page shows Needs attention and the step to fix. The page reloads after it changes and shows the snackbar, unless a policy field has unsaved changes; then the snackbar shows at once and it asks to save them. In coming soon mode the card has a warning notice that agents can't shop the store yet, with Change store visibility.
- Product visibility: Visible, Hidden and Not supported, from the stored report (`products`, `hidden_from_catalog`, `unsupported_types`). Each links to the Products list filtered to those products (`ProductScan::count_query()`, the query the scan counts with). Hidden and Not supported have an info button that opens a popover saying what they mean.
- Setup checklist: a badge with how many steps are left, then the store conditions from `StoreConditions`, the same list the readiness report shows. Open conditions are one list, failing `required` ones first (coming soon mode, HTTPS and the UCP address), marked Required; failing `recommended` ones, such as a missing privacy, terms, refund and returns, or shipping policy page (policy pages are not required by the UCP spec), follow. The card says how many required steps are left to fix, or how many steps are left when none is required. Each step says why it matters and links to where to fix it; a chosen policy page that isn't published links to its editor, and a store page chosen as one asks for another page. Each open step's button says where it goes (View Site Health, Choose page, Edit page and so on). Passing conditions fold behind "Show N completed steps", with the same title and why line. Both lists, and the setup steps in Fix first, go by importance (`ReadinessCheckPage::SETUP_ORDER`): what blocks AI shopping (live, HTTPS, readable permalinks), then payments, the privacy, terms and refund pages, search engine indexing and order emails, then guest checkout and the shipping policy page.
- Store policy pages. Refund and returns, privacy and terms are the existing options, so they stay in sync with Advanced > Page setup and Settings > Privacy; shipping policy, FAQ and warranty are new. They are for the policy links a UCP checkout can carry (`links`); the UCP endpoints don't send them yet. The dropdowns list published pages other than the cart, checkout, shop and My account pages, and saving leaves a stored page in place even when it's a draft or one of those store pages, which then fails its check. A link from the checklist opens the page on its field, focused.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php b/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php
index 5a0d54d7f7d..8362ed70bc0 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php
@@ -83,6 +83,8 @@ class UcpSwitch {
// Plain and index.php permalinks are served from the static file. Write it now so the address exists as soon as UCP is on.
if ( $enable ) {
$this->ucp_discovery->maybe_sync_file();
+ // Checked again: the address is only known to load once the file is written, and a failed write is silent.
+ $failing = $this->store_conditions->failing_required();
}
\WC_Tracks::record_event( 'agentic_commerce_ucp_toggled', array( 'enabled' => $enable ? 'yes' : 'no' ) );
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
index 50ce3b1e6ff..311fafe810a 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
@@ -221,7 +221,7 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
}
/**
- * @testdox Only an https WordPress.com URL can be the connection redirect, and its scheme is lowercased.
+ * @testdox Only an https URL on wordpress.com or jetpack.wordpress.com can be the connection redirect, and its scheme is lowercased.
*
* @testWith ["https://jetpack.wordpress.com/jetpack.authorize/1/?x=1", "https://jetpack.wordpress.com/jetpack.authorize/1/?x=1"]
* ["HTTPS://jetpack.wordpress.com/path", "https://jetpack.wordpress.com/path"]
@@ -230,6 +230,9 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
* ["https://evil.example/phish", ""]
* ["https://wordpress.com.evil.example/", ""]
* ["https://user@jetpack.wordpress.com/path", ""]
+ * ["https://someone.wordpress.com/", ""]
+ * ["https://evil.example\\.jetpack.wordpress.com/", ""]
+ * ["https://jetpack.wordpress.com/a b", ""]
* ["", ""]
*
* @param string $url Candidate redirect.
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
index 3063195d50a..b8613e5418b 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
@@ -6,6 +6,8 @@ namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;
use Automattic\WooCommerce\Internal\AgentReadiness\AgentReadiness;
use Automattic\WooCommerce\Internal\AgentReadiness\ProductFailures;
use Automattic\WooCommerce\Internal\AgentReadiness\ProductScan;
+use Automattic\WooCommerce\Internal\Caches\ProductCache;
+use Automattic\WooCommerce\Internal\Caches\ProductCacheController;
use WC_Helper_Product;
use WC_Unit_Test_Case;
@@ -154,6 +156,162 @@ class ProductFailuresTest extends WC_Unit_Test_Case {
$this->assertContains( 'missing_images', ProductFailures::for_product( $during_id ) );
}
+ /**
+ * @testdox A write at or after the given time stays, and an older write is removed with its marker.
+ */
+ public function test_forget_unless_written_since_keeps_a_later_write(): void {
+ $before = microtime( true );
+ $stale = WC_Helper_Product::create_simple_product();
+ $fresh = WC_Helper_Product::create_simple_product();
+ ProductFailures::store( $stale->get_id(), array(), false );
+ update_post_meta( $stale->get_id(), ProductFailures::WRITTEN_META, sprintf( '%.6F', $before - 5 ) );
+ ProductFailures::store( $fresh->get_id(), array(), true );
+
+ // Read through the product, so its meta cache holds the rows.
+ $this->assertNotEmpty( wc_get_product( $stale->get_id() )->get_meta( ProductFailures::META_KEY, false ) );
+
+ ProductFailures::forget_unless_written_since( array( $stale->get_id(), $fresh->get_id() ), $before );
+
+ $this->assertSame( array(), ProductFailures::stored( $stale->get_id() ) );
+ $this->assertSame( array(), wc_get_product( $stale->get_id() )->get_meta( ProductFailures::META_KEY, false ), 'The product meta cache drops the removed rows' );
+ $this->assertSame( '', get_post_meta( $stale->get_id(), ProductFailures::WRITTEN_META, true ) );
+ $this->assertSame( array( ProductFailures::CHECKED ), ProductFailures::stored( $fresh->get_id() ) );
+ $this->assertNotSame( '', get_post_meta( $fresh->get_id(), ProductFailures::WRITTEN_META, true ) );
+ }
+
+ /**
+ * @testdox After cleanup, with cache invalidation $_dataName, the cached rows and a cached product query on them, like the Products list filter, no longer find the product.
+ * @dataProvider provide_cache_invalidation
+ *
+ * @param bool $suspended Whether cache invalidation is suspended during cleanup.
+ */
+ public function test_cleanup_drops_cached_rows_and_queries( bool $suspended ): void {
+ $before = microtime( true );
+ $id = WC_Helper_Product::create_simple_product()->get_id();
+ ProductFailures::store( $id, array( 'missing_images' => array() ), false );
+ update_post_meta( $id, ProductFailures::WRITTEN_META, sprintf( '%.6F', $before - 5 ) );
+ $this->assertNotEmpty( ProductFailures::stored( $id ), 'Fixture precondition: the meta cache holds the rows' );
+ $query = static fn(): array => get_posts(
+ array(
+ 'post_type' => 'product',
+ 'fields' => 'ids',
+ 'meta_key' => ProductFailures::META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
+ 'meta_value' => 'missing_images', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
+ )
+ );
+ $this->assertSame( array( $id ), $query(), 'Fixture precondition: the query result is cached' );
+
+ $was_suspended = wp_suspend_cache_invalidation( $suspended );
+ try {
+ ProductFailures::forget_unless_written_since( array( $id ), $before );
+ } finally {
+ wp_suspend_cache_invalidation( $was_suspended );
+ }
+
+ $this->assertSame( array(), ProductFailures::stored( $id ) );
+ $this->assertSame( array(), $query(), 'The cached query runs again' );
+ }
+
+ /**
+ * Cache invalidation on and suspended. Imports suspend it; the meta API clears these caches either way.
+ *
+ * @return array<string, array{0:bool}>
+ */
+ public function provide_cache_invalidation(): array {
+ return array(
+ 'on' => array( false ),
+ 'suspended' => array( true ),
+ );
+ }
+
+ /**
+ * @testdox With product instance caching on, cleanup drops the cached product, so it no longer has the removed rows.
+ */
+ public function test_cleanup_drops_the_cached_product(): void {
+ $option = 'woocommerce_feature_' . ProductCacheController::FEATURE_NAME . '_enabled';
+ $was = get_option( $option );
+ $controller = wc_get_container()->get( ProductCacheController::class );
+ update_option( $option, 'yes' );
+ $controller->register_hooks();
+ try {
+ $before = microtime( true );
+ $id = WC_Helper_Product::create_simple_product()->get_id();
+ ProductFailures::store( $id, array( 'missing_images' => array() ), false );
+ update_post_meta( $id, ProductFailures::WRITTEN_META, sprintf( '%.6F', $before - 5 ) );
+ $cached = wc_get_product( $id );
+ $cached->get_meta( ProductFailures::META_KEY, false ); // Meta loads on first read, so the cached product holds the rows.
+ wc_get_container()->get( ProductCache::class )->set( $cached );
+ $this->assertTrue( wc_get_container()->get( ProductCache::class )->is_cached( $id ), 'Fixture precondition: the product is cached' );
+
+ ProductFailures::forget_unless_written_since( array( $id ), $before );
+
+ $this->assertSame( array(), wc_get_product( $id )->get_meta( ProductFailures::META_KEY, false ) );
+ } finally {
+ wc_get_container()->get( ProductCache::class )->flush();
+ remove_action( 'clean_post_cache', array( $controller, 'invalidate_product_cache_on_clean' ), 10 );
+ foreach ( array( 'updated_post_meta', 'added_post_meta', 'deleted_post_meta' ) as $hook ) {
+ remove_action( $hook, array( $controller, 'invalidate_product_cache_by_meta' ), 10 );
+ }
+ remove_action( 'woocommerce_updated_product_stock', array( $controller, 'invalidate_product_cache' ), 10 );
+ remove_action( 'woocommerce_updated_product_sales', array( $controller, 'invalidate_product_cache' ), 10 );
+ false === $was ? delete_option( $option ) : update_option( $option, $was );
+ }
+ }
+
+ /**
+ * @testdox A save records its write time before it changes the rows, so cleanup that runs during the save keeps them.
+ */
+ public function test_cleanup_during_a_save_keeps_its_rows(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $id = $product->get_id();
+ ProductFailures::store( $id, array(), false );
+ $scan_started = microtime( true );
+
+ // Cleanup of a scan that lists this product runs while the save is writing its rows.
+ $cleanup = static function ( $meta_id, $object_id, $meta_key ) use ( $id, $scan_started ): void {
+ unset( $meta_id );
+ if ( $id === (int) $object_id && ProductFailures::META_KEY === $meta_key ) {
+ ProductFailures::forget_unless_written_since( array( $id ), $scan_started );
+ }
+ };
+ add_action( 'added_post_meta', $cleanup, 10, 3 );
+ try {
+ ProductFailures::store( $id, array( 'missing_images' => array() ) );
+ } finally {
+ remove_action( 'added_post_meta', $cleanup, 10 );
+ }
+
+ $this->assertSame( array( ProductFailures::CHECKED, 'missing_images' ), ProductFailures::stored( $id ) );
+ }
+
+ /**
+ * @testdox Cleanup of more products than one delete takes removes old rows past the first chunk, keeps fresh ones, and clears their cached meta.
+ */
+ public function test_forget_unless_written_since_past_one_chunk(): void {
+ $ids = self::factory()->post->create_many( ProductFailures::CLEANUP_CHUNK + 50 );
+ $last_in_first = ProductFailures::CLEANUP_CHUNK - 1;
+ foreach ( $ids as $id ) {
+ ProductFailures::store( $id, array(), false );
+ }
+ $scan_started = microtime( true );
+ $fresh = array( $ids[5], $ids[ ProductFailures::CLEANUP_CHUNK + 20 ] );
+ foreach ( $fresh as $id ) {
+ ProductFailures::store( $id, array() );
+ }
+ foreach ( $ids as $id ) {
+ ProductFailures::stored( $id ); // Prime the meta cache.
+ }
+
+ ProductFailures::forget_unless_written_since( $ids, $scan_started );
+
+ foreach ( array( $ids[0], $ids[ $last_in_first ], $ids[ ProductFailures::CLEANUP_CHUNK ], end( $ids ) ) as $id ) {
+ $this->assertSame( array(), ProductFailures::stored( $id ), "Old rows of product $id are removed" );
+ }
+ foreach ( $fresh as $id ) {
+ $this->assertSame( array( ProductFailures::CHECKED ), ProductFailures::stored( $id ), "Fresh rows of product $id stay" );
+ }
+ }
+
/**
* @testdox Two rows for one value on one product count as one product.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
index cc7a459b06c..9eca699c49d 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
@@ -593,6 +593,40 @@ class ReadinessRestControllerTest extends WC_REST_Unit_Test_Case {
}
}
+ /**
+ * @testdox When the discovery file can't be written as UCP turns on, POST ucp answers needs attention, not active.
+ */
+ public function test_turning_ucp_on_reports_a_failed_discovery_write(): void {
+ if ( is_multisite() ) {
+ $this->markTestSkipped( 'Multisite never writes the discovery file.' );
+ }
+ global $wp_rewrite;
+ StoreConditionsTest::make_store_ready();
+ $wp_rewrite->set_permalink_structure( '' );
+ // A folder where the file goes: its parent is writable, so the switch is allowed, but the write fails.
+ $path = get_temp_dir() . uniqid( 'wc-ucp-' ) . '/ucp';
+ wp_mkdir_p( $path );
+ add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $path );
+ // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler -- The failed write warns, as on a real server.
+ set_error_handler( static fn( int $severity ): bool => E_WARNING === $severity );
+
+ try {
+ $response = $this->dispatch_ucp( true );
+ } finally {
+ restore_error_handler();
+ foreach ( array( $path, dirname( $path ) ) as $dir ) {
+ if ( is_dir( $dir ) ) {
+ rmdir( $dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+ }
+ }
+ }
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertTrue( $response->get_data()['enabled'] );
+ $this->assertSame( UcpSwitch::STATUS_NEEDS_ATTENTION, $response->get_data()['status'] );
+ $this->assertContains( 'ucp_discovery', $response->get_data()['failing_checks'] );
+ }
+
/**
* @testdox A user without manage_woocommerce can't switch UCP.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
index 7739b13a649..8d6694e02f1 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
@@ -415,7 +415,7 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
}
/**
- * @testdox Giving up after a finished batch removes failure rows that batch wrote for products the last report never covered.
+ * @testdox Giving up after a finished batch removes failure rows that batch wrote for products the last report never covered, and keeps rows a save wrote while the scan ran.
*/
public function test_give_up_drops_failure_rows_the_last_report_did_not_cover(): void {
$ids = $this->create_products( ProductScan::BATCH_SIZE + 1 );
@@ -426,6 +426,10 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
// The scan walks newest products first, so the first batch covers the last id created, not $ids[0].
$covered = (int) end( $ids );
$this->assertNotEmpty( ProductFailures::stored( $covered ), 'The finished batch wrote failure rows' );
+ // The first product created is left for the next batch. A save checks it now.
+ $saved = (int) $ids[0];
+ $this->assertSame( array(), ProductFailures::stored( $saved ), 'The first batch did not reach it' );
+ ProductFailures::store( $saved, array() );
$crash = static function (): void {
throw new \RuntimeException( 'Fatal on the next batch' );
@@ -443,6 +447,7 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
$this->assertSame( array(), ProductFailures::stored( $covered ), 'Rows the abandoned scan added are removed' );
+ $this->assertSame( array( ProductFailures::CHECKED ), ProductFailures::stored( $saved ), 'Rows the save wrote stay' );
$this->assertSame( 7, get_option( AgentReadiness::REPORT_OPTION )['products'] );
}