Commit 32c0fde14ec for woocommerce

commit 32c0fde14ec69770e0dd5a6415b516aa3a16e7fa
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date:   Fri Nov 20 20:54:13 2026 +0100

    Agent readiness: run the product scan as one background action per batch (#71024)

    * Agent readiness: run the product scan as one background action per batch

    * Agent readiness: drop partial failure rows when a batched scan is abandoned

    Giving up, cancelling, or replacing a scan left ProductFailures meta from
    finished batches while the last report stayed. Remove rows the abandoned
    scan wrote for products that report never covered, and note that start
    still reads full-store sales once for the total.

    Co-authored-by: Cursor <cursoragent@cursor.com>

    * Assert the give-up test against a product the finished batch scanned.

    * Fix replaced scan batches writing product failures

    A new scan can start while an old batch is still collecting results.
    Store failure rows only after the chain is still current so the old
    batch cannot leave meta that belongs to the new scan.

    * Harden batched agent readiness scan against CodeRabbit findings

    Recheck eligibility per batch, track tested IDs for keep_only, fail closed on catalog/sales query errors, prime meta before storing, and only drop progress after a successful report write.

    * Keep readiness rows until the batched scan's report is stored.

    A failed report write left the old report counting rows keep_only had already deleted. Rows saved while a product was skipped stay, and a successful empty product list is not a query failure.

    Co-authored-by: Cursor <cursoragent@cursor.com>

    * Fix agent readiness scan query-error checks and two tests.

    An ids WP_Query returns before posts_results runs, so the product list
    never saw a database error. Read $wpdb->last_error after the query
    instead, and short-circuit the test query with posts_pre_query.

    pre_update_option passes ( $value, $old_value, $option ); the report
    write test took the option name as the old value, so the write it meant
    to block went through.

    ProductSales: read the query error through a helper PHPStan does not
    narrow, escape the exception message and add its @throws tag.

    * Stop the agent readiness scan on any product list query error.

    The catalog counts read 0 when their own queries fail, so the guard let
    a broken database through as an empty catalog.

    * Keep a failed agent readiness list query out of the cache.

    The product list query skips the query cache, so a failed query is not
    stored as an empty list for the next scan. A batch checks again that its
    scan is current before it writes its progress, so a scan that replaced it
    keeps its own. The scan's own row writes no longer record a write time:
    only saves need it, and an unchanged scan now writes no product meta.

    * Retry a batch when a selected product fails to load

    A false wc_get_product() for a product that still exists must not advance
    the scan or drop prior readiness rows via keep_only(). Deleted products
    still skip without retry.

    Co-authored-by: Cursor <cursoragent@cursor.com>

    ---------

    Co-authored-by: Cursor <cursoragent@cursor.com>

diff --git a/plugins/woocommerce/changelog/fix-store-api-phpstan-cart-updated b/plugins/woocommerce/changelog/fix-store-api-phpstan-cart-updated
new file mode 100644
index 00000000000..e7585d95446
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-store-api-phpstan-cart-updated
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Unblock PHPStan after cart_updated became a no-op and PaymentResult status accessed the protected property.
+
diff --git a/plugins/woocommerce/changelog/update-agent-readiness-batched-scan b/plugins/woocommerce/changelog/update-agent-readiness-batched-scan
new file mode 100644
index 00000000000..d2e21de83e9
--- /dev/null
+++ b/plugins/woocommerce/changelog/update-agent-readiness-batched-scan
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Experimental agent readiness scan runs one batch of products per background action; behind a hidden flag, no merchant change.
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index d2ad4ae2cec..45b42240412 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -10368,12 +10368,6 @@ parameters:
 			count: 1
 			path: includes/class-wc-checkout.php

-		-
-			message: '#^Variable \$order might not be defined\.$#'
-			identifier: variable.undefined
-			count: 1
-			path: includes/class-wc-checkout.php
-
 		-
 			message: '#^Call to static method add_command\(\) on an unknown class WP_CLI\.$#'
 			identifier: class.notFound
@@ -64774,12 +64768,6 @@ parameters:
 			count: 1
 			path: src/StoreApi/Payments/PaymentResult.php

-		-
-			message: '#^Expected 2 @param tags, found 3\.$#'
-			identifier: paramTag.count
-			count: 1
-			path: src/StoreApi/Routes/V1/AbstractCartRoute.php
-
 		-
 			message: '#^Method Automattic\\WooCommerce\\StoreApi\\Routes\\V1\\AbstractCartRoute\:\:cart_updated\(\) has no return type specified\.$#'
 			identifier: missingType.return
@@ -65254,12 +65242,6 @@ parameters:
 			count: 2
 			path: src/StoreApi/Routes/V1/Checkout.php

-		-
-			message: '#^Access to protected property Automattic\\WooCommerce\\StoreApi\\Payments\\PaymentResult\:\:\$status\.$#'
-			identifier: property.protected
-			count: 1
-			path: src/StoreApi/Routes/V1/Checkout.php
-
 		-
 			message: '#^Expression on left side of \?\? is not nullable\.$#'
 			identifier: nullCoalesce.expr
@@ -65488,12 +65470,6 @@ parameters:
 			count: 1
 			path: src/StoreApi/Routes/V1/CheckoutOrder.php

-		-
-			message: '#^Access to protected property Automattic\\WooCommerce\\StoreApi\\Payments\\PaymentResult\:\:\$status\.$#'
-			identifier: property.protected
-			count: 1
-			path: src/StoreApi/Routes/V1/CheckoutOrder.php
-
 		-
 			message: '#^Call to an undefined method WC_Order\|WC_Order_Refund\:\:get_billing_email\(\)\.$#'
 			identifier: method.notFound
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
index 6210fda5ef4..13d2d82651f 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
@@ -30,6 +30,21 @@ class AgentReadiness {
 	 */
 	public const REPORT_OPTION = 'woocommerce_agent_readiness_report';

+	/**
+	 * Option holding the progress of a scan that runs in batches.
+	 */
+	public const SCAN_OPTION = 'woocommerce_agent_readiness_scan';
+
+	/**
+	 * Report field naming the scan that stored it. Removed before the report is read.
+	 */
+	private const REPORT_SCAN_ID = 'scan_id';
+
+	/**
+	 * Times one batch is tried before the scan gives up.
+	 */
+	public const MAX_ATTEMPTS = 3;
+
 	/**
 	 * Store-wide conditions.
 	 *
@@ -212,76 +227,130 @@ class AgentReadiness {
 	}

 	/**
-	 * Run every check over the catalog.
+	 * Run every check over the catalog, in this request, without storing anything.
 	 *
 	 * @return array{generated_at:string,products:int,available:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool,pages_best_seller?:bool,sales:array{days:int,orders:int,imported:bool}|null}
 	 */
 	public function get_report(): array {
-		return $this->build_report();
+		$scan  = $this->start_scan();
+		$total = count( $scan['ids'] );
+		while ( $scan['position'] < $total ) {
+			$scan = $this->scan_batch( $scan, null );
+		}
+		$report = $this->finish_scan( $scan );
+		unset( $report['shared_gtins'] );
+		return $report;
 	}

 	/**
-	 * Run every check over the catalog.
+	 * Start a scan: the rules, the sales period and the products to test, before any is tested.
+	 * Each later step runs from what this returns, so a scan can go on in another request.
 	 *
-	 * @param callable|null $on_tested Called with each product id and its failures.
-	 * @return array{generated_at:string,products:int,available:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool,pages_best_seller:bool,sales:array{days:int,orders:int,imported:bool}|null,shared_gtins?:array<int,string>}
+	 * @return array{ids:array<int,int>,position:int,sales:array{days:int,since:string,orders:int,imported:bool,total:float}|null,ranked:bool,best_seller:int,scan:array<string,mixed>}
 	 */
-	private function build_report( ?callable $on_tested = null ): array {
-		// Rebuild the rules and the scan for each report: a long-running process may have fetched a new rules file or changed GTINs since.
+	private function start_scan(): array {
+		// Rebuild the rules for each scan: a long-running process may have fetched a new rules file since.
 		$this->active_rules = null;
 		$this->product_scan = null;
-		$active             = $this->get_active_rules();
-		$rules              = $active['rules'];
-		$channel_rules      = $active['channel_rules'];
-
-		$sales  = $this->product_sales->last_days();
-		$scan   = new ProductScan();
-		$ranked = null !== $sales && $sales['imported'] && $sales['orders'] >= ProductSales::MIN_ORDERS && $sales['total'] > 0;
+		$sales              = $this->product_sales->last_days();
+		$product_scan       = new ProductScan();
+		$ids                = $product_scan->start();
+		$ranked             = null !== $sales && $sales['imported'] && $sales['orders'] >= ProductSales::MIN_ORDERS && $sales['total'] > 0;
+		// Keep only the best seller id for page checks at finish; the full sales map is not stored between batches.
+		$best_seller = 0;
 		if ( $ranked ) {
-			$scan->use_sales( $sales['by_product'], $sales['by_variation'] );
+			$by_product = array_filter( $sales['by_product'], static fn( $amount ): bool => $amount > 0 );
+			arsort( $by_product );
+			$best_seller = (int) ( array_key_first( $by_product ) ?? 0 );
 		}
-		if ( null === $on_tested ) {
-			$scan->evaluate( $rules, $channel_rules, self::PRODUCT_IDS_LIMIT );
-		} else {
-			$scan->evaluate_each( $rules, $channel_rules, self::PRODUCT_IDS_LIMIT, $on_tested );
+		return array(
+			'ids'         => $ids,
+			'position'    => 0,
+			// The period and totals only: each batch reads its own products' sales, so the whole store's are never kept.
+			'sales'       => null === $sales ? null : array(
+				'days'     => $sales['days'],
+				'since'    => $sales['since'],
+				'orders'   => $sales['orders'],
+				'imported' => $sales['imported'],
+				'total'    => $sales['total'],
+			),
+			'ranked'      => $ranked,
+			'best_seller' => $best_seller,
+			'scan'        => $product_scan->state(),
+		);
+	}
+
+	/**
+	 * Test the next batch of products.
+	 *
+	 * @param array<string, mixed> $scan               What start_scan() or the last batch returned.
+	 * @param callable|null        $on_tested          Called with each product id and its failures.
+	 * @param bool                 $skip_unloadable    When true, products that fail to load are skipped (last attempt).
+	 * @param array<int, int>      $skipped_unloadable Filled with ids skipped when $skip_unloadable is true.
+	 * @return array<string, mixed> The scan with this batch added.
+	 */
+	private function scan_batch( array $scan, ?callable $on_tested, bool $skip_unloadable = false, array &$skipped_unloadable = array() ): array {
+		$active       = $this->get_active_rules();
+		$product_ids  = array_slice( $scan['ids'], $scan['position'], ProductScan::BATCH_SIZE );
+		$product_scan = ProductScan::from_state( $scan['scan'] );
+		if ( $scan['ranked'] ) {
+			$sales = $this->product_sales->for_products( $product_ids, $scan['sales']['since'] );
+			$product_scan->use_sales( $sales['by_product'], $sales['by_variation'] );
 		}
+		$product_scan->test( $product_ids, $active['rules'], $active['channel_rules'], self::PRODUCT_IDS_LIMIT, $on_tested, $skip_unloadable, $skipped_unloadable );
+		$scan['position'] += count( $product_ids );
+		$scan['scan']      = $product_scan->state();
+		return $scan;
+	}
+
+	/**
+	 * Build the report once every batch is tested. The store output checks request the store's own pages, so they run here, once.
+	 *
+	 * @param array<string, mixed> $scan The scan after its last batch.
+	 * @return array{generated_at:string,products:int,available:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool,pages_best_seller:bool,sales:array{days:int,orders:int,imported:bool}|null,shared_gtins?:array<int,string>}
+	 */
+	private function finish_scan( array $scan ): array {
+		$active       = $this->get_active_rules();
+		$product_scan = ProductScan::from_state( $scan['scan'] );
+		$sales        = $scan['sales'];

 		$checks = array();
-		foreach ( $rules as $id => $rule ) {
-			$result   = $scan->result( $id );
+		foreach ( $active['rules'] as $id => $rule ) {
+			$result   = $product_scan->result( $id );
 			$checks[] = array(
 				'id'          => $id,
 				'label'       => $rule->label(),
 				'why'         => $rule->why(),
 				'fix'         => $rule->fix(),
-				'channels'    => $channel_rules[ $id ],
+				'channels'    => $active['channel_rules'][ $id ],
 				'count'       => $result['count'],
 				'product_ids' => $result['product_ids'],
 				// Share of the store's sales on the products that fail; null without enough sales to compare.
-				'sales_share' => $ranked ? self::share( $result['sales'] / $sales['total'] ) : null,
+				'sales_share' => $scan['ranked'] ? self::share( $result['sales'] / $sales['total'] ) : null,
 				'fix_url'     => admin_url( 'edit.php?post_type=product' ),
 			);
 		}

-		$responses = $this->store_output_checks->responses();
-		if ( $ranked ) {
-			// Page checks read the best seller's page first.
-			$responses->use_sales( $sales['by_product'] );
+		$responses   = $this->store_output_checks->responses();
+		$best_seller = (int) ( $scan['best_seller'] ?? 0 );
+		if ( $best_seller > 0 ) {
+			// Page checks read the best seller's page first. Only the id is kept from start(); the amount is unused.
+			$responses->use_sales( array( $best_seller => 1.0 ) );
 		}

 		$report = array(
 			'generated_at'        => gmdate( 'c' ),
-			'products'            => $scan->products(),
-			'available'           => $scan->available(),
-			'hidden_from_catalog' => $scan->hidden_from_catalog(),
-			'unsupported_types'   => $scan->unsupported_types(),
+			'products'            => $product_scan->products(),
+			'available'           => $product_scan->available(),
+			'hidden_from_catalog' => $product_scan->hidden_from_catalog(),
+			'unsupported_types'   => $product_scan->unsupported_types(),
 			'store_checks'        => array_merge( $this->store_conditions->all(), $this->store_output_checks->all_for( $responses ) ),
 			'declared'            => $this->declared_to_agents->all( $responses ),
 			// Whether the product pages the page checks read start with the best seller, or with the newest product.
 			'pages_best_seller'   => $responses->starts_with_best_seller(),
-			'channels'            => $scan->channel_totals(),
+			'channels'            => $product_scan->channel_totals(),
 			'checks'              => $checks,
-			'truncated'           => $scan->truncated(),
+			'truncated'           => $product_scan->truncated(),
 			// How sales shares were measured: null while Analytics is off.
 			'sales'               => null === $sales ? null : array(
 				'days'     => $sales['days'],
@@ -289,9 +358,9 @@ class AgentReadiness {
 				'imported' => $sales['imported'],
 			),
 		);
-		if ( null !== $on_tested && null !== $scan->shared_gtins() ) {
+		if ( null !== $product_scan->shared_gtins() ) {
 			// Stored for checks of one product, so a save doesn't read every published product.
-			$report['shared_gtins'] = $scan->shared_gtins();
+			$report['shared_gtins'] = $product_scan->shared_gtins();
 		}
 		return $report;
 	}
@@ -316,7 +385,7 @@ class AgentReadiness {
 		if ( ! is_array( $report ) ) {
 			return null;
 		}
-		unset( $report['shared_gtins'] );
+		unset( $report['shared_gtins'], $report[ self::REPORT_SCAN_ID ] );
 		return self::with_saved_products( $report );
 	}

@@ -449,25 +518,204 @@ class AgentReadiness {
 	}

 	/**
-	 * Run the report and store it. Not autoloaded: only the readiness screens read it.
+	 * Run the report and store it, in this request. Not autoloaded: only the readiness screens read it.
 	 *
 	 * @return array<string, mixed>
 	 */
 	public function refresh_report(): array {
-		// Captured before the scan. A product saved while it runs is absent here, so its new rows stay.
-		$had_rows = ProductFailures::stored_product_ids();
-		$tested   = array();
-		$report   = $this->build_report(
-			static function ( int $product_id, array $failures ) use ( &$tested ): void {
-				$tested[] = $product_id;
-				ProductFailures::store( $product_id, $failures );
+		$chain = $this->start_refresh();
+		// Each call tests one batch, then the last one stores the report.
+		do {
+			$more = $this->continue_refresh( $chain );
+		} while ( $more );
+		$report = (array) get_option( self::REPORT_OPTION, array() );
+		unset( $report['shared_gtins'], $report[ self::REPORT_SCAN_ID ] );
+		return $report;
+	}
+
+	/**
+	 * Start a scan that runs one batch per call to continue_refresh(), replacing any scan
+	 * in progress. Its progress is kept in SCAN_OPTION, so each batch can run in its own
+	 * background action.
+	 *
+	 * @return string The scan's id, for continue_refresh().
+	 */
+	public function start_refresh(): string {
+		// Drop rows a replaced scan wrote for products the last report never covered.
+		$previous = get_option( self::SCAN_OPTION );
+		if ( is_array( $previous ) ) {
+			$this->abandon_refresh( $previous );
+		}
+		// Taken first, so a save while the product list is read still counts as during the scan.
+		$rows_as_of = microtime( true );
+		$state      = array_merge(
+			$this->start_scan(),
+			array(
+				'id'         => wp_generate_uuid4(),
+				'attempts'   => 0,
+				'rows_as_of' => $rows_as_of,
+				// Taken before the scan. A product saved while it runs is absent here, so its new rows stay.
+				'had_rows'   => ProductFailures::stored_product_ids(),
+				// Product ids evaluated, plus unloadable ids skipped on the last attempt so keep_only leaves their rows.
+				'tested'     => array(),
+			)
+		);
+		update_option( self::SCAN_OPTION, $state, false );
+		return $state['id'];
+	}
+
+	/**
+	 * Test the next batch of the scan in progress, or, once every batch is tested, store the report.
+	 * A batch that ends early is tried again from where the last one stopped, up to MAX_ATTEMPTS times.
+	 *
+	 * @param string $chain The id start_refresh() returned.
+	 * @return bool True while there is more to do; false once the report is stored, or when $chain is not the scan in progress.
+	 */
+	public function continue_refresh( string $chain ): bool {
+		if ( ! $this->is_current( $chain ) ) {
+			return false;
+		}
+		$state = (array) get_option( self::SCAN_OPTION );
+		if ( $state['attempts'] >= self::MAX_ATTEMPTS ) {
+			// The same batch failed every time: give up and keep the last report rather than loop.
+			$this->abandon_refresh( $state );
+			return false;
+		}
+		++$state['attempts'];
+		update_option( self::SCAN_OPTION, $state, false );
+
+		if ( $state['position'] < count( $state['ids'] ) ) {
+			// Collect first, then store only if this chain is still current: a replaced scan must not write failure rows.
+			// On the last attempt, skip products that still fail to load so one broken product cannot freeze every scan.
+			$written            = array();
+			$skipped_unloadable = array();
+			$skip_unloadable    = $state['attempts'] >= self::MAX_ATTEMPTS;
+			$state              = $this->scan_batch(
+				$state,
+				static function ( int $product_id, array $failures ) use ( &$written ): void {
+					$written[ $product_id ] = $failures;
+				},
+				$skip_unloadable,
+				$skipped_unloadable
+			);
+			if ( ! $this->is_current( $chain ) ) {
+				return false;
+			}
+			// ProductScan flushes the runtime cache after the batch; prime again before the store loop.
+			_prime_post_caches( array_map( 'intval', array_keys( $written ) ), true, true );
+			foreach ( $written as $product_id => $failures ) {
+				ProductFailures::store( (int) $product_id, $failures, false );
+			}
+			// Skipped unloadable ids count as tested so keep_only() leaves their existing rows alone.
+			$state['tested'] = array_values(
+				array_unique(
+					array_merge(
+						array_map( 'intval', (array) ( $state['tested'] ?? array() ) ),
+						array_map( 'intval', array_keys( $written ) ),
+						array_map( 'intval', $skipped_unloadable )
+					)
+				)
+			);
+			if ( $skipped_unloadable ) {
+				wc_get_logger()->warning(
+					sprintf(
+						'Agent readiness skipped %d product(s) that failed to load on the last attempt: %s',
+						count( $skipped_unloadable ),
+						implode( ', ', $skipped_unloadable )
+					),
+					array( 'source' => 'agent-readiness' )
+				);
+			}
+			$state['attempts'] = 0;
+			// A scan that replaced this one while the rows were stored keeps its own progress.
+			if ( ! $this->is_current( $chain ) ) {
+				return false;
 			}
+			update_option( self::SCAN_OPTION, $state, false );
+			return true;
+		}
+
+		$report                         = $this->finish_scan( $state );
+		$report['failures_stored']      = true;
+		$report[ self::REPORT_SCAN_ID ] = $chain;
+		if ( ! $this->is_current( $chain ) ) {
+			return false;
+		}
+		// Store the report first. A failed write leaves the previous report and the rows it counts.
+		if ( false === update_option( self::REPORT_OPTION, $report, false ) ) {
+			return true;
+		}
+		if ( ! $this->is_current( $chain ) ) {
+			return false;
+		}
+		$this->keep_tested_rows( $state );
+		// Re-check before deleting: a replacement scan must keep its own progress.
+		if ( ! $this->is_current( $chain ) ) {
+			return false;
+		}
+		delete_option( self::SCAN_OPTION );
+		return false;
+	}
+
+	/**
+	 * Whether a scan is still the one in progress. A new scan replaces it while a batch
+	 * runs, and that batch must not write over the new scan's progress.
+	 *
+	 * @phpstan-impure
+	 *
+	 * @param string $chain Scan id.
+	 */
+	private function is_current( string $chain ): bool {
+		$state = get_option( self::SCAN_OPTION );
+		return is_array( $state ) && ( $state['id'] ?? '' ) === $chain;
+	}
+
+	/**
+	 * Stop the scan in progress, if any, keeping the last stored report.
+	 */
+	public function cancel_refresh(): void {
+		$state = get_option( self::SCAN_OPTION );
+		if ( is_array( $state ) ) {
+			$this->abandon_refresh( $state );
+			return;
+		}
+		delete_option( self::SCAN_OPTION );
+	}
+
+	/**
+	 * 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.
+	 * 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.
+	 */
+	private function abandon_refresh( array $state ): void {
+		$stored  = get_option( self::REPORT_OPTION );
+		$scan_id = (string) ( $state['id'] ?? '' );
+		if ( is_array( $stored ) && '' !== $scan_id && ( $stored[ self::REPORT_SCAN_ID ] ?? '' ) === $scan_id ) {
+			$this->keep_tested_rows( $state );
+			delete_option( self::SCAN_OPTION );
+			return;
+		}
+		$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 );
+		}
+		delete_option( self::SCAN_OPTION );
+	}
+
+	/**
+	 * Drop rows the scan did not test, keeping rows saved while it ran.
+	 *
+	 * @param array{had_rows?:array<int,int>,tested?:array<int,int>,rows_as_of?:float} $state Scan progress.
+	 */
+	private function keep_tested_rows( array $state ): void {
+		ProductFailures::keep_only(
+			array_map( 'intval', (array) ( $state['had_rows'] ?? array() ) ),
+			array_map( 'intval', (array) ( $state['tested'] ?? array() ) ),
+			isset( $state['rows_as_of'] ) ? (float) $state['rows_as_of'] : null
 		);
-		ProductFailures::keep_only( $had_rows, $tested );
-		$report['failures_stored'] = true;
-		update_option( self::REPORT_OPTION, $report, false );
-		unset( $report['shared_gtins'] );
-		return $report;
 	}

 	/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php
index 65fe5f04273..475ee8bd8f3 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductFailures.php
@@ -17,6 +17,11 @@ class ProductFailures {

 	public const META_KEY = '_wc_agent_readiness_failed';

+	/**
+	 * When a product's rows were last written. Hidden from the editor, and not a check value.
+	 */
+	public const WRITTEN_META = '_wc_agent_readiness_written_at';
+
 	/**
 	 * The value every checked product has, passing or not.
 	 */
@@ -42,10 +47,13 @@ class ProductFailures {
 	/**
 	 * Store what a product fails, writing only what changed.
 	 *
-	 * @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 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.
 	 */
-	public static function store( int $product_id, array $failures ): void {
+	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 ) ) );
 		foreach ( ProductScan::statuses( array_values( $failures ) ) as $channel => $status ) {
 			if ( ProductScan::COMPLETE !== $status ) {
@@ -60,6 +68,10 @@ 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 ) ) );
+		}
 	}

 	/**
@@ -80,6 +92,7 @@ class ProductFailures {
 	public static function forget( int $product_id ): void {
 		unset( self::$counts[ get_current_blog_id() ] );
 		delete_post_meta( $product_id, self::META_KEY );
+		delete_post_meta( $product_id, self::WRITTEN_META );
 	}

 	/**
@@ -105,18 +118,40 @@ class ProductFailures {

 	/**
 	 * Remove the rows of products a scan didn't test, such as those now hidden from the catalog.
-	 * $had_rows is taken before the scan, so a product that stores rows during the scan keeps them.
+	 * Rows written at or after $written_after stay: a product skipped by its batch can be saved again before the scan finishes.
 	 *
-	 * @param array<int, int> $had_rows Product ids that had rows when the scan started.
-	 * @param array<int, int> $tested   Product ids the scan tested.
+	 * @param array<int, int> $had_rows      Product ids that had rows when the scan started.
+	 * @param array<int, int> $tested        Product ids the scan tested.
+	 * @param float|null      $written_after Unix time the scan started, or null to drop every untested id.
 	 */
-	public static function keep_only( array $had_rows, array $tested ): void {
+	public static function keep_only( array $had_rows, array $tested, ?float $written_after = null ): void {
 		unset( self::$counts[ get_current_blog_id() ] );
-		foreach ( array_diff( $had_rows, $tested ) as $product_id ) {
+		$drop = array_map( 'intval', array_diff( $had_rows, $tested ) );
+		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 );
 		}
 	}

+	/**
+	 * Products whose rows were written at or after a scan started.
+	 *
+	 * @param float $after Unix time.
+	 * @return array<int, int>
+	 */
+	private static function ids_written_since( float $after ): array {
+		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 );
+	}
+
 	/**
 	 * How many products have each value. Read once per request per site: the report and the settings page both ask.
 	 *
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php
index 4e94356691f..25f7d00d3a6 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php
@@ -34,9 +34,10 @@ class ProductSales {

 	/**
 	 * Net sales by product id and by variation id, their total, the number of orders, and whether
-	 * Analytics holds the store's orders for the period, or null while Analytics is off.
+	 * Analytics holds the store's orders for the period, or null while Analytics is off. `since` is
+	 * the period's start, for reading the same period again for some products with for_products().
 	 *
-	 * @return array{days:int,orders:int,imported:bool,total:float,by_product:array<int,float>,by_variation:array<int,float>}|null
+	 * @return array{days:int,since:string,orders:int,imported:bool,total:float,by_product:array<int,float>,by_variation:array<int,float>}|null
 	 */
 	public function last_days(): ?array {
 		global $wpdb;
@@ -49,14 +50,12 @@ class ProductSales {
 		$start    = new \DateTimeImmutable( '-' . self::DAYS . ' days', wp_timezone() );
 		$since    = $start->format( 'Y-m-d H:i:s' );
 		$excluded = self::excluded_statuses();
-		// A filter may leave nothing to exclude, and `NOT IN ()` is not valid SQL.
-		$not_in = array() === $excluded ? '' : 'AND stats.status NOT IN ( ' . implode( ', ', array_fill( 0, count( $excluded ), '%s' ) ) . ' )';
-		$lookup = $wpdb->prefix . 'wc_order_product_lookup';
-		$stats  = $wpdb->prefix . 'wc_order_stats';
+		$stats    = $wpdb->prefix . 'wc_order_stats';
+		$not_in   = self::not_in( $excluded );

 		// Count first so an Analytics import that commits between the two reads cannot make
 		// the order total cover revenue that this request never saw.
-		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Table names from $wpdb, placeholders built for the excluded statuses; the scan runs this once, in the background.
+		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Table name from $wpdb, placeholders built for the excluded statuses; the scan runs this once, in the background.
 		$orders = (int) $wpdb->get_var(
 			$wpdb->prepare(
 				"SELECT COUNT( DISTINCT stats.order_id )
@@ -65,36 +64,92 @@ class ProductSales {
 				array_merge( array( $since ), $excluded )
 			)
 		);
-		$rows   = $wpdb->get_results(
+		// phpcs:enable
+		$sales = self::revenue( $since, $excluded, null );
+
+		return array(
+			'days'         => self::DAYS,
+			'since'        => $since,
+			'orders'       => $orders,
+			'imported'     => self::is_imported( $orders, self::store_orders( $start, $excluded ) ),
+			'total'        => max( 0.0, array_sum( $sales['by_product'] ) ),
+			'by_product'   => $sales['by_product'],
+			'by_variation' => $sales['by_variation'],
+		);
+	}
+
+	/**
+	 * Net sales of some products and their variations since a date from last_days(), so a scan
+	 * in batches reads one batch's sales instead of keeping the whole store's.
+	 *
+	 * @param array<int, int> $product_ids Product ids.
+	 * @param string          $since       Period start, as last_days() gave it.
+	 * @return array{by_product:array<int,float>,by_variation:array<int,float>}
+	 */
+	public function for_products( array $product_ids, string $since ): array {
+		return self::revenue( $since, self::excluded_statuses(), $product_ids );
+	}
+
+	/**
+	 * Net sales by product and by variation since a date, for every product or only some.
+	 *
+	 * @param string               $since       Period start, in the site's time zone.
+	 * @param array<int, string>   $excluded    Order statuses Analytics leaves out.
+	 * @param array<int, int>|null $product_ids Product ids, or null for every product.
+	 * @return array{by_product:array<int,float>,by_variation:array<int,float>}
+	 *
+	 * @throws \RuntimeException When the sales query fails.
+	 */
+	private static function revenue( string $since, array $excluded, ?array $product_ids ): array {
+		global $wpdb;
+
+		$by_product   = array();
+		$by_variation = array();
+		if ( array() === $product_ids ) {
+			return compact( 'by_product', 'by_variation' );
+		}
+		$lookup   = $wpdb->prefix . 'wc_order_product_lookup';
+		$stats    = $wpdb->prefix . 'wc_order_stats';
+		$not_in   = self::not_in( $excluded );
+		$products = null === $product_ids ? '' : 'AND lookup.product_id IN ( ' . implode( ', ', array_fill( 0, count( $product_ids ), '%d' ) ) . ' )';
+
+		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Table names from $wpdb, placeholders built for the statuses and product ids; the scan reads this in the background.
+		$wpdb->last_error = '';
+		$rows             = $wpdb->get_results(
 			$wpdb->prepare(
 				"SELECT lookup.product_id, lookup.variation_id, SUM( lookup.product_net_revenue ) AS revenue
 				FROM {$lookup} AS lookup
 				INNER JOIN {$stats} AS stats ON stats.order_id = lookup.order_id
-				WHERE lookup.date_created >= %s {$not_in}
+				WHERE lookup.date_created >= %s {$not_in} {$products}
 				GROUP BY lookup.product_id, lookup.variation_id",
-				array_merge( array( $since ), $excluded )
+				array_merge( array( $since ), $excluded, array_map( 'intval', $product_ids ?? array() ) )
 			),
 			ARRAY_A
 		);
 		// phpcs:enable
+		$error = self::db_error();
+		if ( ! is_array( $rows ) || '' !== $error ) {
+			throw new \RuntimeException( esc_html( rtrim( 'Agent readiness sales query failed. ' . $error ) ) );
+		}

-		$by_product   = array();
-		$by_variation = array();
-		foreach ( is_array( $rows ) ? $rows : array() as $row ) {
+		foreach ( $rows as $row ) {
 			$product_id                = (int) $row['product_id'];
 			$by_product[ $product_id ] = ( $by_product[ $product_id ] ?? 0.0 ) + (float) $row['revenue'];
 			if ( (int) $row['variation_id'] > 0 ) {
 				$by_variation[ (int) $row['variation_id'] ] = (float) $row['revenue'];
 			}
 		}
-		return array(
-			'days'         => self::DAYS,
-			'orders'       => $orders,
-			'imported'     => self::is_imported( $orders, self::store_orders( $start, $excluded ) ),
-			'total'        => max( 0.0, array_sum( $by_product ) ),
-			'by_product'   => $by_product,
-			'by_variation' => $by_variation,
-		);
+		return compact( 'by_product', 'by_variation' );
+	}
+
+	/**
+	 * The status filter, with one placeholder per excluded status. Empty when a filter leaves
+	 * nothing to exclude, since `NOT IN ()` is not valid SQL.
+	 *
+	 * @param array<int, string> $excluded Order statuses Analytics leaves out.
+	 */
+	private static function not_in( array $excluded ): string {
+		return array() === $excluded ? '' : 'AND stats.status NOT IN ( ' . implode( ', ', array_fill( 0, count( $excluded ), '%s' ) ) . ' )';
 	}

 	/**
@@ -176,4 +231,14 @@ class ProductSales {
 		}
 		return array_values( array_unique( $statuses ) );
 	}
+
+	/**
+	 * The last database error, read fresh after a query.
+	 *
+	 * @phpstan-impure
+	 */
+	private static function db_error(): string {
+		global $wpdb;
+		return is_string( $wpdb->last_error ) ? $wpdb->last_error : '';
+	}
 }
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
index 54d991e7c41..851eefff3ec 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
@@ -123,7 +123,7 @@ class ProductScan {
 	private bool $truncated = false;

 	/**
-	 * Called with each product id and its failures during evaluate_each(). Cleared when that pass ends.
+	 * Called with each product id and its failures during test(). Cleared when that batch ends.
 	 *
 	 * @var callable|null
 	 */
@@ -153,103 +153,161 @@ class ProductScan {
 	}

 	/**
-	 * Test every covered product, calling $on_tested with each product id and its failures.
+	 * Clear the totals, count the catalog and list the products to test: newest change first,
+	 * up to PRODUCT_LIMIT. The list is read once, so a scan in batches tests the same products
+	 * a single pass would, even when products change between batches.
 	 *
 	 * @since 11.4.0
 	 *
-	 * @param array<string, ReadinessRule>                                    $rules         Rules by id.
-	 * @param array<string, array<string, array{field:string,effect:string}>> $channel_rules Channel map by rule id.
-	 * @param int                                                             $ids_limit     Product ids kept per rule.
-	 * @param callable                                                        $on_tested     Called with each product id and its failures.
-	 */
-	public function evaluate_each( array $rules, array $channel_rules, int $ids_limit, callable $on_tested ): void {
-		$this->tested_callback = $on_tested;
-		try {
-			$this->evaluate( $rules, $channel_rules, $ids_limit );
-		} finally {
-			$this->tested_callback = null;
-		}
-	}
-
-	/**
-	 * Test every covered product against the rules.
+	 * @return array<int, int> Product ids.
 	 *
-	 * @param array<string, ReadinessRule>                                    $rules         Rules by id.
-	 * @param array<string, array<string, array{field:string,effect:string}>> $channel_rules Channel map by rule id.
-	 * @param int                                                             $ids_limit     Product ids kept per rule.
+	 * @throws \RuntimeException When the product list query fails.
 	 */
-	public function evaluate( array $rules, array $channel_rules, int $ids_limit ): void {
-		$this->results             = array_fill_keys(
-			array_keys( $rules ),
-			array(
-				'count'       => 0,
-				'product_ids' => array(),
-				'sales'       => 0.0,
-			)
-		);
+	public function start(): array {
+		$this->results             = array();
 		$this->products            = 0;
 		$this->statuses            = array();
-		$this->truncated           = false;
 		$this->hidden_from_catalog = self::count_published( self::count_query( self::COUNT_HIDDEN ) );
 		$this->available           = self::count_published( self::count_query( self::COUNT_AVAILABLE ) );
 		$this->unsupported_types   = self::count_published( self::count_query( self::COUNT_UNSUPPORTED ) );

-		$flush_runtime_cache = wp_cache_supports( 'flush_runtime' );
-		$page                = 1;
-		do {
-			$query = new \WP_Query(
-				array(
-					'post_type'      => 'product',
-					'post_status'    => 'publish',
-					'posts_per_page' => self::BATCH_SIZE,
-					'paged'          => $page,
-					'fields'         => 'ids',
-					'orderby'        => array(
-						'modified' => 'DESC',
-						'ID'       => 'DESC',
-					),
-					'no_found_rows'  => true,
-					'tax_query'      => self::count_query( self::COUNT_AVAILABLE ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
-				)
-			);
+		global $wpdb;
+		// An ids query returns before posts_results runs, so read the error the query left instead.
+		$wpdb->last_error = '';
+		$query            = new \WP_Query(
+			array(
+				'post_type'      => 'product',
+				'post_status'    => 'publish',
+				// One more than the limit, to tell a catalog cut short from one that fits.
+				'posts_per_page' => self::PRODUCT_LIMIT + 1,
+				'fields'         => 'ids',
+				'orderby'        => array(
+					'modified' => 'DESC',
+					'ID'       => 'DESC',
+				),
+				'no_found_rows'  => true,
+				// A failed query would be cached as an empty list, and the next scan would read it without an error.
+				'cache_results'  => false,
+				'tax_query'      => self::count_query( self::COUNT_AVAILABLE ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
+			)
+		);
+		$query_failed = '' !== self::db_error();

-			$product_ids = array_map(
-				static function ( $post ): int {
-					return $post instanceof \WP_Post ? $post->ID : (int) $post;
-				},
-				$query->posts
-			);
-			$batch_count = count( $product_ids );
-			/**
-			 * Fires after one batch of product ids has been read, before those products are tested.
-			 * A product created here is not in this batch, so the scan does not replace its rows.
-			 *
-			 * An ids query returns before `posts_results` and `the_posts`, so those filters never see this query.
-			 *
-			 * @since 11.4.0
-			 *
-			 * @param int[] $product_ids Product ids in this batch.
-			 */
-			do_action( 'woocommerce_agent_readiness_scan_batch', $product_ids );
-			self::prime_related( $product_ids );
+		$product_ids = array_map(
+			static function ( $post ): int {
+				return $post instanceof \WP_Post ? $post->ID : (int) $post;
+			},
+			is_array( $query->posts ) ? $query->posts : array()
+		);
+		// Only a database error is a failed list, whatever the counts say: they read 0 when their own queries fail.
+		// An empty success publishes a scan of what is left.
+		if ( $query_failed ) {
+			throw new \RuntimeException( 'Agent readiness could not list products to scan.' );
+		}
+		$this->truncated = count( $product_ids ) > self::PRODUCT_LIMIT;
+		return array_slice( $product_ids, 0, self::PRODUCT_LIMIT );
+	}
+
+	/**
+	 * Test one batch of products from start() and add them to the totals.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param array<int, int>                                                 $product_ids         Product ids, at most BATCH_SIZE.
+	 * @param array<string, ReadinessRule>                                    $rules               Rules by id.
+	 * @param array<string, array<string, array{field:string,effect:string}>> $channel_rules       Channel map by rule id.
+	 * @param int                                                             $ids_limit           Product ids kept per rule.
+	 * @param callable|null                                                   $on_tested           Called with each product id and its failures.
+	 * @param bool                                                            $skip_unloadable     When true, products that fail to load are skipped instead of failing the batch (last scan attempt).
+	 * @param array<int, int>                                                 $skipped_unloadable  Filled with ids skipped when $skip_unloadable is true.
+	 *
+	 * @throws \RuntimeException When a selected product still exists but cannot be loaded, and $skip_unloadable is false.
+	 */
+	public function test( array $product_ids, array $rules, array $channel_rules, int $ids_limit, ?callable $on_tested = null, bool $skip_unloadable = false, array &$skipped_unloadable = array() ): void {
+		/**
+		 * Fires after one batch of product ids has been read, before those products are tested.
+		 * A product created here is not in this batch, so the scan does not replace its rows.
+		 *
+		 * @since 11.4.0
+		 *
+		 * @param int[] $product_ids Product ids in this batch.
+		 */
+		do_action( 'woocommerce_agent_readiness_scan_batch', $product_ids );
+		self::prime_related( $product_ids );
+		$this->tested_callback = $on_tested;
+		try {
 			foreach ( $product_ids as $product_id ) {
-				if ( self::PRODUCT_LIMIT === $this->products ) {
-					$this->truncated = true;
-					break 2;
-				}
 				$product = wc_get_product( $product_id );
-				if ( $product ) {
-					$this->record( $product, $rules, $channel_rules, $ids_limit );
+				if ( $product instanceof \WC_Product ) {
+					// Skip products that left the eligible set between start() and this batch.
+					if ( self::covers( $product ) ) {
+						$this->record( $product, $rules, $channel_rules, $ids_limit );
+					}
+					continue;
+				}
+				// Factory returned false. A missing post is gone; a product post that still
+				// exists failed to load. Retry the batch unless this is the last attempt.
+				if ( 'product' === get_post_type( $product_id ) ) {
+					if ( $skip_unloadable ) {
+						$skipped_unloadable[] = (int) $product_id;
+						continue;
+					}
+					throw new \RuntimeException(
+						sprintf( 'Agent readiness could not load product %d to scan.', (int) $product_id )
+					);
 				}
 			}
+		} finally {
+			$this->tested_callback = null;
+		}

-			// A full-catalog read would otherwise keep every product's post, meta and terms in the request's object cache.
-			if ( $flush_runtime_cache ) {
-				wp_cache_flush_runtime();
-			}
-			++$page;
-		} while ( self::BATCH_SIZE === $batch_count );
-		$this->tested_callback = null;
+		// A full-catalog read would otherwise keep every product's post, meta and terms in the request's object cache.
+		if ( wp_cache_supports( 'flush_runtime' ) ) {
+			wp_cache_flush_runtime();
+		}
+	}
+
+	/**
+	 * The totals so far, to carry a scan in batches from one background action to the next.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @return array<string, mixed>
+	 */
+	public function state(): array {
+		return array(
+			'results'             => $this->results,
+			'products'            => $this->products,
+			'statuses'            => $this->statuses,
+			'available'           => $this->available,
+			'hidden_from_catalog' => $this->hidden_from_catalog,
+			'unsupported_types'   => $this->unsupported_types,
+			'truncated'           => $this->truncated,
+			// Read once per scan; past the limit, each batch reads them again rather than storing them all.
+			'shared_gtins'        => null === $this->shared_gtins ? null : $this->shared_gtins(),
+		);
+	}
+
+	/**
+	 * A scan that goes on from state().
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param array<string, mixed> $state Totals from state().
+	 */
+	public static function from_state( array $state ): self {
+		$scan                      = new self();
+		$scan->results             = (array) ( $state['results'] ?? array() );
+		$scan->products            = (int) ( $state['products'] ?? 0 );
+		$scan->statuses            = (array) ( $state['statuses'] ?? array() );
+		$scan->available           = (int) ( $state['available'] ?? 0 );
+		$scan->hidden_from_catalog = (int) ( $state['hidden_from_catalog'] ?? 0 );
+		$scan->unsupported_types   = (int) ( $state['unsupported_types'] ?? 0 );
+		$scan->truncated           = ! empty( $state['truncated'] );
+		if ( is_array( $state['shared_gtins'] ?? null ) ) {
+			$scan->use_shared_gtins( $state['shared_gtins'] );
+		}
+		return $scan;
 	}

 	/**
@@ -402,7 +460,7 @@ class ProductScan {
 	}

 	/**
-	 * Sales to add up per rule over the next evaluate(): each failing product adds its own, or
+	 * Sales to add up per rule over the next test(): each failing product adds its own, or
 	 * only its failing variations' when the check names them.
 	 *
 	 * @param array<int, float> $by_product   Net sales by product id.
@@ -646,4 +704,14 @@ class ProductScan {
 			$this->statuses[ $channel ][ $status ] = ( $this->statuses[ $channel ][ $status ] ?? 0 ) + 1;
 		}
 	}
+
+	/**
+	 * The last database error, read fresh after a query.
+	 *
+	 * @phpstan-impure
+	 */
+	private static function db_error(): string {
+		global $wpdb;
+		return is_string( $wpdb->last_error ) ? $wpdb->last_error : '';
+	}
 }
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index d8e004aa0d7..a38c9698e7b 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -184,7 +184,9 @@ Per check, `channels` maps a channel id to the feed field and the effect, the sa

 ## Background scan and REST

-"Check your store" on WooCommerce > Sales readiness, or `POST wc/v3/agent-readiness/scan`, queues the scan in Action Scheduler (`ScheduledScan`). The report is stored in the `woocommerce_agent_readiness_report` option (not autoloaded). Each run schedules the next one a day later, before scanning, so a failed scan doesn't stop the daily refresh; a run that finds the feature disabled does. If a queued scan still hasn't started 10 minutes after it was due and no other scheduled action has finished, failed or started in that time (Action Scheduler isn't running), the Sales readiness page says so and the scan stays queued. The scan never runs in a page or REST request; splitting the product pass into one action per batch is WOOAI-1661.
+"Check your store" on WooCommerce > Sales readiness, or `POST wc/v3/agent-readiness/scan`, queues the scan in Action Scheduler (`ScheduledScan`). The report is stored in the `woocommerce_agent_readiness_report` option (not autoloaded). Each run schedules the next one a day later, before scanning, so a failed scan doesn't stop the daily refresh; a run that finds the feature disabled does. If a queued scan still hasn't started 10 minutes after it was due and no other scheduled action has finished, failed or started in that time (Action Scheduler isn't running), the Sales readiness page says so and the scan stays queued. The scan never runs in a page or REST request.
+
+A scan runs as a chain of actions (`NEXT_HOOK`, with the scan's id), so no action tests more than one batch of products. The first lists the products to test, newest change first, and stores that list with the totals in the `woocommerce_agent_readiness_scan` option (not autoloaded). Starting still reads the store's 90-day sales once (for the total, whether ranking applies, and the best seller for page checks); each later batch reads only its own products' sales, so the whole store's sales map is never kept between actions. Each action tests the next batch of 200, saves the totals and queues the next; the last builds the report, with the store output checks, and stores it. Before testing, an action queues a retry RETRY_AFTER (10 minutes) later, which it removes when it finishes, so a batch that ends early, as on a timeout, is tried again from the last finished batch. After MAX_ATTEMPTS (3) tries of the same batch, the scan stops and the last report stays. Giving up, cancelling, or replacing a scan removes failure rows it wrote for products the last report never covered, so the Products list stays aligned with that report. A new request (or the daily run) replaces a scan in progress and starts over; the replaced scan's actions change nothing. With the feature off, the next action stops the scan. `refresh_report()` runs the same steps in one request.

 On a store with 11,000 products, a scan (stopping at 5,000) took about 4 seconds and 144 MB. A product saved since the scan is already reflected in the counts, as described under Failures per product.

@@ -192,7 +194,7 @@ On a store with 11,000 products, a scan (stopping at 5,000) took about 4 seconds

 The same shape is meant for every consumer: WooCommerce > Sales readiness and AI shopping, an outside scan of a store, and extensions that rank the findings by sales or offer fixes. Check and channel ids are stable keys.

-The scan walks published simple and variable products not set to Hidden in batches of 200, most recently modified first, primes meta, terms, images and variations per batch, and stops at 5,000 products.
+The scan walks published simple and variable products not set to Hidden in batches of 200, most recently modified first, primes meta, terms, images and variations per batch, and stops at 5,000 products. The list of products is read once when the scan starts, so a product changed while it runs neither moves nor gets tested twice; a product saved meanwhile stores its own results, as described under Failures per product.

 ## Abilities

diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php b/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
index 9aaf16956f7..63d6e06b078 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
@@ -34,6 +34,16 @@ class ScheduledScan implements RegisterHooksInterface {

 	public const DAILY_HOOK = 'woocommerce_agent_readiness_daily_scan';

+	/**
+	 * Hook that tests the next batch of a scan, with the scan's id.
+	 */
+	public const NEXT_HOOK = 'woocommerce_agent_readiness_scan_next';
+
+	/**
+	 * Seconds before a batch that ended early, as on a timeout, is tried again.
+	 */
+	public const RETRY_AFTER = 10 * MINUTE_IN_SECONDS;
+
 	public const GROUP = 'woocommerce-agent-readiness';

 	public const STALLED_AFTER = 10 * MINUTE_IN_SECONDS;
@@ -87,13 +97,15 @@ class ScheduledScan implements RegisterHooksInterface {
 	public function register(): void {
 		add_action( self::RUN_NOW_HOOK, array( $this, 'run' ) );
 		add_action( self::DAILY_HOOK, array( $this, 'run' ) );
+		add_action( self::NEXT_HOOK, array( $this, 'run_batch' ) );
 	}

 	/**
 	 * Queue a scan unless one is already waiting or running.
 	 */
 	public function queue(): void {
-		if ( ! $this->is_pending() ) {
+		// A scan already testing batches is replaced: the new one starts over with the current catalog.
+		if ( ! $this->is_starting() ) {
 			// A single action due now rather than an async one, which has no date to tell a stalled scan by.
 			// Unique, so two requests that both found nothing pending still queue one scan.
 			as_schedule_single_action( time(), self::RUN_NOW_HOOK, array(), self::GROUP, true );
@@ -101,10 +113,17 @@ class ScheduledScan implements RegisterHooksInterface {
 	}

 	/**
-	 * Whether a requested scan has not finished yet, or the daily scan started running in the
-	 * last RUNNING_FOR seconds. The next daily scan, still waiting for its date, doesn't count.
+	 * Whether a scan has not finished yet: requested, testing batches, or a daily scan that
+	 * started in the last RUNNING_FOR seconds. The next daily scan, still waiting for its date, doesn't count.
 	 */
 	public function is_pending(): bool {
+		return $this->is_starting() || as_has_scheduled_action( self::NEXT_HOOK, null, self::GROUP );
+	}
+
+	/**
+	 * Whether a requested scan has not started its batches yet, or the daily scan started running in the last RUNNING_FOR seconds.
+	 */
+	private function is_starting(): bool {
 		if ( ActionSchedulerUtil::has_scheduled_action( self::RUN_NOW_HOOK, array(), self::GROUP ) ) {
 			return true;
 		}
@@ -133,6 +152,7 @@ class ScheduledScan implements RegisterHooksInterface {
 		}
 		// The timestamp of a pending action; true while it runs.
 		$due = as_next_scheduled_action( self::RUN_NOW_HOOK, array(), self::GROUP );
+		$due = false === $due ? as_next_scheduled_action( self::NEXT_HOOK, null, self::GROUP ) : $due;
 		if ( ! is_int( $due ) || time() - $due <= self::STALLED_AFTER ) {
 			return false;
 		}
@@ -149,7 +169,8 @@ class ScheduledScan implements RegisterHooksInterface {
 	}

 	/**
-	 * Schedule the next daily run, fetch the rules file, then run the scan and store the report.
+	 * Schedule the next daily run, fetch the rules file, then start the scan, replacing one in progress.
+	 * Each batch of products runs in its own action, then the last stores the report.
 	 *
 	 * @internal
 	 */
@@ -161,6 +182,30 @@ class ScheduledScan implements RegisterHooksInterface {
 		as_schedule_single_action( time() + DAY_IN_SECONDS, self::DAILY_HOOK, array(), self::GROUP );

 		$this->remote_rules->refresh( array_keys( $this->agent_readiness->get_default_rules() ) );
-		$this->agent_readiness->refresh_report();
+		as_unschedule_all_actions( self::NEXT_HOOK );
+		as_schedule_single_action( time(), self::NEXT_HOOK, array( $this->agent_readiness->start_refresh() ), self::GROUP );
+	}
+
+	/**
+	 * Test one batch of a scan, then queue the next, or store the report after the last.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $chain Scan id. Untyped, so a stray call without one does nothing instead of failing.
+	 */
+	public function run_batch( $chain = '' ): void {
+		$chain = is_string( $chain ) ? $chain : '';
+		if ( ! $this->features_controller->feature_is_enabled( AgenticCommerceSettings::FEATURE_ID ) ) {
+			$this->agent_readiness->cancel_refresh();
+			as_unschedule_all_actions( self::NEXT_HOOK );
+			return;
+		}
+		// Runs only if this action ends early, as on a timeout, and goes on from the last finished batch.
+		as_schedule_single_action( time() + self::RETRY_AFTER, self::NEXT_HOOK, array( $chain ), self::GROUP );
+		$more = $this->agent_readiness->continue_refresh( $chain );
+		as_unschedule_all_actions( self::NEXT_HOOK, array( $chain ), self::GROUP );
+		if ( $more ) {
+			as_schedule_single_action( time(), self::NEXT_HOOK, array( $chain ), self::GROUP );
+		}
 	}
 }
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
index 2b7b62b3969..6b1099541e8 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
@@ -767,7 +767,7 @@ class Checkout extends AbstractCartRoute {
 			array(
 				'order_object'           => $order,
 				'processed_with_payment' => $order->needs_payment() ? 'yes' : 'no',
-				'payment_status'         => $payment_result->status,
+				'payment_status'         => $payment_result->get_status(),
 			),
 			true
 		);
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php
index 024066ba7da..1bd69c40e98 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/AbstractCartRoute.php
@@ -16,8 +16,8 @@ use Automattic\WooCommerce\StoreApi\Utilities\Ucp\Utils;
 /**
  * Shared behaviour of the UCP cart routes.
  *
- * Inherits session binding, cart loading and draft order sync from the Store API cart
- * route. Adds the UCP envelope, and keys the session off the path instead of a header.
+ * Inherits session binding and cart loading from the Store API cart route. Adds the UCP
+ * envelope, and keys the session off the path instead of a header.
  *
  * Writes are last-wins, as for every Store API cart: the session row is read when the
  * request starts and written whole at shutdown, with no lock or version check. Two
@@ -150,27 +150,6 @@ abstract class AbstractCartRoute extends StoreApiCartRoute {
 		return $response;
 	}

-	/**
-	 * Sync the draft order with the cart after a write, unless it was handed off for payment.
-	 *
-	 * The buyer may be paying a pending or failed order, and a save would put this request's copy over theirs.
-	 *
-	 * @param \WP_REST_Request $request Request object.
-	 *
-	 * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
-	 *
-	 * @return void
-	 */
-	protected function cart_updated( \WP_REST_Request $request ) {
-		$order = $this->get_draft_order();
-
-		if ( $order && ! $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {
-			return;
-		}
-
-		parent::cart_updated( $request );
-	}
-
 	/**
 	 * Put the request's cart token slot back the way it was found.
 	 *
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/CheckoutTrait.php b/plugins/woocommerce/src/StoreApi/Utilities/CheckoutTrait.php
index bf8e5aaddef..298103b47a0 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/CheckoutTrait.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/CheckoutTrait.php
@@ -35,7 +35,7 @@ trait CheckoutTrait {
 		];

 		if ( isset( $item->payment_result ) && $item->payment_result instanceof PaymentResult ) {
-			$response->set_status( $status_codes[ $item->payment_result->status ] ?? 200 );
+			$response->set_status( $status_codes[ $item->payment_result->get_status() ] ?? 200 );
 		}

 		return $response;
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
index 8af09cdeff5..3063195d50a 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
@@ -99,10 +99,39 @@ class ProductFailuresTest extends WC_Unit_Test_Case {
 		$this->assertSame( 3, $this->check_count( 'missing_images' ) );
 	}

+	/**
+	 * @testdox A product that becomes hidden after start() is not recorded and its old rows are cleared.
+	 */
+	public function test_product_hidden_between_start_and_batch_is_cleared(): void {
+		$product = WC_Helper_Product::create_simple_product();
+		$id      = $product->get_id();
+		$this->readiness->refresh_report();
+		$this->assertNotEmpty( ProductFailures::for_product( $id ) );
+
+		$hook = static function ( array $product_ids ) use ( $id ): void {
+			if ( ! in_array( $id, array_map( 'intval', $product_ids ), true ) ) {
+				return;
+			}
+			$product = wc_get_product( $id );
+			$product->set_catalog_visibility( 'hidden' );
+			$product->save();
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $hook );
+		try {
+			$this->readiness->refresh_report();
+		} finally {
+			remove_action( 'woocommerce_agent_readiness_scan_batch', $hook );
+		}
+
+		$this->assertSame( array(), ProductFailures::for_product( $id ) );
+	}
+
 	/**
 	 * @testdox A product that stores rows while the scan runs keeps them.
 	 */
 	public function test_product_stored_during_scan_keeps_its_rows(): void {
+		// A product to scan, so there is a batch for the new product to be saved during.
+		WC_Helper_Product::create_simple_product();
 		$during_id = 0;
 		$hook      = static function () use ( &$during_id ) {
 			if ( 0 !== $during_id ) {
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
index d22b93da003..7fa88d4ac5c 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ScheduledScanTest.php
@@ -4,8 +4,11 @@ declare( strict_types = 1 );
 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\AgentReadiness\RemoteRules;
 use Automattic\WooCommerce\Internal\AgentReadiness\ScheduledScan;
+use Automattic\WooCommerce\Internal\Caches\ProductCache;
 use WC_Helper_Product;
 use WC_Unit_Test_Case;

@@ -33,6 +36,8 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
 		delete_option( AgentReadiness::REPORT_OPTION );
 		as_unschedule_all_actions( ScheduledScan::RUN_NOW_HOOK );
 		as_unschedule_all_actions( ScheduledScan::DAILY_HOOK );
+		as_unschedule_all_actions( ScheduledScan::NEXT_HOOK );
+		delete_option( AgentReadiness::SCAN_OPTION );
 		$this->sut = wc_get_container()->get( ScheduledScan::class );
 	}

@@ -42,6 +47,7 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
 	public function tearDown(): void {
 		as_unschedule_all_actions( ScheduledScan::RUN_NOW_HOOK );
 		as_unschedule_all_actions( ScheduledScan::DAILY_HOOK );
+		as_unschedule_all_actions( ScheduledScan::NEXT_HOOK );
 		delete_option( 'woocommerce_feature_agent_readiness_enabled' );
 		parent::tearDown();
 	}
@@ -195,6 +201,7 @@ class ScheduledScanTest extends WC_Unit_Test_Case {

 		$this->sut->run();
 		$this->sut->run();
+		$this->run_batches();

 		$report = wc_get_container()->get( AgentReadiness::class )->get_cached_report();
 		$this->assertSame( 1, $report['products'] );
@@ -226,6 +233,7 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
 		WC_Helper_Product::create_simple_product();

 		$this->sut->run();
+		$this->run_batches();
 		remove_filter( 'pre_http_request', $answer );
 		delete_option( RemoteRules::OPTION );

@@ -250,6 +258,7 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
 		WC_Helper_Product::create_simple_product();

 		$this->sut->run();
+		$this->run_batches();
 		remove_filter( 'pre_http_request', $fail );

 		$report = wc_get_container()->get( AgentReadiness::class )->get_cached_report();
@@ -291,6 +300,554 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
 		$this->assertFalse( as_has_scheduled_action( ScheduledScan::DAILY_HOOK ) );
 	}

+	/**
+	 * Run the scan's batch actions as Action Scheduler would, until the scan stores its report.
+	 *
+	 * @return int Batch actions run.
+	 */
+	private function run_batches(): int {
+		$runs = 0;
+		while ( $runs < 20 && is_array( get_option( AgentReadiness::SCAN_OPTION ) ) ) {
+			$this->sut->run_batch( get_option( AgentReadiness::SCAN_OPTION )['id'] );
+			++$runs;
+		}
+		return $runs;
+	}
+
+	/**
+	 * Create published simple products quickly, without images, so they fail the image check.
+	 *
+	 * @param int $count Products to create.
+	 * @return array<int, int> Product ids.
+	 */
+	private function create_products( int $count ): array {
+		$ids = array();
+		for ( $i = 0; $i < $count; $i++ ) {
+			$id = wp_insert_post(
+				array(
+					'post_type'   => 'product',
+					'post_status' => 'publish',
+					'post_title'  => 'Product ' . $i,
+				)
+			);
+			wp_set_object_terms( $id, 'simple', 'product_type' );
+			update_post_meta( $id, '_regular_price', '10' );
+			update_post_meta( $id, '_price', '10' );
+			$ids[] = $id;
+		}
+		return $ids;
+	}
+
+	/**
+	 * @testdox A scan tests one batch per action, then stores the same report a single pass gives.
+	 */
+	public function test_scan_runs_one_batch_per_action_and_matches_a_single_pass(): void {
+		$this->create_products( ProductScan::BATCH_SIZE + 1 );
+		$single  = wc_get_container()->get( AgentReadiness::class )->get_report();
+		$batches = array();
+		$count   = static function ( array $product_ids ) use ( &$batches ): void {
+			$batches[] = count( $product_ids );
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $count );
+
+		$this->sut->run();
+		$this->assertTrue( $this->sut->is_pending(), 'A scan testing batches is pending' );
+		$runs = $this->run_batches();
+		remove_action( 'woocommerce_agent_readiness_scan_batch', $count );
+
+		$this->assertSame( array( ProductScan::BATCH_SIZE, 1 ), $batches, 'One batch per action' );
+		$this->assertSame( 3, $runs, 'Two batches, then the report' );
+		$this->assertFalse( $this->sut->is_pending() );
+		$this->assertFalse( as_has_scheduled_action( ScheduledScan::NEXT_HOOK ), 'No retry is left behind' );
+		$report = wc_get_container()->get( AgentReadiness::class )->get_cached_report();
+		$this->assertSame( ProductScan::BATCH_SIZE + 1, $report['products'] );
+		foreach ( array( 'products', 'available', 'channels', 'truncated' ) as $key ) {
+			$this->assertSame( $single[ $key ], $report[ $key ], $key );
+		}
+		$this->assertSame( array_column( $single['checks'], 'count', 'id' ), array_column( $report['checks'], 'count', 'id' ) );
+	}
+
+	/**
+	 * @testdox A batch that ends early is tried again from where the last finished batch stopped.
+	 */
+	public function test_stopped_batch_resumes(): void {
+		$this->create_products( ProductScan::BATCH_SIZE + 1 );
+		$this->sut->run();
+		$chain = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		$this->sut->run_batch( $chain );
+		$crash = static function (): void {
+			throw new \RuntimeException( 'Timed out' );
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $crash );
+		// Action Scheduler has started the queued batch, so it is no longer pending.
+		as_unschedule_all_actions( ScheduledScan::NEXT_HOOK );
+
+		try {
+			$this->sut->run_batch( $chain );
+			$this->fail( 'The batch should have stopped' );
+		} catch ( \RuntimeException $e ) {
+			unset( $e );
+		} finally {
+			remove_action( 'woocommerce_agent_readiness_scan_batch', $crash );
+		}
+
+		$retry = as_next_scheduled_action( ScheduledScan::NEXT_HOOK, array( $chain ), ScheduledScan::GROUP );
+		$this->assertIsInt( $retry, 'A retry is queued' );
+		$this->assertGreaterThan( time() + ScheduledScan::RETRY_AFTER / 2, $retry, 'The retry waits for the stopped action to time out' );
+		$this->assertSame( ProductScan::BATCH_SIZE, get_option( AgentReadiness::SCAN_OPTION )['position'], 'The finished batch is kept' );
+
+		$this->run_batches();
+		$this->assertSame( ProductScan::BATCH_SIZE + 1, wc_get_container()->get( AgentReadiness::class )->get_cached_report()['products'] );
+	}
+
+	/**
+	 * @testdox A batch that fails every time ends the scan after MAX_ATTEMPTS, keeping the last report.
+	 */
+	public function test_batch_that_always_fails_gives_up(): void {
+		$this->create_products( 1 );
+		update_option( AgentReadiness::REPORT_OPTION, array( 'products' => 7 ) );
+		$this->sut->run();
+		$crash = static function (): void {
+			throw new \RuntimeException( 'Fatal on this product' );
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $crash );
+		$chain = get_option( AgentReadiness::SCAN_OPTION )['id'];
+
+		for ( $i = 0; $i < AgentReadiness::MAX_ATTEMPTS; $i++ ) {
+			try {
+				$this->sut->run_batch( $chain );
+			} catch ( \RuntimeException $e ) {
+				unset( $e );
+			}
+		}
+		remove_action( 'woocommerce_agent_readiness_scan_batch', $crash );
+		$this->sut->run_batch( $chain );
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertFalse( as_has_scheduled_action( ScheduledScan::NEXT_HOOK, array( $chain ) ), 'No retry is left behind' );
+		$this->assertSame( 7, get_option( AgentReadiness::REPORT_OPTION )['products'] );
+	}
+
+	/**
+	 * @testdox Giving up after a finished batch removes failure rows that batch wrote for products the last report never covered.
+	 */
+	public function test_give_up_drops_failure_rows_the_last_report_did_not_cover(): void {
+		$ids = $this->create_products( ProductScan::BATCH_SIZE + 1 );
+		update_option( AgentReadiness::REPORT_OPTION, array( 'products' => 7 ) );
+		$this->sut->run();
+		$chain = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		$this->sut->run_batch( $chain );
+		// 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' );
+
+		$crash = static function (): void {
+			throw new \RuntimeException( 'Fatal on the next batch' );
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $crash );
+		for ( $i = 0; $i < AgentReadiness::MAX_ATTEMPTS; $i++ ) {
+			try {
+				$this->sut->run_batch( $chain );
+			} catch ( \RuntimeException $e ) {
+				unset( $e );
+			}
+		}
+		remove_action( 'woocommerce_agent_readiness_scan_batch', $crash );
+		$this->sut->run_batch( $chain );
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertSame( array(), ProductFailures::stored( $covered ), 'Rows the abandoned scan added are removed' );
+		$this->assertSame( 7, get_option( AgentReadiness::REPORT_OPTION )['products'] );
+	}
+
+	/**
+	 * @testdox A new scan request during a scan starts over, and the replaced scan's actions do nothing.
+	 */
+	public function test_new_request_restarts_the_scan(): void {
+		$this->create_products( ProductScan::BATCH_SIZE + 1 );
+		$this->sut->run();
+		$first = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		$this->sut->run_batch( $first );
+
+		$this->sut->queue();
+		$this->assertTrue( as_has_scheduled_action( ScheduledScan::RUN_NOW_HOOK ), 'A request during a scan queues a new one' );
+		$this->sut->run();
+		$second = get_option( AgentReadiness::SCAN_OPTION );
+
+		$this->assertNotSame( $first, $second['id'] );
+		$this->assertSame( 0, $second['position'] );
+		$this->assertFalse( as_has_scheduled_action( ScheduledScan::NEXT_HOOK, array( $first ) ), 'The old scan has nothing left to run' );
+		$this->sut->run_batch( $first );
+		$this->assertSame( 0, get_option( AgentReadiness::SCAN_OPTION )['position'], 'The old scan changes nothing' );
+
+		$this->run_batches();
+		$this->assertSame( ProductScan::BATCH_SIZE + 1, wc_get_container()->get( AgentReadiness::class )->get_cached_report()['products'] );
+	}
+
+	/**
+	 * @testdox A batch replaced mid-run does not store the failure rows it collected.
+	 */
+	public function test_replaced_batch_does_not_store_failures(): void {
+		$ids = $this->create_products( ProductScan::BATCH_SIZE + 1 );
+		$this->sut->run();
+		$first   = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		$covered = (int) end( $ids );
+
+		$replace = function (): void {
+			$this->sut->run();
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $replace );
+		$this->sut->run_batch( $first );
+		remove_action( 'woocommerce_agent_readiness_scan_batch', $replace );
+
+		$this->assertNotSame( $first, get_option( AgentReadiness::SCAN_OPTION )['id'] );
+		$this->assertSame( array(), ProductFailures::stored( $covered ), 'The replaced batch stored nothing' );
+	}
+
+	/**
+	 * @testdox A scan replaced while its batch stores rows does not write its progress over the new scan.
+	 */
+	public function test_scan_replaced_during_the_store_loop_keeps_the_new_progress(): void {
+		$this->create_products( ProductScan::BATCH_SIZE + 1 );
+		$this->sut->run();
+		$first = get_option( AgentReadiness::SCAN_OPTION )['id'];
+
+		$replaced = false;
+		$replace  = function ( $meta_id, $object_id, $meta_key ) use ( &$replaced ): void {
+			unset( $meta_id, $object_id );
+			if ( $replaced || ProductFailures::META_KEY !== $meta_key ) {
+				return;
+			}
+			$replaced = true;
+			$this->sut->run();
+		};
+		add_action( 'added_post_meta', $replace, 10, 3 );
+		try {
+			$this->sut->run_batch( $first );
+		} finally {
+			remove_action( 'added_post_meta', $replace, 10 );
+		}
+
+		$state = get_option( AgentReadiness::SCAN_OPTION );
+		$this->assertTrue( $replaced );
+		$this->assertNotSame( $first, $state['id'] );
+		$this->assertSame( 0, $state['position'], 'The new scan has not tested a batch yet' );
+	}
+
+	/**
+	 * @testdox A scan that finds nothing changed writes no product meta.
+	 */
+	public function test_unchanged_scan_writes_no_product_meta(): void {
+		$ids = $this->create_products( 2 );
+		$this->sut->run();
+		$this->run_batches();
+		$this->assertSame( '', get_post_meta( $ids[0], ProductFailures::WRITTEN_META, true ), 'The scan records no write time' );
+
+		$writes = 0;
+		$count  = static function ( $meta_id, $object_id, $meta_key ) use ( &$writes ): void {
+			unset( $meta_id, $object_id );
+			if ( in_array( $meta_key, array( ProductFailures::META_KEY, ProductFailures::WRITTEN_META ), true ) ) {
+				++$writes;
+			}
+		};
+		foreach ( array( 'added_post_meta', 'updated_post_meta', 'deleted_post_meta' ) as $hook ) {
+			add_action( $hook, $count, 10, 3 );
+		}
+		try {
+			$this->sut->run();
+			$this->run_batches();
+		} finally {
+			foreach ( array( 'added_post_meta', 'updated_post_meta', 'deleted_post_meta' ) as $hook ) {
+				remove_action( $hook, $count, 10 );
+			}
+		}
+
+		$this->assertSame( 0, $writes );
+	}
+
+	/**
+	 * @testdox A report that fails to store leaves the previous report's failure rows in place.
+	 */
+	public function test_failed_report_write_keeps_the_previous_rows(): void {
+		$stale = $this->create_products( 1 )[0];
+		ProductFailures::store( $stale, array() );
+		$this->hide_product( $stale );
+		update_option( AgentReadiness::REPORT_OPTION, array( 'products' => 4 ) );
+		$this->create_products( 1 );
+		$this->sut->run();
+		$keep_old = static function ( $value, $old ) {
+			unset( $value );
+			return $old;
+		};
+		add_filter( 'pre_update_option_' . AgentReadiness::REPORT_OPTION, $keep_old, 10, 2 );
+		try {
+			$this->run_batches();
+		} finally {
+			remove_filter( 'pre_update_option_' . AgentReadiness::REPORT_OPTION, $keep_old, 10 );
+		}
+
+		$this->assertSame( array( ProductFailures::CHECKED ), ProductFailures::stored( $stale ) );
+		$this->assertSame( 4, get_option( AgentReadiness::REPORT_OPTION )['products'] );
+	}
+
+	/**
+	 * @testdox Rows saved after a product was skipped by its batch are still there when the scan finishes.
+	 */
+	public function test_rows_saved_after_a_skipped_product_stay(): void {
+		$kept  = $this->create_products( 1 )[0];
+		$stale = $this->create_products( 1 )[0];
+		ProductFailures::store( $kept, array() );
+		ProductFailures::store( $stale, array() );
+		$this->hide_product( $stale );
+		$skip = function () use ( $kept ): void {
+			$this->hide_product( $kept );
+		};
+		add_action( 'woocommerce_agent_readiness_scan_batch', $skip );
+		$this->sut->run();
+		$this->sut->run_batch( get_option( AgentReadiness::SCAN_OPTION )['id'] );
+		remove_action( 'woocommerce_agent_readiness_scan_batch', $skip );
+		wp_set_object_terms( $kept, array(), 'product_visibility' );
+		clean_post_cache( $kept );
+		ProductFailures::store( $kept, array() );
+
+		$this->run_batches();
+
+		$this->assertSame( array( ProductFailures::CHECKED ), ProductFailures::stored( $kept ) );
+		$this->assertSame( array(), ProductFailures::stored( $stale ), 'Rows from before the scan, on a product it did not test, are removed' );
+	}
+
+	/**
+	 * @testdox Giving up after the report is stored keeps the rows that report counts.
+	 */
+	public function test_give_up_after_the_report_is_stored_keeps_its_rows(): void {
+		$product_id = $this->create_products( 1 )[0];
+		$this->sut->run();
+		$this->run_batches();
+		$report = get_option( AgentReadiness::REPORT_OPTION );
+		$this->assertNotEmpty( ProductFailures::stored( $product_id ) );
+
+		update_option(
+			AgentReadiness::SCAN_OPTION,
+			array(
+				'id'         => $report['scan_id'],
+				'attempts'   => AgentReadiness::MAX_ATTEMPTS,
+				'ids'        => array( $product_id ),
+				'had_rows'   => array(),
+				'tested'     => array( $product_id ),
+				'position'   => 1,
+				'rows_as_of' => microtime( true ),
+			),
+			false
+		);
+		$this->sut->run_batch( $report['scan_id'] );
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertContains( ProductFailures::CHECKED, ProductFailures::stored( $product_id ) );
+		$this->assertArrayNotHasKey( 'scan_id', wc_get_container()->get( AgentReadiness::class )->get_cached_report() );
+	}
+
+	/**
+	 * @testdox An empty product list from a successful query is an empty catalog, and a query error stops the scan.
+	 */
+	public function test_empty_product_list_follows_the_query(): void {
+		$this->create_products( 1 );
+		$selection = static function ( $posts, $query ) {
+			if ( ProductScan::PRODUCT_LIMIT + 1 !== (int) $query->get( 'posts_per_page' ) ) {
+				return $posts;
+			}
+			return array();
+		};
+		add_filter( 'posts_pre_query', $selection, 10, 2 );
+		try {
+			$this->assertSame( array(), ( new ProductScan() )->start() );
+		} finally {
+			remove_filter( 'posts_pre_query', $selection, 10 );
+		}
+
+		$fail = static function ( $posts, $query ) {
+			if ( ProductScan::PRODUCT_LIMIT + 1 !== (int) $query->get( 'posts_per_page' ) ) {
+				return $posts;
+			}
+			global $wpdb;
+			$wpdb->last_error = 'database unavailable';
+			return array();
+		};
+		add_filter( 'posts_pre_query', $fail, 10, 2 );
+		try {
+			$this->expectException( \RuntimeException::class );
+			( new ProductScan() )->start();
+		} finally {
+			remove_filter( 'posts_pre_query', $fail, 10 );
+			global $wpdb;
+			$wpdb->last_error = '';
+		}
+	}
+
+	/**
+	 * @testdox A failed product list query is not cached, so the next scan lists the products.
+	 */
+	public function test_failed_list_query_is_not_cached(): void {
+		global $wpdb;
+		$ids   = $this->create_products( 1 );
+		$break = static function ( $sql ) {
+			return false !== strpos( (string) $sql, 'LIMIT 0, ' . ( ProductScan::PRODUCT_LIMIT + 1 ) ) ? $sql . ' BROKEN' : $sql;
+		};
+		add_filter( 'query', $break );
+		$suppress = $wpdb->suppress_errors( true );
+		try {
+			( new ProductScan() )->start();
+			$this->fail( 'A list query error stops the scan' );
+		} catch ( \RuntimeException $e ) {
+			unset( $e );
+		} finally {
+			remove_filter( 'query', $break );
+			$wpdb->suppress_errors( $suppress );
+			$wpdb->last_error = '';
+		}
+
+		$this->assertSame( $ids, ( new ProductScan() )->start() );
+	}
+
+	/**
+	 * @testdox A product list query error stops the scan even when the counts found no products.
+	 */
+	public function test_list_query_error_stops_the_scan_without_products(): void {
+		$fail = static function ( $posts, $query ) {
+			if ( ProductScan::PRODUCT_LIMIT + 1 !== (int) $query->get( 'posts_per_page' ) ) {
+				return $posts;
+			}
+			global $wpdb;
+			$wpdb->last_error = 'database unavailable';
+			return array();
+		};
+		add_filter( 'posts_pre_query', $fail, 10, 2 );
+		try {
+			$this->expectException( \RuntimeException::class );
+			( new ProductScan() )->start();
+		} finally {
+			remove_filter( 'posts_pre_query', $fail, 10 );
+			global $wpdb;
+			$wpdb->last_error = '';
+		}
+	}
+
+	/**
+	 * @testdox A selected product that still exists but fails to load stops the batch so prior rows stay, and a later batch can finish.
+	 */
+	public function test_product_load_failure_retries_and_keeps_prior_rows(): void {
+		$product_id = $this->create_products( 1 )[0];
+		ProductFailures::store( $product_id, array( 'missing_images' => array() ) );
+		$prior = ProductFailures::stored( $product_id );
+
+		$fail = static function ( $classname, $product_type, $context, $id ) use ( $product_id ) {
+			unset( $product_type, $context );
+			return (int) $id === $product_id ? BrokenAgentReadinessProduct::class : $classname;
+		};
+		add_filter( 'woocommerce_product_class', $fail, 10, 4 );
+		wc_get_container()->get( ProductCache::class )->remove( $product_id );
+		clean_post_cache( $product_id );
+		$this->sut->run();
+		$chain = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		try {
+			$this->sut->run_batch( $chain );
+			$this->fail( 'A product load failure stops the batch' );
+		} catch ( \RuntimeException $e ) {
+			$this->assertStringContainsString( (string) $product_id, $e->getMessage() );
+		} finally {
+			remove_filter( 'woocommerce_product_class', $fail, 10 );
+			wc_get_container()->get( ProductCache::class )->remove( $product_id );
+			clean_post_cache( $product_id );
+		}
+
+		$state = get_option( AgentReadiness::SCAN_OPTION );
+		$this->assertSame( 0, $state['position'], 'The batch must not advance past a load failure' );
+		$this->assertSame( $prior, ProductFailures::stored( $product_id ), 'Prior rows stay until a successful test' );
+
+		$this->run_batches();
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertContains( ProductFailures::CHECKED, ProductFailures::stored( $product_id ) );
+	}
+
+	/**
+	 * @testdox On the last attempt, a product that still fails to load is skipped so the scan finishes and its rows stay.
+	 */
+	public function test_product_load_failure_on_last_attempt_skips_and_keeps_rows(): void {
+		$ids = $this->create_products( 2 );
+		ProductFailures::store( $ids[0], array( 'missing_images' => array() ) );
+		$prior = ProductFailures::stored( $ids[0] );
+
+		$fail = static function ( $classname, $product_type, $context, $id ) use ( $ids ) {
+			unset( $product_type, $context );
+			return (int) $id === $ids[0] ? BrokenAgentReadinessProduct::class : $classname;
+		};
+		add_filter( 'woocommerce_product_class', $fail, 10, 4 );
+		wc_get_container()->get( ProductCache::class )->remove( $ids[0] );
+		clean_post_cache( $ids[0] );
+		$this->sut->run();
+		$state             = get_option( AgentReadiness::SCAN_OPTION );
+		$state['attempts'] = AgentReadiness::MAX_ATTEMPTS - 1;
+		update_option( AgentReadiness::SCAN_OPTION, $state, false );
+
+		try {
+			$this->run_batches();
+		} finally {
+			remove_filter( 'woocommerce_product_class', $fail, 10 );
+			wc_get_container()->get( ProductCache::class )->remove( $ids[0] );
+			clean_post_cache( $ids[0] );
+		}
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertSame( $prior, ProductFailures::stored( $ids[0] ), 'Rows for the unloadable product stay' );
+		$this->assertContains( ProductFailures::CHECKED, ProductFailures::stored( $ids[1] ) );
+		$this->assertNotNull( wc_get_container()->get( AgentReadiness::class )->get_cached_report() );
+	}
+
+	/**
+	 * @testdox A product deleted between listing and its batch is skipped without retrying the batch.
+	 */
+	public function test_deleted_product_is_skipped_without_retry(): void {
+		$ids = $this->create_products( 2 );
+		ProductFailures::store( $ids[0], array() );
+		$this->sut->run();
+		$chain = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		wp_delete_post( $ids[0], true );
+
+		$this->sut->run_batch( $chain );
+		$this->run_batches();
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertSame( array(), ProductFailures::stored( $ids[0] ), 'Rows for a deleted product are removed at finish' );
+		$this->assertContains( ProductFailures::CHECKED, ProductFailures::stored( $ids[1] ) );
+	}
+
+	/**
+	 * Set a product to Catalog visibility Hidden without saving it through the product editor.
+	 *
+	 * @param int $product_id Product id.
+	 */
+	private function hide_product( int $product_id ): void {
+		wp_set_object_terms( $product_id, array( 'exclude-from-catalog', 'exclude-from-search' ), 'product_visibility' );
+		clean_post_cache( $product_id );
+	}
+
+	/**
+	 * @testdox Turning the feature off during a scan stops it at the next batch, storing nothing.
+	 */
+	public function test_feature_off_stops_the_scan(): void {
+		$this->create_products( ProductScan::BATCH_SIZE + 1 );
+		$this->sut->run();
+		$chain = get_option( AgentReadiness::SCAN_OPTION )['id'];
+		$this->sut->run_batch( $chain );
+
+		update_option( 'woocommerce_feature_agent_readiness_enabled', 'no' );
+		$this->sut->run_batch( $chain );
+
+		$this->assertFalse( get_option( AgentReadiness::SCAN_OPTION ) );
+		$this->assertFalse( as_has_scheduled_action( ScheduledScan::NEXT_HOOK ) );
+		$this->assertNull( wc_get_container()->get( AgentReadiness::class )->get_cached_report() );
+	}
+
 	/**
 	 * Date every finished, failed or running action an hour back, so only what the
 	 * test does next counts as recent queue activity.
@@ -300,3 +857,24 @@ class ScheduledScanTest extends WC_Unit_Test_Case {
 		$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}actionscheduler_actions SET last_attempt_gmt = %s WHERE status IN ( 'complete', 'failed', 'in-progress' )", gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS ) ) );
 	}
 }
+
+/**
+ * Product class that fails to construct, so wc_get_product() returns false while the post remains.
+ *
+ * phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound
+ * phpcs:disable Squiz.Classes.ClassFileName.NoMatch
+ * phpcs:disable SlevomatCodingStandard.Files.TypeNameMatchesFileName.NoMatchBetweenTypeNameAndFileName
+ * phpcs:disable SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
+ */
+class BrokenAgentReadinessProduct extends \WC_Product_Simple {
+
+	/**
+	 * @param mixed $data Product id or data ignored; construction always fails.
+	 * @param array $args Unused factory args.
+	 */
+	public function __construct( $data = 0, $args = array() ) {
+		unset( $data, $args );
+		throw new \Exception( 'forced product load failure' );
+	}
+}
+// phpcs:enable