Commit d6530c584c7 for woocommerce
commit d6530c584c7fe9de304b765695aa33f4587b073e
Author: Barry Hughes <3594411+barryhughes@users.noreply.github.com>
Date: Tue Nov 24 11:30:47 2026 -0700
Subscriptions engine: throw on failed repository reads instead of returning empty results (#71382)
* Throw on failed plan list, count and meta reads
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Throw on failed contract list, count, customer and cycle reads
The contracts REST route answers a failed read with a logged 500.
* Throw when a contract or cycle child read fails
A failed items, addresses or snapshot read throws instead of returning
a partial contract or cycle.
* Throw on a failed due scan and log it in the dispatcher
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Add changelog entry for the read failure throws
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Subscriptions engine: tighten read-failure tests, fix a permission check docblock
Co-Authored-By: Claude Code <noreply@anthropic.com>
* Subscriptions engine: make the logged-500 test pass PHPStan
Co-Authored-By: Claude Code <noreply@anthropic.com>
---------
Co-authored-by: Claude Code <noreply@anthropic.com>
diff --git a/packages/php/woocommerce-subscriptions-engine/changelog/update-subscriptions-engine-repository-read-failures b/packages/php/woocommerce-subscriptions-engine/changelog/update-subscriptions-engine-repository-read-failures
new file mode 100644
index 00000000000..7f2cf4d66c8
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/changelog/update-subscriptions-engine-repository-read-failures
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Throw on failed reads in the unreleased subscriptions engine instead of returning empty results; no changelog entry needed.
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
index c19b0270894..4b7da8b1e73 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
@@ -243,6 +243,7 @@ final class Contracts {
* @throws ValidationException If `extension_slug` is missing or a value is invalid, with every invalid value reported.
* @throws InvalidArgumentException If the lock is for another contract or another extension.
* @throws ContractLockedException If another operation holds the lock, or `$lock` was lost.
+ * @throws \RuntimeException If the contract read fails.
*/
public static function update( int $contract_id, array $args, ?ContractLock $lock = null ): ?ContractView {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::CONTRACT_KEYS );
@@ -453,6 +454,7 @@ final class Contracts {
*
* @param int $order_id Order id.
* @return array<int, CycleView>
+ * @throws \RuntimeException If the read fails.
*/
public static function find_cycles_by_order( int $order_id ): array {
return self::cycle_views( ( new ContractRepository() )->find_cycles_by_order_id( $order_id ) );
@@ -534,6 +536,7 @@ final class Contracts {
* @param bool $single With a key: return the first value only.
* @return mixed Empty key: values grouped by key. Key + `$single`: the first value, or ''
* when absent. Key only: the list of values (`[]` when absent).
+ * @throws \RuntimeException If the read fails.
*/
public static function get_meta( int $contract_id, string $key = '', bool $single = false ) {
return ( new ContractRepository() )->get_meta( $contract_id, $key, $single );
@@ -544,6 +547,7 @@ final class Contracts {
*
* @param int $contract_id Contract id.
* @return ContractView|null The contract, or null when none exists.
+ * @throws \RuntimeException If the read fails.
*/
public static function get( int $contract_id ): ?ContractView {
return self::view( ( new ContractRepository() )->find( $contract_id ), true );
@@ -554,6 +558,7 @@ final class Contracts {
*
* @param int $order_id Origin order id.
* @return array<int, ContractView>
+ * @throws \RuntimeException If the read fails.
*/
public static function find_by_origin_order( int $order_id ): array {
return self::views( ( new ContractRepository() )->find_by_origin_order( $order_id ) );
@@ -576,6 +581,7 @@ final class Contracts {
* @type string $search Numeric term matches contract id or origin order id; text term matches the owning customer.
* }
* @return array<int, ContractView> Contracts in the requested order (children not loaded).
+ * @throws \RuntimeException If the read fails.
*/
public static function list( array $args = array() ): array {
return self::views( ( new ContractRepository() )->query( $args ) );
@@ -587,6 +593,7 @@ final class Contracts {
* is the caller's `array_sum()`. Independent of any search or paging.
*
* @return array<string, int> Status => count, every known status present.
+ * @throws \RuntimeException If the read fails.
*/
public static function count_by_status(): array {
return ( new ContractRepository() )->count_by_status();
@@ -599,6 +606,7 @@ final class Contracts {
*
* @param array<string, mixed> $args Query args (only `status` and `search` are read).
* @return int The matching contract count.
+ * @throws \RuntimeException If the read fails.
*/
public static function count( array $args = array() ): int {
return ( new ContractRepository() )->count( $args );
@@ -612,11 +620,13 @@ final class Contracts {
*
* @param array<int, int> $contract_ids Contract ids to count items for.
* @return array<int, int> Contract id => line-item count, one entry per requested id.
+ * @throws \RuntimeException If the read fails.
*/
public static function item_counts( array $contract_ids ): array {
return ( new ContractRepository() )->count_items_by_contract( $contract_ids );
}
+ // phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- @throws also lists exceptions raised by the methods called.
/**
* List a single customer's contracts, newest first - the customer
* portal's owner-scoped list read.
@@ -643,6 +653,7 @@ final class Contracts {
* }
* @return array<int, ContractView> The customer's contracts, newest first.
* @throws ValidationException If `extension_slug` is empty, not a string, not a valid extension slug, or `any`.
+ * @throws \RuntimeException If the read fails.
*/
public static function list_for_customer( int $customer_id, int $limit = 20, int $offset = 0, array $args = array() ): array {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::LIST_FOR_CUSTOMER_KEYS );
@@ -674,6 +685,7 @@ final class Contracts {
return self::views( ( new ContractRepository() )->find_by_customer_id( $customer_id, $query ) );
}
+ // phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
/**
* Fetch a contract a customer owns - the customer portal's ownership-checked read.
@@ -688,12 +700,14 @@ final class Contracts {
* @param int $contract_id Contract id.
* @param int $customer_id Customer that must own the contract.
* @return ContractView|null The contract when owned by `$customer_id`, else null.
+ * @throws \RuntimeException If the read fails.
* @phpstan-impure
*/
public static function get_for_customer( int $contract_id, int $customer_id ): ?ContractView {
return self::view( ( new ContractRepository() )->find_for_customer( $contract_id, $customer_id ), true );
}
+ // phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- @throws also lists exceptions raised by the methods called.
/**
* Fetch a window of the contract's billing cycles, newest first. A negative `$limit` or
* `$offset` throws a {@see ValidationException}.
@@ -703,6 +717,7 @@ final class Contracts {
* @param int $offset Cycles to skip (for paging).
* @return array<int, CycleView> Cycles newest first.
* @throws ValidationException If `$limit` or `$offset` is negative, with both reported.
+ * @throws \RuntimeException If the read fails.
*/
public static function get_cycles( int $contract_id, int $limit = 20, int $offset = 0 ): array {
$validator = new ArgumentValidator();
@@ -716,6 +731,7 @@ final class Contracts {
return self::cycle_views( ( new ContractRepository() )->find_cycle_history( $contract_id, Cycle::KIND_BILLING, $limit, $offset ) );
}
+ // phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
/**
* Check the positional scope arguments of a write: the expected owner and, for a meta write,
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php
index 4a3a1954cc3..1f5cf650c07 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Plans.php
@@ -277,6 +277,7 @@ final class Plans {
* @param bool $single With a key: return the first value only.
* @return mixed Empty key: values grouped by key. Key + `$single`: the first value, or ''
* when absent. Key only: the list of values (`[]` when absent).
+ * @throws RuntimeException If the read fails.
*/
public static function get_meta( int $plan_id, string $key = '', bool $single = false ) {
return ( new PlanRepository() )->get_meta( $plan_id, $key, $single );
@@ -295,6 +296,7 @@ final class Plans {
return null === $plan ? null : PlanView::from_plan( $plan );
}
+ // phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- @throws also lists exceptions raised by the methods called.
/**
* List plans, oldest id first. Without args: every extension's plans in every status.
*
@@ -319,6 +321,7 @@ final class Plans {
* or non-string slug or status, a slug that is not a valid extension
* slug (1-64 of `[a-z0-9_-]`), `any` as a slug, a non-positive or
* non-integer id or limit, a negative or non-integer offset.
+ * @throws RuntimeException If the read fails.
*/
public static function list( array $args = array() ): array {
$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::LIST_KEYS );
@@ -375,6 +378,7 @@ final class Plans {
( new PlanRepository() )->query( $query )
);
}
+ // phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
/**
* Check the positional scope arguments of a meta write, the expected owner and the key,
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/ContractsController.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/ContractsController.php
index e1b20417c08..6fd9ce16eb6 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/ContractsController.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/ContractsController.php
@@ -9,6 +9,7 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\SubscriptionsEngine\Api\Rest;
+use RuntimeException;
use SplObjectStorage;
use Throwable;
use UnexpectedValueException;
@@ -153,8 +154,8 @@ final class ContractsController extends WP_REST_Controller {
}
/**
- * Check whether the current user may read the contract. Anything that is not a 401 is the
- * same 404, so a caller cannot probe for contracts it may not read.
+ * Check whether the current user may read the contract. Anything that is not a 401 or a
+ * failed read (500) is the same 404, so a caller cannot probe for contracts it may not read.
*
* @param WP_REST_Request $request Request.
* @return true|WP_Error
@@ -171,8 +172,9 @@ final class ContractsController extends WP_REST_Controller {
}
/**
- * Check whether the current user may run the requested action on the contract. Anything
- * that is not a 401 is the same 404, so a caller cannot probe for contracts it may not act on.
+ * Check whether the current user may run the requested action on the contract. Anything that
+ * is not a 401 or a failed read (500) is the same 404, so a caller cannot probe for contracts
+ * it may not act on.
*
* @param WP_REST_Request $request Request.
* @return true|WP_Error
@@ -393,14 +395,21 @@ final class ContractsController extends WP_REST_Controller {
/**
* The contract, once the current user may read it (`read_subscription_contract`); resolved
- * once per request. Unknown and unreadable contracts are the same 404.
+ * once per request. Unknown and unreadable contracts are the same 404; a failed read is a
+ * 500, answered before the ownership check.
*
* @param WP_REST_Request $request Request.
* @return ContractView|WP_Error
*/
private function resolve_read( WP_REST_Request $request ) {
if ( ! isset( $this->resolved_reads[ $request ] ) ) {
- $contract = Contracts::get( Coercion::coerce_int( $request->get_param( 'id' ) ) );
+ $contract_id = Coercion::coerce_int( $request->get_param( 'id' ) );
+ try {
+ $contract = Contracts::get( $contract_id );
+ } catch ( RuntimeException $e ) {
+ $this->resolved_reads[ $request ] = $this->get_read_failed_error( $e, $contract_id );
+ return $this->resolved_reads[ $request ];
+ }
$this->resolved_reads[ $request ] = null !== $contract && current_user_can( ContractCapabilities::READ, $contract )
? $contract
@@ -466,6 +475,28 @@ final class ContractsController extends WP_REST_Controller {
);
}
+ /**
+ * Log a failed contract read and return a generic 500, so database details stay out of the response.
+ *
+ * @param RuntimeException $e Failure.
+ * @param int $contract_id Contract id.
+ */
+ private function get_read_failed_error( RuntimeException $e, int $contract_id ): WP_Error {
+ wc_get_logger()->error(
+ sprintf( 'ContractsController: the read of contract %d failed: %s', $contract_id, $e->getMessage() ),
+ array(
+ 'source' => self::LOG_SOURCE,
+ 'contract_id' => $contract_id,
+ )
+ );
+
+ return new WP_Error(
+ 'woocommerce_subscriptions_engine_contract_read_failed',
+ __( 'The contract could not be read.', 'woocommerce' ),
+ array( 'status' => 500 )
+ );
+ }
+
/**
* Validate `action_args` against the action's property schemas: defaults filled in, unknown
* keys dropped, a 400 when a value does not match.
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php b/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php
index 23c727f7fc8..7f4fec55a2b 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Rest/PlansController.php
@@ -247,8 +247,12 @@ final class PlansController extends WP_REST_Controller {
}
}
- $plans = $this->plan_repository->query( $args );
- $total = $this->plan_repository->count( $args );
+ try {
+ $plans = $this->plan_repository->query( $args );
+ $total = $this->plan_repository->count( $args );
+ } catch ( RuntimeException $e ) {
+ return $this->read_failed_error( $e );
+ }
$response = new WP_REST_Response(
array_map(
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Dispatch/DueDispatcher.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Dispatch/DueDispatcher.php
index 0306ed9a410..56167e88c44 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Dispatch/DueDispatcher.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Dispatch/DueDispatcher.php
@@ -185,7 +185,16 @@ final class DueDispatcher {
$utc = new DateTimeZone( 'UTC' );
$scan_now = $now ?? new DateTimeImmutable( 'now', $utc );
- $due_rows = $this->contracts->find_due( $scan_now, $limit, $owners );
+ try {
+ $due_rows = $this->contracts->find_due( $scan_now, $limit, $owners );
+ } catch ( Throwable $e ) {
+ // A failed scan reads like "nothing due" for this tick; the next tick scans again.
+ wc_get_logger()->error(
+ sprintf( 'DueDispatcher::run_batch(): due-index scan failed - due dispatch may stall until this is fixed. %s', $e->getMessage() ),
+ array( 'source' => self::LOG_SOURCE )
+ );
+ return 0;
+ }
$notified = 0;
$skipped = 0;
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
index ef69b00a6a1..be5f4c18248 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
@@ -321,7 +321,7 @@ final class ContractRepository {
*
* @param int $id Contract id.
* @return Contract|null Hydrated contract, or null if not found.
- * @throws \RuntimeException If the contract row read fails.
+ * @throws \RuntimeException If the contract row or a child read fails: a failed child read must not look like a contract without it.
*/
public function find( int $id ): ?Contract {
$row = $this->find_contract_row( $id );
@@ -344,6 +344,7 @@ final class ContractRepository {
* @param int $contract_id Contract id.
* @param int $customer_id Customer that must own the contract.
* @return Contract|null Hydrated contract when owned by `$customer_id`, else null.
+ * @throws \RuntimeException If the row or a child read fails: a failed read must not look like "not yours".
*/
public function find_for_customer( int $contract_id, int $customer_id ): ?Contract {
global $wpdb;
@@ -353,6 +354,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$row = $wpdb->get_row( $wpdb->prepare( "SELECT {$select} FROM {$table} WHERE id = %d AND customer_id = %d", $contract_id, $customer_id ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read contract %d: %s', $contract_id, $wpdb->last_error ) ) );
+ }
if ( ! is_array( $row ) ) {
return null;
}
@@ -365,6 +369,7 @@ final class ContractRepository {
* items and addresses - the one full-read construction path.
*
* @param array<string, mixed> $row Contract row.
+ * @throws \RuntimeException If a child read fails.
*/
private function hydrate_row( array $row ): Contract {
$id = Coercion::coerce_int( $row['id'] ?? 0 );
@@ -427,6 +432,7 @@ final class ContractRepository {
* @type string $search A numeric term matches contract id or origin order id; a text term matches the owning customer.
* }
* @return array<int, Contract> Contracts in the requested order.
+ * @throws \RuntimeException If the read fails: a failed read must not look like no contracts.
*/
public function query( array $args = array() ): array {
global $wpdb;
@@ -463,6 +469,9 @@ final class ContractRepository {
ARRAY_A
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read contracts: %s', $wpdb->last_error ) ) );
+ }
return $this->contracts_from_rows( is_array( $rows ) ? $rows : array() );
}
@@ -577,6 +586,7 @@ final class ContractRepository {
* the views count the whole store, not the current page).
*
* @return array<string, int> Status => count, every registered status present.
+ * @throws \RuntimeException If the read fails: a failed read must not look like zero counts.
*/
public function count_by_status(): array {
global $wpdb;
@@ -585,6 +595,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rows = $wpdb->get_results( "SELECT status, COUNT(*) AS total FROM {$table} GROUP BY status", ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to count contracts by status: %s', $wpdb->last_error ) ) );
+ }
// Seed every registered status at 0 so the map is complete and stably ordered.
$counts = array();
@@ -615,6 +628,7 @@ final class ContractRepository {
*
* @param array<string, mixed> $args Query args (only `status` and `search` are read).
* @return int The matching contract count.
+ * @throws \RuntimeException If the read fails: a failed read must not look like a zero count.
*/
public function count( array $args = array() ): int {
global $wpdb;
@@ -631,6 +645,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$total = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE {$where_sql}", $params ) );
}
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to count contracts: %s', $wpdb->last_error ) ) );
+ }
return Coercion::coerce_int( $total );
}
@@ -644,6 +661,7 @@ final class ContractRepository {
*
* @param array<int, int> $contract_ids Contract ids to count items for.
* @return array<int, int> Contract id => line-item count, one entry per requested id.
+ * @throws \RuntimeException If the read fails: a failed read must not look like zero items.
*/
public function count_items_by_contract( array $contract_ids ): array {
// Keep only scalar, positive ids (this is a public entry point): casting an object or
@@ -673,6 +691,9 @@ final class ContractRepository {
// The id placeholders join dynamically, so the sniff sees none in the literal.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT contract_id, COUNT(*) AS total FROM {$table} WHERE contract_id IN ({$placeholders}) GROUP BY contract_id", $ids ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to count contract items: %s', $wpdb->last_error ) ) );
+ }
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
if ( ! is_array( $row ) ) {
@@ -694,6 +715,7 @@ final class ContractRepository {
*
* @param array<int, mixed> $rows Fetched rows (non-arrays are skipped).
* @return array<int, Contract> Contracts in row order.
+ * @throws \RuntimeException If the snapshot read fails.
*/
private function contracts_from_rows( array $rows ): array {
$clean_rows = array();
@@ -731,6 +753,7 @@ final class ContractRepository {
* @param int $limit Maximum rows to return (the batch size).
* @param array<int, string> $owners Owner slugs whose contracts may be selected.
* @return array<int, array{id: int, extension_slug: string, next_payment_gmt: string}> Due rows, least recently locked first, then oldest-due.
+ * @throws \RuntimeException If the scan fails: a failed scan must not look like "nothing due".
*/
public function find_due( DateTimeImmutable $now, int $limit, array $owners ): array {
if ( $limit < 1 ) {
@@ -772,13 +795,8 @@ final class ContractRepository {
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
- // A failed scan otherwise reads exactly like "nothing due" and dispatch stalls
- // store-wide with no signal; the return stays empty either way.
if ( '' !== $wpdb->last_error ) {
- wc_get_logger()->error(
- sprintf( 'ContractRepository::find_due(): due-index scan failed - due dispatch may stall until this is fixed. %s', $wpdb->last_error ),
- array( 'source' => self::LOG_SOURCE )
- );
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read due contracts: %s', $wpdb->last_error ) ) );
}
$result = array();
@@ -1247,6 +1265,7 @@ final class ContractRepository {
* guards use). Absent: every extension.
* }
* @return array<int, Contract> Contracts the customer owns, newest first.
+ * @throws \RuntimeException If the read fails: a failed read must not look like no contracts.
*/
public function find_by_customer_id( int $customer_id, ?array $args = null ): array {
global $wpdb;
@@ -1301,6 +1320,9 @@ final class ContractRepository {
ARRAY_A
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read the contracts of customer %d: %s', $customer_id, $wpdb->last_error ) ) );
+ }
return $this->contracts_from_rows( is_array( $rows ) ? $rows : array() );
}
@@ -1311,6 +1333,7 @@ final class ContractRepository {
*
* @param int $order_id Origin order id.
* @return array<int, Contract>
+ * @throws \RuntimeException If the read fails: a failed read must not look like an order without contracts.
*/
public function find_by_origin_order( int $order_id ): array {
global $wpdb;
@@ -1320,6 +1343,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT {$select} FROM {$table} WHERE origin_order_id = %d ORDER BY id ASC", $order_id ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read the contracts of order %d: %s', $order_id, $wpdb->last_error ) ) );
+ }
return $this->contracts_from_rows( is_array( $rows ) ? $rows : array() );
}
@@ -1937,6 +1963,7 @@ final class ContractRepository {
* @param int $limit Maximum rows to return.
* @param int $offset Rows to skip (for paging).
* @return array<int, Cycle> Cycles newest first.
+ * @throws \RuntimeException If the read fails: a failed read must not look like an empty chain.
*/
public function find_cycle_history( int $contract_id, string $kind = Cycle::KIND_BILLING, int $limit = 20, int $offset = 0 ): array {
global $wpdb;
@@ -1945,6 +1972,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE contract_id = %d AND kind = %s ORDER BY sequence_no DESC LIMIT %d OFFSET %d", $contract_id, $kind, $limit, $offset ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read the cycles of contract %d: %s', $contract_id, $wpdb->last_error ) ) );
+ }
$cycles = array();
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
@@ -1963,6 +1993,7 @@ final class ContractRepository {
*
* @param int $order_id WooCommerce order id.
* @return array<int, Cycle> Cycles linked to the order, newest first.
+ * @throws \RuntimeException If the read fails: a failed read must not look like an order that bills no cycle.
*/
public function find_cycles_by_order_id( int $order_id ): array {
global $wpdb;
@@ -1971,6 +2002,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE order_id = %d ORDER BY id DESC", $order_id ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read the cycles of order %d: %s', $order_id, $wpdb->last_error ) ) );
+ }
$cycles = array();
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
@@ -1988,6 +2022,7 @@ final class ContractRepository {
*
* @param array<string, mixed> $row Cycle row.
* @return Cycle The hydrated cycle.
+ * @throws \RuntimeException If a snapshot read fails.
*/
private function hydrate_cycle( array $row ): Cycle {
$cycle = Cycle::from_storage( $row );
@@ -2057,6 +2092,7 @@ final class ContractRepository {
*
* @param int|null $snapshot_id Snapshot row id, or null.
* @return PlanSnapshot|null The decoded value object, or null.
+ * @throws \RuntimeException If the read fails.
*/
private function find_plan_snapshot( ?int $snapshot_id ): ?PlanSnapshot {
$decoded = $this->find_snapshot_payload( $snapshot_id );
@@ -2074,6 +2110,7 @@ final class ContractRepository {
*
* @param array<int, int> $snapshot_ids Snapshot row ids (deduplicated by the caller or not - the IN() dedupes).
* @return array<int, PlanSnapshot> Decoded value objects keyed by snapshot row id.
+ * @throws \RuntimeException If the read fails: a failed read must not look like contracts without plan terms.
*/
private function find_plan_snapshots( array $snapshot_ids ): array {
global $wpdb;
@@ -2098,6 +2135,9 @@ final class ContractRepository {
ARRAY_A
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read plan snapshots: %s', $wpdb->last_error ) ) );
+ }
$snapshots = array();
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
@@ -2120,6 +2160,7 @@ final class ContractRepository {
*
* @param int|null $snapshot_id Snapshot row id, or null.
* @return ItemsSnapshot|null The decoded value object, or null.
+ * @throws \RuntimeException If the read fails.
*/
private function find_items_snapshot( ?int $snapshot_id ): ?ItemsSnapshot {
$decoded = $this->find_snapshot_payload( $snapshot_id );
@@ -2135,6 +2176,7 @@ final class ContractRepository {
*
* @param int|null $snapshot_id Snapshot row id, or null.
* @return array{payload: array<int|string, mixed>, schema_version: int}|null
+ * @throws \RuntimeException If the read fails: a failed read must not look like a missing snapshot.
*/
private function find_snapshot_payload( ?int $snapshot_id ): ?array {
global $wpdb;
@@ -2147,6 +2189,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$row = $wpdb->get_row( $wpdb->prepare( "SELECT payload, schema_version FROM {$table} WHERE id = %d", $snapshot_id ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read snapshot %d: %s', $snapshot_id, $wpdb->last_error ) ) );
+ }
if ( null === $row ) {
return null;
@@ -2457,6 +2502,7 @@ final class ContractRepository {
*
* @param int $contract_id Contract id.
* @return array<int, array<string, mixed>>
+ * @throws \RuntimeException If the read fails: a failed read must not look like a contract without items.
*/
private function find_items( int $contract_id ): array {
global $wpdb;
@@ -2465,6 +2511,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE contract_id = %d ORDER BY id ASC", $contract_id ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read the items of contract %d: %s', $contract_id, $wpdb->last_error ) ) );
+ }
return Coercion::coerce_list_of_arrays( $rows );
}
@@ -2474,6 +2523,7 @@ final class ContractRepository {
*
* @param int $contract_id Contract id.
* @return array<string, array<string, mixed>>
+ * @throws \RuntimeException If the read fails: a failed read must not look like a contract without addresses.
*/
private function find_addresses( int $contract_id ): array {
global $wpdb;
@@ -2482,6 +2532,9 @@ final class ContractRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE contract_id = %d", $contract_id ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( esc_html( sprintf( 'Failed to read the addresses of contract %d: %s', $contract_id, $wpdb->last_error ) ) );
+ }
$by_type = array();
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php
index b75e98f1db7..2aa3d002552 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/PlanRepository.php
@@ -140,6 +140,7 @@ final class PlanRepository {
*
* @param array<string, mixed> $args Query args.
* @return array<int, Plan>
+ * @throws \RuntimeException If the read fails: a failed read must not look like no plans.
*/
public function query( array $args = array() ): array {
global $wpdb;
@@ -159,6 +160,9 @@ final class PlanRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table}{$where_sql} {$order} LIMIT %d OFFSET %d", $params ), ARRAY_A );
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( sprintf( 'Failed to read plans: %s', esc_html( $wpdb->last_error ) ) );
+ }
if ( ! is_array( $rows ) ) {
return array();
}
@@ -180,6 +184,7 @@ final class PlanRepository {
* Supported args are the filter args accepted by query().
*
* @param array<string, mixed> $args Query args.
+ * @throws \RuntimeException If the read fails: a failed read must not look like a zero count.
*/
public function count( array $args = array() ): int {
global $wpdb;
@@ -199,6 +204,9 @@ final class PlanRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$result = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table}{$where_sql}", $where_params ) );
}
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( sprintf( 'Failed to count plans: %s', esc_html( $wpdb->last_error ) ) );
+ }
return (int) $result;
}
@@ -550,6 +558,7 @@ final class PlanRepository {
* @param bool $single With a key: return the first value only.
* @return mixed Empty key: `array<string, array<int, mixed>>` of all keys. Key + `$single`:
* the first value, or '' when absent. Key only: the list of values (`[]` when absent).
+ * @throws \RuntimeException If the read fails.
*/
public function get_meta( int $plan_id, string $key = '', bool $single = false ) {
if ( '' === $key ) {
@@ -780,6 +789,7 @@ final class PlanRepository {
* @param int $plan_id Plan id.
* @param string $key Meta key.
* @return array<int, mixed>
+ * @throws \RuntimeException If the read fails.
*/
private function find_meta_values( int $plan_id, string $key ): array {
$values = array();
@@ -796,6 +806,7 @@ final class PlanRepository {
* @param int $plan_id Plan id.
* @param string|null $key Meta key, or null for every key.
* @return array<int, array{meta_key: string, meta_value: string}>
+ * @throws \RuntimeException If the read fails: a failed read must not look like an absent key.
*/
private function find_meta_rows( int $plan_id, ?string $key ): array {
global $wpdb;
@@ -811,6 +822,9 @@ final class PlanRepository {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$table} WHERE plan_id = %d AND meta_key = %s ORDER BY id ASC", $plan_id, $key ), ARRAY_A );
}
+ if ( '' !== $wpdb->last_error ) {
+ throw new \RuntimeException( sprintf( 'Failed to read plan meta for plan %d: %s', (int) $plan_id, esc_html( $wpdb->last_error ) ) );
+ }
$result = array();
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
index 6cc3f64457c..bb045bbcec5 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractsTest.php
@@ -3048,4 +3048,89 @@ class ContractsTest extends EngineIntegrationTestCase {
$this->assertNull( Contracts::get_for_customer( $id, 45 ), 'foreign-owned reads as not found' );
$this->assertNull( Contracts::get_for_customer( 987654, 44 ), 'unknown id reads as not found' );
}
+
+ /**
+ * @testdox A facade read throws on a failed query instead of returning an empty value.
+ * @dataProvider provide_failing_facade_reads
+ *
+ * @param string $pattern The query to fail.
+ * @param callable $read Runs the facade read for the contract.
+ * @param string $message The expected message prefix, with {contract}, {customer} and {order} placeholders.
+ */
+ public function test_facade_read_throws_on_a_failed_query( string $pattern, callable $read, string $message ): void {
+ $contract = $this->sign_up_contract( 46 );
+
+ $this->fail_next_query( $pattern );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage(
+ strtr(
+ $message,
+ array(
+ '{contract}' => (string) $contract->get_id(),
+ '{customer}' => (string) $contract->get_customer_id(),
+ '{order}' => (string) $contract->get_origin_order_id(),
+ )
+ )
+ );
+
+ $read( $contract );
+ }
+
+ /**
+ * @return array<string, array{0: string, 1: callable, 2: string}>
+ */
+ public function provide_failing_facade_reads(): array {
+ $row_read = '/^\s*SELECT\s+\*,\s*\(\s*lock_token.*WHERE id = \d+\s*$/s';
+
+ return array(
+ 'get' => array( $row_read, static fn ( Contract $contract ) => Contracts::get( (int) $contract->get_id() ), 'Failed to read contract {contract}:' ),
+ 'get_for_customer' => array( '/WHERE id = \d+ AND customer_id = \d+/', static fn ( Contract $contract ) => Contracts::get_for_customer( (int) $contract->get_id(), 46 ), 'Failed to read contract {contract}:' ),
+ 'list' => array( '/^\s*SELECT\s+\*,\s*\(\s*lock_token.*LIMIT \d+ OFFSET/s', static fn () => Contracts::list(), 'Failed to read contracts:' ),
+ 'count' => array( '/^\s*SELECT COUNT\(\*\) FROM \S*subscription_contracts WHERE/', static fn () => Contracts::count(), 'Failed to count contracts:' ),
+ 'count_by_status' => array( '/SELECT status, COUNT\(\*\) AS total/', static fn () => Contracts::count_by_status(), 'Failed to count contracts by status:' ),
+ 'item_counts' => array( '/SELECT contract_id, COUNT\(\*\) AS total/', static fn ( Contract $contract ) => Contracts::item_counts( array( (int) $contract->get_id() ) ), 'Failed to count contract items:' ),
+ 'list_for_customer' => array( '/WHERE customer_id = \d+/', static fn () => Contracts::list_for_customer( 46 ), 'Failed to read the contracts of customer {customer}:' ),
+ 'find_by_origin_order' => array( '/WHERE origin_order_id = \d+/', static fn ( Contract $contract ) => Contracts::find_by_origin_order( (int) $contract->get_origin_order_id() ), 'Failed to read the contracts of order {order}:' ),
+ 'get_cycles' => array( '/^\s*SELECT \* FROM \S*subscription_cycles WHERE contract_id = \d+ AND kind/', static fn ( Contract $contract ) => Contracts::get_cycles( (int) $contract->get_id() ), 'Failed to read the cycles of contract {contract}:' ),
+ 'find_cycles_by_order' => array( '/^\s*SELECT \* FROM \S*subscription_cycles WHERE order_id = \d+/', static fn ( Contract $contract ) => Contracts::find_cycles_by_order( (int) $contract->get_origin_order_id() ), 'Failed to read the cycles of order {order}:' ),
+ 'get_meta' => array( '/^\s*SELECT\s+meta_key,\s*meta_value/i', static fn ( Contract $contract ) => Contracts::get_meta( (int) $contract->get_id(), 'note', true ), 'Failed to read contract meta for contract {contract}:' ),
+ 'update' => array(
+ $row_read,
+ static fn ( Contract $contract ) => Contracts::update(
+ (int) $contract->get_id(),
+ array(
+ 'extension_slug' => (string) $contract->get_extension_slug(),
+ 'billing_total' => '29.99',
+ )
+ ),
+ 'Failed to read contract {contract}:',
+ ),
+ );
+ }
+
+ /**
+ * @testdox update writes nothing when its row read fails.
+ */
+ public function test_update_writes_nothing_on_a_failed_row_read(): void {
+ $contract = $this->sign_up_contract( 46 );
+ $contract_id = (int) $contract->get_id();
+
+ $this->fail_next_query( '/^\s*SELECT\s+\*,\s*\(\s*lock_token.*WHERE id = \d+\s*$/s' );
+ $thrown = null;
+ try {
+ Contracts::update(
+ $contract_id,
+ array(
+ 'extension_slug' => (string) $contract->get_extension_slug(),
+ 'billing_total' => '29.99',
+ )
+ );
+ } catch ( \RuntimeException $e ) {
+ $thrown = $e;
+ }
+
+ $this->assertInstanceOf( \RuntimeException::class, $thrown, 'The update throws.' );
+ $this->assertSame( '19.99000000', $this->entity( $contract_id )->get_billing_total(), 'The refused update wrote nothing.' );
+ }
}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php
index cb325af9603..18fcc49fea1 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/PlansTest.php
@@ -1205,6 +1205,29 @@ class PlansTest extends EngineIntegrationTestCase {
$this->assertSame( 'Monthly', $this->stored( $id )->get_name() );
}
+ /**
+ * @testdox list and get_meta throw on a failed read instead of returning an empty value.
+ */
+ public function test_list_and_get_meta_throw_on_a_failed_read(): void {
+ $id = $this->create();
+
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*selling_plans\b.* LIMIT /s' );
+ try {
+ Plans::list();
+ $this->fail( 'Expected list() to throw.' );
+ } catch ( RuntimeException $e ) {
+ $this->assertStringContainsString( 'Failed to read plans', $e->getMessage() );
+ }
+
+ $this->fail_next_query( '/^\s*SELECT meta_key, meta_value FROM \S*selling_plan_meta/' );
+ try {
+ Plans::get_meta( $id, 'note', true );
+ $this->fail( 'Expected get_meta() to throw.' );
+ } catch ( RuntimeException $e ) {
+ $this->assertStringContainsString( "Failed to read plan meta for plan {$id}", $e->getMessage() );
+ }
+ }
+
/**
* @testdox list without args returns every extension's plans in every status, oldest id first.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/ContractsControllerTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/ContractsControllerTest.php
index ee81ac44c0d..49958125623 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/ContractsControllerTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/ContractsControllerTest.php
@@ -29,6 +29,11 @@ class ContractsControllerTest extends EngineIntegrationTestCase {
private const EXTENSION_SLUG = 'test-extension';
+ /**
+ * The contract row read by id.
+ */
+ private const ROW_READ = '/^\s*SELECT\s+\*,\s*\(\s*lock_token.*WHERE id = \d+\s*$/s';
+
/**
* Action callback calls, as `array( action, contract id, action_args )`.
*
@@ -36,6 +41,13 @@ class ContractsControllerTest extends EngineIntegrationTestCase {
*/
private $calls = array();
+ /**
+ * Engine error log messages captured by a test.
+ *
+ * @var string[]
+ */
+ private $logged_errors = array();
+
public function set_up(): void {
parent::set_up();
@@ -154,6 +166,61 @@ class ContractsControllerTest extends EngineIntegrationTestCase {
$this->assertSame( 'woocommerce_subscriptions_engine_contract_not_found', $this->response_data( $response )['code'] );
}
+ /**
+ * A failed contract read is a logged 500 on the item and the action list, with no database
+ * details in the response.
+ */
+ public function test_a_failed_contract_read_is_a_logged_500(): void {
+ $contract = $this->create_contract( null );
+ wp_set_current_user( $this->create_user( 'administrator' ) );
+
+ $capture = function ( $message, $level, $context ) {
+ if ( 'error' === $level && is_string( $message ) && is_array( $context ) && 'woocommerce-subscriptions-engine' === ( $context['source'] ?? null ) ) {
+ $this->logged_errors[] = $message;
+ }
+ return $message;
+ };
+ add_filter( 'woocommerce_logger_log_message', $capture, 10, 3 );
+
+ try {
+ $responses = array();
+ $logged = array();
+ foreach ( array( 'item', 'actions' ) as $route ) {
+ $logged_before = count( $this->logged_errors );
+ $this->fail_next_query( self::ROW_READ );
+ $responses[ $route ] = 'item' === $route ? $this->get( (int) $contract->get_id() ) : $this->list_actions( (int) $contract->get_id() );
+ $logged[ $route ] = array_slice( $this->logged_errors, $logged_before );
+ }
+ } finally {
+ remove_filter( 'woocommerce_logger_log_message', $capture, 10 );
+ }
+
+ foreach ( $responses as $route => $response ) {
+ $this->assertSame( 500, $response->get_status(), "The {$route} route answers 500." );
+ $this->assertSame( 'woocommerce_subscriptions_engine_contract_read_failed', $this->response_data( $response )['code'] );
+ $this->assertStringNotContainsString( 'table_that_does_not_exist', (string) wp_json_encode( $response->get_data() ), 'Database details stay out of the response.' );
+ $this->assertNotEmpty( $logged[ $route ], "The {$route} route logs the failed read." );
+ $this->assertStringContainsString( 'table_that_does_not_exist', $logged[ $route ][0], "The {$route} route's log carries the database error." );
+ }
+ }
+
+ /**
+ * A failed row read is a 500 before any ownership check: a caller without access gets the same
+ * 500 for a contract it cannot read and for an unknown id, never a 404 that depends on existence.
+ */
+ public function test_a_failed_row_read_is_a_500_for_a_caller_without_access(): void {
+ $contract = $this->create_contract( $this->create_user( 'customer' ) );
+ wp_set_current_user( $this->create_user( 'customer' ) );
+
+ foreach ( array( (int) $contract->get_id(), 999999 ) as $contract_id ) {
+ $this->fail_next_query( self::ROW_READ );
+ $response = $this->get( $contract_id );
+
+ $this->assertSame( 500, $response->get_status() );
+ $this->assertSame( 'woocommerce_subscriptions_engine_contract_read_failed', $this->response_data( $response )['code'] );
+ }
+ }
+
/**
* A `map_meta_cap` filter on the read capability decides the read.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php
index d108d881fc6..3db26e28718 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/Rest/PlansControllerTest.php
@@ -1516,6 +1516,48 @@ class PlansControllerTest extends EngineIntegrationTestCase {
$this->assertStringNotContainsString( 'table_that_does_not_exist', (string) wp_json_encode( $response->get_data() ), 'Database details stay out of the response.' );
}
+ /**
+ * @dataProvider provide_failing_list_reads
+ *
+ * @param string $pattern Regex of the read to break.
+ */
+ public function test_get_items_answers_a_failed_read_with_a_logged_500( string $pattern ): void {
+ wp_set_current_user( $this->admin_id );
+ $this->create_plan( 'Stored' );
+
+ $errors = array();
+ $capture = static function ( $message, $level, $context ) use ( &$errors ) {
+ if ( 'error' === $level && is_string( $message ) && is_array( $context ) && 'woocommerce-subscriptions-engine' === ( $context['source'] ?? null ) ) {
+ $errors[] = $message;
+ }
+ return $message;
+ };
+ add_filter( 'woocommerce_logger_log_message', $capture, 10, 3 );
+ $this->fail_next_query( $pattern );
+
+ try {
+ $response = $this->request( 'GET', self::BASE, array(), array( 'extension_slug' => self::EXTENSION_SLUG ) );
+ } finally {
+ remove_filter( 'woocommerce_logger_log_message', $capture, 10 );
+ }
+
+ $this->assertSame( 500, $response->get_status() );
+ $this->assertSame( 'woocommerce_subscriptions_engine_plan_read_failed', $this->response_data( $response )['code'] );
+ $this->assertStringNotContainsString( 'table_that_does_not_exist', (string) wp_json_encode( $response->get_data() ), 'Database details stay out of the response.' );
+ $this->assertNotEmpty( $errors, 'A failed read is logged.' );
+ $this->assertStringContainsString( 'table_that_does_not_exist', $errors[0], 'The log carries the database error.' );
+ }
+
+ /**
+ * @return array<string, array{0: string}>
+ */
+ public function provide_failing_list_reads(): array {
+ return array(
+ 'list' => array( '/^\s*SELECT \* FROM \S*selling_plans\b.* LIMIT /s' ),
+ 'count' => array( '/^\s*SELECT COUNT\(\*\) FROM \S*selling_plans\b/' ),
+ );
+ }
+
public function test_single_plan_routes_404_a_plan_of_another_extension_slug_or_an_unknown_id(): void {
wp_set_current_user( $this->admin_id );
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Dispatch/DueDispatcherTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Dispatch/DueDispatcherTest.php
index 9cad2fcad76..c0cf433a883 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Dispatch/DueDispatcherTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Dispatch/DueDispatcherTest.php
@@ -492,6 +492,59 @@ class DueDispatcherTest extends EngineIntegrationTestCase {
$this->assertNull( $this->get_lock_holder( $first )['operation'], 'Nothing ran, so the lock is released.' );
}
+ /**
+ * @testdox A failed items read after the lock is logged per contract; the handler never sees a contract without items.
+ */
+ public function test_a_failed_items_read_after_the_lock_is_caught_per_contract(): void {
+ $this->register_recording_handler();
+ $first = $this->create_due_contract( '2026-02-14 00:00:00' );
+ $second = $this->create_due_contract( '2026-02-15 00:00:00' );
+
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*contract_items WHERE contract_id/' );
+ $errors = $this->capture_engine_log(
+ 'error',
+ array( 'contract_id' => $first ),
+ function (): void {
+ $this->assertSame( 1, $this->sut->run_batch( $this->now() ) );
+ }
+ );
+
+ $this->assertNotSame( array(), $errors );
+ $this->assertSame( array( $second ), $this->notified_ids() );
+ $this->assertNull( $this->get_lock_holder( $first )['operation'], 'Nothing ran, so the lock is released.' );
+ }
+
+ /**
+ * @testdox A failed due scan is logged and dispatches nothing; the next run scans again.
+ */
+ public function test_a_failed_due_scan_is_logged_and_the_next_run_dispatches(): void {
+ $this->register_recording_handler();
+ $id = $this->create_due_contract();
+
+ $messages = array();
+ $capture = static function ( $message, $level, $context ) use ( &$messages ) {
+ if ( 'error' === $level && is_string( $message ) && is_array( $context ) && 'woocommerce-subscriptions-engine' === ( $context['source'] ?? null ) ) {
+ $messages[] = $message;
+ }
+ return $message;
+ };
+ add_filter( 'woocommerce_logger_log_message', $capture, 10, 3 );
+ $this->fail_next_query( '/^\s*SELECT id, extension_slug, next_payment_gmt/' );
+ try {
+ $this->assertSame( 0, $this->sut->run_batch( $this->now() ) );
+ } finally {
+ remove_filter( 'woocommerce_logger_log_message', $capture, 10 );
+ }
+
+ $this->assertNotSame( array(), $messages );
+ $this->assertStringContainsString( 'due-index scan failed - due dispatch may stall until this is fixed', $messages[0] );
+ $this->assertStringContainsString( 'table_that_does_not_exist', $messages[0], 'The log carries the database error.' );
+ $this->assertSame( array(), $this->notified_ids() );
+
+ $this->assertSame( 1, $this->sut->run_batch( $this->now() ) );
+ $this->assertSame( array( $id ), $this->notified_ids() );
+ }
+
/**
* @testdox An owner registered without a handler is not dispatched and its contracts stay untouched.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php
index 592b31c6ef0..8da881e2bde 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractCustomerReadTest.php
@@ -218,4 +218,43 @@ class ContractCustomerReadTest extends EngineIntegrationTestCase {
// Indistinguishable from "owned by someone else" - the asymmetric not-found rule.
$this->assertNull( $this->sut->find_for_customer( 123456, 14 ) );
}
+
+ /**
+ * @dataProvider provide_customer_list_args
+ *
+ * @param array<string, mixed> $args List args.
+ */
+ public function test_find_by_customer_id_throws_on_a_failed_read( array $args ): void {
+ $this->seed( 30, ContractStatus::ACTIVE );
+
+ $this->fail_next_query( '/^\s*SELECT\s+\*,.*WHERE customer_id = \d+/s' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read the contracts of customer 30' );
+
+ $this->sut->find_by_customer_id( 30, $args );
+ }
+
+ /**
+ * @return array<string, array{0: array<string, mixed>}>
+ */
+ public function provide_customer_list_args(): array {
+ return array(
+ 'without an owner filter' => array( array() ),
+ 'with an owner filter' => array( array( 'extension_slug' => 'engine-tests' ) ),
+ );
+ }
+
+ public function test_find_for_customer_throws_on_a_failed_read_and_still_hides_a_foreign_contract(): void {
+ $id = $this->seed( 31, ContractStatus::ACTIVE );
+
+ $this->assertNull( $this->sut->find_for_customer( $id, 32 ), 'A foreign contract still reads as null.' );
+
+ $this->fail_next_query( '/WHERE id = \d+ AND customer_id = \d+/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( "Failed to read contract {$id}" );
+
+ $this->sut->find_for_customer( $id, 31 );
+ }
}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php
index d92084e0c34..bb4a2824429 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractRepositoryTest.php
@@ -1069,6 +1069,18 @@ class ContractRepositoryTest extends EngineIntegrationTestCase {
$this->assertNotContains( $not_yet, $this->due_ids( $now, 50 ) );
}
+ /**
+ * @testdox find_due throws on a failed scan instead of reading as "nothing due".
+ */
+ public function test_find_due_throws_on_a_failed_scan(): void {
+ $this->fail_next_query( '/^\s*SELECT id, extension_slug, next_payment_gmt/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read due contracts' );
+
+ $this->sut->find_due( new \DateTimeImmutable( '2026-08-01 00:00:00', new \DateTimeZone( 'UTC' ) ), 10, array( self::OWNER ) );
+ }
+
/**
* @testdox find_due selects a due contract whose stored status is not registered.
*/
@@ -1945,6 +1957,197 @@ class ContractRepositoryTest extends EngineIntegrationTestCase {
$this->sut->find( $id );
}
+ /**
+ * @testdox query throws on a failed read instead of returning no contracts.
+ */
+ public function test_query_throws_on_a_failed_read(): void {
+ $this->insert_released( $this->make_contract() );
+
+ $this->fail_next_query( '/^\s*SELECT\s+\*,\s*\(\s*lock_token.*LIMIT \d+ OFFSET/s' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read contracts' );
+
+ $this->sut->query();
+ }
+
+ /**
+ * @testdox count throws on a failed read, filtered or not, instead of counting zero.
+ * @dataProvider provide_count_args
+ *
+ * @param array<string, mixed> $args Count args.
+ */
+ public function test_count_throws_on_a_failed_read( array $args ): void {
+ $this->insert_released( $this->make_contract() );
+
+ $this->fail_next_query( '/^\s*SELECT COUNT\(\*\) FROM \S*subscription_contracts WHERE/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to count contracts' );
+
+ $this->sut->count( $args );
+ }
+
+ /**
+ * @return array<string, array{0: array<string, mixed>}>
+ */
+ public function provide_count_args(): array {
+ return array(
+ 'unfiltered' => array( array() ),
+ 'filtered' => array( array( 'status' => ContractStatus::ACTIVE ) ),
+ );
+ }
+
+ /**
+ * @testdox find_by_origin_order throws on a failed read instead of finding no contract.
+ */
+ public function test_find_by_origin_order_throws_on_a_failed_read(): void {
+ $this->insert_released( $this->make_contract() );
+
+ $this->fail_next_query( '/WHERE origin_order_id = \d+/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read the contracts of order 1001' );
+
+ $this->sut->find_by_origin_order( 1001 );
+ }
+
+ /**
+ * @testdox find_cycle_history throws on a failed read instead of returning an empty chain.
+ */
+ public function test_find_cycle_history_throws_on_a_failed_read(): void {
+ $id = $this->insert_released( $this->make_contract() );
+ $this->append_cycle_locked( $this->make_cycle( $id, 1, 1, '2026-07-15 00:00:00', '2026-08-15 00:00:00' ) );
+
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*subscription_cycles WHERE contract_id = \d+ AND kind/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( "Failed to read the cycles of contract {$id}" );
+
+ $this->sut->find_cycle_history( $id );
+ }
+
+ /**
+ * @testdox find_cycles_by_order_id throws on a failed read instead of finding no cycle.
+ */
+ public function test_find_cycles_by_order_id_throws_on_a_failed_read(): void {
+ $id = $this->insert_released( $this->make_contract() );
+ $this->append_cycle_locked( $this->make_cycle( $id, 1, 1, '2026-07-15 00:00:00', '2026-08-15 00:00:00', null, null, 5005 ) );
+
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*subscription_cycles WHERE order_id = \d+/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read the cycles of order 5005' );
+
+ $this->sut->find_cycles_by_order_id( 5005 );
+ }
+
+ /**
+ * @testdox count_by_status throws on a failed read instead of counting zero per status.
+ */
+ public function test_count_by_status_throws_on_a_failed_read(): void {
+ $this->insert_released( $this->make_contract() );
+
+ $this->fail_next_query( '/SELECT status, COUNT\(\*\) AS total/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to count contracts by status' );
+
+ $this->sut->count_by_status();
+ }
+
+ /**
+ * @testdox count_items_by_contract throws on a failed read instead of counting zero items.
+ */
+ public function test_count_items_by_contract_throws_on_a_failed_read(): void {
+ $id = $this->insert_released( $this->make_contract() );
+
+ $this->fail_next_query( '/SELECT contract_id, COUNT\(\*\) AS total/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to count contract items' );
+
+ $this->sut->count_items_by_contract( array( $id ) );
+ }
+
+ /**
+ * @testdox find throws when a child read fails after the row read, instead of returning a partial contract.
+ * @dataProvider provide_failing_child_reads
+ *
+ * @param string $pattern Regex of the child read to break.
+ * @param string $message Expected message prefix.
+ */
+ public function test_find_throws_on_a_failed_child_read( string $pattern, string $message ): void {
+ $id = $this->insert_released( $this->make_contract() );
+ $contract = $this->sut->find( $id );
+ $this->assertInstanceOf( Contract::class, $contract );
+ $this->seed_plan_snapshot( $contract, array( 'selling_plan_id' => 7 ) );
+
+ $this->fail_next_query( $pattern );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( $message );
+
+ $this->sut->find( $id );
+ }
+
+ /**
+ * @return array<string, array{0: string, 1: string}>
+ */
+ public function provide_failing_child_reads(): array {
+ return array(
+ 'items' => array( '/^\s*SELECT \* FROM \S*contract_items WHERE contract_id/', 'Failed to read the items of contract' ),
+ 'addresses' => array( '/^\s*SELECT \* FROM \S*contract_addresses WHERE contract_id/', 'Failed to read the addresses of contract' ),
+ 'plan snapshot' => array( '/^\s*SELECT payload, schema_version FROM \S*subscription_snapshots WHERE id = /', 'Failed to read snapshot' ),
+ );
+ }
+
+ /**
+ * @testdox A cycle read throws when its snapshot read fails, instead of a cycle without its snapshot.
+ * @dataProvider provide_failing_cycle_snapshot_reads
+ *
+ * @param int $skip Snapshot reads to let through first: 0 breaks the plan snapshot, 1 the items snapshot.
+ */
+ public function test_cycle_read_throws_on_a_failed_snapshot_read( int $skip ): void {
+ $id = $this->insert_released( $this->make_contract() );
+ $snapshot_ids = $this->seed_cycle_snapshots( $id );
+ $this->append_cycle_locked( $this->make_cycle( $id, 1, 1, '2026-07-15 00:00:00', '2026-08-15 00:00:00', ...$snapshot_ids ) );
+
+ $this->fail_next_query( '/^\s*SELECT payload, schema_version FROM \S*subscription_snapshots WHERE id = /', $skip );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( "Failed to read snapshot {$snapshot_ids[ $skip ]}:" );
+
+ $this->sut->find_cycle_history( $id );
+ }
+
+ /**
+ * @return array<string, array{0: int}>
+ */
+ public function provide_failing_cycle_snapshot_reads(): array {
+ return array(
+ 'plan snapshot' => array( 0 ),
+ 'items snapshot' => array( 1 ),
+ );
+ }
+
+ /**
+ * @testdox A list read throws when its plan snapshot batch read fails, instead of contracts without plan terms.
+ */
+ public function test_list_read_throws_on_a_failed_snapshot_batch_read(): void {
+ $id = $this->insert_released( $this->make_contract() );
+ $contract = $this->sut->find( $id );
+ $this->assertInstanceOf( Contract::class, $contract );
+ $this->seed_plan_snapshot( $contract, array( 'selling_plan_id' => 7 ) );
+
+ $this->fail_next_query( '/FROM \S*subscription_snapshots\s+WHERE id IN/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read plan snapshots' );
+
+ $this->sut->query();
+ }
+
/**
* @testdox Multiple non-counting cycles (count = null) coexist in one chain.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php
index 51169cc2f10..6220d04e814 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanMetaTest.php
@@ -161,6 +161,35 @@ class PlanMetaTest extends EngineIntegrationTestCase {
);
}
+ /**
+ * @testdox get_meta throws on a failed read instead of reading the key as absent.
+ * @dataProvider provide_get_meta_shapes
+ *
+ * @param string $key Meta key; empty for every key.
+ * @param bool $single Return the first value only.
+ */
+ public function test_get_meta_throws_on_a_failed_read( string $key, bool $single ): void {
+ $this->sut->add_meta( $this->id, self::OWNER, 'note', 'one' );
+
+ $this->fail_next_query( '/^\s*SELECT meta_key, meta_value FROM \S*selling_plan_meta/' );
+
+ $this->expectException( RuntimeException::class );
+ $this->expectExceptionMessage( "Failed to read plan meta for plan {$this->id}" );
+
+ $this->sut->get_meta( $this->id, $key, $single );
+ }
+
+ /**
+ * @return array<string, array{0: string, 1: bool}>
+ */
+ public function provide_get_meta_shapes(): array {
+ return array(
+ 'every key' => array( '', false ),
+ 'one key' => array( 'note', false ),
+ 'single value' => array( 'note', true ),
+ );
+ }
+
/**
* @testdox arrays round-trip through serialization.
*/
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php
index d7ac0af6a0a..0663757692e 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/PlanRepositoryTest.php
@@ -238,6 +238,49 @@ class PlanRepositoryTest extends EngineIntegrationTestCase {
);
}
+ /**
+ * @testdox query throws on a failed read instead of returning no plans.
+ */
+ public function test_query_throws_on_a_failed_read(): void {
+ $repo = new PlanRepository();
+ $this->insert_plan( $repo, 'Stored' );
+
+ $this->fail_next_query( '/^\s*SELECT \* FROM \S*selling_plans\b.* LIMIT /s' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to read plans' );
+
+ $repo->query();
+ }
+
+ /**
+ * @testdox count throws on a failed read, filtered or not, instead of counting zero.
+ * @dataProvider provide_count_args
+ *
+ * @param array<string, mixed> $args Count args.
+ */
+ public function test_count_throws_on_a_failed_read( array $args ): void {
+ $repo = new PlanRepository();
+ $this->insert_plan( $repo, 'Stored' );
+
+ $this->fail_next_query( '/^\s*SELECT COUNT\(\*\) FROM \S*selling_plans\b/' );
+
+ $this->expectException( \RuntimeException::class );
+ $this->expectExceptionMessage( 'Failed to count plans' );
+
+ $repo->count( $args );
+ }
+
+ /**
+ * @return array<string, array{0: array<string, mixed>}>
+ */
+ public function provide_count_args(): array {
+ return array(
+ 'unfiltered' => array( array() ),
+ 'filtered' => array( array( 'status' => PlanStatus::ACTIVE ) ),
+ );
+ }
+
/**
* @testdox update_fields writes nothing and returns false when the row belongs to another extension.
*/