Commit 836078373d0 for woocommerce

commit 836078373d053290b7aae8f30592f5e419e3f674
Author: Vlad Olaru <vlad.olaru@automattic.com>
Date:   Wed Nov 18 17:48:46 2026 +0200

    Fix variable products losing custom stock statuses (#68546)

    * fix: preserve custom variable stock statuses

    Variable product synchronization only recognizes WooCommerce's three built-in stock statuses, so a parent is forced out of stock even when every variation shares a registered custom status.

    Preserve the overridable built-in precedence checks, then inherit a custom status only when one registered byte-identical value accounts for every child. Ambiguous, stale, and malformed status sets retain the conservative out-of-stock result.

    Refs #45463

    * chore: add custom stock sync changelog

    Record the variable-product custom stock synchronization fix for release notes.

    Refs #45463

    * fix(woocommerce): use CAST( ... AS BINARY ) for child stock comparison

    The child stock status aggregate compared values byte-for-byte using the
    BINARY operator. MySQL deprecated that operator in 8.0.27 and documents
    it as subject to removal, recommending CAST( ... AS BINARY ) instead.

    Were the operator to be removed, the failure would be silent rather than
    loud: the query errors, get_var() returns null, is_string() is false, and
    the derived status falls back to out of stock. That is #45463 again, on a
    production store, with nothing shown to the merchant.

    CAST( ... AS BINARY ) is the documented equivalent and is already the
    form OrdersTableMetaQuery builds for binary meta comparisons.

    Refs #45463

    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

    * docs(woocommerce): explain why the custom-status branch queries directly

    The delegation note read as though sync_stock_status() always routes
    child checks through overridable methods. That is true of the in-stock
    and on-backorder branches, but not of the custom-status branch added for
    #45463, which queries the lookup table or postmeta directly.

    Say why. child_has_stock_status() stops at the first match, so it answers
    "does any child have this status" rather than "do all children agree",
    which is what the custom-status branch needs. No existing overridable
    child check expresses that question, so the branch cannot delegate
    without adding new public API.

    Refs #45463

    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

    * test(woocommerce): pin catalog visibility of a custom-status parent

    Inheriting a custom status changes where the parent appears. Once the
    stored status is no longer outofstock, update_visibility() stops adding
    the outofstock visibility term, and it rewrites the whole term set on
    every save, so the term goes away. With "Hide out of stock items" on,
    the parent returns to the catalog.

    That is deliberate: a simple product holding a custom status is already
    visible today, and this makes variable parents behave the same way. It
    was untested, though, so nothing would catch a silent flip either way.

    Assert through the real catalog query rather than is_visible(). The
    latter routes through is_in_stock(), which returns the same answer
    before and after this change once a store filters
    woocommerce_product_is_in_stock, so a test built on it catches nothing.

    Refs #45463

    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

    * test(woocommerce): Import ProductStatus in variable data store test

    The catalog visibility test added for custom-status parents uses
    ProductStatus::PUBLISH, but the file only imported ProductStockStatus.
    Every PHP unit test job failed with "Class ProductStatus not found".

    Refs #45463

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

    * test(woocommerce): tighten child stock status agreement coverage

    A mutation pass over the custom-status agreement rules found two rules
    whose removal no test caught.

    The byte-for-byte test only rewrote the second child's stored value to
    CUSTOM_STATUS_A, which is not registered. A case-insensitive comparison
    then still fell back to out of stock through the registration check, so
    the test passed whether or not the comparison was byte exact. It now
    runs for a case difference and a trailing space in both storage modes,
    and registers the variant too, so only the comparison can reject it.

    Nothing covered the custom-options check either: when an extension's
    child_is_in_stock() and child_is_on_backorder() report no stock while
    storage says instock, the parent must not inherit instock from storage.
    Add a test for that.

    Both tests pass against the current aggregate SQL, so they pin existing
    behavior ahead of restructuring it.

    Refs #45463

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

    * refactor(woocommerce): check custom stock status agreement in PHP

    The custom-status branch of sync_stock_status() decided whether all
    children agree inside one aggregate query: MIN over CAST( ... AS
    BINARY ), with four HAVING clauses rejecting missing, NULL, duplicate
    and differing rows. Review asked for the status logic in private
    methods, with the database read kept apart from the calculation, and
    questioned CAST( ... AS BINARY ) on SQLite and its cost.

    Split the branch into steps:

    - get_custom_stock_status_options() and child ID normalization run
      before the read.
    - read_child_stock_statuses() is a plain SELECT of child ID and status
      from the lookup table, or postmeta while it regenerates.
    - get_shared_stock_status() is a pure static method: one row per
      child, none NULL, all equal with ===.
    - set_custom_or_out_of_stock_status() applies the result.

    With the comparison in PHP the query no longer depends on how a driver
    translates CAST( ... AS BINARY ). The rows are one per variation,
    matched through the primary key, so the read costs no more than the
    aggregate did.

    Also drop the re-check of the registered options before the setter.
    The guard after it already turns a status the setter rejects into out
    of stock, so the parent can never end up in stock through this path.
    The only difference is when a registration disappears in the middle of
    one sync: a parent already out of stock then records a no-op change.
    The registration-change test now covers that single case.

    Refs #45463

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

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    * Minor tweaks.

    ---------

    Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
    Co-authored-by: Oleksandr Aratovskyi <79862886+oaratovskyi@users.noreply.github.com>
    Co-authored-by: kalessil <kalessil@gmail.com>

diff --git a/plugins/woocommerce/changelog/fix-variable-custom-stock-status b/plugins/woocommerce/changelog/fix-variable-custom-stock-status
new file mode 100644
index 00000000000..52140ad3c12
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-variable-custom-stock-status
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Preserve unanimous registered custom stock statuses when synchronizing variable products.
diff --git a/plugins/woocommerce/includes/data-stores/class-wc-product-variable-data-store-cpt.php b/plugins/woocommerce/includes/data-stores/class-wc-product-variable-data-store-cpt.php
index 9562c09f560..e36aac9903c 100644
--- a/plugins/woocommerce/includes/data-stores/class-wc-product-variable-data-store-cpt.php
+++ b/plugins/woocommerce/includes/data-stores/class-wc-product-variable-data-store-cpt.php
@@ -994,12 +994,104 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple
 	 * @since 3.0.0
 	 */
 	public function sync_stock_status( &$product ) {
-		// Performance note: direct DB fetch would be faster, but child_is_in_stock/child_is_on_backorder are overridable — keep delegation.
+		// child_is_in_stock()/child_is_on_backorder() are overridable hence keep delegation. The custom-status branch queries
+		// directly: it needs "do all children agree", which child_has_stock_status() (first-match) cannot answer.
 		if ( $product->child_is_in_stock() ) {
 			$product->set_stock_status( ProductStockStatus::IN_STOCK );
 		} elseif ( $product->child_is_on_backorder() ) {
 			$product->set_stock_status( ProductStockStatus::ON_BACKORDER );
 		} else {
+			$this->set_custom_or_out_of_stock_status( $product, $this->get_unanimous_custom_child_stock_status( $product ) );
+		}
+	}
+
+	/**
+	 * Get the registered custom stock status every child shares, or out of stock when they don't all share one.
+	 *
+	 * @param WC_Product_Variable $product Product object.
+	 * @return string
+	 */
+	private function get_unanimous_custom_child_stock_status( $product ): string {
+		$custom_statuses = $this->get_custom_stock_status_options();
+		if ( $custom_statuses ) {
+			$child_ids           = array_values( array_unique( array_filter( array_map( 'absint', (array) $product->get_children() ) ) ) );
+			$shared_stock_status = $child_ids ? $this->get_shared_stock_status( $child_ids, $this->read_child_stock_statuses( $child_ids ) ) : null;
+			if ( null !== $shared_stock_status && array_key_exists( $shared_stock_status, $custom_statuses ) ) {
+				return $shared_stock_status;
+			}
+		}
+
+		return ProductStockStatus::OUT_OF_STOCK;
+	}
+
+	/**
+	 * Get the registered stock status options, excluding the three core statuses.
+	 *
+	 * @return array<string, string>
+	 */
+	private function get_custom_stock_status_options(): array {
+		$core_stock_statuses = array(
+			ProductStockStatus::IN_STOCK     => true,
+			ProductStockStatus::OUT_OF_STOCK => true,
+			ProductStockStatus::ON_BACKORDER => true,
+		);
+
+		return array_diff_key( wc_get_product_stock_status_options(), $core_stock_statuses );
+	}
+
+	/**
+	 * Read the stored stock status rows of the given children, from postmeta while the lookup table is regenerating.
+	 *
+	 * @param int[] $child_ids Child product IDs.
+	 * @return array<int, array{child_id: string, stock_status: string|null}>
+	 */
+	private function read_child_stock_statuses( array $child_ids ): array {
+		global $wpdb;
+
+		$placeholders = implode( ', ', array_fill( 0, count( $child_ids ), '%d' ) );
+		if ( get_option( 'woocommerce_product_lookup_table_is_generating' ) ) {
+			$query = "SELECT post_id AS child_id, meta_value AS stock_status FROM {$wpdb->postmeta} WHERE meta_key = '_stock_status' AND post_id IN ( {$placeholders} )";
+		} else {
+			$query = "SELECT product_id AS child_id, stock_status FROM {$wpdb->wc_product_meta_lookup} WHERE product_id IN ( {$placeholders} )";
+		}
+
+		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
+		$rows = $wpdb->get_results( $wpdb->prepare( $query, ...$child_ids ), ARRAY_A );
+
+		return is_array( $rows ) ? $rows : array();
+	}
+
+	/**
+	 * Get the stock status shared by all children, or null when a child has no row, several rows, a NULL status or a different status.
+	 *
+	 * @param int[]                                                          $child_ids Child product IDs.
+	 * @param array<int, array{child_id: string, stock_status: string|null}> $rows      Stored stock status rows of those children.
+	 * @return string|null
+	 */
+	private function get_shared_stock_status( array $child_ids, array $rows ): ?string {
+		$child_statuses = array_filter( array_column( $rows, 'stock_status', 'child_id' ) );
+		$children_count = count( $child_ids );
+		if ( count( $child_statuses ) === $children_count && count( $rows ) === $children_count ) {
+			$unique = array_values( array_unique( $child_statuses ) );
+			if ( 1 === count( $unique ) ) {
+				return $unique[0];
+			}
+		}
+
+		return null;
+	}
+
+	/**
+	 * Apply a derived custom stock status, falling back to out of stock if the setter rejects it.
+	 *
+	 * The setter replaces a status it does not recognize with in stock, which is never right when no child is in stock.
+	 *
+	 * @param WC_Product_Variable $product      Product object.
+	 * @param string              $stock_status Custom stock status, or out of stock.
+	 */
+	private function set_custom_or_out_of_stock_status( $product, string $stock_status ): void {
+		$product->set_stock_status( $stock_status );
+		if ( $stock_status !== $product->get_stock_status( 'edit' ) ) {
 			$product->set_stock_status( ProductStockStatus::OUT_OF_STOCK );
 		}
 	}
diff --git a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-product-variable-data-store-cpt-test.php b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-product-variable-data-store-cpt-test.php
index cc6ec683936..8282e661239 100644
--- a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-product-variable-data-store-cpt-test.php
+++ b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-product-variable-data-store-cpt-test.php
@@ -1,5 +1,6 @@
 <?php declare( strict_types = 1 );

+use Automattic\WooCommerce\Enums\ProductStatus;
 use Automattic\WooCommerce\Enums\ProductStockStatus;

 /**
@@ -97,6 +98,7 @@ class WC_Product_Variable_Data_Store_CPT_Test extends WC_Unit_Test_Case {
 	 */
 	public function tearDown(): void {
 		delete_option( 'woocommerce_product_lookup_table_is_generating' );
+		delete_option( 'woocommerce_hide_out_of_stock_items' );
 		parent::tearDown();
 	}

@@ -113,6 +115,432 @@ class WC_Product_Variable_Data_Store_CPT_Test extends WC_Unit_Test_Case {
 		);
 	}

+	/**
+	 * Create a variable product with children using the supplied stock statuses.
+	 *
+	 * @param string[] $stock_statuses Child stock statuses.
+	 * @return WC_Product_Variable
+	 */
+	private function create_variable_product_with_child_stock_statuses( array $stock_statuses ): WC_Product_Variable {
+		$product = new WC_Product_Variable();
+		$product->set_name( 'Variable product for stock status sync' );
+		$product->save();
+
+		$child_ids = array();
+		foreach ( $stock_statuses as $stock_status ) {
+			$variation = new WC_Product_Variation();
+			$variation->set_parent_id( $product->get_id() );
+			$variation->set_stock_status( $stock_status );
+			$child_ids[] = $variation->save();
+		}
+
+		$product->set_children( $child_ids );
+
+		return $product;
+	}
+
+	/**
+	 * Register custom stock statuses for the current test.
+	 *
+	 * @param string[] $custom_stock_statuses Custom stock status keys.
+	 * @return Closure Removable registration callback.
+	 */
+	private function register_custom_stock_statuses( array $custom_stock_statuses ): Closure {
+		$register = static function ( $stock_statuses ) use ( $custom_stock_statuses ) {
+			return array_merge( $stock_statuses, array_fill_keys( $custom_stock_statuses, 'Custom status' ) );
+		};
+		add_filter( 'woocommerce_product_stock_status_options', $register );
+
+		return $register;
+	}
+
+	/**
+	 * Named stock status sync scenarios for lookup and postmeta storage.
+	 *
+	 * @return array<string, array{bool, string[], string}>
+	 */
+	public static function stock_status_sync_data(): array {
+		$scenarios = array(
+			'unanimous custom status' => array( array( 'custom_status_a', 'custom_status_a' ), 'custom_status_a' ),
+			'mixed custom statuses'   => array( array( 'custom_status_a', 'custom_status_b' ), ProductStockStatus::OUT_OF_STOCK ),
+			'custom and out of stock' => array( array( 'custom_status_a', ProductStockStatus::OUT_OF_STOCK ), ProductStockStatus::OUT_OF_STOCK ),
+			'custom and in stock'     => array( array( 'custom_status_a', ProductStockStatus::IN_STOCK ), ProductStockStatus::IN_STOCK ),
+			'custom and on backorder' => array( array( 'custom_status_a', ProductStockStatus::ON_BACKORDER ), ProductStockStatus::ON_BACKORDER ),
+			'no children'             => array( array(), ProductStockStatus::OUT_OF_STOCK ),
+		);
+		$data      = array();
+
+		foreach ( array( false, true ) as $lookup_table_is_generating ) {
+			$storage_name = $lookup_table_is_generating ? 'postmeta' : 'lookup table';
+			foreach ( $scenarios as $scenario_name => $scenario ) {
+				$data[ "$storage_name: $scenario_name" ] = array( $lookup_table_is_generating, $scenario[0], $scenario[1] );
+			}
+		}
+
+		return $data;
+	}
+
+	/**
+	 * @testdox sync_stock_status() derives the parent status from its children.
+	 * @dataProvider stock_status_sync_data
+	 *
+	 * @param bool     $lookup_table_is_generating Whether lookup table generation is active.
+	 * @param string[] $child_stock_statuses Child stock statuses.
+	 * @param string   $expected_stock_status Expected parent stock status.
+	 */
+	public function test_sync_stock_status_derives_parent_status_from_children( bool $lookup_table_is_generating, array $child_stock_statuses, string $expected_stock_status ): void {
+		$this->register_custom_stock_statuses( array( 'custom_status_a', 'custom_status_b' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', $lookup_table_is_generating );
+
+		$product    = $this->create_variable_product_with_child_stock_statuses( $child_stock_statuses );
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( $expected_stock_status, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() uses unique nonzero children supplied by the children filter.
+	 * @dataProvider provider_lookup_table_generating
+	 *
+	 * @param bool $lookup_table_is_generating Whether lookup table generation is active.
+	 */
+	public function test_sync_stock_status_normalizes_filtered_children( bool $lookup_table_is_generating ): void {
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', $lookup_table_is_generating );
+		$product = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		add_filter(
+			'woocommerce_get_children',
+			static function ( $children ) {
+				return array_merge( $children, array( (string) $children[0], 0 ) );
+			}
+		);
+
+		$sut = new WC_Product_Variable_Data_Store_CPT();
+		$sut->sync_stock_status( $product );
+
+		$this->assertSame( 'custom_status_a', $product->get_stock_status( 'edit' ) );
+	}
+
+	/**
+	 * @testdox sync_stock_status() rejects a stale stored custom status when another custom status remains registered.
+	 * @dataProvider provider_lookup_table_generating
+	 *
+	 * @param bool $lookup_table_is_generating Whether lookup table generation is active.
+	 */
+	public function test_sync_stock_status_rejects_stale_stored_custom_status_when_another_custom_status_is_registered( bool $lookup_table_is_generating ): void {
+		$register_stored_statuses = $this->register_custom_stock_statuses( array( 'custom_status_a', 'custom_status_b' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', $lookup_table_is_generating );
+
+		$product = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_b', 'custom_status_b' ) );
+		remove_filter( 'woocommerce_product_stock_status_options', $register_stored_statuses );
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() rejects a custom status when a child storage row is missing.
+	 * @dataProvider provider_lookup_table_generating
+	 *
+	 * @param bool $lookup_table_is_generating Whether lookup table generation is active.
+	 */
+	public function test_sync_stock_status_rejects_custom_status_when_child_storage_row_is_missing( bool $lookup_table_is_generating ): void {
+		global $wpdb;
+
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', $lookup_table_is_generating );
+
+		$product          = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		$missing_child_id = $product->get_children()[0];
+
+		if ( $lookup_table_is_generating ) {
+			delete_post_meta( $missing_child_id, '_stock_status' );
+		} else {
+			$wpdb->delete( $wpdb->wc_product_meta_lookup, array( 'product_id' => $missing_child_id ), array( '%d' ) );
+		}
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() rejects duplicate postmeta even when its row count masks a missing child.
+	 * @testWith [false]
+	 *           [true]
+	 *
+	 * @param bool $missing_child Whether another child's stock status is missing.
+	 */
+	public function test_sync_stock_status_rejects_custom_status_when_child_has_duplicate_identical_postmeta_rows( bool $missing_child ): void {
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', true );
+
+		$product             = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		$duplicated_child_id = $product->get_children()[0];
+		add_post_meta( $duplicated_child_id, '_stock_status', 'custom_status_a' );
+		if ( $missing_child ) {
+			delete_post_meta( $product->get_children()[1], '_stock_status' );
+		}
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() rejects a custom status when child storage contains a NULL status value.
+	 * @dataProvider provider_lookup_table_generating
+	 *
+	 * @param bool $lookup_table_is_generating Whether lookup table generation is active.
+	 */
+	public function test_sync_stock_status_rejects_custom_status_when_child_storage_contains_null( bool $lookup_table_is_generating ): void {
+		global $wpdb;
+
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', $lookup_table_is_generating );
+
+		$product        = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		$affected_child = $product->get_children()[0];
+
+		if ( $lookup_table_is_generating ) {
+			$wpdb->query(
+				$wpdb->prepare(
+					"INSERT INTO {$wpdb->postmeta} ( post_id, meta_key, meta_value ) VALUES ( %d, %s, NULL )",
+					$affected_child,
+					'_stock_status'
+				)
+			);
+		} else {
+			$wpdb->query(
+				$wpdb->prepare(
+					"UPDATE {$wpdb->wc_product_meta_lookup} SET stock_status = NULL WHERE product_id = %d",
+					$affected_child
+				)
+			);
+		}
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+	}
+
+	/**
+	 * Storage modes combined with stored values that differ from `custom_status_a` only in case or trailing space.
+	 *
+	 * @return array<string, array{bool, string}>
+	 */
+	public static function byte_for_byte_comparison_data(): array {
+		$data = array();
+		foreach ( array( false, true ) as $lookup_table_is_generating ) {
+			$storage_name = $lookup_table_is_generating ? 'postmeta' : 'lookup table';
+
+			$data[ "{$storage_name}: different case" ] = array( $lookup_table_is_generating, 'CUSTOM_STATUS_A' );
+			$data[ "{$storage_name}: trailing space" ] = array( $lookup_table_is_generating, 'custom_status_a ' );
+		}
+
+		return $data;
+	}
+
+	/**
+	 * @testdox sync_stock_status() compares child statuses byte-for-byte in each storage mode.
+	 * @dataProvider byte_for_byte_comparison_data
+	 *
+	 * @param bool   $lookup_table_is_generating Whether lookup table generation is active.
+	 * @param string $mutated_stock_status       Stored value of the second child, registered too so only the comparison can reject it.
+	 */
+	public function test_sync_stock_status_compares_child_statuses_byte_for_byte( bool $lookup_table_is_generating, string $mutated_stock_status ): void {
+		global $wpdb;
+
+		$this->register_custom_stock_statuses( array( 'custom_status_a', $mutated_stock_status ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', $lookup_table_is_generating );
+
+		$product          = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		$mutated_child_id = $product->get_children()[1];
+
+		if ( $lookup_table_is_generating ) {
+			$wpdb->update(
+				$wpdb->postmeta,
+				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Direct mutation is required to create malformed storage.
+				array( 'meta_value' => $mutated_stock_status ),
+				array(
+					'post_id'  => $mutated_child_id,
+					// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Direct mutation is required to create malformed storage.
+					'meta_key' => '_stock_status',
+				),
+				array( '%s' ),
+				array( '%d', '%s' )
+			);
+		} else {
+			$wpdb->update(
+				$wpdb->wc_product_meta_lookup,
+				array( 'stock_status' => $mutated_stock_status ),
+				array( 'product_id' => $mutated_child_id ),
+				array( '%s' ),
+				array( '%d' )
+			);
+		}
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() falls back to out of stock when the custom status stops being registered before the setter runs.
+	 */
+	public function test_sync_stock_status_falls_back_when_custom_status_registration_changes_during_sync(): void {
+		$register_status_once = static function ( $stock_statuses ) {
+			static $invocation_count = 0;
+
+			++$invocation_count;
+			if ( 1 === $invocation_count ) {
+				$stock_statuses['custom_status_a'] = 'Custom status A';
+			}
+
+			return $stock_statuses;
+		};
+
+		$register_stable_status = $this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', false );
+
+		$product = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		$product->set_stock_status( ProductStockStatus::IN_STOCK );
+		$product->apply_changes();
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		remove_filter( 'woocommerce_product_stock_status_options', $register_stable_status );
+		add_filter( 'woocommerce_product_stock_status_options', $register_status_once );
+
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+		$this->assertSame( array( 'stock_status' => ProductStockStatus::OUT_OF_STOCK ), $product->get_changes() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() leaves a clean product unchanged when it already has the unanimous custom status.
+	 */
+	public function test_sync_stock_status_does_not_change_clean_product_with_unanimous_custom_status(): void {
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', false );
+
+		$product = $this->create_variable_product_with_child_stock_statuses( array( 'custom_status_a', 'custom_status_a' ) );
+		$product->set_stock_status( 'custom_status_a' );
+		$product->save();
+
+		$product    = new WC_Product_Variable( $product->get_id() );
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( 'custom_status_a', $product->get_stock_status( 'edit' ) );
+		$this->assertSame( array(), $product->get_changes() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() does not inherit a core status from storage when the overridable child checks report none in stock.
+	 */
+	public function test_sync_stock_status_does_not_inherit_core_status_from_storage(): void {
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_product_lookup_table_is_generating', false );
+
+		$stored_product = $this->create_variable_product_with_child_stock_statuses( array( ProductStockStatus::IN_STOCK, ProductStockStatus::IN_STOCK ) );
+		$stored_product->save();
+
+		// phpcs:disable Generic.CodeAnalysis, Squiz.Commenting
+		$product = new class( $stored_product->get_id() ) extends WC_Product_Variable {
+			public function child_is_in_stock() {
+				return false;
+			}
+
+			public function child_is_on_backorder() {
+				return false;
+			}
+		};
+		// phpcs:enable Generic.CodeAnalysis, Squiz.Commenting
+		$this->assertCount( 2, $product->get_children(), 'The overriding product reads the stored children.' );
+
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox sync_stock_status() preserves variable product child stock delegation.
+	 */
+	public function test_sync_stock_status_preserves_variable_product_child_stock_delegation(): void {
+		// phpcs:disable Generic.CodeAnalysis, Squiz.Commenting
+		$product = new class() extends WC_Product_Variable {
+			public function child_is_in_stock() {
+				return false;
+			}
+
+			public function child_is_on_backorder() {
+				return true;
+			}
+		};
+		// phpcs:enable Generic.CodeAnalysis, Squiz.Commenting
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+
+		$data_store->sync_stock_status( $product );
+
+		$this->assertSame( ProductStockStatus::ON_BACKORDER, $product->get_stock_status() );
+	}
+
+	/**
+	 * @testdox A parent inheriting a custom stock status drops the out of stock visibility term and stays in the catalog.
+	 */
+	public function test_inherited_custom_stock_status_changes_catalog_visibility(): void {
+		$this->register_custom_stock_statuses( array( 'custom_status_a' ) );
+		update_option( 'woocommerce_hide_out_of_stock_items', 'yes' );
+		$data_store = new WC_Product_Variable_Data_Store_CPT();
+
+		$out_of_stock_product = $this->create_variable_product_with_child_stock_statuses(
+			array( ProductStockStatus::OUT_OF_STOCK, ProductStockStatus::OUT_OF_STOCK )
+		);
+		$data_store->sync_stock_status( $out_of_stock_product );
+		$out_of_stock_product->save();
+
+		$custom_status_product = $this->create_variable_product_with_child_stock_statuses(
+			array( 'custom_status_a', 'custom_status_a' )
+		);
+		$data_store->sync_stock_status( $custom_status_product );
+		$custom_status_product->save();
+
+		$this->assertSame( ProductStockStatus::OUT_OF_STOCK, $out_of_stock_product->get_stock_status() );
+		$this->assertSame( 'custom_status_a', $custom_status_product->get_stock_status() );
+
+		$out_of_stock_terms  = wp_get_object_terms( $out_of_stock_product->get_id(), 'product_visibility', array( 'fields' => 'slugs' ) );
+		$custom_status_terms = wp_get_object_terms( $custom_status_product->get_id(), 'product_visibility', array( 'fields' => 'slugs' ) );
+
+		$this->assertContains( ProductStockStatus::OUT_OF_STOCK, $out_of_stock_terms, 'A parent stored as out of stock carries the outofstock visibility term.' );
+		$this->assertNotContains( ProductStockStatus::OUT_OF_STOCK, $custom_status_terms, 'A parent holding a custom status carries no outofstock visibility term.' );
+
+		// Assert through the real catalog query rather than is_visible(), which routes through is_in_stock() and so
+		// returns the same answer before and after this change once a store filters woocommerce_product_is_in_stock.
+		$visible_ids = ( new WP_Query(
+			array(
+				'post_type'      => 'product',
+				'post_status'    => ProductStatus::PUBLISH,
+				'fields'         => 'ids',
+				'posts_per_page' => -1,
+				'tax_query'      => WC()->query->get_tax_query(), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
+			)
+		) )->posts;
+
+		$this->assertNotContains( $out_of_stock_product->get_id(), $visible_ids, 'Hide out of stock items excludes the out of stock parent.' );
+		$this->assertContains( $custom_status_product->get_id(), $visible_ids, 'The parent holding a custom status is no longer excluded, matching a simple product with the same status.' );
+	}
+
 	/**
 	 * Helper filter to force prices inclusive of tax.
 	 */