Commit 4e3522f9fd6 for woocommerce

commit 4e3522f9fd649b9dbac017ce9f640e2b9198ea61
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Mon Nov 23 18:51:13 2026 +0100

    Restore a removed coupon's use only once (#71264)

    Forwardport of 603-gh-Automattic/woocommerce.

    Source PR head: af52d3e850126bea85d7964f8bf18409072d8764

    Co-authored-by: Rostislav Wolny <rosta.wolny@automattic.com>

diff --git a/plugins/woocommerce/includes/abstracts/abstract-wc-order.php b/plugins/woocommerce/includes/abstracts/abstract-wc-order.php
index 477dcecc3a5..ea230bf51ab 100644
--- a/plugins/woocommerce/includes/abstracts/abstract-wc-order.php
+++ b/plugins/woocommerce/includes/abstracts/abstract-wc-order.php
@@ -2296,7 +2296,9 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
 		// Remove the coupon line.
 		foreach ( $coupons as $coupon ) {
 			if ( wc_is_same_coupon( $coupon->get_code(), $code ) ) {
-				$this->remove_item( $this->get_stored_item_key( $coupon ) );
+				$item_key    = $this->get_stored_item_key( $coupon );
+				$stored_item = $this->get_item( $item_key, false );
+				$this->remove_item( $item_key );
 				$coupon_object = new WC_Coupon( $code );

 				$staged = isset( $this->staged_coupons[ $coupon_object->get_code() ] );
@@ -2308,18 +2310,10 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
 					}
 				}

-				if ( $has_recorded ) {
-					// Mirror the stored flag into this instance so clearing it below is tracked as a change and saved.
-					$this->set_recorded_coupon_usage_counts( true );
-
-					if ( ! $staged ) {
-						$this->write_or_defer( 'release_coupon_usage_' . $coupon_object->get_code(), array( $this, 'release_removed_coupon_usage' ), array( $coupon_object, $used_by ) );
-					}
-
-					$remaining_codes = array_filter( $this->get_coupon_codes(), fn( $remaining_code ) => ! StringUtil::is_null_or_whitespace( $remaining_code ) );
-					if ( ! $remaining_codes ) {
-						$this->set_recorded_coupon_usage_counts( false );
-					}
+				if ( $has_recorded && ! $staged ) {
+					$this->write_or_defer( 'release_coupon_usage_' . $coupon_object->get_code(), array( $this, 'release_removed_coupon_usage' ), array( $stored_item, $coupon_object, $used_by ) );
+				} elseif ( $has_recorded ) {
+					$this->clear_recorded_coupon_usage_without_coupons();
 				}

 				if ( $this->writing_through ) {
@@ -2338,16 +2332,89 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
 	}

 	/**
-	 * Lower the usage count of a removed coupon, and forget the identity it was counted under.
+	 * Delete the line of a removed coupon whose use the order counted, and give the use back if this call deleted it.
 	 *
-	 * @param WC_Coupon  $coupon_object Removed coupon.
-	 * @param int|string $used_by       User ID or billing email to use when no identity was stored.
+	 * @param WC_Order_Item|false $stored_item   Removed coupon line, as stored in this order.
+	 * @param WC_Coupon           $coupon_object Removed coupon.
+	 * @param int|string          $used_by       User ID or billing email to use when no identity was stored.
 	 */
-	private function release_removed_coupon_usage( WC_Coupon $coupon_object, $used_by ): void {
-		$identities = $this->get_coupon_usage_identities();
-		$coupon_object->decrease_usage_count( $identities[ $coupon_object->get_id() ] ?? $used_by );
-		unset( $identities[ $coupon_object->get_id() ] );
-		$this->save_coupon_usage_identities( $identities );
+	private function release_removed_coupon_usage( $stored_item, WC_Coupon $coupon_object, $used_by ): void {
+		// Read before the line is deleted: a cancellation running meanwhile deletes the identities.
+		$identities     = $this->get_coupon_usage_identities();
+		$gives_use_back = $this->delete_counted_coupon_line( $stored_item );
+
+		// Null: another call deleted the line, or the delete failed and the use stays counted. Either way the counted flag is left alone.
+		if ( null !== $gives_use_back ) {
+			$this->clear_recorded_coupon_usage_without_coupons();
+		}
+
+		if ( $gives_use_back ) {
+			$coupon_object->decrease_usage_count( $identities[ $coupon_object->get_id() ] ?? $used_by );
+			unset( $identities[ $coupon_object->get_id() ] );
+			$this->save_coupon_usage_identities( $identities );
+		}
+	}
+
+	/**
+	 * Delete the coupon line of an order that counted its use, and tell whether this call should give the use back.
+	 *
+	 * Only the call that deleted the line gives the use back, and only while the stored order is still counted, so
+	 * parallel removals and a parallel cancellation give it back at most once.
+	 * If a cancellation, or a removal that empties the order, runs at the same moment, both can skip it and the count stays one too high.
+	 *
+	 * @param WC_Order_Item|false $stored_item Removed coupon line, as stored in this order.
+	 * @return bool|null True if this call should give the coupon's use back, false if not, null if another call deleted the line or the delete failed.
+	 */
+	private function delete_counted_coupon_line( $stored_item ): ?bool {
+		if ( ! $stored_item instanceof WC_Order_Item_Coupon || ! $stored_item->get_id() ) {
+			return true;
+		}
+
+		/**
+		 * Data store wrapper.
+		 *
+		 * @var WC_Data_Store $item_data_store
+		 */
+		$item_data_store = $stored_item->get_data_store();
+		$deleted         = $item_data_store->delete( $stored_item );
+		if ( false === $deleted ) {
+			// A database error. The delete that remove_item() queued runs again on save.
+			return null;
+		}
+
+		// The row is gone, so the delete that remove_item() queued for save() must not run again.
+		$stored_item->set_id( 0 );
+
+		// No row deleted: another call deleted the line first. Item data stores that return nothing (custom or
+		// overridden) cannot report it, so only the counted check below applies to them.
+		if ( null !== $deleted && ! $deleted ) {
+			return null;
+		}
+
+		/**
+		 * Data store wrapper.
+		 *
+		 * @var WC_Data_Store $order_data_store
+		 */
+		$order_data_store = $this->get_data_store();
+		if ( ! $order_data_store->has_callable( 'get_stored_recorded_coupon_usage_counts' ) ) {
+			return true;
+		}
+
+		// @phpstan-ignore-next-line method.notFound (Guarded by has_callable() and called via __call() on the underlying order data store instance.)
+		return $order_data_store->get_stored_recorded_coupon_usage_counts( $this );
+	}
+
+	/**
+	 * Clear the counted flag when the order has no coupon left.
+	 */
+	private function clear_recorded_coupon_usage_without_coupons(): void {
+		$remaining_codes = array_filter( $this->get_coupon_codes(), fn( $remaining_code ) => ! StringUtil::is_null_or_whitespace( $remaining_code ) );
+		if ( ! $remaining_codes ) {
+			// Mirror the stored flag into this instance so clearing it is tracked as a change and saved.
+			$this->set_recorded_coupon_usage_counts( true );
+			$this->set_recorded_coupon_usage_counts( false );
+		}
 	}

 	/**
diff --git a/plugins/woocommerce/includes/class-wc-data-store.php b/plugins/woocommerce/includes/class-wc-data-store.php
index 4d263ef4336..13f96ac3b08 100644
--- a/plugins/woocommerce/includes/class-wc-data-store.php
+++ b/plugins/woocommerce/includes/class-wc-data-store.php
@@ -202,11 +202,13 @@ class WC_Data_Store {
 	 * Delete an object from the data store.
 	 *
 	 * @since 3.0.0
+	 * @since 11.3.1 Returns what the data store returns.
 	 * @param WC_Data $data WooCommerce data instance.
 	 * @param array   $args Array of args to pass to the delete method.
+	 * @return mixed What the data store returns, if anything.
 	 */
 	public function delete( &$data, $args = array() ) {
-		$this->instance->delete( $data, $args );
+		return $this->instance->delete( $data, $args );
 	}

 	/**
diff --git a/plugins/woocommerce/includes/data-stores/abstract-wc-order-item-type-data-store.php b/plugins/woocommerce/includes/data-stores/abstract-wc-order-item-type-data-store.php
index 05ae66b7c65..f635b647e7a 100644
--- a/plugins/woocommerce/includes/data-stores/abstract-wc-order-item-type-data-store.php
+++ b/plugins/woocommerce/includes/data-stores/abstract-wc-order-item-type-data-store.php
@@ -133,16 +133,22 @@ abstract class Abstract_WC_Order_Item_Type_Data_Store extends WC_Data_Store_WP i
 	 * @param WC_Order_Item $item Order item object.
 	 * @param array         $args Array of args to pass to the delete method.
 	 * @since 3.0.0
+	 * @since 11.3.1 Returns the number of item rows deleted.
+	 *
+	 * @return int|false Number of item rows this call deleted (0 when another call already deleted the row), or false on a database error.
 	 */
 	public function delete( &$item, $args = array() ) {
+		$deleted = 0;
 		if ( $item->get_id() ) {
 			global $wpdb;
 			do_action( 'woocommerce_before_delete_order_item', $item->get_id() );
-			$wpdb->delete( $wpdb->prefix . 'woocommerce_order_items', array( 'order_item_id' => $item->get_id() ) );
+			$deleted = $wpdb->delete( $wpdb->prefix . 'woocommerce_order_items', array( 'order_item_id' => $item->get_id() ) );
 			$wpdb->delete( $wpdb->prefix . 'woocommerce_order_itemmeta', array( 'order_item_id' => $item->get_id() ) );
 			do_action( 'woocommerce_delete_order_item', $item->get_id() );
 			$this->clear_cache( $item );
 		}
+
+		return $deleted;
 	}

 	/**
diff --git a/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php b/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
index 0551e1435b9..22dfde139fb 100644
--- a/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
+++ b/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
@@ -768,6 +768,29 @@ class WC_Order_Data_Store_CPT extends Abstract_WC_Order_Data_Store_CPT implement
 		return true;
 	}

+	/**
+	 * Reads the "coupon usage counted" flag straight from the database, skipping the meta cache.
+	 *
+	 * @since 11.3.1
+	 *
+	 * @internal For use by WC_Abstract_Order::remove_coupon() only.
+	 *
+	 * @param WC_Order $order Order object.
+	 * @return bool
+	 */
+	public function get_stored_recorded_coupon_usage_counts( $order ): bool {
+		global $wpdb;
+
+		$value = $wpdb->get_var(
+			$wpdb->prepare(
+				"SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_recorded_coupon_usage_counts' ORDER BY meta_id ASC LIMIT 1",
+				$order->get_id()
+			)
+		);
+
+		return wc_string_to_bool( (string) $value );
+	}
+
 	/**
 	 * Whether email have been sent for this order.
 	 *
diff --git a/plugins/woocommerce/includes/wc-order-functions.php b/plugins/woocommerce/includes/wc-order-functions.php
index 2cd53faefb0..9b864c11fd8 100644
--- a/plugins/woocommerce/includes/wc-order-functions.php
+++ b/plugins/woocommerce/includes/wc-order-functions.php
@@ -1080,6 +1080,7 @@ function wc_update_coupon_usage_counts( $order_id ) {

 	$is_invalid = $order->has_status( $invalid_statuses );

+	$stored_coupon_codes = null;
 	if ( $is_invalid && $has_recorded ) {
 		$action = 'reduce';
 		if ( $data_store->has_callable( 'clear_recorded_coupon_usage_counts' ) ) {
@@ -1092,6 +1093,23 @@ function wc_update_coupon_usage_counts( $order_id ) {
 		} else {
 			$order->get_data_store()->set_recorded_coupon_usage_counts( $order, false );
 		}
+
+		if ( $data_store->has_callable( 'get_item_ids' ) ) {
+			try {
+				// @phpstan-ignore-next-line method.notFound (Guarded by has_callable() and called via __call() on the underlying order data store instance.)
+				$stored_item_ids = $data_store->get_item_ids( $order, 'coupon' );
+			} catch ( Exception $e ) {
+				// Give nothing back rather than risk giving a use back twice.
+				$stored_item_ids = array();
+			}
+
+			$stored_coupon_codes = array();
+			foreach ( $order->get_items( 'coupon' ) as $coupon_item ) {
+				if ( $coupon_item instanceof WC_Order_Item_Coupon && in_array( $coupon_item->get_id(), $stored_item_ids, true ) ) {
+					$stored_coupon_codes[] = $coupon_item->get_code();
+				}
+			}
+		}
 	} elseif ( ! $is_invalid && $coupon_codes && ! $has_recorded ) {
 		$action = 'increase';
 		$order->get_data_store()->set_recorded_coupon_usage_counts( $order, true );
@@ -1116,7 +1134,10 @@ function wc_update_coupon_usage_counts( $order_id ) {

 			switch ( $action ) {
 				case 'reduce':
-					$coupon->decrease_usage_count( $identities[ $coupon->get_id() ] ?? $used_by );
+					// A coupon removed from the order after it was loaded here already gave its use back.
+					if ( null === $stored_coupon_codes || in_array( $code, $stored_coupon_codes, true ) ) {
+						$coupon->decrease_usage_count( $identities[ $coupon->get_id() ] ?? $used_by );
+					}
 					break;
 				case 'increase':
 					$coupon->increase_usage_count( $used_by, $order );
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index dd2342fead1..3771eb67dff 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -10746,12 +10746,6 @@ parameters:
 			count: 1
 			path: includes/class-wc-customer.php

-		-
-			message: '#^Method WC_Data_Store\:\:delete\(\) has no return type specified\.$#'
-			identifier: missingType.return
-			count: 1
-			path: includes/class-wc-data-store.php
-
 		-
 			message: '#^Method WC_Data_Store\:\:read\(\) has no return type specified\.$#'
 			identifier: missingType.return
diff --git a/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php b/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php
index 0000759dcf7..6d8e74c275f 100644
--- a/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php
+++ b/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php
@@ -1042,6 +1042,27 @@ class OrdersTableDataStore extends \Abstract_WC_Order_Data_Store_CPT implements
 		return true;
 	}

+	/**
+	 * Reads the "coupon usage counted" flag straight from the database, skipping the order cache.
+	 *
+	 * @since 11.3.1
+	 *
+	 * @internal For use by WC_Abstract_Order::remove_coupon() only.
+	 *
+	 * @param \WC_Order $order Order object.
+	 * @return bool
+	 */
+	public function get_stored_recorded_coupon_usage_counts( $order ): bool {
+		global $wpdb;
+
+		$operational_data_table = self::get_operational_data_table_name();
+
+		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted table name.
+		$value = $wpdb->get_var( $wpdb->prepare( "SELECT coupon_usages_are_counted FROM {$operational_data_table} WHERE order_id = %d", $order->get_id() ) );
+
+		return (bool) $value;
+	}
+
 	/**
 	 * Whether email have been sent for this order.
 	 *
diff --git a/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php b/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php
index 79d4601c716..40d385652be 100644
--- a/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php
+++ b/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php
@@ -1100,6 +1100,167 @@ class WC_Abstract_Order_Test extends WC_Unit_Test_Case {
 		$this->assertEquals( 1, $coupon->get_usage_count() );
 	}

+	/**
+	 * @testdox Two copies of one order that both remove the same coupon give its use back only once.
+	 */
+	public function test_remove_coupon_from_two_copies_of_order_gives_use_back_once(): void {
+		$order       = $this->create_pending_order_with_counted_coupons( array( 'two-copies', 'two-copies-kept' ) );
+		$first_copy  = wc_get_order( $order->get_id() );
+		$second_copy = wc_get_order( $order->get_id() );
+		$this->assertCount( 2, $first_copy->get_items( 'coupon' ), 'The first copy should load both coupon lines' );
+		$this->assertCount( 2, $second_copy->get_items( 'coupon' ), 'The second copy should load both coupon lines before the first one removes a coupon' );
+		$decreases_before = did_action( 'woocommerce_decrease_coupon_usage_count' );
+		$removals_before  = did_action( 'woocommerce_order_removed_coupon' );
+		$deletes_before   = did_action( 'woocommerce_delete_order_item' );
+
+		$this->assertTrue( $first_copy->remove_coupon( 'two-copies' ), 'The first copy should remove the coupon' );
+		$this->assertSame( 1, did_action( 'woocommerce_delete_order_item' ) - $deletes_before, 'The coupon line should be deleted once, not again on save' );
+		$this->assertTrue( $second_copy->remove_coupon( 'two-copies' ), 'The second copy should also report the coupon as removed' );
+
+		$this->assertSame( 1, did_action( 'woocommerce_decrease_coupon_usage_count' ) - $decreases_before, 'The use should be given back once' );
+		$this->assertSame( 2, did_action( 'woocommerce_order_removed_coupon' ) - $removals_before, 'Both copies should fire the removed coupon hook' );
+		$this->assertSame( 5, ( new WC_Coupon( 'two-copies' ) )->get_usage_count(), 'The removed coupon should be back at its count before this order' );
+		$this->assertSame( 6, ( new WC_Coupon( 'two-copies-kept' ) )->get_usage_count(), 'The kept coupon should stay counted' );
+		$stored = wc_get_order( $order->get_id() );
+		$this->assertSame( array( 'two-copies-kept' ), $stored->get_coupon_codes(), 'Only the kept coupon should stay on the order' );
+		$this->assertTrue( $stored->get_data_store()->get_recorded_coupon_usage_counts( $stored ), 'The order should stay counted for the kept coupon' );
+	}
+
+	/**
+	 * @testdox Two copies of one order that both stage the removal of the same coupon and save give its use back only once.
+	 */
+	public function test_stage_coupon_removal_on_two_copies_of_order_gives_use_back_once(): void {
+		$order       = $this->create_pending_order_with_counted_coupons( array( 'two-staged-copies' ) );
+		$first_copy  = wc_get_order( $order->get_id() );
+		$second_copy = wc_get_order( $order->get_id() );
+		$this->assertCount( 1, $second_copy->get_items( 'coupon' ), 'The second copy should load the coupon line before the first one removes it' );
+
+		$this->assertTrue( $first_copy->stage_coupon_removal( 'two-staged-copies' ), 'The first copy should stage the removal' );
+		$this->assertTrue( $second_copy->stage_coupon_removal( 'two-staged-copies' ), 'The second copy should also stage the removal' );
+		$this->assertCount( 1, wc_get_order( $order->get_id() )->get_items( 'coupon' ), 'Staging should leave the stored coupon line until the save' );
+		$this->assertSame( 6, ( new WC_Coupon( 'two-staged-copies' ) )->get_usage_count(), 'Staging should not give the use back yet' );
+		$first_copy->save();
+		$second_copy->save();
+
+		$this->assertSame( 5, ( new WC_Coupon( 'two-staged-copies' ) )->get_usage_count(), 'The use should be given back once' );
+		$stored = wc_get_order( $order->get_id() );
+		$this->assertSame( array(), $stored->get_coupon_codes(), 'The coupon should be gone from the order' );
+		$this->assertFalse( $stored->get_data_store()->get_recorded_coupon_usage_counts( $stored ), 'The order should no longer be counted' );
+	}
+
+	/**
+	 * @testdox Removing two coupons one after the other gives each use back and clears the counted flag after the last one.
+	 */
+	public function test_remove_coupons_one_after_another_gives_each_use_back(): void {
+		$order = $this->create_pending_order_with_counted_coupons( array( 'sequence-first', 'sequence-second' ) );
+
+		$this->assertTrue( $order->remove_coupon( 'sequence-first' ) );
+		$this->assertSame( 5, ( new WC_Coupon( 'sequence-first' ) )->get_usage_count(), 'The first coupon should be given back' );
+		$this->assertSame( 6, ( new WC_Coupon( 'sequence-second' ) )->get_usage_count(), 'The second coupon should stay counted' );
+		$this->assertTrue( $order->get_data_store()->get_recorded_coupon_usage_counts( $order->get_id() ), 'The order should stay counted while a coupon remains' );
+
+		$this->assertTrue( $order->remove_coupon( 'sequence-second' ) );
+		$this->assertSame( 5, ( new WC_Coupon( 'sequence-second' ) )->get_usage_count(), 'The second coupon should be given back' );
+		$this->assertFalse( $order->get_data_store()->get_recorded_coupon_usage_counts( $order->get_id() ), 'The order should no longer be counted' );
+	}
+
+	/**
+	 * @testdox Removing a coupon gives the use back once when the coupon line's data store does not report deleted rows, and keeps it when the first delete fails.
+	 *
+	 * @testWith [null, false, 5]
+	 *           [false, false, 6]
+	 *           [null, true, 5]
+	 *
+	 * @param bool|null $first_result     What the coupon line data store's first delete() call returns.
+	 * @param bool      $cancel_meanwhile Whether a cancellation gives the use back while the line is being deleted.
+	 * @param int       $expected_count   Coupon usage count expected after the removal.
+	 */
+	public function test_remove_coupon_with_item_data_store_that_does_not_report_rows( ?bool $first_result, bool $cancel_meanwhile, int $expected_count ): void {
+		$order = $this->create_pending_order_with_counted_coupons( array( 'custom-item-store' ) );
+		$store = new class() extends WC_Order_Item_Coupon_Data_Store {
+			/**
+			 * What the first delete() call returns: null deletes the row and reports nothing, false fails like a database error.
+			 *
+			 * @var bool|null
+			 */
+			public $first_result;
+
+			/**
+			 * Number of delete() calls.
+			 *
+			 * @var int
+			 */
+			private $calls = 0;
+
+			/**
+			 * Delete the item and report nothing, failing the first call when set up to.
+			 *
+			 * @param WC_Order_Item $item Order item.
+			 * @param array         $args Delete arguments.
+			 * @return bool|null
+			 */
+			public function delete( &$item, $args = array() ) {
+				++$this->calls;
+				if ( 1 === $this->calls && false === $this->first_result ) {
+					return false;
+				}
+				parent::delete( $item, $args );
+				return null;
+			}
+		};
+
+		$store->first_result = $first_result;
+		add_filter(
+			'woocommerce_data_stores',
+			function ( $stores ) use ( $store ) {
+				$stores['order-item-coupon'] = $store;
+				return $stores;
+			}
+		);
+
+		$removing_copy = wc_get_order( $order->get_id() );
+		if ( $cancel_meanwhile ) {
+			$has_run = false;
+			add_action(
+				'woocommerce_before_delete_order_item',
+				function () use ( $order, &$has_run ) {
+					if ( ! $has_run ) {
+						$has_run = true;
+						wc_get_order( $order->get_id() )->update_status( OrderStatus::CANCELLED );
+					}
+				}
+			);
+		}
+
+		$this->assertTrue( $removing_copy->remove_coupon( 'custom-item-store' ), 'The coupon should be removed' );
+
+		$this->assertSame( array(), $order->get_data_store()->get_item_ids( $order, 'coupon' ), 'The coupon line should be deleted, by the save when the first delete failed' );
+		$this->assertSame( $expected_count, ( new WC_Coupon( 'custom-item-store' ) )->get_usage_count(), 'The use should be given back once when the store reports nothing, and kept when the first delete failed' );
+	}
+
+	/**
+	 * Create a pending order that counted a use of each coupon. Each coupon starts at 5 uses, so 6 with this order.
+	 *
+	 * The count starts above 1 because WC_Coupon::decrease_usage_count() skips a coupon whose loaded count is 0,
+	 * which would hide a second release.
+	 *
+	 * @param string[] $codes Coupon codes to create and apply.
+	 * @return WC_Order
+	 */
+	private function create_pending_order_with_counted_coupons( array $codes ): WC_Order {
+		$order = WC_Helper_Order::create_order();
+		$order->set_status( OrderStatus::PENDING );
+		$order->save();
+		foreach ( $codes as $code ) {
+			WC_Helper_Coupon::create_coupon( $code, array( 'usage_count' => 5 ) );
+			$order->apply_coupon( $code );
+			$this->assertSame( 6, ( new WC_Coupon( $code ) )->get_usage_count(), 'The order should count its coupon use' );
+		}
+		$this->assertTrue( $order->get_data_store()->get_recorded_coupon_usage_counts( $order->get_id() ), 'The order should be marked as counted' );
+
+		return $order;
+	}
+
 	/**
 	 * Create a pending order with one $100 product whose line total was manually edited to $50.
 	 *
diff --git a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php
index 72c67842dc6..44e5314df51 100644
--- a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php
+++ b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php
@@ -2146,6 +2146,31 @@ class WC_Order_Data_Store_CPT_Test extends WC_Unit_Test_Case {
 		$this->assertFalse( $sut->clear_recorded_coupon_usage_counts( $order ), 'A cleared flag should not be cleared again' );
 	}

+	/**
+	 * @testdox get_stored_recorded_coupon_usage_counts() reads the flag from the database, not from the cache.
+	 */
+	public function test_get_stored_recorded_coupon_usage_counts(): void {
+		global $wpdb;
+
+		$sut   = new WC_Order_Data_Store_CPT();
+		$order = $this->create_cancelled_order_with_counted_coupon_usage( $sut );
+		$this->assertFalse( $sut->get_stored_recorded_coupon_usage_counts( WC_Helper_Order::create_order() ), 'An order without the flag should read as not counted' );
+		$this->assertTrue( $sut->get_stored_recorded_coupon_usage_counts( $order ), 'A set flag should read as counted' );
+
+		$this->assertTrue( $sut->get_recorded_coupon_usage_counts( $order ), 'The cached read should see the set flag' );
+		$wpdb->update(
+			$wpdb->postmeta,
+			array( 'meta_value' => 'no' ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
+			array(
+				'post_id'  => $order->get_id(),
+				'meta_key' => '_recorded_coupon_usage_counts', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
+			)
+		);
+
+		$this->assertTrue( $sut->get_recorded_coupon_usage_counts( $order ), 'The cached read should still see the old value' );
+		$this->assertFalse( $sut->get_stored_recorded_coupon_usage_counts( $order ), 'The stored read should see the cleared flag' );
+	}
+
 	/**
 	 * Create a cancelled order marked as having its coupon usage counted.
 	 *
diff --git a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-item-data-store-test.php b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-item-data-store-test.php
index f38817e7fc7..86d743efb86 100644
--- a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-item-data-store-test.php
+++ b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-item-data-store-test.php
@@ -345,4 +345,22 @@ class WC_Order_Item_Data_Store_Test extends WC_Unit_Test_Case {
 		$this->assertSame( '7', $reloaded_coupon->get_discount() );
 		$this->assertSame( '2', $reloaded_coupon->get_discount_tax() );
 	}
+
+	/**
+	 * @testdox Deleting an order item through the data store returns how many item rows the call deleted.
+	 */
+	public function test_delete_returns_number_of_deleted_rows(): void {
+		$order = WC_Helper_Order::create_order();
+		$item  = new WC_Order_Item_Coupon();
+		$item->set_code( 'delete-count' );
+		$order->add_item( $item );
+		$order->save();
+		$first_copy  = new WC_Order_Item_Coupon( $item->get_id() );
+		$second_copy = new WC_Order_Item_Coupon( $item->get_id() );
+		$unsaved     = new WC_Order_Item_Coupon();
+
+		$this->assertSame( 1, $first_copy->get_data_store()->delete( $first_copy ), 'The first delete should remove the row' );
+		$this->assertSame( 0, $second_copy->get_data_store()->delete( $second_copy ), 'A second delete of the same row should remove nothing' );
+		$this->assertSame( 0, $unsaved->get_data_store()->delete( $unsaved ), 'An item without ID should remove nothing' );
+	}
 }
diff --git a/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php b/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php
index 114bb792459..c8aa3ea8e04 100644
--- a/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php
+++ b/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php
@@ -213,6 +213,129 @@ class WC_Update_Coupon_Usage_Counts_Test extends \WC_Unit_Test_Case {
 		$this->assertSame( 'no', get_post_meta( $order_id, '_recorded_coupon_usage_counts', true ), 'The order should no longer be marked as counted' );
 	}

+	/**
+	 * @testdox Cancelling an order does not give back a coupon use that a coupon removal gave back after the order was loaded.
+	 *
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+	 */
+	public function test_cancel_skips_coupon_removed_by_another_request( bool $hpos_enabled ): void {
+		$this->toggle_cot_authoritative( $hpos_enabled );
+		$order = $this->create_pending_order_with_counted_coupon( 'removed-meanwhile' );
+		WC_Helper_Coupon::create_coupon( 'kept-meanwhile' );
+		$order->apply_coupon( 'kept-meanwhile' );
+
+		$this->run_once_between_flag_read_and_write(
+			function () use ( $order ) {
+				wc_get_order( $order->get_id() )->remove_coupon( 'removed-meanwhile' );
+			}
+		);
+		$order->update_status( OrderStatus::CANCELLED );
+
+		$this->assertSame( 1, ( new WC_Coupon( 'removed-meanwhile' ) )->get_usage_count(), 'The removed coupon should be given back only by the removal' );
+		$this->assertSame( 0, ( new WC_Coupon( 'kept-meanwhile' ) )->get_usage_count(), 'The coupon still on the order should be given back by the cancellation' );
+	}
+
+	/**
+	 * @testdox Removing one of two coupons does not give its use back, or mark the order as counted again, when the order was cancelled while the coupon line was being deleted.
+	 *
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+	 */
+	public function test_remove_coupon_skips_use_given_back_by_cancel_meanwhile( bool $hpos_enabled ): void {
+		$this->toggle_cot_authoritative( $hpos_enabled );
+		$order   = $this->create_pending_order_with_counted_coupon( 'cancelled-meanwhile' );
+		$item_id = array_key_first( $order->get_items( 'coupon' ) );
+		WC_Helper_Coupon::create_coupon( 'kept-on-cancel' );
+		$order->apply_coupon( 'kept-on-cancel' );
+
+		$has_run = false;
+		add_action(
+			'woocommerce_before_delete_order_item',
+			function ( $deleted_item_id ) use ( $order, $item_id, &$has_run ) {
+				if ( ! $has_run && (int) $deleted_item_id === (int) $item_id ) {
+					$has_run = true;
+					wc_get_order( $order->get_id() )->update_status( OrderStatus::CANCELLED );
+				}
+			}
+		);
+		$this->assertTrue( $order->remove_coupon( 'cancelled-meanwhile' ), 'The coupon should be removed' );
+
+		$this->assertTrue( $has_run, 'The cancellation should run while the coupon line is deleted' );
+		$this->assertSame( OrderStatus::CANCELLED, wc_get_order( $order->get_id() )->get_status(), 'The order should stay cancelled after the removal saves it' );
+		$this->assertFalse( $order->get_data_store()->get_stored_recorded_coupon_usage_counts( $order ), 'The cancelled order should stay marked as not counted' );
+		$this->assertSame( 1, ( new WC_Coupon( 'cancelled-meanwhile' ) )->get_usage_count(), 'The use should be given back only by the cancellation' );
+		$this->assertCount( 1, ( new WC_Coupon( 'cancelled-meanwhile' ) )->get_used_by(), 'Only one customer use record should be removed' );
+		$this->assertSame( 0, ( new WC_Coupon( 'kept-on-cancel' ) )->get_usage_count(), 'The cancellation should give back the coupon still on the order' );
+	}
+
+	/**
+	 * @testdox A cancellation that lands right after a coupon removal deletes the line does not give the use back twice.
+	 *
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+	 */
+	public function test_cancel_right_after_coupon_line_delete_does_not_give_use_back_twice( bool $hpos_enabled ): void {
+		$this->toggle_cot_authoritative( $hpos_enabled );
+		$order   = $this->create_pending_order_with_counted_coupon( 'cancelled-after-delete' );
+		$item_id = array_key_first( $order->get_items( 'coupon' ) );
+
+		$has_run = false;
+		add_action(
+			'woocommerce_delete_order_item',
+			function ( $deleted_item_id ) use ( $order, $item_id, &$has_run ) {
+				if ( ! $has_run && (int) $deleted_item_id === (int) $item_id ) {
+					$has_run = true;
+					wc_get_order( $order->get_id() )->update_status( OrderStatus::CANCELLED );
+				}
+			}
+		);
+		$this->assertTrue( $order->remove_coupon( 'cancelled-after-delete' ), 'The coupon should be removed' );
+
+		$this->assertTrue( $has_run, 'The cancellation should run right after the coupon line is deleted' );
+		$this->assertSame( 2, ( new WC_Coupon( 'cancelled-after-delete' ) )->get_usage_count(), 'At this exact moment both requests skip the use, so it stays counted rather than given back twice' );
+		$this->assertCount( 2, ( new WC_Coupon( 'cancelled-after-delete' ) )->get_used_by(), 'No customer use record should be removed' );
+	}
+
+	/**
+	 * @testdox A removal that finds the coupon line already deleted does not stop the removal that deleted it from giving the use back.
+	 *
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+	 */
+	public function test_losing_removal_keeps_flag_for_winning_removal( bool $hpos_enabled ): void {
+		$this->toggle_cot_authoritative( $hpos_enabled );
+		$order       = $this->create_pending_order_with_counted_coupon( 'lost-removal' );
+		$winner      = wc_get_order( $order->get_id() );
+		$loser       = wc_get_order( $order->get_id() );
+		$item_id     = array_key_first( $winner->get_items( 'coupon' ) );
+		$loser_items = $loser->get_items( 'coupon' );
+		$this->assertArrayHasKey( $item_id, $loser_items, 'The losing copy should load the coupon line before it is deleted' );
+
+		$has_run = false;
+		add_action(
+			'woocommerce_delete_order_item',
+			function ( $deleted_item_id ) use ( $loser, $item_id, &$has_run ) {
+				if ( ! $has_run && (int) $deleted_item_id === (int) $item_id ) {
+					$has_run = true;
+					$loser->remove_coupon( 'lost-removal' );
+				}
+			}
+		);
+		$this->assertTrue( $winner->remove_coupon( 'lost-removal' ), 'The coupon should be removed' );
+
+		$this->assertTrue( $has_run, 'The losing removal should run right after the line is deleted' );
+		$this->assertSame( 1, ( new WC_Coupon( 'lost-removal' ) )->get_usage_count(), 'The use should be given back once' );
+	}
+
 	/**
 	 * Create a pending order whose coupon use is counted, after another order already used the same coupon.
 	 *
diff --git a/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php b/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
index 28fc3202703..f0a745b9d4e 100644
--- a/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
+++ b/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
@@ -4836,6 +4836,27 @@ class OrdersTableDataStoreTests extends \HposTestCase {
 		$this->assertFalse( $this->sut->clear_recorded_coupon_usage_counts( $order ), 'A cleared flag should not be cleared again' );
 	}

+	/**
+	 * @testDox get_stored_recorded_coupon_usage_counts() reads the flag from the database, not from the order cache.
+	 */
+	public function test_get_stored_recorded_coupon_usage_counts(): void {
+		global $wpdb;
+
+		$this->toggle_cot_feature_and_usage( true );
+		$order = $this->create_cancelled_order_with_counted_coupon_usage();
+		$this->assertFalse( $this->sut->get_stored_recorded_coupon_usage_counts( OrderHelper::create_order() ), 'An order without the flag should read as not counted' );
+		$this->assertTrue( $this->sut->get_stored_recorded_coupon_usage_counts( $order ), 'A set flag should read as counted' );
+
+		$wpdb->update(
+			OrdersTableDataStore::get_operational_data_table_name(),
+			array( 'coupon_usages_are_counted' => 0 ),
+			array( 'order_id' => $order->get_id() )
+		);
+
+		$this->assertTrue( $order->get_recorded_coupon_usage_counts(), 'The loaded order should still see the old value' );
+		$this->assertFalse( $this->sut->get_stored_recorded_coupon_usage_counts( $order ), 'The stored read should see the cleared flag' );
+	}
+
 	/**
 	 * Create a cancelled order marked as having its coupon usage counted.
 	 *