Commit 4f0cf594905 for woocommerce

commit 4f0cf594905feb800479d9001de0fe0d61469ff8
Author: Barry Hughes <3594411+barryhughes@users.noreply.github.com>
Date:   Wed Nov 25 19:34:45 2026 -0700

    Subscriptions engine: owner-scoped history delete and address email read (#71466)

    * Add an owner-scoped history delete to the subscriptions engine contracts facade

    Contracts::delete_history() deletes every history entry of a contract under the
    caller's lock, as one statement fenced like the other child writes, and returns
    the number of entries deleted. The owner decides when to call it, for example
    to erase personal data on request; the engine deletes no entry on its own.

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

    * Add an owner-scoped address email read to the subscriptions engine contracts facade

    Contracts::list_for_address_email() lists an extension's contracts whose billing
    or shipping address email equals the given email, newest first and each once,
    paged by limit and offset. The owner is required, so one extension never reads
    another's contracts by email. The contract addresses table gains an email index
    for this read (schema 2.11.0), and an email longer than the column is refused
    with a new too_long validation error code.

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

    * Add a changelog entry and README notes for the subscriptions engine privacy reads

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

    * Tidy the subscriptions engine privacy reads after review

    Refuse a blank address email as required: the default collations ignore
    trailing spaces, so it would otherwise match stored empty emails. Pin the
    address email read as an exact match, with no prefix or wildcard matching.
    Note in the README that the address email read is owner-scoped, and correct
    the history delete docblock and the email index comment.

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

    * Delete subscriptions engine contract history only while the lock is held

    The history delete ran unconditionally after the child-write fence, so a caller
    that stalled after the fence and lost its lock could delete entries a later lock
    holder had written. The delete now joins the contract row and deletes only while
    the caller's lock is held on the database clock; when it deletes nothing, a lost
    lock throws ContractLockedException instead of reading as an empty history.

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

    * Report a failed lock check after an empty history delete

    delete_history() returned 0 when its delete matched no row and the
    follow-up lock check could not read the lock, so a lock lost after the
    fence could read as an empty history. The delete path now uses a strict
    check: a failed read throws RuntimeException, a lost lock throws
    ContractLockedException, and 0 is returned only once the lock is
    confirmed held. Failed child inserts keep their own error as before.

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

    * Treat a removed contract as a lost lock after an empty history delete

    A lock the fence still trusts can reach the zero-row path after its
    contract row is gone. delete_history() now throws
    ContractLockedException there instead of returning 0. Failed child
    inserts still let a missing contract fall through to their own error.

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

    * Tighten the address email read and the history delete lock check

    - Trim the email before matching, in ArgumentValidator::validate_bounded_string(),
      which now refuses a blank value as required; the facade's inline check goes.
    - Document the real matching rules: the addresses table's collation, on default
      installs case- and accent-insensitive with trailing spaces ignored.
    - Read whether the lock is held and its holder in one statement after an empty
      history delete.
    - State that delete_history() on a removed contract throws ContractLockedException.
    - Cross-reference the 320-character email limit and the column width.
    - Test an expired lock not taken over, a lock lost after the fence on an empty
      history, a trimmed email, and an email longer than the index prefix.

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

    * Trim the address email in the facade, keeping the validator a shape check

    validate_bounded_string() goes back to checking shape only, like the
    other ArgumentValidator helpers. list_for_address_email() trims the
    email before validating it, so a blank value is still refused as
    required, and says why next to the call.

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

    ---------

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

diff --git a/packages/php/woocommerce-subscriptions-engine/README.md b/packages/php/woocommerce-subscriptions-engine/README.md
index b214a57c6cc..3663c5463ef 100644
--- a/packages/php/woocommerce-subscriptions-engine/README.md
+++ b/packages/php/woocommerce-subscriptions-engine/README.md
@@ -5,8 +5,9 @@ This package implements a general-purpose subscriptions engine for WooCommerce.
 The engine records subscription facts (plans, contracts, billing cycles) and offers tools to work with them; extensions own every flow and decision. In particular:

 - **Due dispatch:** an extension registers a contract due handler with its slug, and the engine calls it when one of its contracts reaches its next due moment, passing the dispatcher's contract lock. What happens then (renew, skip, clear the due moment) is the extension's decision.
-- **Ownership:** every plan and contract records its owning extension (`extension_slug`). Reads work across extensions. Every write names the expected owner, the row's owning extension (also when acting for that extension, for example a listener writing with the owner's lock passes the contract's `extension_slug`), and never touches a row of another extension: such a row reads as missing to the write. This guards against writing another extension's row by mistake; it is not authorization. `Plans::update()`, `Contracts::update()`, `add_cycle()` and `transition_cycle()` take `extension_slug` in their arguments; `Contracts::lock()` and the contract and plan meta writes take it as their second parameter, for example `Contracts::lock( $contract_id, $extension_slug, $operation )` and `Plans::add_meta( $plan_id, $extension_slug, $key, $value )`.
-- **Contract lock:** one lock per contract on the facade. `Contracts::lock( $contract_id, $extension_slug, $operation )` takes it for an operation (null when another operation holds it or no contract of that extension has the id) and `Contracts::create()` creates every contract locked from birth (null when its optional creation key is taken); every write takes the lock as its last parameter. Every write runs under a lock: the caller's, or, for an update or meta write made without one, an internal lock the engine takes for that call. Every contract write is owner-scoped where its lock is taken. Cycle writes require the caller's lock. A write is refused with `ContractLockedException` while another operation holds the lock, and with `InvalidArgumentException` when it names an owner other than its lock's. One exception: a history entry added without a lock is a plain owner-scoped insert that no held lock refuses (see below).
-- **Contract history:** `Contracts::add_history_entry( $contract_id, $args, $lock )` records an entry the owning extension writes on its own command: a `type` slug it chooses, an optional cycle of the contract, an opaque JSON `payload` and an optional `creation_key` that makes the add idempotent per contract (null when taken). `Contracts::get_history( $contract_id, $args )` reads entries newest first. The engine writes no entries itself and gives types and payloads no meaning. With the caller's lock the write is fenced by it; without one it is never blocked by a lock another operation holds.
+- **Ownership:** every plan and contract records its owning extension (`extension_slug`). Reads work across extensions, except `Contracts::list_for_address_email()`, which is owner-scoped. Every write names the expected owner, the row's owning extension (also when acting for that extension, for example a listener writing with the owner's lock passes the contract's `extension_slug`), and never touches a row of another extension: such a row reads as missing to the write. This guards against writing another extension's row by mistake; it is not authorization. `Plans::update()`, `Contracts::update()`, `add_cycle()` and `transition_cycle()` take `extension_slug` in their arguments; `Contracts::lock()` and the contract and plan meta writes take it as their second parameter, for example `Contracts::lock( $contract_id, $extension_slug, $operation )` and `Plans::add_meta( $plan_id, $extension_slug, $key, $value )`.
+- **Contract lock:** one lock per contract on the facade. `Contracts::lock( $contract_id, $extension_slug, $operation )` takes it for an operation (null when another operation holds it or no contract of that extension has the id) and `Contracts::create()` creates every contract locked from birth (null when its optional creation key is taken); every write takes the lock as its last parameter. Every write runs under a lock: the caller's, or, for an update or meta write made without one, an internal lock the engine takes for that call. Every contract write is owner-scoped where its lock is taken. Cycle writes and the history delete require the caller's lock. A write is refused with `ContractLockedException` while another operation holds the lock, and with `InvalidArgumentException` when it names an owner other than its lock's. One exception: a history entry added without a lock is a plain owner-scoped insert that no held lock refuses (see below).
+- **Contract history:** `Contracts::add_history_entry( $contract_id, $args, $lock )` records an entry the owning extension writes on its own command: a `type` slug it chooses, an optional cycle of the contract, an opaque JSON `payload` and an optional `creation_key` that makes the add idempotent per contract (null when taken). `Contracts::get_history( $contract_id, $args )` reads entries newest first. The engine writes no entries itself and gives types and payloads no meaning. With the caller's lock the write is fenced by it; without one it is never blocked by a lock another operation holds. `Contracts::delete_history( $contract_id, $args, $lock )` deletes every entry of a contract under the caller's lock; the engine deletes none on its own.
+- **Personal data:** the engine registers no personal data exporter or eraser. Each owning extension registers its own for its contracts, finding them with `Contracts::list_for_customer()` and `Contracts::list_for_address_email()` (contracts of that extension whose billing or shipping address email matches the trimmed value under the addresses table's collation: on default installs case- and accent-insensitive, trailing spaces ignored) and erasing with `Contracts::update()` and `Contracts::delete_history()`.
 - **Cycle tools:** cycle appends are append-if-absent on the chain's positions, and status transitions are compare-and-set.
 - **Payments broker:** `Api\Payments` lets an extension ask the order's gateway to take a scheduled payment off-session (`Payments::process_scheduled_payment( $order )`). Gateways opt in by adding the `subscriptions_engine` feature to their `$supports` and charging the order on `woocommerce_subscriptions_engine_scheduled_payment_{gateway_id}( $order )`, reporting the outcome through the order status. What a gateway can do beyond that (renewal payments, payment method changes, ...) it declares with the existing WooCommerce gateway features; extensions check the ones an operation needs with `Payments::gateway_supports( $gateway_id, $features )`, and the engine does not interpret them.
diff --git a/packages/php/woocommerce-subscriptions-engine/changelog/add-subscriptions-engine-privacy-reads b/packages/php/woocommerce-subscriptions-engine/changelog/add-subscriptions-engine-privacy-reads
new file mode 100644
index 00000000000..4ed8ab0b9fa
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/changelog/add-subscriptions-engine-privacy-reads
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Add a contract history delete and an address email read to the unreleased subscriptions engine; 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 f9deca903c7..38e19cd7e48 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/Contracts.php
@@ -12,10 +12,11 @@
  *
  * One lock per contract ({@see self::lock()}): every write runs under a lock, the caller's or,
  * for an update or meta write made without one, an internal one the engine takes for that call.
- * Every contract write is owner-scoped where its lock is taken. Cycle writes require the caller's
- * lock. A write is refused with {@see ContractLockedException} while another operation holds the
- * lock. One exception: a history entry ({@see self::add_history_entry()}) is fenced by the caller's
- * lock when one is passed, and is otherwise a plain owner-scoped insert that no held lock refuses.
+ * Every contract write is owner-scoped where its lock is taken. Cycle writes and the history
+ * delete require the caller's lock. A write is refused with {@see ContractLockedException} while
+ * another operation holds the lock. One exception: a history entry
+ * ({@see self::add_history_entry()}) is fenced by the caller's lock when one is passed, and is
+ * otherwise a plain owner-scoped insert that no held lock refuses.
  *
  * @package Automattic\WooCommerce\SubscriptionsEngine\Api
  */
@@ -162,6 +163,15 @@ final class Contracts {
 		'offset' => true,
 	);

+	/**
+	 * Keys accepted by {@see self::delete_history()}, as a key map.
+	 *
+	 * @var array<string, true>
+	 */
+	private const HISTORY_DELETE_KEYS = array(
+		'extension_slug' => true,
+	);
+
 	/**
 	 * Keys accepted by {@see self::list_for_customer()}, as a key map.
 	 *
@@ -172,6 +182,21 @@ final class Contracts {
 		'extension_slug' => true,
 	);

+	/**
+	 * Keys accepted by {@see self::list_for_address_email()}, as a key map.
+	 *
+	 * @var array<string, true>
+	 */
+	private const LIST_FOR_ADDRESS_EMAIL_KEYS = array(
+		'extension_slug' => true,
+	);
+
+	/**
+	 * Width of the stored address email column, the longest email {@see self::list_for_address_email()} can match.
+	 * Keep in step with `email VARCHAR(320)` of the contract addresses table in `SchemaInstaller`.
+	 */
+	private const ADDRESS_EMAIL_MAX_LENGTH = 320;
+
 	/**
 	 * Take the contract's lock for `$operation`, for the synchronous section of this request.
 	 * Pass the lock to every write of the operation and release it when done; an unreleased
@@ -714,6 +739,53 @@ final class Contracts {
 	}
 	// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber

+	// phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- @throws also lists exceptions raised by the methods called.
+	/**
+	 * List an extension's contracts with a billing or shipping address whose email equals `$email`,
+	 * newest first, each once. Owner-scoped: `extension_slug` is required, so one extension never
+	 * reads another's contracts by email. The email is trimmed, then matched under the addresses
+	 * table's collation (`utf8mb4_unicode_520_ci` on default installs): case- and accent-insensitive
+	 * (`é` = `e`, `ß` = `ss`), trailing spaces ignored. Views carry no items or addresses. Unknown
+	 * keys get `_doing_it_wrong()`.
+	 *
+	 * @param string               $email  The address email to match (1-320 characters once trimmed; no format check).
+	 * @param int                  $limit  Maximum contracts to return.
+	 * @param int                  $offset Contracts to skip (for paging).
+	 * @param array<string, mixed> $args   `extension_slug` (required, the owning extension; `any` is refused).
+	 * @return array<int, ContractView> The matching contracts, newest first.
+	 * @throws ValidationException If `$email` is empty, blank or too long, `$limit` or `$offset` is negative, or
+	 *                             `extension_slug` is missing, invalid or `any`, with every error reported.
+	 * @throws \RuntimeException   If the read fails.
+	 */
+	public static function list_for_address_email( string $email, int $limit = 20, int $offset = 0, array $args = array() ): array {
+		$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::LIST_FOR_ADDRESS_EMAIL_KEYS );
+
+		// The email is trimmed before matching: the default collations ignore trailing spaces but not leading ones,
+		// and a blank value would match stored empty emails, so it is refused as required.
+		$validator      = new ArgumentValidator();
+		$email          = $validator->get_bounded_string( 'email', trim( $email ), self::ADDRESS_EMAIL_MAX_LENGTH );
+		$limit          = (int) $validator->get_non_negative_int( 'limit', $limit );
+		$offset         = (int) $validator->get_non_negative_int( 'offset', $offset );
+		$extension_slug = (string) $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] ?? null );
+		if ( 'any' === $extension_slug ) {
+			$validator->add(
+				new InvalidInputException(
+					ValidationErrorCode::INVALID_VALUE,
+					'extension_slug',
+					'"extension_slug" must not be "any": name the owning extension.'
+				)
+			);
+		}
+		try {
+			$validator->throw_errors();
+		} catch ( InvalidInputException $e ) {
+			throw ValidationException::from_core( $e ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- from_core() escapes the message.
+		}
+
+		return self::views( ( new ContractRepository() )->find_by_address_email( (string) $email, $extension_slug, $limit, $offset ) );
+	}
+	// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
+
 	/**
 	 * Fetch a contract a customer owns - the customer portal's ownership-checked read.
 	 *
@@ -843,6 +915,40 @@ final class Contracts {
 	}
 	// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber

+	// phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- @throws also lists exceptions raised by the methods called.
+	/**
+	 * Delete every history entry of a contract of the given extension, under the caller's lock. The
+	 * engine deletes no entry on its own; the owner decides when (for example a privacy erasure). An
+	 * entry added without a lock is not held back by the lock, so one may land right after the delete.
+	 * Unknown keys get `_doing_it_wrong()`.
+	 *
+	 * @param int                  $contract_id Contract id.
+	 * @param array<string, mixed> $args        `extension_slug` (required, the expected owner).
+	 * @param ContractLock         $lock        The caller's lock on this contract, from {@see self::lock()},
+	 *                                          {@see self::create()} or the due handler's context.
+	 * @return int The number of entries deleted; 0 when the contract has none.
+	 * @throws ValidationException      If `extension_slug` is missing or invalid.
+	 * @throws InvalidArgumentException If the lock is for another contract or another extension.
+	 * @throws ContractLockedException  If `$lock` was lost, including when the contract no longer exists.
+	 * @throws \RuntimeException        If the delete fails.
+	 */
+	public static function delete_history( int $contract_id, array $args, ContractLock $lock ): int {
+		$filtered_args = ArgumentFilter::filter_known_keys( __METHOD__, $args, self::HISTORY_DELETE_KEYS );
+
+		$validator      = new ArgumentValidator();
+		$extension_slug = (string) $validator->get_extension_slug( 'extension_slug', $filtered_args['extension_slug'] ?? null );
+		try {
+			$validator->throw_errors();
+		} catch ( InvalidInputException $e ) {
+			throw ValidationException::from_core( $e ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- from_core() escapes the message.
+		}
+
+		ContractRepository::assert_lock_owner( $lock, $extension_slug );
+
+		return ( new ContractRepository() )->delete_history( $contract_id, $lock );
+	}
+	// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
+
 	/**
 	 * Check the positional scope arguments of a write: the expected owner and, for a meta write,
 	 * the key; every error is reported at once.
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php b/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php
index 88339579f31..78b9ae65a20 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Api/ValidationException.php
@@ -116,6 +116,12 @@ final class ValidationException extends InvalidArgumentException {
 					return sprintf( __( 'Must be less than or equal to %d.', 'woocommerce' ), $max );
 				}
 				break;
+			case ValidationErrorCode::TOO_LONG:
+				if ( null !== $max ) {
+					/* translators: %d: most characters allowed. */
+					return sprintf( _n( 'Must be at most %d character.', 'Must be at most %d characters.', $max, 'woocommerce' ), $max );
+				}
+				break;
 			case ValidationErrorCode::NOT_IN_ENUM:
 				if ( isset( $params['allowed'] ) && is_array( $params['allowed'] ) ) {
 					/* translators: %l: list of allowed values, such as "day, week, and month". */
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php
index 8e3539ce650..bb35a3390bd 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ArgumentValidator.php
@@ -109,6 +109,22 @@ final class ArgumentValidator {
 		}
 	}

+	/**
+	 * Collecting {@see self::validate_bounded_string()}: the value, or null when refused.
+	 *
+	 * @param string $key        Field name.
+	 * @param mixed  $value      Caller value.
+	 * @param int    $max_length Most characters allowed.
+	 */
+	public function get_bounded_string( string $key, $value, int $max_length ): ?string {
+		try {
+			return self::validate_bounded_string( $key, $value, $max_length );
+		} catch ( InvalidInputException $e ) {
+			$this->add( $e );
+			return null;
+		}
+	}
+
 	/**
 	 * Collecting {@see self::validate_extension_slug()}: the slug, or null when refused.
 	 *
@@ -356,6 +372,24 @@ final class ArgumentValidator {
 		return $value;
 	}

+	/**
+	 * Validate and return a non-empty string of at most `$max_length` characters, for a value
+	 * matched against a column of that width. No trimming: the caller trims when it needs to.
+	 *
+	 * @param string $key        Field name.
+	 * @param mixed  $value      Caller value.
+	 * @param int    $max_length Most characters allowed.
+	 * @throws InvalidInputException If the value is missing, empty, not a string or too long.
+	 */
+	public static function validate_bounded_string( string $key, $value, int $max_length ): string {
+		$string = self::validate_non_empty_string( $key, $value );
+		if ( mb_strlen( $string ) > $max_length ) {
+			throw self::get_invalid_input( ValidationErrorCode::TOO_LONG, $key, sprintf( 'must be at most %d characters', $max_length ), array( 'max' => $max_length ) );
+		}
+
+		return $string;
+	}
+
 	/**
 	 * Validate and return an extension slug: a non-empty string matching
 	 * {@see self::SLUG_PATTERN}. No trimming or case folding: a slug that differs is
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php
index ea7375b03b3..7fd56b82345 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Core/Support/ValidationErrorCode.php
@@ -41,6 +41,11 @@ final class ValidationErrorCode {
 	 */
 	public const NOT_IN_ENUM = 'not_in_enum';

+	/**
+	 * A string is longer than allowed. Params: `max` (int), the most characters allowed.
+	 */
+	public const TOO_LONG = 'too_long';
+
 	/**
 	 * A well-typed value is malformed or forbidden. No params.
 	 */
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 f5164040350..318ee0c68d7 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/ContractRepository.php
@@ -83,6 +83,11 @@ final class ContractRepository {
 	 */
 	private const HOLDS_LOCK = 'lock_token = %s AND locked_until_gmt > UTC_TIMESTAMP()';

+	/**
+	 * {@see self::HOLDS_LOCK} on a contract row joined as `c`.
+	 */
+	private const C_HOLDS_LOCK = 'c.lock_token = %s AND c.locked_until_gmt > UTC_TIMESTAMP()';
+
 	/**
 	 * SQL condition: the row's owner is exactly the bound slug. The column's binary collation makes
 	 * the match case-sensitive, as the engine's PHP comparisons of the owner are.
@@ -1330,6 +1335,55 @@ final class ContractRepository {
 		return $this->contracts_from_rows( is_array( $rows ) ? $rows : array() );
 	}

+	/**
+	 * Contracts of `$extension_slug` with a billing or shipping address whose email equals `$email`,
+	 * newest first, each once. The match uses the addresses table's collation through its `email`
+	 * index: on default installs (`utf8mb4_unicode_520_ci`) case- and accent-insensitive (`é` = `e`,
+	 * `ß` = `ss`), trailing spaces ignored. The value is matched as given: the facade trims it.
+	 * Row-only reads, plan terms batch-hydrated.
+	 *
+	 * @param string $email          The address email to match.
+	 * @param string $extension_slug The owning extension.
+	 * @param int    $limit          Maximum contracts to return.
+	 * @param int    $offset         Contracts to skip (for paging).
+	 * @return array<int, Contract> Contracts newest first.
+	 * @throws \RuntimeException If the read fails: a failed read must not look like no contracts.
+	 */
+	public function find_by_address_email( string $email, string $extension_slug, int $limit, int $offset ): array {
+		global $wpdb;
+
+		$contracts   = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACTS );
+		$addresses   = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACT_ADDRESSES );
+		$select      = self::CONTRACT_SELECT;
+		$owner_match = self::OWNER_MATCH;
+
+		// A subquery, not a join: a contract with the email on both addresses is returned once. The
+		// owner placeholder comes from OWNER_MATCH, so the sniff cannot count it.
+		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+		$rows = $wpdb->get_results(
+			$wpdb->prepare(
+				"SELECT {$select}
+				FROM {$contracts}
+				WHERE {$owner_match}
+				AND id IN ( SELECT contract_id FROM {$addresses} WHERE email = %s )
+				ORDER BY id DESC
+				LIMIT %d OFFSET %d",
+				$extension_slug,
+				$email,
+				$limit,
+				$offset
+			),
+			ARRAY_A
+		);
+		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+		if ( '' !== $wpdb->last_error ) {
+			// The message leaves the email out: exception messages end up in logs.
+			throw new \RuntimeException( esc_html( sprintf( 'Failed to read the contracts of extension "%s" by address email: %s', $extension_slug, $wpdb->last_error ) ) );
+		}
+
+		return $this->contracts_from_rows( is_array( $rows ) ? $rows : array() );
+	}
+
 	/**
 	 * Contracts whose `origin_order_id` is `$order_id`, oldest first. Row-only reads
 	 * (no items / addresses) with their frozen plan terms batch-hydrated.
@@ -2152,6 +2206,47 @@ final class ContractRepository {
 		return $entries;
 	}

+	// phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- @throws also lists exceptions raised by the methods called.
+	/**
+	 * Delete every history entry of a contract in one statement that deletes only while the caller's
+	 * lock is held on the database clock, so a caller that lost its lock after the fence cannot delete
+	 * entries a later holder wrote. The fence still refuses a lock for another contract or one already
+	 * known lost before any delete runs. The facade checks the lock's owner ({@see self::assert_lock_owner()}).
+	 *
+	 * @param int          $contract_id Contract id.
+	 * @param ContractLock $lock        The caller's lock on this contract.
+	 * @return int The number of entries deleted; 0 only once the lock is confirmed held and the contract has none.
+	 * @throws \InvalidArgumentException If the lock is for another contract.
+	 * @throws ContractLockedException If the lock was lost.
+	 * @throws \RuntimeException If the delete, or the lock check after an empty delete, fails.
+	 */
+	public function delete_history( int $contract_id, ContractLock $lock ): int {
+		global $wpdb;
+
+		$this->fence_child_write( $lock, $contract_id );
+
+		$history    = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACT_HISTORY );
+		$contracts  = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACTS );
+		$holds_lock = self::C_HOLDS_LOCK;
+
+		// Table names and the lock predicate are constants; every value is a placeholder.
+		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+		$deleted = $wpdb->query( $wpdb->prepare( "DELETE h FROM {$history} h JOIN {$contracts} c ON c.id = h.contract_id WHERE h.contract_id = %d AND {$holds_lock}", $contract_id, $lock->get_state()->get_token() ) );
+		if ( false === $deleted ) {
+			throw new \RuntimeException( esc_html( sprintf( 'Failed to delete the history of contract %d: %s', $contract_id, $wpdb->last_error ) ) );
+		}
+		// No row deleted: an empty history, or a lock lost since the fence, which must not read as empty.
+		if ( 0 === (int) $deleted ) {
+			$holder = $this->find_lost_lock_holder( $lock );
+			if ( null !== $holder ) {
+				throw self::locked_exception( $contract_id, $holder ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- the exception message is not output.
+			}
+		}
+
+		return (int) $deleted;
+	}
+	// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
+
 	/**
 	 * All cycles linked to `$order_id`, across kinds and contracts. `order_id` is a
 	 * non-1:1 reference (an aggregate order may serve many cycles), so this returns
@@ -2226,31 +2321,62 @@ final class ContractRepository {
 	// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber

 	/**
-	 * After a failed child insert, report a lost lock instead of the database error: throws when
-	 * `$lock` is no longer held. Returns when it is held, or the check fails, so the caller
-	 * throws its own error.
+	 * After a failed child insert, report a lost lock: throws when `$lock` is no longer held on an
+	 * existing contract. Returns when it is held, the contract is gone, or the check fails, so the
+	 * caller goes on with its own error.
 	 *
 	 * @param ContractLock $lock The caller's lock.
 	 * @throws ContractLockedException If the lock was lost.
 	 */
 	private function throw_if_lock_lost( ContractLock $lock ): void {
+		try {
+			$holder = $this->find_lost_lock_holder( $lock );
+		} catch ( \RuntimeException $e ) {
+			return;
+		}
+
+		if ( null !== $holder && $holder['exists'] ) {
+			throw self::locked_exception( $lock->get_contract_id(), $holder ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- the exception message is not output.
+		}
+	}
+
+	/**
+	 * The lock holder when `$lock` is no longer held, read on the database clock; null only when it
+	 * is held. One read gives both facts from the same row. A contract that is gone reads as not
+	 * held, with `exists` false.
+	 *
+	 * @param ContractLock $lock The caller's lock.
+	 * @return array{exists: bool, operation: ?string}|null
+	 * @throws \RuntimeException If the read fails.
+	 */
+	private function find_lost_lock_holder( ContractLock $lock ): ?array {
 		global $wpdb;

 		$contract_id = $lock->get_contract_id();
 		$contracts   = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACTS );
 		$holds_lock  = self::HOLDS_LOCK;
-		try {
-			$holder = $this->get_lock_holder( $contract_id );
-			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
-			$held = $wpdb->get_var( $wpdb->prepare( "SELECT 1 FROM {$contracts} WHERE id = %d AND {$holds_lock}", $contract_id, $lock->get_state()->get_token() ) );
-		} catch ( \RuntimeException $e ) {
-			return;
+		$lock_live   = self::LOCK_LIVE;
+
+		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+		$row = $wpdb->get_row( $wpdb->prepare( "SELECT ( {$holds_lock} ) AS held, {$lock_live} AS live, lock_operation FROM {$contracts} WHERE id = %d", $lock->get_state()->get_token(), $contract_id ), ARRAY_A );
+		if ( '' !== $wpdb->last_error ) {
+			throw new \RuntimeException( esc_html( sprintf( 'Failed to check the lock on contract %d: %s', $contract_id, $wpdb->last_error ) ) );
 		}

-		if ( '' !== $wpdb->last_error || ! $holder['exists'] || null !== $held ) {
-			return;
+		if ( ! is_array( $row ) ) {
+			return array(
+				'exists'    => false,
+				'operation' => null,
+			);
 		}
-		throw self::locked_exception( $contract_id, $holder ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- the exception message is not output.
+		if ( ! empty( $row['held'] ) ) {
+			return null;
+		}
+
+		return array(
+			'exists'    => true,
+			'operation' => ! empty( $row['live'] ) ? Coercion::coerce_nullable_string( $row['lock_operation'] ?? null ) : null,
+		);
 	}

 	/**
diff --git a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php
index a618702d10f..53f4e0d050c 100644
--- a/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php
+++ b/packages/php/woocommerce-subscriptions-engine/src/Integration/Storage/SchemaInstaller.php
@@ -68,13 +68,15 @@ final class SchemaInstaller {
 	 * 2.10.0 - new contract_history table: per-contract extension records (type, optional cycle,
 	 *          opaque JSON payload, a binary-collated `creation_key` unique per contract), read
 	 *          newest first through the `contract` index. dbDelta creates it; nothing to recreate.
+	 * 2.11.0 - contract_addresses gain an `email` index for the owner-scoped address email read.
+	 *          dbDelta adds it; nothing to recreate.
 	 *
 	 * Pre-freeze, tables are recreated rather than migrated. dbDelta adds columns but
 	 * does not change an existing column's nullability or drop unused ones, so a dev box
 	 * on an earlier schema must drop and recreate the tables (and clear VERSION_OPTION)
 	 * to pick up such changes - in-place ALTERs and backfills arrive with the freeze.
 	 */
-	private const VERSION = '2.10.0';
+	private const VERSION = '2.11.0';

 	/**
 	 * Option key tracking the installed schema version.
@@ -340,7 +342,9 @@ final class SchemaInstaller {
 ) {$collate};";

 		// One billing + one shipping address per contract: composite PK on
-		// (contract_id, address_type).
+		// (contract_id, address_type). `email` keys the owner-scoped address email read on a
+		// 191-character prefix: 191 utf8mb4 characters (4 bytes each) fit the 767-byte index limit.
+		// Keep the `email` width in step with Api\Contracts::ADDRESS_EMAIL_MAX_LENGTH.
 		$contract_addresses_sql = "CREATE TABLE {$contract_addresses} (
   contract_id BIGINT UNSIGNED NOT NULL,
   address_type VARCHAR(20) NOT NULL,
@@ -355,7 +359,8 @@ final class SchemaInstaller {
   country TEXT NULL,
   email VARCHAR(320) NULL,
   phone VARCHAR(100) NULL,
-  PRIMARY KEY  (contract_id, address_type)
+  PRIMARY KEY  (contract_id, address_type),
+  KEY email (email(191))
 ) {$collate};";

 		$contract_meta_sql = "CREATE TABLE {$contract_meta} (
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractAddressEmailListTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractAddressEmailListTest.php
new file mode 100644
index 00000000000..1ac070580f2
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractAddressEmailListTest.php
@@ -0,0 +1,226 @@
+<?php
+/**
+ * Integration tests for Contracts::list_for_address_email().
+ *
+ * @package Automattic\WooCommerce\SubscriptionsEngine
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\SubscriptionsEngine\Tests\Integration\Api;
+
+use EngineIntegrationTestCase;
+use RuntimeException;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\Contracts;
+use Automattic\WooCommerce\SubscriptionsEngine\Api\View\ContractView;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ArgumentValidator;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Support\ValidationErrorCode;
+use Automattic\WooCommerce\SubscriptionsEngine\Tests\Integration\AssertsValidationErrors;
+
+/**
+ * @covers \Automattic\WooCommerce\SubscriptionsEngine\Api\Contracts
+ */
+class ContractAddressEmailListTest extends EngineIntegrationTestCase {
+
+	use AssertsValidationErrors;
+
+	private const EXTENSION_SLUG = 'acme-subs';
+
+	private const EMAIL = 'ada@example.com';
+
+	/**
+	 * @testdox list_for_address_email() returns the owner's contracts with the email on either address, newest first, each once.
+	 */
+	public function test_lists_the_owners_matching_contracts(): void {
+		$billing  = $this->seed( array( 'billing' => self::EMAIL ) );
+		$both     = $this->seed(
+			array(
+				'billing'  => self::EMAIL,
+				'shipping' => self::EMAIL,
+			)
+		);
+		$shipping = $this->seed( array( 'shipping' => 'ADA@example.com' ) );
+		$this->seed( array( 'billing' => self::EMAIL ), 'another-extension' );
+		$this->seed( array( 'billing' => 'grace@example.com' ) );
+
+		$views = Contracts::list_for_address_email( self::EMAIL, 20, 0, array( 'extension_slug' => self::EXTENSION_SLUG ) );
+
+		$this->assertSame( array( $shipping, $both, $billing ), $this->ids( $views ), 'Case-insensitive under the default collation; other owners excluded.' );
+		$this->assertContainsOnlyInstancesOf( ContractView::class, $views );
+		$this->assertNull( $views[0]->get_addresses(), 'Views carry no addresses.' );
+		$this->assertNull( $views[0]->get_items(), 'Views carry no items.' );
+		$this->assertSame( array(), Contracts::list_for_address_email( 'nobody@example.com', 20, 0, array( 'extension_slug' => self::EXTENSION_SLUG ) ) );
+	}
+
+	/**
+	 * @testdox list_for_address_email() pages with limit and offset.
+	 */
+	public function test_pages_with_limit_and_offset(): void {
+		$first  = $this->seed( array( 'billing' => self::EMAIL ) );
+		$second = $this->seed( array( 'billing' => self::EMAIL ) );
+		$third  = $this->seed( array( 'billing' => self::EMAIL ) );
+		$args   = array( 'extension_slug' => self::EXTENSION_SLUG );
+
+		$this->assertSame( array( $third, $second ), $this->ids( Contracts::list_for_address_email( self::EMAIL, 2, 0, $args ) ) );
+		$this->assertSame( array( $first ), $this->ids( Contracts::list_for_address_email( self::EMAIL, 2, 2, $args ) ) );
+		$this->assertSame( array( $third, $second, $first ), $this->ids( Contracts::list_for_address_email( self::EMAIL, 20, 0, $args ) ), 'The defaults page 20 from the start.' );
+	}
+
+	/**
+	 * @testdox list_for_address_email() reports an empty email, a negative limit and offset, and a missing owner together.
+	 */
+	public function test_reports_every_shape_error_together(): void {
+		$this->assert_validation_errors(
+			static function (): void {
+				Contracts::list_for_address_email( '', -1, -2 );
+			},
+			array(
+				array( ValidationErrorCode::REQUIRED, 'email' ),
+				array( ValidationErrorCode::REQUIRED, 'extension_slug' ),
+				array( ValidationErrorCode::OUT_OF_BOUNDS, 'limit', array( 'min' => 0 ) ),
+				array( ValidationErrorCode::OUT_OF_BOUNDS, 'offset', array( 'min' => 0 ) ),
+			)
+		);
+	}
+
+	/**
+	 * @testdox list_for_address_email() refuses a blank email as required, so it cannot match stored empty emails.
+	 */
+	public function test_refuses_a_blank_email(): void {
+		$this->seed( array( 'billing' => '' ) );
+
+		foreach ( array( ' ', "\t \n" ) as $email ) {
+			$this->assert_validation_errors(
+				static function () use ( $email ): void {
+					Contracts::list_for_address_email( $email, 20, 0, array( 'extension_slug' => self::EXTENSION_SLUG ) );
+				},
+				array(
+					array( ValidationErrorCode::REQUIRED, 'email' ),
+				)
+			);
+		}
+	}
+
+	/**
+	 * @testdox list_for_address_email() trims the email, so leading and trailing spaces match alike.
+	 */
+	public function test_trims_the_email(): void {
+		$id   = $this->seed( array( 'billing' => self::EMAIL ) );
+		$args = array( 'extension_slug' => self::EXTENSION_SLUG );
+
+		foreach ( array( ' ' . self::EMAIL, self::EMAIL . ' ', "\t" . self::EMAIL . "\n" ) as $email ) {
+			$this->assertSame( array( $id ), $this->ids( Contracts::list_for_address_email( $email, 20, 0, $args ) ), 'Matched once trimmed: ' . wp_json_encode( $email ) );
+		}
+	}
+
+	/**
+	 * @testdox list_for_address_email() refuses an email longer than the 320-character column and accepts one at the limit.
+	 */
+	public function test_refuses_an_email_longer_than_the_column(): void {
+		$args = array( 'extension_slug' => self::EXTENSION_SLUG );
+
+		$this->assert_validation_errors(
+			static function () use ( $args ): void {
+				Contracts::list_for_address_email( str_repeat( 'a', 309 ) . '@example.com', 20, 0, $args );
+			},
+			array(
+				array( ValidationErrorCode::TOO_LONG, 'email', array( 'max' => 320 ) ),
+			)
+		);
+
+		$this->assertSame( array(), Contracts::list_for_address_email( str_repeat( 'a', 308 ) . '@example.com', 20, 0, $args ) );
+	}
+
+	/**
+	 * @testdox list_for_address_email() refuses an ill-typed, malformed or `any` extension_slug.
+	 * @dataProvider provide_invalid_owners
+	 *
+	 * @param mixed             $slug     The extension_slug value.
+	 * @param array<int, mixed> $expected Expected error.
+	 */
+	public function test_refuses_an_invalid_owner( $slug, array $expected ): void {
+		$this->seed( array( 'billing' => self::EMAIL ) );
+
+		$this->assert_validation_errors(
+			static function () use ( $slug ): void {
+				Contracts::list_for_address_email( self::EMAIL, 20, 0, array( 'extension_slug' => $slug ) );
+			},
+			array( $expected )
+		);
+	}
+
+	/**
+	 * @return array<string, array{0: mixed, 1: array<int, mixed>}>
+	 */
+	public function provide_invalid_owners(): array {
+		return array(
+			'empty'     => array( '', array( ValidationErrorCode::REQUIRED, 'extension_slug' ) ),
+			'not text'  => array( 5, array( ValidationErrorCode::INVALID_TYPE, 'extension_slug', array( 'type' => 'string' ) ) ),
+			'malformed' => array( 'Acme Subs', array( ValidationErrorCode::INVALID_PATTERN, 'extension_slug', array( 'pattern' => ArgumentValidator::SLUG_PATTERN ) ) ),
+			'any'       => array( 'any', array( ValidationErrorCode::INVALID_VALUE, 'extension_slug' ) ),
+		);
+	}
+
+	/**
+	 * @testdox list_for_address_email() ignores unknown keys with a notice.
+	 */
+	public function test_ignores_unknown_keys(): void {
+		$this->setExpectedIncorrectUsage( Contracts::class . '::list_for_address_email' );
+		$id   = $this->seed( array( 'billing' => self::EMAIL ) );
+		$args = array(
+			'extension_slug' => self::EXTENSION_SLUG,
+			'status'         => 'cancelled',
+		);
+
+		$this->assertSame( array( $id ), $this->ids( Contracts::list_for_address_email( self::EMAIL, 20, 0, $args ) ), 'The unknown status filter is ignored.' );
+	}
+
+	/**
+	 * @testdox list_for_address_email() throws RuntimeException on a failed read instead of returning no contracts.
+	 */
+	public function test_a_failed_read_throws(): void {
+		$this->seed( array( 'billing' => self::EMAIL ) );
+		$this->fail_next_query( '/contract_addresses WHERE email = /' );
+
+		$this->expectException( RuntimeException::class );
+		Contracts::list_for_address_email( self::EMAIL, 20, 0, array( 'extension_slug' => self::EXTENSION_SLUG ) );
+	}
+
+	/**
+	 * Create a released contract with the given address emails.
+	 *
+	 * @param array<string, string> $emails         Address type => email.
+	 * @param string                $extension_slug Owning extension.
+	 */
+	private function seed( array $emails, string $extension_slug = self::EXTENSION_SLUG ): int {
+		$addresses = array();
+		foreach ( $emails as $type => $email ) {
+			$addresses[ $type ] = array(
+				'first_name' => 'Ada',
+				'email'      => $email,
+			);
+		}
+
+		return (int) $this->create_released(
+			array(
+				'extension_slug' => $extension_slug,
+				'addresses'      => $addresses,
+			)
+		)->get_id();
+	}
+
+	/**
+	 * The ids of contract views, in order.
+	 *
+	 * @param array<int, ContractView> $views Views.
+	 * @return array<int, int>
+	 */
+	private function ids( array $views ): array {
+		return array_map(
+			static function ( ContractView $view ): int {
+				return $view->get_id();
+			},
+			$views
+		);
+	}
+}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractHistoryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractHistoryTest.php
index c4e092c5f3f..c71a112a908 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractHistoryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ContractHistoryTest.php
@@ -300,6 +300,116 @@ class ContractHistoryTest extends EngineIntegrationTestCase {
 		$this->assertSame( array(), Contracts::get_history( $this->id, array( 'per_page' => 5 ) ) );
 	}

+	/**
+	 * @testdox delete_history() deletes every entry of the contract under the caller's lock and returns the count.
+	 */
+	public function test_delete_history_deletes_under_the_lock(): void {
+		$other = $this->create_released( array( 'extension_slug' => self::EXTENSION_SLUG ) )->get_id();
+		$this->add_entries( $this->id, array( 'a', 'b' ) );
+		$this->add_entries( $other, array( 'c' ) );
+		$lock = $this->take_lock( $this->id, 'erase' );
+
+		$this->assertSame( 2, Contracts::delete_history( $this->id, array( 'extension_slug' => self::EXTENSION_SLUG ), $lock ) );
+		$this->assertSame( array(), Contracts::get_history( $this->id ) );
+		$this->assertSame( array( 'c' ), $this->types( Contracts::get_history( $other ) ) );
+		$this->assertSame( 0, Contracts::delete_history( $this->id, array( 'extension_slug' => self::EXTENSION_SLUG ), $lock ), 'A second delete finds nothing.' );
+		$this->assertSame( 'erase', $this->get_lock_holder( $this->id )['operation'], 'The caller keeps its lock.' );
+	}
+
+	/**
+	 * @testdox delete_history() refuses a lock for another contract or for another extension and deletes nothing.
+	 */
+	public function test_delete_history_refuses_a_lock_for_another_contract_or_extension(): void {
+		$other   = $this->create_released( array( 'extension_slug' => self::EXTENSION_SLUG ) )->get_id();
+		$foreign = $this->create_released( array( 'extension_slug' => 'another-extension' ) )->get_id();
+		$this->add_entries( $this->id, array( 'a' ) );
+		$this->add_entries( $foreign, array( 'b' ), 'another-extension' );
+		$args = array( 'extension_slug' => self::EXTENSION_SLUG );
+
+		try {
+			Contracts::delete_history( $this->id, $args, $this->take_lock( $other, 'erase' ) );
+			$this->fail( 'Expected a lock for another contract to be refused.' );
+		} catch ( InvalidArgumentException $e ) {
+			$this->assertStringContainsString( "not contract {$this->id}", $e->getMessage() );
+		}
+
+		try {
+			Contracts::delete_history( $foreign, $args, $this->take_lock( $foreign, 'erase' ) );
+			$this->fail( 'Expected a lock of another extension to be refused.' );
+		} catch ( InvalidArgumentException $e ) {
+			$this->assertStringContainsString( 'another extension', $e->getMessage() );
+		}
+
+		$this->assertCount( 1, Contracts::get_history( $this->id ) );
+		$this->assertCount( 1, Contracts::get_history( $foreign ) );
+	}
+
+	/**
+	 * @testdox delete_history() reports a missing, ill-typed or malformed extension_slug and deletes nothing.
+	 * @dataProvider provide_invalid_delete_owners
+	 *
+	 * @param array<string, mixed> $args     Arguments.
+	 * @param array<int, mixed>    $expected Expected error.
+	 */
+	public function test_delete_history_reports_an_invalid_owner( array $args, array $expected ): void {
+		$this->add_entries( $this->id, array( 'a' ) );
+		$lock = $this->take_lock( $this->id, 'erase' );
+
+		$this->assert_validation_errors(
+			function () use ( $args, $lock ): void {
+				Contracts::delete_history( $this->id, $args, $lock );
+			},
+			array( $expected )
+		);
+
+		$this->assertCount( 1, Contracts::get_history( $this->id ) );
+	}
+
+	/**
+	 * @return array<string, array{0: array<string, mixed>, 1: array<int, mixed>}>
+	 */
+	public function provide_invalid_delete_owners(): array {
+		return array(
+			'missing'   => array( array(), array( ValidationErrorCode::REQUIRED, 'extension_slug' ) ),
+			'not text'  => array( array( 'extension_slug' => 5 ), array( ValidationErrorCode::INVALID_TYPE, 'extension_slug', array( 'type' => 'string' ) ) ),
+			'malformed' => array( array( 'extension_slug' => 'Acme Subs' ), array( ValidationErrorCode::INVALID_PATTERN, 'extension_slug', array( 'pattern' => ArgumentValidator::SLUG_PATTERN ) ) ),
+		);
+	}
+
+	/**
+	 * @testdox delete_history() ignores unknown keys with a notice.
+	 */
+	public function test_delete_history_ignores_unknown_keys(): void {
+		$this->setExpectedIncorrectUsage( Contracts::class . '::delete_history' );
+		$this->add_entries( $this->id, array( 'a', 'b' ) );
+		$args = array(
+			'extension_slug' => self::EXTENSION_SLUG,
+			'type'           => 'a',
+		);
+
+		$this->assertSame( 2, Contracts::delete_history( $this->id, $args, $this->take_lock( $this->id, 'erase' ) ), 'The unknown type filter is ignored.' );
+	}
+
+	/**
+	 * Add entries of the given types to a contract, without a lock.
+	 *
+	 * @param int                $contract_id    Contract id.
+	 * @param array<int, string> $types          Entry types, oldest first.
+	 * @param string             $extension_slug The contract's owner.
+	 */
+	private function add_entries( int $contract_id, array $types, string $extension_slug = self::EXTENSION_SLUG ): void {
+		foreach ( $types as $type ) {
+			$view = Contracts::add_history_entry(
+				$contract_id,
+				array(
+					'extension_slug' => $extension_slug,
+					'type'           => $type,
+				)
+			);
+			$this->assertNotNull( $view );
+		}
+	}
+
 	/**
 	 * The types of entry views, in order.
 	 *
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php
index d63cea26967..d71115be19a 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/OwnerSlugValidationTest.php
@@ -41,6 +41,11 @@ class OwnerSlugValidationTest extends EngineIntegrationTestCase {
 	 */
 	private const CUSTOMER_ID = 41;

+	/**
+	 * Address email looked up by the address email read.
+	 */
+	private const EMAIL = 'ada@example.com';
+
 	/**
 	 * Id of a contract of {@see self::OWNER}.
 	 *
@@ -135,6 +140,26 @@ class OwnerSlugValidationTest extends EngineIntegrationTestCase {
 		if ( 'Plans::delete_meta' === $entry ) {
 			Plans::add_meta( $this->plan_id, self::OWNER, 'note', 'x' );
 		}
+		if ( 'Contracts::list_for_address_email' === $entry ) {
+			Contracts::update(
+				$this->contract_id,
+				array(
+					'extension_slug' => self::OWNER,
+					'addresses'      => array( 'billing' => array( 'email' => self::EMAIL ) ),
+				),
+				$this->lock
+			);
+		}
+		if ( 'Contracts::delete_history' === $entry ) {
+			Contracts::add_history_entry(
+				$this->contract_id,
+				array(
+					'extension_slug' => self::OWNER,
+					'type'           => 'note',
+				),
+				$this->lock
+			);
+		}

 		$result = $this->call( $entry, self::OWNER );

@@ -165,7 +190,11 @@ class OwnerSlugValidationTest extends EngineIntegrationTestCase {
 				$this->assertInstanceOf( HistoryEntryView::class, $result );
 				$this->assertSame( $this->contract_id, $result->get_contract_id() );
 				return;
+			case 'Contracts::delete_history':
+				$this->assertSame( 1, $result );
+				return;
 			case 'Contracts::list_for_customer':
+			case 'Contracts::list_for_address_email':
 				$this->assertSame( array( $this->contract_id ), self::get_ids( $result ) );
 				return;
 			case 'Plans::create':
@@ -203,7 +232,9 @@ class OwnerSlugValidationTest extends EngineIntegrationTestCase {
 			'Contracts::update_meta',
 			'Contracts::delete_meta',
 			'Contracts::add_history_entry',
+			'Contracts::delete_history',
 			'Contracts::list_for_customer',
+			'Contracts::list_for_address_email',
 			'Plans::create',
 			'Plans::update',
 			'Plans::add_meta',
@@ -301,8 +332,12 @@ class OwnerSlugValidationTest extends EngineIntegrationTestCase {
 					),
 					$this->lock
 				);
+			case 'Contracts::delete_history':
+				return Contracts::delete_history( $this->contract_id, array( 'extension_slug' => $slug ), $this->lock );
 			case 'Contracts::list_for_customer':
 				return Contracts::list_for_customer( self::CUSTOMER_ID, 20, 0, array( 'extension_slug' => $slug ) );
+			case 'Contracts::list_for_address_email':
+				return Contracts::list_for_address_email( self::EMAIL, 20, 0, array( 'extension_slug' => $slug ) );
 			case 'Plans::create':
 				return Plans::create(
 					array(
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php
index e7b70ebf0d5..78a53b42dbe 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Api/ValidationExceptionTest.php
@@ -29,6 +29,7 @@ class ValidationExceptionTest extends EngineIntegrationTestCase {
 		ValidationErrorCode::INVALID_TYPE    => array( 'type' => 'string' ),
 		ValidationErrorCode::OUT_OF_BOUNDS   => array( 'min' => 1 ),
 		ValidationErrorCode::NOT_IN_ENUM     => array( 'allowed' => array( 'day', 'week' ) ),
+		ValidationErrorCode::TOO_LONG        => array( 'max' => 320 ),
 		ValidationErrorCode::INVALID_VALUE   => array(),
 		ValidationErrorCode::INVALID_PATTERN => array( 'pattern' => '^[a-z]+$' ),
 		ValidationErrorCode::NOT_REGISTERED  => array( 'value' => 'seasonal' ),
@@ -75,6 +76,8 @@ class ValidationExceptionTest extends EngineIntegrationTestCase {
 		$this->assertSame( 'This field is required.', self::message_for( ValidationErrorCode::REQUIRED, 'name' ) );
 		$this->assertSame( 'Must be of type integer.', self::message_for( ValidationErrorCode::INVALID_TYPE, 'interval', array( 'type' => 'integer' ) ) );
 		$this->assertSame( 'This value is not valid.', self::message_for( ValidationErrorCode::INVALID_VALUE, 'currency' ) );
+		$this->assertSame( 'Must be at most 320 characters.', self::message_for( ValidationErrorCode::TOO_LONG, 'email', array( 'max' => 320 ) ) );
+		$this->assertSame( 'Must be at most 1 character.', self::message_for( ValidationErrorCode::TOO_LONG, 'code', array( 'max' => 1 ) ) );
 		$this->assertSame( '"seasonal" is not registered.', self::message_for( ValidationErrorCode::NOT_REGISTERED, 'status', array( 'value' => 'seasonal' ) ) );
 	}

@@ -131,6 +134,7 @@ class ValidationExceptionTest extends EngineIntegrationTestCase {
 	public function test_an_unknown_code_gets_the_generic_message(): void {
 		$this->assertSame( 'This value is not valid.', self::message_for( 'acme_unknown', 'name' ) );
 		$this->assertSame( 'This value is not valid.', self::message_for( ValidationErrorCode::OUT_OF_BOUNDS, 'limit' ) );
+		$this->assertSame( 'This value is not valid.', self::message_for( ValidationErrorCode::TOO_LONG, 'email' ) );
 		$this->assertSame( 'This value is not valid.', self::message_for( ValidationErrorCode::INVALID_TYPE, 'name', array( 'type' => 3 ) ) );
 		$this->assertSame( 'This value is not valid.', self::message_for( ValidationErrorCode::NOT_IN_ENUM, 'period', array( 'allowed' => 'day' ) ) );
 	}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractAddressEmailReadTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractAddressEmailReadTest.php
new file mode 100644
index 00000000000..f3604ff0925
--- /dev/null
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractAddressEmailReadTest.php
@@ -0,0 +1,198 @@
+<?php
+/**
+ * Integration tests for the owner-scoped address email read on ContractRepository.
+ *
+ * @package Automattic\WooCommerce\SubscriptionsEngine
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\SubscriptionsEngine\Tests\Integration\Integration\Storage;
+
+use EngineIntegrationTestCase;
+use RuntimeException;
+use Automattic\WooCommerce\SubscriptionsEngine\Core\Entity\Contract;
+use Automattic\WooCommerce\SubscriptionsEngine\Integration\Storage\ContractRepository;
+
+/**
+ * @covers \Automattic\WooCommerce\SubscriptionsEngine\Integration\Storage\ContractRepository
+ */
+class ContractAddressEmailReadTest extends EngineIntegrationTestCase {
+
+	/**
+	 * Owning extension of the fixture contracts.
+	 */
+	private const OWNER = 'acme-subs';
+
+	/**
+	 * The email the reads look up.
+	 */
+	private const EMAIL = 'ada@example.com';
+
+	/**
+	 * The System Under Test.
+	 *
+	 * @var ContractRepository
+	 */
+	private $sut;
+
+	public function setUp(): void {
+		parent::setUp();
+		$this->sut = new ContractRepository();
+	}
+
+	/**
+	 * @testdox A billing or a shipping address email matches; a contract with the email on both is returned once, newest first.
+	 */
+	public function test_matches_either_address_once_newest_first(): void {
+		$billing  = $this->seed( array( 'billing' => self::EMAIL ) );
+		$shipping = $this->seed( array( 'shipping' => self::EMAIL ) );
+		$both     = $this->seed(
+			array(
+				'billing'  => self::EMAIL,
+				'shipping' => self::EMAIL,
+			)
+		);
+		$this->seed( array( 'billing' => 'grace@example.com' ) );
+		$this->seed( array() );
+
+		$this->assertSame( array( $both, $shipping, $billing ), $this->ids( $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 20, 0 ) ) );
+	}
+
+	/**
+	 * @testdox Only the named extension's contracts are returned, matched on the exact owner.
+	 */
+	public function test_is_owner_scoped(): void {
+		$mine = $this->seed( array( 'billing' => self::EMAIL ) );
+		$this->seed( array( 'billing' => self::EMAIL ), 'another-extension' );
+
+		$this->assertSame( array( $mine ), $this->ids( $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 20, 0 ) ) );
+		$this->assertSame( array(), $this->sut->find_by_address_email( self::EMAIL, 'ACME-SUBS', 20, 0 ), 'The owner match is case-sensitive.' );
+	}
+
+	/**
+	 * @testdox The email matches case-insensitively under the default collation, and a different email matches nothing.
+	 */
+	public function test_matches_by_the_column_collation(): void {
+		$id = $this->seed( array( 'billing' => 'Ada@Example.com' ) );
+
+		$this->assertSame( array( $id ), $this->ids( $this->sut->find_by_address_email( 'ada@example.COM', self::OWNER, 20, 0 ) ) );
+		$this->assertSame( array(), $this->sut->find_by_address_email( 'ada@example.org', self::OWNER, 20, 0 ) );
+	}
+
+	/**
+	 * @testdox The email is an exact match: a prefix, or a value with `%` or `_`, matches nothing.
+	 */
+	public function test_is_an_exact_match(): void {
+		$id = $this->seed( array( 'billing' => 'ada_b@example.com' ) );
+
+		$this->assertSame( array( $id ), $this->ids( $this->sut->find_by_address_email( 'ada_b@example.com', self::OWNER, 20, 0 ) ) );
+		$this->assertSame( array(), $this->sut->find_by_address_email( 'ada_b@example.co', self::OWNER, 20, 0 ), 'A prefix does not match.' );
+		$this->assertSame( array(), $this->sut->find_by_address_email( 'ada%@example.com', self::OWNER, 20, 0 ), '% is not a wildcard.' );
+		$this->assertSame( array(), $this->sut->find_by_address_email( 'ada_c@example.com', self::OWNER, 20, 0 ), 'A different character does not match.' );
+		$this->assertSame( array(), $this->sut->find_by_address_email( 'ad__b@example.com', self::OWNER, 20, 0 ), '_ is not a wildcard.' );
+	}
+
+	/**
+	 * @testdox An email longer than the 191-character index prefix matches only its full value, not another sharing the prefix.
+	 */
+	public function test_a_long_email_matches_its_full_value_past_the_index_prefix(): void {
+		$local = str_repeat( 'a', 200 );
+		$id    = $this->seed( array( 'billing' => $local . '@example.com' ) );
+		$this->seed( array( 'billing' => $local . '@example.org' ) );
+
+		$this->assertSame( array( $id ), $this->ids( $this->sut->find_by_address_email( $local . '@example.com', self::OWNER, 20, 0 ) ) );
+		$this->assertSame( array(), $this->sut->find_by_address_email( $local . '@example.net', self::OWNER, 20, 0 ), 'Sharing the first 191 characters is not a match.' );
+	}
+
+	/**
+	 * @testdox Pages with limit and offset over the de-duplicated set.
+	 */
+	public function test_pages_with_limit_and_offset(): void {
+		$ids = array();
+		for ( $i = 0; $i < 5; $i++ ) {
+			$ids[] = $this->seed(
+				array(
+					'billing'  => self::EMAIL,
+					'shipping' => self::EMAIL,
+				)
+			);
+		}
+		$newest_first = array_reverse( $ids );
+
+		$this->assertSame( array_slice( $newest_first, 0, 2 ), $this->ids( $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 2, 0 ) ) );
+		$this->assertSame( array_slice( $newest_first, 2, 2 ), $this->ids( $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 2, 2 ) ) );
+		$this->assertSame( array_slice( $newest_first, 4, 1 ), $this->ids( $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 2, 4 ) ) );
+		$this->assertSame( array(), $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 2, 6 ) );
+	}
+
+	/**
+	 * @testdox Each contract is a row-only read: no items or addresses loaded.
+	 */
+	public function test_returns_row_only_contracts(): void {
+		$this->seed( array( 'billing' => self::EMAIL ) );
+
+		$contracts = $this->sut->find_by_address_email( self::EMAIL, self::OWNER, 20, 0 );
+
+		$this->assertCount( 1, $contracts );
+		$this->assertSame( array(), $contracts[0]->get_addresses() );
+		$this->assertSame( self::OWNER, $contracts[0]->get_extension_slug() );
+	}
+
+	/**
+	 * @testdox A failed read throws RuntimeException without the email in its message.
+	 */
+	public function test_a_failed_read_throws_without_the_email(): void {
+		$this->seed( array( 'billing' => self::EMAIL ) );
+		$this->fail_next_query( '/contract_addresses WHERE email = /' );
+
+		try {
+			$this->sut->find_by_address_email( self::EMAIL, self::OWNER, 20, 0 );
+			$this->fail( 'Expected the failed read to throw.' );
+		} catch ( RuntimeException $e ) {
+			$this->assertStringContainsString( 'Failed to read the contracts of extension', $e->getMessage() );
+			$this->assertStringContainsString( 'by address email', $e->getMessage() );
+			$this->assertStringNotContainsString( self::EMAIL, $e->getMessage() );
+		}
+	}
+
+	/**
+	 * Insert a released contract with the given address emails.
+	 *
+	 * @param array<string, string> $emails         Address type => email.
+	 * @param string                $extension_slug Owning extension.
+	 */
+	private function seed( array $emails, string $extension_slug = self::OWNER ): int {
+		$addresses = array();
+		foreach ( $emails as $type => $email ) {
+			$addresses[ $type ] = array(
+				'first_name' => 'Ada',
+				'email'      => $email,
+			);
+		}
+
+		return $this->insert_released(
+			Contract::create(
+				array(
+					'extension_slug' => $extension_slug,
+					'addresses'      => $addresses,
+				)
+			)
+		);
+	}
+
+	/**
+	 * Map a result set to its contract ids.
+	 *
+	 * @param array<int, Contract> $contracts Contracts.
+	 * @return array<int, int>
+	 */
+	private function ids( array $contracts ): array {
+		return array_map(
+			static function ( Contract $contract ): int {
+				return (int) $contract->get_id();
+			},
+			$contracts
+		);
+	}
+}
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractHistoryTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractHistoryTest.php
index 354eb88f7f8..4d5142cc05b 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractHistoryTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/ContractHistoryTest.php
@@ -395,6 +395,231 @@ class ContractHistoryTest extends EngineIntegrationTestCase {
 		$this->assertCount( 1, $this->sut->find_history( $other ) );
 	}

+	/**
+	 * @testdox delete_history() deletes every entry of the contract in one statement and returns the count; other contracts keep theirs.
+	 */
+	public function test_delete_history_deletes_the_contracts_entries(): void {
+		$other = $this->insert_released( Contract::create( array( 'extension_slug' => self::OWNER ) ) );
+		foreach ( array( 'a', 'b', 'c' ) as $type ) {
+			$this->sut->add_history_entry( $this->entry( array( 'type' => $type ) ), self::OWNER );
+		}
+		$this->sut->add_history_entry( $this->entry( array( 'contract_id' => $other ) ), self::OWNER );
+		$lock = $this->take_lock( $this->id, 'erase' );
+
+		$deleted    = null;
+		$statements = $this->statements_during(
+			function () use ( &$deleted, $lock ): void {
+				$deleted = $this->sut->delete_history( $this->id, $lock );
+			}
+		);
+
+		$this->assertSame( 3, $deleted );
+		$this->assertSame( array(), $this->sut->find_history( $this->id ) );
+		$this->assertCount( 1, $this->sut->find_history( $other ) );
+		$this->assertCount( 1, $statements, 'A trusted lock costs no query, so the delete is the only statement.' );
+		$this->assertMatchesRegularExpression( '/^DELETE h FROM \S*contract_history h JOIN \S*contracts c ON c\.id = h\.contract_id WHERE h\.contract_id = ' . $this->id . ' AND c\.lock_token = /', $statements[0] );
+	}
+
+	/**
+	 * @testdox delete_history() returns 0 for a contract with no entries, after one read that confirms the lock is held.
+	 */
+	public function test_delete_history_of_an_empty_history_returns_zero(): void {
+		$lock = $this->take_lock( $this->id, 'erase' );
+
+		$deleted    = null;
+		$statements = $this->statements_during(
+			function () use ( &$deleted, $lock ): void {
+				$deleted = $this->sut->delete_history( $this->id, $lock );
+			}
+		);
+
+		$this->assertSame( 0, $deleted );
+		$this->assertCount( 2, $statements, 'The delete, then one lock check read; the fence runs no query because the lock was just taken.' );
+		$this->assertMatchesRegularExpression( '/^SELECT \( lock_token = .* \) AS held, .* AS live, lock_operation FROM \S*contracts WHERE id = ' . $this->id . '$/', $statements[1] );
+	}
+
+	/**
+	 * @testdox delete_history() refuses a lock for another contract and deletes nothing.
+	 */
+	public function test_delete_history_refuses_a_lock_for_another_contract(): void {
+		$other = $this->insert_released( Contract::create( array( 'extension_slug' => self::OWNER ) ) );
+		$this->sut->add_history_entry( $this->entry(), self::OWNER );
+
+		try {
+			$this->sut->delete_history( $this->id, $this->take_lock( $other, 'erase' ) );
+			$this->fail( 'Expected the lock for another contract to be refused.' );
+		} catch ( InvalidArgumentException $e ) {
+			$this->assertStringContainsString( "not contract {$this->id}", $e->getMessage() );
+		}
+
+		$this->assertCount( 1, $this->sut->find_history( $this->id ) );
+	}
+
+	/**
+	 * @testdox delete_history() with a lost lock throws ContractLockedException and deletes nothing.
+	 */
+	public function test_delete_history_with_a_lost_lock_deletes_nothing(): void {
+		$this->sut->add_history_entry( $this->entry(), self::OWNER );
+		$this->pin_db_clock( '2035-01-01 00:00:00' );
+		$old = $this->sut->acquire_lock( $this->id, self::OWNER, 'erase' );
+		$this->assertInstanceOf( ContractLock::class, $old );
+
+		$this->pin_db_clock( '2035-01-01 00:10:00' );
+		$this->assertInstanceOf( ContractLock::class, $this->sut->acquire_lock( $this->id, self::OWNER, 'cancel' ) );
+		$this->age_lock_trust( $old );
+
+		try {
+			$this->sut->delete_history( $this->id, $old );
+			$this->fail( 'Expected the lost lock to be refused.' );
+		} catch ( ContractLockedException $e ) {
+			$this->assertSame( 'cancel', $e->get_operation() );
+		}
+
+		$this->assertCount( 1, $this->sut->find_history( $this->id ) );
+	}
+
+	/**
+	 * @testdox delete_history() with a lock lost after the fence deletes nothing, throws ContractLockedException, and the new holder's entries survive.
+	 */
+	public function test_delete_history_with_a_lock_lost_after_the_fence_deletes_nothing(): void {
+		$this->sut->add_history_entry( $this->entry( array( 'type' => 'before' ) ), self::OWNER );
+		$this->pin_db_clock( '2035-01-01 00:00:00' );
+		$old = $this->sut->acquire_lock( $this->id, self::OWNER, 'erase' );
+		$this->assertInstanceOf( ContractLock::class, $old );
+
+		// The old lock expires and is taken over; the new holder appends an entry.
+		$this->pin_db_clock( '2035-01-01 00:10:00' );
+		$new = $this->sut->acquire_lock( $this->id, self::OWNER, 'cancel' );
+		$this->assertInstanceOf( ContractLock::class, $new );
+		$this->sut->add_history_entry( $this->entry( array( 'type' => 'cancelled' ) ), self::OWNER, $new );
+
+		// The old lock is still inside its trusted window, so the fence lets the delete run: the
+		// statement itself must refuse it.
+		try {
+			$this->sut->delete_history( $this->id, $old );
+			$this->fail( 'Expected the lost lock to be refused.' );
+		} catch ( ContractLockedException $e ) {
+			$this->assertSame( 'cancel', $e->get_operation() );
+		}
+
+		$this->assertSame( array( 'cancelled', 'before' ), $this->types( $this->sut->find_history( $this->id ) ) );
+		$this->assertSame( 2, $this->sut->delete_history( $this->id, $new ), 'The holder of the live lock deletes.' );
+	}
+
+	/**
+	 * @testdox delete_history() with a lock that expired and was not taken over throws ContractLockedException without an operation and deletes nothing.
+	 */
+	public function test_delete_history_with_an_expired_lock_deletes_nothing(): void {
+		$this->sut->add_history_entry( $this->entry(), self::OWNER );
+		$this->pin_db_clock( '2035-01-01 00:00:00' );
+		$old = $this->sut->acquire_lock( $this->id, self::OWNER, 'erase' );
+		$this->assertInstanceOf( ContractLock::class, $old );
+
+		// The lock expires on the database clock; nobody takes it. It is still inside its trusted
+		// window, so the fence lets the delete run.
+		$this->pin_db_clock( '2035-01-01 00:10:00' );
+		try {
+			$this->sut->delete_history( $this->id, $old );
+			$this->fail( 'Expected the expired lock to be refused.' );
+		} catch ( ContractLockedException $e ) {
+			$this->assertNull( $e->get_operation() );
+		}
+
+		$this->assertCount( 1, $this->sut->find_history( $this->id ) );
+	}
+
+	/**
+	 * @testdox delete_history() of an empty history with a lock lost after the fence throws ContractLockedException instead of returning 0.
+	 */
+	public function test_delete_history_of_an_empty_history_with_a_lock_lost_after_the_fence_throws(): void {
+		$this->pin_db_clock( '2035-01-01 00:00:00' );
+		$old = $this->sut->acquire_lock( $this->id, self::OWNER, 'erase' );
+		$this->assertInstanceOf( ContractLock::class, $old );
+		$this->pin_db_clock( '2035-01-01 00:10:00' );
+		$this->assertInstanceOf( ContractLock::class, $this->sut->acquire_lock( $this->id, self::OWNER, 'cancel' ) );
+
+		try {
+			$this->sut->delete_history( $this->id, $old );
+			$this->fail( 'Expected the lost lock to be refused.' );
+		} catch ( ContractLockedException $e ) {
+			$this->assertSame( 'cancel', $e->get_operation() );
+		}
+	}
+
+	/**
+	 * @testdox delete_history() throws RuntimeException on a failed delete, opens no transaction and deletes nothing.
+	 */
+	public function test_delete_history_throws_on_a_failed_delete(): void {
+		$this->sut->add_history_entry( $this->entry(), self::OWNER );
+		$lock = $this->take_lock( $this->id, 'erase' );
+
+		$this->fail_next_query( '/^DELETE h FROM \S*contract_history/' );
+		$statements = $this->statements_during(
+			function () use ( $lock ): void {
+				try {
+					$this->sut->delete_history( $this->id, $lock );
+					$this->fail( 'Expected the failed delete to throw.' );
+				} catch ( RuntimeException $e ) {
+					$this->assertStringContainsString( "Failed to delete the history of contract {$this->id}", $e->getMessage() );
+				}
+			}
+		);
+
+		foreach ( $statements as $statement ) {
+			$this->assertSame( 0, preg_match( '/^\s*(START TRANSACTION|BEGIN|COMMIT|ROLLBACK)\b/i', $statement ), 'The delete opens no transaction.' );
+		}
+		$this->assertCount( 1, $this->sut->find_history( $this->id ) );
+	}
+
+	/**
+	 * @testdox delete_history() of an empty history throws RuntimeException when the read of its lock check fails, instead of returning 0.
+	 */
+	public function test_delete_history_propagates_a_failed_lock_check(): void {
+		$lock = $this->take_lock( $this->id, 'erase' );
+
+		$this->fail_next_query( '/AS held, .* AS live, lock_operation FROM \S*contracts/' );
+		try {
+			$this->sut->delete_history( $this->id, $lock );
+			$this->fail( 'Expected the failed lock check to throw.' );
+		} catch ( RuntimeException $e ) {
+			$this->assertNotInstanceOf( ContractLockedException::class, $e );
+			$this->assertStringContainsString( "lock on contract {$this->id}", $e->getMessage() );
+		}
+	}
+
+	/**
+	 * @testdox delete_history() with a still-trusted lock on a contract removed after the fence throws ContractLockedException, instead of returning 0.
+	 */
+	public function test_delete_history_of_a_removed_contract_throws(): void {
+		global $wpdb;
+
+		$lock = $this->take_lock( $this->id, 'erase' );
+		$wpdb->delete( SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACTS ), array( 'id' => $this->id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
+
+		try {
+			$this->sut->delete_history( $this->id, $lock );
+			$this->fail( 'Expected the removed contract to read as a lost lock.' );
+		} catch ( ContractLockedException $e ) {
+			$this->assertNull( $e->get_operation() );
+		}
+	}
+
+	/**
+	 * @testdox After delete_history(), new entries are written and paged, and a freed creation key can be written again.
+	 */
+	public function test_a_deleted_history_takes_new_entries_and_frees_creation_keys(): void {
+		$this->sut->add_history_entry( $this->entry( array( 'creation_key' => 'renewal-paid-7' ) ), self::OWNER );
+		$lock = $this->take_lock( $this->id, 'erase' );
+		$this->assertSame( 1, $this->sut->delete_history( $this->id, $lock ) );
+
+		$this->assertInstanceOf( HistoryEntry::class, $this->sut->add_history_entry( $this->entry( array( 'type' => 'personal-data-removed' ) ), self::OWNER, $lock ) );
+		$this->assertInstanceOf( HistoryEntry::class, $this->sut->add_history_entry( $this->entry( array( 'creation_key' => 'renewal-paid-7' ) ), self::OWNER ) );
+
+		$this->assertSame( array( 'held', 'personal-data-removed' ), $this->types( $this->sut->find_history( $this->id ) ) );
+		$this->assertSame( array( 'held' ), $this->types( $this->sut->find_history( $this->id, 1, 0 ) ) );
+		$this->assertSame( array( 'personal-data-removed' ), $this->types( $this->sut->find_history( $this->id, 1, 1 ) ) );
+	}
+
 	/**
 	 * A new entry on the fixture contract.
 	 *
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php
index 7cdb3b29589..d095f1f7e32 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/integration/Integration/Storage/SchemaInstallerTest.php
@@ -292,10 +292,10 @@ class SchemaInstallerTest extends EngineIntegrationTestCase {
 	}

 	/**
-	 * @testdox The schema version is 2.10.0 (contract history table).
+	 * @testdox The schema version is 2.11.0 (contract address email index).
 	 */
-	public function test_schema_version_is_2_10_0(): void {
-		$this->assertSame( '2.10.0', SchemaInstaller::get_version() );
+	public function test_schema_version_is_2_11_0(): void {
+		$this->assertSame( '2.11.0', SchemaInstaller::get_version() );
 	}

 	/**
@@ -729,6 +729,24 @@ class SchemaInstallerTest extends EngineIntegrationTestCase {
 		$this->assertTrue( $this->index_is_unique( $table, 'creation' ) );
 	}

+	/**
+	 * @testdox The contract addresses table keys the address email read on a 191-character email prefix.
+	 */
+	public function test_contract_addresses_email_index(): void {
+		global $wpdb;
+
+		$table = SchemaInstaller::get_table_name( SchemaInstaller::TABLE_CONTRACT_ADDRESSES );
+
+		$this->assertEqualsCanonicalizing( array( 'PRIMARY', 'email' ), $this->index_names( $table ) );
+		$this->assertSame( array( 'email' ), $this->index_columns( $table, 'email' ) );
+		$this->assertFalse( $this->index_is_unique( $table, 'email' ) );
+
+		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+		$row = $wpdb->get_row( "SHOW INDEX FROM {$table} WHERE Key_name = 'email'", ARRAY_A );
+		$this->assertIsArray( $row );
+		$this->assertSame( 191, Coercion::coerce_int( $row['Sub_part'] ?? null ), 'The index covers a 191-character prefix.' );
+	}
+
 	/**
 	 * Whether `$table` has a column named `$column`.
 	 *
diff --git a/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php b/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php
index 85cad4a4fd3..2aa6acfdbed 100644
--- a/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php
+++ b/packages/php/woocommerce-subscriptions-engine/tests/unit/Core/Support/ArgumentValidatorTest.php
@@ -50,6 +50,9 @@ class ArgumentValidatorTest extends TestCase {
 			'extension slug chars'  => array( 'validate_extension_slug', array( 'extension_slug', 'acme_2-x' ), 'acme_2-x' ),
 			'extension slug 64'     => array( 'validate_extension_slug', array( 'extension_slug', str_repeat( 'a', 64 ) ), str_repeat( 'a', 64 ) ),
 			'slug'                  => array( 'validate_slug', array( 'type', 'renewal-paid_2' ), 'renewal-paid_2' ),
+			'bounded string'        => array( 'validate_bounded_string', array( 'email', 'ada@example.com', 320 ), 'ada@example.com' ),
+			'bounded string at max' => array( 'validate_bounded_string', array( 'email', str_repeat( 'é', 320 ), 320 ), str_repeat( 'é', 320 ) ),
+			'bounded string as is'  => array( 'validate_bounded_string', array( 'email', " ada@example.com\t", 320 ), " ada@example.com\t" ),
 			'creation key'          => array( 'validate_creation_key', array( 'renewal-paid-12' ), 'renewal-paid-12' ),
 			'creation key null'     => array( 'validate_creation_key', array( null ), null ),
 			'creation key 100'      => array( 'validate_creation_key', array( str_repeat( 'é', 100 ) ), str_repeat( 'é', 100 ) ),
@@ -160,6 +163,9 @@ class ArgumentValidatorTest extends TestCase {
 			'type slug uppercase'   => array( 'validate_slug', array( 'type', 'Held' ), ValidationErrorCode::INVALID_PATTERN, 'type', $slug_pattern ),
 			'type slug null'        => array( 'validate_slug', array( 'type', null ), ValidationErrorCode::REQUIRED, 'type', array() ),
 			'type slug not string'  => array( 'validate_slug', array( 'type', 5 ), ValidationErrorCode::INVALID_TYPE, 'type', $type_string ),
+			'bounded string empty'  => array( 'validate_bounded_string', array( 'email', '', 320 ), ValidationErrorCode::REQUIRED, 'email', array() ),
+			'bounded string int'    => array( 'validate_bounded_string', array( 'email', 5, 320 ), ValidationErrorCode::INVALID_TYPE, 'email', $type_string ),
+			'bounded string long'   => array( 'validate_bounded_string', array( 'email', str_repeat( 'é', 321 ), 320 ), ValidationErrorCode::TOO_LONG, 'email', array( 'max' => 320 ) ),
 			'creation key int'      => array( 'validate_creation_key', array( 5 ), ValidationErrorCode::INVALID_TYPE, 'creation_key', $type_string ),
 			'creation key empty'    => array( 'validate_creation_key', array( '' ), ValidationErrorCode::INVALID_VALUE, 'creation_key', array() ),
 			'creation key 101'      => array( 'validate_creation_key', array( str_repeat( 'a', 101 ) ), ValidationErrorCode::INVALID_VALUE, 'creation_key', array() ),