Commit 587246911a1 for woocommerce

commit 587246911a10c1dfd1988d9bfe578866307cd7d4
Author: Luis Felipe Zaguini <26530524+zaguiini@users.noreply.github.com>
Date:   Fri Dec 4 16:19:22 2026 -0300

    Let each ability resource clear its own caches after a rollback (#71783)

    * Clear the caches of rolled back objects with a callback of their resource, and cover coupons

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Add a changelog entry for the resource cache callback

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Log a failed cache cleanup after a rollback and keep the error of the call

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Clean the cache of a new term when a create_term hook fails after the insert

    Split the product term extension field test into one test per behavior.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Keep cleaning rolled back objects when the logger throws

    Check that the cleanup callback runs, and use targeted assertions in the object_types and query args tests.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    * Record the term ID only for the ability's own insertion

    A pre_insert_term hook can insert another term of the same taxonomy, which
    fires create_term first. Match the insertion by a marker in its arguments.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

    ---------

    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/plugins/woocommerce/changelog/wooai-1946-resource-clean-cache-callback b/plugins/woocommerce/changelog/wooai-1946-resource-clean-cache-callback
new file mode 100644
index 00000000000..2b547dee822
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1946-resource-clean-cache-callback
@@ -0,0 +1,4 @@
+Significance: minor
+Type: dev
+Comment: Let each ability resource clear its own caches after a rolled back write; the extensible abilities API is experimental.
+
diff --git a/plugins/woocommerce/src/Abilities/ActionableAbility.php b/plugins/woocommerce/src/Abilities/ActionableAbility.php
index 4c1cdbbb586..2e2b73fbe54 100644
--- a/plugins/woocommerce/src/Abilities/ActionableAbility.php
+++ b/plugins/woocommerce/src/Abilities/ActionableAbility.php
@@ -8,7 +8,6 @@ declare( strict_types=1 );
 namespace Automattic\WooCommerce\Abilities;

 use Automattic\WooCommerce\Internal\Abilities\Ability;
-use Automattic\WooCommerce\Internal\Caches\ProductCache;
 use Automattic\WooCommerce\Internal\Utilities\DatabaseTransaction;

 defined( 'ABSPATH' ) || exit;
@@ -321,11 +320,11 @@ abstract class ActionableAbility extends Ability {
 				}
 			);
 		} catch ( \Throwable $e ) {
-			$this->forget_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
+			$this->clean_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
 			throw $e;
 		}
 		if ( is_wp_error( $saved ) ) {
-			$this->forget_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
+			$this->clean_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
 			return $saved;
 		}

@@ -416,40 +415,28 @@ abstract class ActionableAbility extends Ability {
 	/**
 	 * Drop the object caches of the objects a rolled back save() touched. The
 	 * saves filled the caches with rows the rollback removed, so a read in the
-	 * same request would still see them. The `WC_Data` meta cache, the product type cache, the
-	 * product instance cache and the price lookup cache are separate from the post cache.
-	 * A term has its own object cache and meta cache.
+	 * same request would still see them. A failed cleanup is logged, so the
+	 * other objects are still cleaned and the caller gets the error of the call.
 	 *
 	 * @param array<int, array{0: object, 1: array, 2: string}> $objects The primary object and the secondary objects.
 	 * @param object[]                                          $deleted The objects the call deleted.
 	 */
-	private function forget_rolled_back_objects( array $objects, array $deleted = array() ): void {
-		$product_cache = wc_get_container()->get( ProductCache::class );
+	private function clean_rolled_back_objects( array $objects, array $deleted = array() ): void {
 		foreach ( array_merge( $objects, array_map( fn( $item ) => array( $item, array(), $this->get_resource() ), $deleted ) ) as list( $object, , $resource_name ) ) {
-			$id = ExtensibleAbilities::get_object_id( $object, $resource_name );
-			if ( $id > 0 && $object instanceof \WC_Data ) {
-				$object->delete_meta_cache();
-			}
-			if ( $id > 0 && $object instanceof \WC_Product ) {
-				clean_post_cache( $id );
-				wp_cache_delete( 'lookup_table', 'object_' . $id );
-				\WC_Cache_Helper::invalidate_cache_group( 'product_' . $id );
-				wc_delete_product_transients( $id );
-				$product_cache->remove( $id );
-				if ( $object->get_parent_id() > 0 ) {
-					clean_post_cache( $object->get_parent_id() );
-					wp_cache_delete( 'lookup_table', 'object_' . $object->get_parent_id() );
-					wc_delete_product_transients( $object->get_parent_id() );
-					$product_cache->remove( $object->get_parent_id() );
+			try {
+				$id = ExtensibleAbilities::get_object_id( $object, $resource_name );
+				if ( $id > 0 ) {
+					ExtensibleAbilities::clean_object_cache( $object, $id, $resource_name );
+				}
+			} catch ( \Throwable $e ) {
+				try {
+					wc_get_logger()->error(
+						sprintf( 'The cache cleanup of the "%s" resource failed after a rollback: %s', $resource_name, $e->getMessage() ),
+						array( 'source' => 'extensible-abilities' )
+					);
+				} catch ( \Throwable $logging_error ) {
+					unset( $logging_error );
 				}
-			} elseif ( $id > 0 && $object instanceof \WC_Abstract_Order ) {
-				wc_get_container()->get( \Automattic\WooCommerce\Caches\OrderCache::class )->remove( $id );
-				clean_post_cache( $id );
-			} elseif ( $id > 0 && $object instanceof \WC_Customer ) {
-				clean_user_cache( $id );
-			} elseif ( $id > 0 && $object instanceof \WP_Term ) {
-				clean_term_cache( $id, $object->taxonomy );
-				wp_cache_delete( $id, 'term_meta' );
 			}
 		}
 	}
diff --git a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
index 6298be0bac8..cbdff24a5db 100644
--- a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
+++ b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
@@ -113,7 +113,7 @@ class ExtensibleAbilities {
 	 *
 	 * @param string $resource_name Slug of the resource, such as `ticket`.
 	 * @param array  $args          {
-	 *     Arguments of the resource. Both callbacks are required.
+	 *     Arguments of the resource. The ID and type callbacks are required.
 	 *
 	 *     @type callable $object_id_callback   Receives an object of the resource and returns its ID as an integer,
 	 *                                          or zero when the object is not saved yet. Core's `product` returns
@@ -126,6 +126,10 @@ class ExtensibleAbilities {
 	 *     @type string[] $query_clauses        Optional. Clauses that the list ability of the resource runs, such as
 	 *                                          `meta_query`, `tax_query`, `include_ids` and `exclude_ids`. A query
 	 *                                          filter can return only these. Without it, a filter can return any clause.
+	 *     @type callable $clean_cache_callback Optional. Receives an object of the resource and its ID, and drops the
+	 *                                          caches of the object. Core calls it when it rolls back a call that saved
+	 *                                          or deleted the object, so a later read in the same request does not see
+	 *                                          the rolled back rows.
 	 * }
 	 */
 	public static function register_resource( string $resource_name, array $args = array() ): void {
@@ -152,6 +156,11 @@ class ExtensibleAbilities {
 			$args['query_clauses'] = array_values( $args['query_clauses'] );
 		}

+		if ( isset( $args['clean_cache_callback'] ) && ! is_callable( $args['clean_cache_callback'] ) ) {
+			wc_doing_it_wrong( __METHOD__, sprintf( 'The "clean_cache_callback" argument of the "%s" resource must be callable.', $resource_name ), '11.5.0' );
+			return;
+		}
+
 		self::$resources[ $resource_name ] = self::$resources[ $resource_name ] ?? $args;
 	}

@@ -1051,6 +1060,24 @@ class ExtensibleAbilities {
 		return call_user_func( self::get_registered_resource( $resource_name )['object_type_callback'], $subject );
 	}

+	/**
+	 * Drop the caches of an object with the `clean_cache_callback` of its resource. Does nothing when the
+	 * resource has no such callback.
+	 *
+	 * @since 11.5.0
+	 *
+	 * @param mixed  $subject       The object.
+	 * @param int    $id            The ID of the object.
+	 * @param string $resource_name Resource of the object.
+	 * @throws \LogicException When the resource is not registered.
+	 */
+	public static function clean_object_cache( $subject, int $id, string $resource_name ): void {
+		$callback = self::get_registered_resource( $resource_name )['clean_cache_callback'] ?? null;
+		if ( null !== $callback ) {
+			call_user_func( $callback, $subject, $id );
+		}
+	}
+
 	/**
 	 * The ID of an object, from the `object_id_callback` of its resource.
 	 *
diff --git a/plugins/woocommerce/src/Internal/Abilities/AGENTS.md b/plugins/woocommerce/src/Internal/Abilities/AGENTS.md
index 454c8ea7607..96df7ee085a 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AGENTS.md
+++ b/plugins/woocommerce/src/Internal/Abilities/AGENTS.md
@@ -39,4 +39,4 @@ A test that needs the `extensible_abilities` feature on uses `Automattic\WooComm
 - Call `isolate_extensible_abilities()` when the feature is off. It empties the registries and registers Core's resources, because a write ability refuses a call when its resource is not registered, also with the feature off.
 - Do not restore anything by hand. The trait restores the registries after each test.

-Turning only the option on is not enough. When an earlier test built the abilities registry while the feature was off, Core's resources are not registered, and an ability that saves a secondary object refuses the call.
+Turning only the option on is not enough. When an earlier test built the abilities registry while the feature was off, `woocommerce_extensible_abilities_init` did not fire, so the fields, validators, syncs and filters of the test are not registered.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 9230e19af11..2bb87c56626 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -10,6 +10,7 @@ namespace Automattic\WooCommerce\Internal\Abilities;
 use Automattic\WooCommerce\Abilities\AbilityDefinition;
 use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
 use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Caches\OrderCache;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderAddNote;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderCreate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderNotesQuery;
@@ -52,6 +53,7 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\TaxRatesQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\TaxRateUpdate;
 use Automattic\WooCommerce\Internal\AgentReadiness\ReportAbility;
 use Automattic\WooCommerce\Internal\AgentReadiness\RunCheckAbility;
+use Automattic\WooCommerce\Internal\Caches\ProductCache;
 use Automattic\WooCommerce\Internal\Abilities\Domain\StoreSettingsGet;
 use Automattic\WooCommerce\Internal\Abilities\Domain\SettingsQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\SettingsUpdate;
@@ -190,6 +192,7 @@ class AbilitiesLoader {
 				'object_id_callback'   => $data_id,
 				'object_type_callback' => $data_type,
 				'query_clauses'        => array( 'meta_query', 'tax_query', 'include_ids', 'exclude_ids' ),
+				'clean_cache_callback' => array( __CLASS__, 'clean_product_cache' ),
 			)
 		);
 		ExtensibleAbilities::register_resource(
@@ -198,6 +201,7 @@ class AbilitiesLoader {
 				'object_id_callback'   => $data_id,
 				'object_type_callback' => $data_type,
 				'query_clauses'        => array( 'meta_query', 'include_ids', 'exclude_ids' ),
+				'clean_cache_callback' => array( __CLASS__, 'clean_order_cache' ),
 			)
 		);
 		ExtensibleAbilities::register_resource(
@@ -205,6 +209,9 @@ class AbilitiesLoader {
 			array(
 				'object_id_callback'   => $data_id,
 				'object_type_callback' => $data_type,
+				'clean_cache_callback' => static function ( \WC_Order_Item $item ): void {
+					$item->delete_meta_cache();
+				},
 			)
 		);
 		ExtensibleAbilities::register_resource(
@@ -213,6 +220,7 @@ class AbilitiesLoader {
 				'object_id_callback'   => $data_id,
 				'object_type_callback' => $data_type,
 				'query_clauses'        => array( 'include_ids', 'exclude_ids' ),
+				'clean_cache_callback' => array( __CLASS__, 'clean_order_cache' ),
 			)
 		);
 		ExtensibleAbilities::register_resource(
@@ -220,6 +228,10 @@ class AbilitiesLoader {
 			array(
 				'object_id_callback'   => $data_id,
 				'object_type_callback' => static fn( \WC_Coupon $coupon ): string => $coupon->get_discount_type(),
+				'clean_cache_callback' => static function ( \WC_Coupon $coupon, int $id ): void {
+					$coupon->delete_meta_cache();
+					clean_post_cache( $id );
+				},
 			)
 		);
 		ExtensibleAbilities::register_resource(
@@ -228,6 +240,10 @@ class AbilitiesLoader {
 				'object_id_callback'   => $data_id,
 				'object_type_callback' => static fn( \WC_Customer $customer ): string => $customer->get_role(),
 				'query_clauses'        => array( 'include_ids', 'exclude_ids' ),
+				'clean_cache_callback' => static function ( \WC_Customer $customer, int $id ): void {
+					$customer->delete_meta_cache();
+					clean_user_cache( $id );
+				},
 			)
 		);
 		ExtensibleAbilities::register_resource(
@@ -243,10 +259,53 @@ class AbilitiesLoader {
 				'object_id_callback'   => static fn( \WP_Term $term ): int => $term->term_id,
 				'object_type_callback' => static fn( \WP_Term $term ): string => $term->taxonomy,
 				'query_clauses'        => array( 'meta_query', 'include_ids', 'exclude_ids' ),
+				'clean_cache_callback' => static function ( \WP_Term $term, int $id ): void {
+					clean_term_cache( $id, $term->taxonomy );
+					wp_cache_delete( $id, 'term_meta' );
+				},
 			)
 		);
 	}

+	/**
+	 * Drop the caches of an order or a refund.
+	 *
+	 * @internal
+	 *
+	 * @since 11.5.0
+	 *
+	 * @param \WC_Abstract_Order $order The order.
+	 * @param int                $id    The ID of the order.
+	 */
+	public static function clean_order_cache( \WC_Abstract_Order $order, int $id ): void {
+		$order->delete_meta_cache();
+		wc_get_container()->get( OrderCache::class )->remove( $id );
+		clean_post_cache( $id );
+	}
+
+	/**
+	 * Drop the caches of a product and its parent. The product type cache, the product
+	 * instance cache and the price lookup cache are separate from the post cache.
+	 *
+	 * @internal
+	 *
+	 * @since 11.5.0
+	 *
+	 * @param \WC_Product $product The product.
+	 * @param int         $id      The ID of the product.
+	 */
+	public static function clean_product_cache( \WC_Product $product, int $id ): void {
+		$product->delete_meta_cache();
+		\WC_Cache_Helper::invalidate_cache_group( 'product_' . $id );
+		$product_cache = wc_get_container()->get( ProductCache::class );
+		foreach ( array_filter( array( $id, $product->get_parent_id() ) ) as $product_id ) {
+			clean_post_cache( $product_id );
+			wp_cache_delete( 'lookup_table', 'object_' . $product_id );
+			wc_delete_product_transients( $product_id );
+			$product_cache->remove( $product_id );
+		}
+	}
+
 	/**
 	 * Add the extension filter clauses of a list ability to its WP_Query arguments.
 	 *
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php
index 50e9aff281e..61dcf0dc776 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php
@@ -45,6 +45,7 @@ trait ProductTermWriteTrait {

 	/**
 	 * Create or update the term, then give the object its stored values, so syncs get the term ID and the final slug.
+	 * A new term gets its ID when WordPress inserts it, before other `create_term` hooks run, so a rollback cleans its cache.
 	 *
 	 * @param \WP_Term $subject Term.
 	 * @return null|\WP_Error
@@ -55,7 +56,20 @@ trait ProductTermWriteTrait {
 		if ( 0 === $subject->term_id ) {
 			$name = $args['name'] ?? '';
 			unset( $args['name'] );
-			$result = wp_insert_term( wp_slash( $name ), $subject->taxonomy, wp_slash( $args ) );
+			$marker                             = wp_generate_uuid4();
+			$args['woocommerce_ability_insert'] = $marker;
+			$track                              = static function ( $term_id, $tt_id, $taxonomy, $insert_args ) use ( $subject, $marker, &$track ) {
+				if ( ( $insert_args['woocommerce_ability_insert'] ?? null ) === $marker ) {
+					$subject->term_id = (int) $term_id;
+					remove_action( 'create_term', $track, PHP_INT_MIN );
+				}
+			};
+			add_action( 'create_term', $track, PHP_INT_MIN, 4 );
+			try {
+				$result = wp_insert_term( wp_slash( $name ), $subject->taxonomy, wp_slash( $args ) );
+			} finally {
+				remove_action( 'create_term', $track, PHP_INT_MIN );
+			}
 		} elseif ( ! empty( $args ) ) {
 			$result = wp_update_term( $subject->term_id, $subject->taxonomy, wp_slash( $args ) );
 		} else {
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php
index 4abb986199e..8a2fed68681 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php
@@ -672,7 +672,7 @@ class ProductTermWritesTest extends WC_Unit_Test_Case {
 	}

 	/**
-	 * @testdox Should write a sent extension field of a new and of an existing term in a sync, and save nothing when a validator or a sync refuses or the field does not apply to the taxonomy.
+	 * @testdox Should write a sent extension field of a new and of an existing term in a sync.
 	 */
 	public function test_writes_extension_fields(): void {
 		$id = self::factory()->term->create(
@@ -681,6 +681,146 @@ class ProductTermWritesTest extends WC_Unit_Test_Case {
 				'name'     => 'Existing',
 			)
 		);
+		$this->register_label_field();
+
+		$created = $this->create(
+			array(
+				'taxonomy'   => 'product_tag',
+				'name'       => 'Sale',
+				'extensions' => array( 'test-ext' => array( 'label' => 'new' ) ),
+			)
+		);
+		$updated = $this->update(
+			array(
+				'taxonomy'   => 'product_tag',
+				'id'         => $id,
+				'extensions' => array( 'test-ext' => array( 'label' => 'changed' ) ),
+			)
+		);
+
+		$this->assertSame( 'new', $created['term']['extensions']['test-ext']['label'] );
+		$this->assertSame( 'new', get_term_meta( $created['term']['id'], '_test_label', true ) );
+		$this->assertSame( 'changed', $updated['term']['extensions']['test-ext']['label'] );
+		$this->assertSame( 'Existing', $updated['term']['name'] );
+	}
+
+	/**
+	 * @testdox Should save nothing when a validator refuses the term.
+	 */
+	public function test_validator_refusal_saves_nothing(): void {
+		$id = self::factory()->term->create(
+			array(
+				'taxonomy' => 'product_tag',
+				'name'     => 'Existing',
+			)
+		);
+		$this->register_label_field();
+
+		$refused = $this->update(
+			array(
+				'taxonomy'   => 'product_tag',
+				'id'         => $id,
+				'name'       => 'Refused',
+				'extensions' => array( 'test-ext' => array( 'label' => 'lost' ) ),
+			)
+		);
+
+		$this->assertWPError( $refused );
+		$this->assertSame( 'test-ext:refused', $refused->get_error_code() );
+		$this->assertSame( 'Existing', get_term( $id, 'product_tag' )->name );
+		$this->assertSame( '', get_term_meta( $id, '_test_label', true ) );
+	}
+
+	/**
+	 * @testdox Should roll back the new term when a sync fails.
+	 */
+	public function test_sync_failure_rolls_back_the_new_term(): void {
+		$this->register_label_field();
+
+		$rolled_back = $this->create(
+			array(
+				'taxonomy'   => 'product_tag',
+				'name'       => 'Rolled back',
+				'extensions' => array( 'test-ext' => array( 'label' => 'fail' ) ),
+			)
+		);
+
+		$this->assertWPError( $rolled_back );
+		$this->assertSame( 'sync_failed', $rolled_back->get_error_code() );
+		$this->assertFalse( get_term_by( 'name', 'Rolled back', 'product_tag' ) );
+	}
+
+	/**
+	 * @testdox Should refuse a field that does not apply to the taxonomy of the term.
+	 */
+	public function test_field_of_another_taxonomy_is_refused(): void {
+		$this->register_label_field();
+
+		$other_type = $this->create(
+			array(
+				'taxonomy'   => 'product_cat',
+				'name'       => 'Other taxonomy',
+				'extensions' => array( 'test-ext' => array( 'label' => 'new' ) ),
+			)
+		);
+
+		$this->assertWPError( $other_type );
+		$this->assertSame( 'test-ext:woocommerce_ability_field_object_type', $other_type->get_error_code() );
+		$this->assertFalse( get_term_by( 'name', 'Other taxonomy', 'product_cat' ) );
+	}
+
+	/**
+	 * @testdox Should drop the cache of a new term when a created_term hook caches it and then throws.
+	 * @testWith [false]
+	 *           [true]
+	 *
+	 * @param bool $nested_insert Whether a pre_insert_term hook first inserts another term of the same taxonomy.
+	 */
+	public function test_rolled_back_create_drops_the_term_cache( bool $nested_insert ): void {
+		if ( $nested_insert ) {
+			add_filter(
+				'pre_insert_term',
+				static function ( $term, $taxonomy ) {
+					if ( 'Cached' === $term ) {
+						wp_insert_term( 'Nested', $taxonomy );
+					}
+					return $term;
+				},
+				10,
+				2
+			);
+		}
+		$term_id = 0;
+		add_action(
+			'created_term',
+			static function ( $id ) use ( &$term_id ) {
+				if ( 'Cached' !== get_term( $id )->name ) {
+					return;
+				}
+				$term_id = (int) $id;
+				get_term( $term_id );
+				throw new \RuntimeException( 'The hook failed.' );
+			}
+		);
+
+		$result = $this->create(
+			array(
+				'taxonomy' => 'product_tag',
+				'name'     => 'Cached',
+			)
+		);
+
+		$this->assertWPError( $result );
+		$this->assertGreaterThan( 0, $term_id );
+		$this->assertFalse( get_term_by( 'name', 'Cached', 'product_tag' ) );
+		$this->assertFalse( wp_cache_get( $term_id, 'terms' ) );
+	}
+
+	/**
+	 * Register a `label` field of `product_tag` terms, a validator that refuses the name "Refused",
+	 * and a sync that saves the label in term meta and fails for the label "fail".
+	 */
+	private function register_label_field(): void {
 		update_option( 'woocommerce_feature_extensible_abilities_enabled', 'yes' );
 		$this->enable_extensible_abilities(
 			static function () {
@@ -725,59 +865,6 @@ class ProductTermWritesTest extends WC_Unit_Test_Case {
 				);
 			}
 		);
-		$extensions = static fn( string $label ) => array( 'test-ext' => array( 'label' => $label ) );
-
-		$created     = $this->create(
-			array(
-				'taxonomy'   => 'product_tag',
-				'name'       => 'Sale',
-				'extensions' => $extensions( 'new' ),
-			)
-		);
-		$updated     = $this->update(
-			array(
-				'taxonomy'   => 'product_tag',
-				'id'         => $id,
-				'extensions' => $extensions( 'changed' ),
-			)
-		);
-		$refused     = $this->update(
-			array(
-				'taxonomy'   => 'product_tag',
-				'id'         => $id,
-				'name'       => 'Refused',
-				'extensions' => $extensions( 'lost' ),
-			)
-		);
-		$rolled_back = $this->create(
-			array(
-				'taxonomy'   => 'product_tag',
-				'name'       => 'Rolled back',
-				'extensions' => $extensions( 'fail' ),
-			)
-		);
-		$other_type  = $this->create(
-			array(
-				'taxonomy'   => 'product_cat',
-				'name'       => 'Other taxonomy',
-				'extensions' => $extensions( 'new' ),
-			)
-		);
-
-		$this->assertSame( 'new', $created['term']['extensions']['test-ext']['label'] );
-		$this->assertSame( 'new', get_term_meta( $created['term']['id'], '_test_label', true ) );
-		$this->assertSame( 'changed', $updated['term']['extensions']['test-ext']['label'] );
-		$this->assertSame( 'Existing', $updated['term']['name'] );
-		$this->assertWPError( $refused );
-		$this->assertSame( 'test-ext:refused', $refused->get_error_code() );
-		$this->assertSame( 'Existing', get_term( $id, 'product_tag' )->name );
-		$this->assertSame( 'changed', get_term_meta( $id, '_test_label', true ) );
-		$this->assertWPError( $rolled_back );
-		$this->assertSame( 'sync_failed', $rolled_back->get_error_code() );
-		$this->assertFalse( get_term_by( 'name', 'Rolled back', 'product_tag' ) );
-		$this->assertWPError( $other_type );
-		$this->assertSame( 'test-ext:woocommerce_ability_field_object_type', $other_type->get_error_code() );
-		$this->assertFalse( get_term_by( 'name', 'Other taxonomy', 'product_cat' ) );
 	}

 	/**
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index 64c8197f84c..6065b135593 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -4348,6 +4348,90 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 		$this->assertSame( 'red', wc_get_product( $product->get_id() )->get_meta( '_test_color' ) );
 	}

+	/**
+	 * @testdox Should drop the cache of a coupon when a sync refuses the change.
+	 */
+	public function test_a_sync_refusal_drops_the_cache_of_the_coupon(): void {
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'rollback-code' );
+		$coupon->set_amount( 5 );
+		$coupon->save();
+		$this->register_sync(
+			'coupon',
+			'test-ext',
+			static function ( array $saved ) {
+				( new \WC_Coupon( $saved[0]->get_id() ) )->get_amount();
+				return new \WP_Error( 'test_refused', 'Refused.' );
+			}
+		);
+
+		$response = $this->run_ability_response(
+			'woocommerce/coupon-update',
+			array(
+				'id'     => $coupon->get_id(),
+				'amount' => '20',
+			)
+		);
+
+		$this->assertSame( 400, $response->get_status() );
+		$this->assertSame( 5.0, (float) ( new \WC_Coupon( $coupon->get_id() ) )->get_amount() );
+	}
+
+	/**
+	 * @testdox Should return the sync refusal when the cache cleanup of the resource throws.
+	 */
+	public function test_a_failed_cache_cleanup_keeps_the_sync_refusal(): void {
+		$cleanups = 0;
+		$clean    = static function () use ( &$cleanups ) {
+			++$cleanups;
+			throw new \RuntimeException( 'Cache server is down.' );
+		};
+		$this->add_test_action(
+			'woocommerce_extensible_abilities_resources_init',
+			static fn() => ExtensibleAbilities::register_resource(
+				'ticket',
+				array(
+					'object_id_callback'   => static fn( \WC_Product $product ): int => $product->get_id(),
+					'object_type_callback' => static fn(): string => 'ticket',
+					'clean_cache_callback' => $clean,
+				)
+			)
+		);
+		$this->register_sync( 'ticket', 'test-ext', static fn() => new \WP_Error( 'test_refused', 'Refused.' ) );
+		$this->get_ability( 'woocommerce/products-query' );
+		$product = \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
+		$ability = new class(
+			'test-ext/ticket-rename',
+			array(
+				'label'               => 'Rename ticket',
+				'description'         => 'Renames a ticket product.',
+				'category'            => 'woocommerce',
+				'output_schema'       => array( 'type' => 'object' ),
+				'permission_callback' => '__return_true',
+			)
+		) extends TestProductRenameAbility {
+			/**
+			 * The resource of the extension.
+			 *
+			 * @return string
+			 */
+			public function get_resource(): string {
+				return 'ticket';
+			}
+		};
+
+		$result = $ability->execute_change(
+			array(
+				'id'   => $product->get_id(),
+				'name' => 'Pencil',
+			)
+		);
+
+		$this->assertWPError( $result );
+		$this->assertSame( 'test_refused', $result->get_error_code() );
+		$this->assertSame( 1, $cleanups );
+	}
+
 	/**
 	 * @testdox Should let a validator refuse a delete, and then delete nothing.
 	 */
@@ -5691,8 +5775,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 			return ExtensibleAbilities::add_fields_to_object( array(), 'coupon', $coupon );
 		};

-		$this->assertSame( array( 'test-ext' => array( 'typed' => 'value' ) ), $read( 'percent' )['extensions'] );
-		$this->assertSame( array(), $read( 'fixed_cart' ) );
+		$this->assertSame( 'value', $read( 'percent' )['extensions']['test-ext']['typed'] );
+		$this->assertArrayNotHasKey( 'extensions', $read( 'fixed_cart' ) );
 	}

 	/**
@@ -5726,7 +5810,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 		$list = $this->run_ability( $ability, $create_input() )[ $list_key ];

 		$this->assertCount( 2, $list );
-		$this->assertSame( array( 'typed' => 'value' ), $list[0]['extensions']['test-ext'] );
+		$this->assertSame( 'value', $list[0]['extensions']['test-ext']['typed'] );
+		$this->assertArrayNotHasKey( 'other', $list[0]['extensions']['test-ext'] );
 	}

 	/**