Commit 951eea2cbd8 for woocommerce

commit 951eea2cbd854db904cf28785d7eb6306217adf1
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date:   Mon Nov 23 14:35:43 2026 +0100

    Agent readiness: count catalog search failures in the tracker snapshot (#71309)

    * Agent readiness: count catalog search failures in the tracker snapshot

    Each catalog search check that sends its request adds to running counts kept
    in one option: checks run, first-try failures, failures after the retry, no
    answer, and what the store last answered when one didn't pass. The tracker
    snapshot sends them as ucp_search, so we can see how often stores fail the
    check and whether the retry helps. A scan that sends no request, in coming
    soon mode or when the store can't reach its home page, isn't counted.

    * Document how catalog search retry counts combine

    first_try_failed includes failed and no_answer, so checks the retry recovered are first_try_failed minus those two. Cover a 5xx in the counter test.

    * Keep the catalog search answer when the retry times out

    A retry with no response was dropping the first answer, and an unknown content type was stored as sent.

    * Record what catalog search recovered from, and when last_seen was set

    A retry that gets past a first-try failure now keeps that first answer as last_recovered. last_seen gets a day so an old failure is not read as the cause of recent ones.

diff --git a/plugins/woocommerce/changelog/fix-agent-readiness-ucp-search-failure-counts b/plugins/woocommerce/changelog/fix-agent-readiness-ucp-search-failure-counts
new file mode 100644
index 00000000000..67d9f109066
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-agent-readiness-ucp-search-failure-counts
@@ -0,0 +1,4 @@
+Significance: patch
+Type: add
+
+Count how often the AI shopping catalog search check fails, in the usage data stores share when they opt in to tracking.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index 131a6410259..1801018a815 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -244,8 +244,9 @@ With the flag on, the weekly WC Tracker snapshot (sent only by stores that allow
 - `truncated`: `yes` when the last scan stopped at the product limit, otherwise `no` (including before the first scan). On a truncated scan, product check statuses cover only the products that were checked.
 - `store_checks`: each store check id with `pass`, `problem` or `unknown` (couldn't check, or still waiting for a result). Setup steps are read when the snapshot is built, so they are there before the first scan too; output checks come from the stored report.
 - `product_checks`: each product check id with `problem` when any product fails it, otherwise `pass`.
+- `ucp_search`: running counts of the catalog search check (`ucp_endpoints_live`) since `since` (`Y-m-d`, the first counted check): `checks` run, `first_try_failed`, `failed` after the retry, `no_answer` (a 5xx or no answer, shown as couldn't check), `last_seen` / `last_seen_on` (status and content type of the last answer that didn't pass, such as `403 text/html`, and the day), and `last_recovered` / `last_recovered_on` (what the first try answered when the retry got past it, and the day). `first_try_failed` includes `failed` and `no_answer`; the retry recovered `first_try_failed - failed - no_answer`. Only checks that sent the request count, so not in coming soon mode. A scan that runs the check again before the report is stored (a failed write, or an action that dies and is retried) can count more than once. Totals only grow; compare two snapshots for a week's numbers.

-Check ids and statuses only: no URLs, product names, ids or counts.
+Check ids, statuses and the catalog search counts only: no URLs, product names or product ids.

 ## Updating rules

diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
index b88d65084c7..58f8af70b8b 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
@@ -28,6 +28,11 @@ defined( 'ABSPATH' ) || exit;
  */
 class StoreOutputChecks {

+	/**
+	 * Option holding the running counts of catalog search checks, read by the tracker snapshot.
+	 */
+	public const SEARCH_COUNTS_OPTION = 'woocommerce_agent_readiness_ucp_search_counts';
+
 	/**
 	 * Coming soon mode helper.
 	 *
@@ -1445,10 +1450,79 @@ class StoreOutputChecks {
 	 * @param StoreResponses $responses Store responses.
 	 */
 	private static function ucp_endpoint_answers( StoreResponses $responses ): ?bool {
-		$url    = self::catalog_search_url( $responses );
-		$answer = self::endpoint_answer( $responses->post_json( $url, array() ) );
+		$url            = self::catalog_search_url( $responses );
+		$first_response = $responses->post_json( $url, array() );
+		$first          = self::endpoint_answer( $first_response );
 		// Asked once more before it fails, so one slow or briefly refused request doesn't mark AI shopping as broken.
-		return true === $answer ? true : self::endpoint_answer( $responses->post_json_again( $url, array() ) );
+		$answer = true === $first ? true : self::endpoint_answer( $responses->post_json_again( $url, array() ) );
+		if ( $responses->can_request( $url ) ) {
+			// The first answer is read before the retry replaces it, so a recovery still says what was in the way.
+			$first_seen = self::seen_from( $first_response );
+			$recovered  = true === $answer && true !== $first ? $first_seen : '';
+			$seen       = true === $answer ? '' : self::search_seen( $responses );
+			self::count_search_answer( $first, $answer, $seen, $recovered );
+		}
+		return $answer;
+	}
+
+	/**
+	 * Add one catalog search check to the running counts the tracker snapshot sends, so we can see
+	 * how often stores fail it, and whether the retry helps.
+	 *
+	 * @param bool|null $first     The first answer: true when it was the JSON, null when the store didn't answer.
+	 * @param bool|null $answer    The result after the retry.
+	 * @param string    $seen      What the store last answered, such as `403 text/html`, when the check didn't pass.
+	 * @param string    $recovered What the first try answered when the retry got past it.
+	 */
+	private static function count_search_answer( ?bool $first, ?bool $answer, string $seen, string $recovered ): void {
+		$counts          = self::search_counts();
+		$counts['since'] = '' === $counts['since'] ? gmdate( 'Y-m-d' ) : $counts['since'];
+		++$counts['checks'];
+		if ( true !== $first ) {
+			++$counts['first_try_failed'];
+		}
+		if ( false === $answer ) {
+			++$counts['failed'];
+		} elseif ( null === $answer ) {
+			++$counts['no_answer'];
+		}
+		$today = gmdate( 'Y-m-d' );
+		if ( '' !== $seen ) {
+			$counts['last_seen']    = $seen;
+			$counts['last_seen_on'] = $today;
+		}
+		if ( '' !== $recovered ) {
+			$counts['last_recovered']    = $recovered;
+			$counts['last_recovered_on'] = $today;
+		}
+		update_option( self::SEARCH_COUNTS_OPTION, $counts, false );
+	}
+
+	/**
+	 * Running counts of catalog search checks since `since`. `first_try_failed` includes `failed`
+	 * and `no_answer` (a 5xx or none, shown as couldn't check). The retry recovered
+	 * `first_try_failed - failed - no_answer`. `last_seen` / `last_seen_on` are what the store last
+	 * answered when one didn't pass, and the day. `last_recovered` / `last_recovered_on` are what the
+	 * first try answered when the retry got past it, and the day.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @return array{since:string,checks:int,first_try_failed:int,failed:int,no_answer:int,last_seen:string,last_seen_on:string,last_recovered:string,last_recovered_on:string}
+	 */
+	public static function search_counts(): array {
+		$stored = get_option( self::SEARCH_COUNTS_OPTION, array() );
+		$stored = is_array( $stored ) ? $stored : array();
+		return array(
+			'since'             => is_string( $stored['since'] ?? null ) ? $stored['since'] : '',
+			'checks'            => (int) ( $stored['checks'] ?? 0 ),
+			'first_try_failed'  => (int) ( $stored['first_try_failed'] ?? 0 ),
+			'failed'            => (int) ( $stored['failed'] ?? 0 ),
+			'no_answer'         => (int) ( $stored['no_answer'] ?? 0 ),
+			'last_seen'         => is_string( $stored['last_seen'] ?? null ) ? $stored['last_seen'] : '',
+			'last_seen_on'      => is_string( $stored['last_seen_on'] ?? null ) ? $stored['last_seen_on'] : '',
+			'last_recovered'    => is_string( $stored['last_recovered'] ?? null ) ? $stored['last_recovered'] : '',
+			'last_recovered_on' => is_string( $stored['last_recovered_on'] ?? null ) ? $stored['last_recovered_on'] : '',
+		);
 	}

 	/**
@@ -1462,17 +1536,30 @@ class StoreOutputChecks {

 	/**
 	 * The status and content type of the last answer from catalog search, such as `403 text/html`,
-	 * so a failed check says what was in the way. Empty when the store didn't answer.
+	 * so a failed check says what was in the way. Only a known media type is kept. Empty when the store didn't answer.
 	 *
 	 * @param StoreResponses $responses Store responses.
 	 */
 	private static function search_seen( StoreResponses $responses ): string {
-		$response = $responses->post_json( self::catalog_search_url( $responses ), array() );
+		return self::seen_from( $responses->post_json( self::catalog_search_url( $responses ), array() ) );
+	}
+
+	/**
+	 * Status and content type from one catalog search answer, such as `403 text/html`. Only a known
+	 * media type is kept. Empty when there was no answer.
+	 *
+	 * @param array{status:int,body:string,headers:array<string,string>,truncated:bool}|null $response Response.
+	 */
+	private static function seen_from( ?array $response ): string {
 		if ( null === $response ) {
 			return '';
 		}
-		$type = strtolower( trim( explode( ';', $response['headers']['content-type'] ?? '' )[0] ) );
-		return trim( $response['status'] . ' ' . sanitize_text_field( $type ) );
+		$type = strtolower( trim( explode( ';', (string) ( $response['headers']['content-type'] ?? '' ) )[0] ) );
+		$type = sanitize_text_field( $type );
+		if ( ! in_array( $type, array( 'text/html', 'text/plain', 'application/json', 'application/problem+json' ), true ) ) {
+			$type = '';
+		}
+		return trim( $response['status'] . ' ' . $type );
 	}

 	/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php
index 0e3bab74d6d..97cd9b38cea 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php
@@ -192,16 +192,35 @@ class StoreResponses {
 		return $this->responses[ $key ];
 	}

+	/**
+	 * Whether this scan sends a request to a URL: only while the store is live, only to the store,
+	 * and not once the home page couldn't be reached.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param string $url URL or path.
+	 */
+	public function can_request( string $url ): bool {
+		return $this->site_live && $this->reachable && $this->is_store_url( self::absolute( $url ) );
+	}
+
 	/**
 	 * The response to a POST of a JSON object, sent again instead of read from this scan's earlier answer.
+	 * A retry that gets no answer leaves the earlier one in place, so the scan can still say what came back.
 	 *
 	 * @param string               $url  URL or path.
 	 * @param array<string, mixed> $body JSON object.
 	 * @return array{status:int,body:string,headers:array<string,string>,truncated:bool}|null Null when the store could not be reached.
 	 */
 	public function post_json_again( string $url, array $body ): ?array {
-		unset( $this->responses[ self::post_key( self::absolute( $url ), $body ) ] );
-		return $this->post_json( $url, $body );
+		$key      = self::post_key( self::absolute( $url ), $body );
+		$previous = $this->responses[ $key ] ?? null;
+		unset( $this->responses[ $key ] );
+		$again = $this->post_json( $url, $body );
+		if ( null === $again && null !== $previous ) {
+			$this->responses[ $key ] = $previous;
+		}
+		return $again;
 	}

 	/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Telemetry.php b/plugins/woocommerce/src/Internal/AgentReadiness/Telemetry.php
index 5c5192edcaa..c230b7cf55a 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Telemetry.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Telemetry.php
@@ -14,7 +14,7 @@ defined( 'ABSPATH' ) || exit;

 /**
  * Adds the readiness check to the weekly WC Tracker snapshot, which only stores that opted in to usage tracking send.
- * Check ids and statuses only: no URLs, product names or store content.
+ * Check ids and statuses, and counts of catalog search checks: no URLs, product names or page content.
  */
 class Telemetry implements RegisterHooksInterface {

@@ -74,8 +74,9 @@ class Telemetry implements RegisterHooksInterface {
 	/**
 	 * The feature flag, when the last scan ran, whether it stopped at the product limit, and each check's status.
 	 * The store conditions are read now; output and product checks are as the last scan left them.
+	 * `ucp_search` counts the catalog search checks, to see how often they fail and whether the retry helps.
 	 *
-	 * @return array{feature_enabled:string,last_scan:string,truncated:string,store_checks:array<string,string>,product_checks:array<string,string>}
+	 * @return array{feature_enabled:string,last_scan:string,truncated:string,store_checks:array<string,string>,product_checks:array<string,string>,ucp_search?:array{since:string,checks:int,first_try_failed:int,failed:int,no_answer:int,last_seen:string,last_seen_on:string,last_recovered:string,last_recovered_on:string}}
 	 */
 	public function snapshot(): array {
 		$snapshot = array(
@@ -89,6 +90,7 @@ class Telemetry implements RegisterHooksInterface {
 			return $snapshot;
 		}
 		$snapshot['feature_enabled'] = 'yes';
+		$snapshot['ucp_search']      = StoreOutputChecks::search_counts();

 		// Setup steps are read now, so they are known before the first scan too.
 		$report = $this->agent_readiness->get_served_report();
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php
index dd1b5e82ff4..f09dda4bb44 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php
@@ -605,6 +605,129 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
 		$this->assertTrue( $this->results()['ucp_endpoints_live'], 'A refusal followed by the endpoint passes' );
 	}

+	/**
+	 * @testdox Each catalog search check adds to the running counts: first-try failures, failures after the retry, no answer, and what a failing one answered.
+	 */
+	public function test_catalog_search_counts(): void {
+		update_option( 'woocommerce_feature_ucp_enabled', 'yes' );
+		delete_option( StoreOutputChecks::SEARCH_COUNTS_OPTION );
+		$search    = substr( rest_url( 'wc/ucp/v1' ), strlen( untrailingslashit( home_url() ) ) ) . '/catalog/search';
+		$responses = $this->good_store();
+		$run       = function ( ?array $answer ) use ( $responses, $search ): void {
+			$responses[ 'POST ' . $search ] = $answer;
+			$this->serve( $responses );
+			$this->sut->all();
+		};
+
+		$today = gmdate( 'Y-m-d' );
+		$run( array( 200, '{"ucp":{"status":"success"},"products":[]}' ) );
+		$counts = StoreOutputChecks::search_counts();
+		$this->assertSame( $today, $counts['since'] );
+		$this->assertSame( array( 1, 0, 0, 0, '', '', '', '' ), array( $counts['checks'], $counts['first_try_failed'], $counts['failed'], $counts['no_answer'], $counts['last_seen'], $counts['last_seen_on'], $counts['last_recovered'], $counts['last_recovered_on'] ), 'A pass counts only as a check' );
+
+		$run( array( 403, '<html>Blocked</html>', array( 'content-type' => 'text/html; charset=UTF-8' ) ) );
+		$run( null );
+		$counts = StoreOutputChecks::search_counts();
+		$this->assertSame( 3, $counts['checks'] );
+		$this->assertSame( 2, $counts['first_try_failed'] );
+		$this->assertSame( 1, $counts['failed'], 'A refusal fails after the retry' );
+		$this->assertSame( 1, $counts['no_answer'], 'A timeout is no answer, shown as couldn\'t check' );
+		$this->assertSame( '403 text/html', $counts['last_seen'], 'No answer leaves the last answer in place' );
+		$this->assertSame( $today, $counts['last_seen_on'] );
+		$this->assertSame( '', $counts['last_recovered'] );
+
+		$run( array( 503, '<html>Unavailable</html>', array( 'content-type' => 'text/html' ) ) );
+		$counts = StoreOutputChecks::search_counts();
+		$this->assertSame( array( 4, 3, 1, 2, '503 text/html', $today ), array( $counts['checks'], $counts['first_try_failed'], $counts['failed'], $counts['no_answer'], $counts['last_seen'], $counts['last_seen_on'] ), 'A 5xx is no answer and keeps what came back' );
+
+		$this->serve( $responses );
+		$answers = array( array( 403, '<html>Blocked</html>', array( 'content-type' => 'text/html' ) ), array( 200, '{"ucp":{"status":"success"},"products":[]}' ) );
+		add_filter(
+			'pre_http_request',
+			function ( $pre, $args, $url ) use ( $search, &$answers ) {
+				if ( 'POST' !== $args['method'] || substr( $url, strlen( untrailingslashit( home_url() ) ) ) !== $search || array() === $answers ) {
+					return $pre;
+				}
+				$answer = array_shift( $answers );
+				return array(
+					'headers'  => new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( $answer[2] ?? array() ),
+					'body'     => $answer[1],
+					'response' => array(
+						'code'    => $answer[0],
+						'message' => '',
+					),
+					'cookies'  => array(),
+				);
+			},
+			20,
+			3
+		);
+		$this->sut->all();
+		$counts = StoreOutputChecks::search_counts();
+		$this->assertSame( array( 5, 4, 1 ), array( $counts['checks'], $counts['first_try_failed'], $counts['failed'] ), 'A refusal the retry gets past counts as a first-try failure only' );
+		$this->assertSame( '503 text/html', $counts['last_seen'], 'A recovery leaves the last failure in place' );
+		$this->assertSame( '403 text/html', $counts['last_recovered'], 'A recovery keeps what the first try answered' );
+		$this->assertSame( $today, $counts['last_recovered_on'] );
+
+		update_option( 'woocommerce_coming_soon', 'yes' );
+		$this->serve( $responses );
+		$this->sut->all();
+		$this->assertNotContains( 'POST ' . $search, $this->requested );
+		$this->assertSame( array( 5, 4, 2 ), array( StoreOutputChecks::search_counts()['checks'], StoreOutputChecks::search_counts()['first_try_failed'], StoreOutputChecks::search_counts()['no_answer'] ), 'In coming soon mode nothing is asked, so nothing is counted' );
+		update_option( 'woocommerce_coming_soon', 'no' );
+
+		$unreachable      = $responses;
+		$unreachable['/'] = null;
+		$this->serve( $unreachable );
+		$this->sut->all();
+		$this->assertNotContains( 'POST ' . $search, $this->requested );
+		$this->assertSame( 5, StoreOutputChecks::search_counts()['checks'], 'A store that can\'t reach its home page sends nothing more, so nothing is counted' );
+
+		update_option( 'woocommerce_feature_ucp_enabled', 'no' );
+		$this->serve( $responses );
+		$this->sut->all();
+		$this->assertSame( 5, StoreOutputChecks::search_counts()['checks'], 'With UCP off, catalog search isn\'t checked or counted' );
+
+		update_option( 'woocommerce_feature_ucp_enabled', 'yes' );
+		$this->serve( $responses );
+		$answers = array( array( 403, '<html>Blocked</html>', array( 'content-type' => 'text/html' ) ), null );
+		add_filter(
+			'pre_http_request',
+			function ( $pre, $args, $url ) use ( $search, &$answers ) {
+				if ( 'POST' !== $args['method'] || substr( $url, strlen( untrailingslashit( home_url() ) ) ) !== $search || array() === $answers ) {
+					return $pre;
+				}
+				$answer = array_shift( $answers );
+				if ( null === $answer ) {
+					return new \WP_Error( 'http_request_failed', 'Timed out' );
+				}
+				return array(
+					'headers'  => new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( $answer[2] ?? array() ),
+					'body'     => $answer[1],
+					'response' => array(
+						'code'    => $answer[0],
+						'message' => '',
+					),
+					'cookies'  => array(),
+				);
+			},
+			20,
+			3
+		);
+		$checks = array_column( $this->sut->all(), null, 'id' );
+		$counts = StoreOutputChecks::search_counts();
+		$this->assertNull( $checks['ucp_endpoints_live']['ok'], 'A retry that times out is couldn\'t check' );
+		$this->assertSame( '403 text/html', $checks['ucp_endpoints_live']['source'], 'A retry that times out keeps the first answer' );
+		$this->assertSame( array( 6, 5, 1, 3, '403 text/html', $today ), array( $counts['checks'], $counts['first_try_failed'], $counts['failed'], $counts['no_answer'], $counts['last_seen'], $counts['last_seen_on'] ) );
+		$this->assertSame( '403 text/html', $counts['last_recovered'], 'A later failure leaves the last recovery in place' );
+
+		$run( array( 403, '<html>Blocked</html>', array( 'content-type' => 'https://store.example/cart' ) ) );
+		$counts = StoreOutputChecks::search_counts();
+		$this->assertSame( '403', $counts['last_seen'], 'An unknown content type is left out' );
+		$this->assertSame( $today, $counts['last_seen_on'] );
+		$this->assertSame( array( 7, 6, 2 ), array( $counts['checks'], $counts['first_try_failed'], $counts['failed'] ) );
+	}
+
 	/**
 	 * @testdox Only the UCP checkout check waits as pending, until this WooCommerce serves UCP checkout; the product structured data checks run.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/TelemetryTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/TelemetryTest.php
index 499636e2661..f1bd3621b3c 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/TelemetryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/TelemetryTest.php
@@ -4,6 +4,7 @@ declare( strict_types=1 );
 namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;

 use Automattic\WooCommerce\Internal\AgentReadiness\AgentReadiness;
+use Automattic\WooCommerce\Internal\AgentReadiness\StoreOutputChecks;
 use Automattic\WooCommerce\Internal\AgentReadiness\Telemetry;
 use WC_Unit_Test_Case;

@@ -160,6 +161,29 @@ class TelemetryTest extends WC_Unit_Test_Case {
 		$this->assertStringNotContainsString( 'product_ids', $sent, 'No product ids' );
 	}

+	/**
+	 * @testdox The snapshot sends the catalog search counts, and none with the feature off.
+	 */
+	public function test_catalog_search_counts(): void {
+		$counts = array(
+			'since'             => '2026-11-20',
+			'checks'            => 11,
+			'first_try_failed'  => 3,
+			'failed'            => 1,
+			'no_answer'         => 0,
+			'last_seen'         => '403 text/html',
+			'last_seen_on'      => '2026-11-18',
+			'last_recovered'    => '403 text/html',
+			'last_recovered_on' => '2026-11-19',
+		);
+		update_option( StoreOutputChecks::SEARCH_COUNTS_OPTION, $counts );
+
+		$this->assertSame( $counts, $this->sut->snapshot()['ucp_search'] );
+
+		update_option( 'woocommerce_feature_agent_readiness_enabled', 'no' );
+		$this->assertArrayNotHasKey( 'ucp_search', $this->sut->snapshot() );
+	}
+
 	/**
 	 * @testdox A scan that stopped at the product limit is marked truncated in the snapshot.
 	 */