Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,39 @@ The lock is released between two calls, so other workers can take their turn.

See [docs/decisions.md](./docs/decisions.md) for the reasoning.

## Exceptions during a catch-up

An exception that escapes a catch-up, for example a deadlock, rolls back the current run and is rethrown.
Positions and everything else that is part of the transaction stay at the last committed batch, so the catch-up can be repeated with the same engine instance.

> [!NOTE]
> A database error inside a subscriber is not an escaping exception: The subscription goes to `ERROR` and the run continues without it.

### Stores on MySQL and MariaDB

With the default isolation level (`REPEATABLE READ`), workers that wait for a subscription lock can deadlock with a worker that changes the status of a subscription.
`SubscriptionStore` implementations should use `READ COMMITTED` for their transactions on these databases, as [wwwision/subscription-engine-doctrine](https://packagist.org/packages/wwwision/subscription-engine-doctrine) does.

## Upgrading to 2.0

`EventStoreAdapter::read()` has a new parameter that implementations have to add, otherwise PHP fails with a fatal error:
Implementations of the following interfaces have to be adjusted, otherwise PHP fails with a fatal error.
Implementations with these changes are also compatible with 1.x.

`EventStoreAdapter::read()` has a new parameter:

```php
public function read(Position $startPosition, int|null $limit = null): iterable;
```

Implementations must return at most `$limit` events, and all events if it is `null`.
An implementation with the additional parameter is also compatible with 1.x.

`SubscriptionStore` has a new method:

```php
public function rollback(): void;
```

It discards all changes since the last `beginTransaction()`. Afterwards the store must be usable for a new transaction.

> [!NOTE]
> The signature of this method might still change until 2.0 is released.
Expand Down
28 changes: 24 additions & 4 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,30 @@ For concurrent subscriptions:

- They may revisit the one-lock-per-run model and the advice on per-subscription runs.

## `processingSubscriptions` is not restored after an escaped exception
## Escaping exceptions roll back the run (target: 2.0)

The early return for "only detached subscriptions" restores `processingSubscriptions`. A `try/finally` that also covers escaped exceptions was rejected.
### Context

`SubscriptionStore` had no rollback, so an exception that escaped a catch-up left its transaction open.
On MySQL and MariaDB this is easy to reach: Workers booting concurrently deadlock.
With DBAL, the `commit()` of later runs only decremented the nesting level. Workers that caught the exception and kept going reported processed events that were not persisted, and subscriptions ended in `ERROR`.

### Decisions

`SubscriptionStore` has no rollback, so an escaped exception leaves its transaction open. With DBAL, the `commit()` of any later run only decrements the nesting level and nothing is persisted. Today the following no-criteria run fails loudly with `RecursiveCatchUpException`. A `finally` would remove that signal and let a long-running worker lose work silently.
| # | Topic | Decision | Why |
|---|-------|----------|-----|
| 1 | Store contract | Breaking: `SubscriptionStore::rollback(): void` | Only the store can end its transaction |
| 2 | Escaping exception before the commit | Roll back and rethrow the original exception. A failed rollback is ignored | Repeating the run is safe with the same engine instance. The original exception says what went wrong, a failed rollback usually only means that the connection is gone |
| 3 | Escaping exception after the commit | No rollback | The batch is persisted. This covers listeners of `CatchUpFinished` |
| 4 | `processingSubscriptions` | Restored on every exit path with `finally` | This was rejected before, because it would have hidden the open transaction. With the rollback there is nothing left to hide |
| 5 | Isolation level | `DoctrineSubscriptionStore` uses `READ COMMITTED` for its transactions on MySQL and MariaDB. It only applies to the next transaction, and not if the connection is already in one | With `REPEATABLE READ`, `SELECT ... FOR UPDATE` takes next-key locks on the `status` index. Moving a row within that index then deadlocks with waiting workers |

### Known consequences

- Subscriber handlers that share the connection also run with `READ COMMITTED` in these transactions
- A transaction that was started outside of the store keeps its isolation level

### Open points

Handling this properly needs a rollback on `SubscriptionStore`, which is out of scope here.
- A database error inside a subscriber is handled like any other subscriber failure: The subscription goes to `ERROR` and the run continues. If the database has rolled back the transaction because of that error (deadlock on MySQL), the rest of the run is not part of the transaction that the handlers assume
- On PostgreSQL an SQL error aborts the transaction, so the following `update()` fails and escapes
6 changes: 6 additions & 0 deletions src/Store/SubscriptionStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,10 @@ public function update(Subscription $subscription): void;
public function beginTransaction(): void;

public function commit(): void;

/**
* Discard all changes since the last {@see self::beginTransaction()}
* The subscription engine calls this if an exception escapes a catch-up, afterwards the store must be usable for a new transaction
*/
public function rollback(): void;
}
154 changes: 87 additions & 67 deletions src/SubscriptionEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,87 +283,107 @@ private function catchUpSubscriptions(SubscriptionEngineCriteria $criteria, Subs
$errors = [];

$this->subscriptionStore->beginTransaction();

$subscriptionsToCatchup = $this->subscriptionStore->findByCriteriaForUpdate($subscriptionCriteria);
$processingSubscriptionsBackup = $this->processingSubscriptions;
$this->processingSubscriptions = $this->processingSubscriptions->merge($subscriptionsToCatchup->getIds());
foreach ($subscriptionsToCatchup as $subscription) {
if (!$this->subscribers->contain($subscription->id)) {
// mark detached subscriptions as we cannot handle them and exclude them from catchup
$this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::DETACHED));
$this->dispatchEngineEvent(new SubscriptionDetached($subscription));
$subscriptionsToCatchup = $subscriptionsToCatchup->without($subscription->id);
$committed = false;
try {
$subscriptionsToCatchup = $this->subscriptionStore->findByCriteriaForUpdate($subscriptionCriteria);
$this->processingSubscriptions = $this->processingSubscriptions->merge($subscriptionsToCatchup->getIds());
foreach ($subscriptionsToCatchup as $subscription) {
if (!$this->subscribers->contain($subscription->id)) {
// mark detached subscriptions as we cannot handle them and exclude them from catchup
$this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::DETACHED));
$this->dispatchEngineEvent(new SubscriptionDetached($subscription));
$subscriptionsToCatchup = $subscriptionsToCatchup->without($subscription->id);
}
}
}
$initialSubscriptionsToCatchup = $subscriptionsToCatchup;
$initialSubscriptionsToCatchup = $subscriptionsToCatchup;

if ($subscriptionsToCatchup->isEmpty()) {
$this->dispatchEngineEvent(new NoSubscriptionsFound($subscriptionCriteria));
$this->subscriptionStore->commit();
$this->processingSubscriptions = $processingSubscriptionsBackup;
return ProcessedResult::success(0);
}
if ($subscriptionsToCatchup->isEmpty()) {
$this->dispatchEngineEvent(new NoSubscriptionsFound($subscriptionCriteria));
$this->subscriptionStore->commit();
$committed = true;
return ProcessedResult::success(0);
}

$startPosition = $subscriptionsToCatchup->lowestPosition()?->next() ?? Position::none();
$this->dispatchEngineEvent(new CatchUpStarted($subscriptionsToCatchup, $startPosition));
$startPosition = $subscriptionsToCatchup->lowestPosition()?->next() ?? Position::none();
$this->dispatchEngineEvent(new CatchUpStarted($subscriptionsToCatchup, $startPosition));

/** @var array<string,Position> $highestPositionForSubscriber */
$highestPositionForSubscriber = [];
/** @var array<string,Position> $highestPositionForSubscriber */
$highestPositionForSubscriber = [];

$hasPendingEvents = false;
foreach ($this->eventStoreAdapter->read($startPosition, $limit !== null ? $limit + 1 : null) as $event) {
if ($numberOfProcessedEvents === $limit) {
$hasPendingEvents = true;
break;
$hasPendingEvents = false;
foreach ($this->eventStoreAdapter->read($startPosition, $limit !== null ? $limit + 1 : null) as $event) {
if ($numberOfProcessedEvents === $limit) {
$hasPendingEvents = true;
break;
}
$eventPosition = $this->eventStoreAdapter->eventPosition($event);
foreach ($subscriptionsToCatchup as $subscription) {
$subscriber = $this->subscribers->get($subscription->id);
if (!$eventPosition->isAheadOf($subscription->position)) {
$this->dispatchEngineEvent(new SubscriberSkippedEvent($subscription, $event, $eventPosition));
continue;
}
try {
($subscriber->handler)($event);
} catch (Throwable $e) {
// ERROR Case:
$errors[] = Error::create($subscription->id, $e->getMessage(), $errors === [] ? $e : null, $eventPosition);
$this->dispatchEngineEvent(new SubscriberFailedToHandleEvent($subscription, $event, $eventPosition, $e));

// for the leftover events we are not including this failed subscription for catchup
$subscriptionsToCatchup = $subscriptionsToCatchup->without($subscription->id);
// update the subscription error state on either its unchanged or new position (if some events worked)
// note that the possibly partially applied event will not be rolled back.
$this->subscriptionStore->update($subscription->withError(SubscriptionError::fromPreviousStatusAndException($subscription->status, $e))->with(position: $highestPositionForSubscriber[$subscription->id->value] ?? $subscription->position));
continue;
}
// HAPPY Case:
$this->dispatchEngineEvent(new SubscriberHandledEvent($subscription, $event, $eventPosition));
$highestPositionForSubscriber[$subscription->id->value] = $eventPosition;
}
$numberOfProcessedEvents++;
}
$eventPosition = $this->eventStoreAdapter->eventPosition($event);
// without any remaining subscription, calling the catch-up again could not process more events
$hasPendingEvents = $hasPendingEvents && !$subscriptionsToCatchup->isEmpty();
foreach ($subscriptionsToCatchup as $subscription) {
$subscriber = $this->subscribers->get($subscription->id);
if (!$eventPosition->isAheadOf($subscription->position)) {
$this->dispatchEngineEvent(new SubscriberSkippedEvent($subscription, $event, $eventPosition));
// The position will be set to the one the subscriber handled last, or if no events were in the stream, and we booted we keep the persisted position
$position = $highestPositionForSubscriber[$subscription->id->value] ?? $subscription->position;
if ($hasPendingEvents) {
// a partial catch-up keeps the status: Booting subscriptions must not be triggered automatically until they reached the end of the event log
$this->subscriptionStore->update($subscription->with(position: $position));
continue;
}
try {
($subscriber->handler)($event);
} catch (Throwable $e) {
// ERROR Case:
$errors[] = Error::create($subscription->id, $e->getMessage(), $errors === [] ? $e : null, $eventPosition);
$this->dispatchEngineEvent(new SubscriberFailedToHandleEvent($subscription, $event, $eventPosition, $e));

// for the leftover events we are not including this failed subscription for catchup
$subscriptionsToCatchup = $subscriptionsToCatchup->without($subscription->id);
// update the subscription error state on either its unchanged or new position (if some events worked)
// note that the possibly partially applied event will not be rolled back.
$this->subscriptionStore->update($subscription->withError(SubscriptionError::fromPreviousStatusAndException($subscription->status, $e))->with(position: $highestPositionForSubscriber[$subscription->id->value] ?? $subscription->position));
continue;
// after catchup mark all subscriptions as active, so they are triggered automatically now.
$this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::ACTIVE, position: $position));
if ($subscription->status !== SubscriptionStatus::ACTIVE) {
$this->dispatchEngineEvent(new SubscriptionActivated($subscription, $subscription->status));
}
// HAPPY Case:
$this->dispatchEngineEvent(new SubscriberHandledEvent($subscription, $event, $eventPosition));
$highestPositionForSubscriber[$subscription->id->value] = $eventPosition;
}
$numberOfProcessedEvents++;
}
// without any remaining subscription, calling the catch-up again could not process more events
$hasPendingEvents = $hasPendingEvents && !$subscriptionsToCatchup->isEmpty();
foreach ($subscriptionsToCatchup as $subscription) {
// The position will be set to the one the subscriber handled last, or if no events were in the stream, and we booted we keep the persisted position
$position = $highestPositionForSubscriber[$subscription->id->value] ?? $subscription->position;
if ($hasPendingEvents) {
// a partial catch-up keeps the status: Booting subscriptions must not be triggered automatically until they reached the end of the event log
$this->subscriptionStore->update($subscription->with(position: $position));
continue;
}
// after catchup mark all subscriptions as active, so they are triggered automatically now.
$this->subscriptionStore->update($subscription->with(status: SubscriptionStatus::ACTIVE, position: $position));
if ($subscription->status !== SubscriptionStatus::ACTIVE) {
$this->dispatchEngineEvent(new SubscriptionActivated($subscription, $subscription->status));
$this->subscriptionStore->commit();
$committed = true;
$errorsVo = $errors !== [] ? Errors::fromArray($errors) : null;
$this->dispatchEngineEvent(new CatchUpFinished($initialSubscriptionsToCatchup, $numberOfProcessedEvents, $errorsVo, $hasPendingEvents));
return $errorsVo === null ? ProcessedResult::success($numberOfProcessedEvents, $hasPendingEvents) : ProcessedResult::failed($numberOfProcessedEvents, $errorsVo, $hasPendingEvents);
} catch (Throwable $e) {
if (!$committed) {
$this->rollbackTransaction();
}
throw $e;
} finally {
$this->processingSubscriptions = $processingSubscriptionsBackup;
}
}

/**
* A failed rollback must not hide the exception that caused it, usually the connection is gone in that case and the transaction with it
*/
private function rollbackTransaction(): void
{
try {
$this->subscriptionStore->rollback();
} catch (Throwable) {
}
$this->subscriptionStore->commit();
$errorsVo = $errors !== [] ? Errors::fromArray($errors) : null;
$this->dispatchEngineEvent(new CatchUpFinished($initialSubscriptionsToCatchup, $numberOfProcessedEvents, $errorsVo, $hasPendingEvents));
$this->processingSubscriptions = $processingSubscriptionsBackup;
return $errorsVo === null ? ProcessedResult::success($numberOfProcessedEvents, $hasPendingEvents) : ProcessedResult::failed($numberOfProcessedEvents, $errorsVo, $hasPendingEvents);
}

/**
Expand Down
42 changes: 38 additions & 4 deletions tests/Mocks/InMemorySubscriptionStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@ final class InMemorySubscriptionStore implements SubscriptionStore

private bool $setupCalled = false;

private bool $transactionActive = false;
/**
* @var array<array<string, Subscription>>
*/
private array $transactionSnapshots = [];
private bool $rollbackCalled = false;
private bool $failOnRollback = false;
private bool $failOnCommit = false;
private bool $hasPendingChanges = false;
private bool $hasCommittedChanges = false;

Expand Down Expand Up @@ -66,12 +72,25 @@ public function update(Subscription $subscription): void

public function beginTransaction(): void
{
$this->transactionActive = true;
$this->transactionSnapshots[] = $this->subscriptionsById;
}

public function rollback(): void
{
$this->rollbackCalled = true;
if ($this->failOnRollback) {
throw new \RuntimeException('Rollback failed');
}
$this->subscriptionsById = array_pop($this->transactionSnapshots);
$this->hasPendingChanges = false;
}

public function commit(): void
{
$this->transactionActive = false;
if ($this->failOnCommit) {
throw new \RuntimeException('Commit failed');
}
array_pop($this->transactionSnapshots);
if ($this->hasPendingChanges) {
$this->hasCommittedChanges = true;
$this->hasPendingChanges = false;
Expand All @@ -86,14 +105,29 @@ public function _setSubscriptions(Subscription ...$subscriptions): void
}
}

public function _wasRollbackCalled(): bool
{
return $this->rollbackCalled;
}

public function _failOnRollback(): void
{
$this->failOnRollback = true;
}

public function _failOnCommit(): void
{
$this->failOnCommit = true;
}

public function _wasSetupCalled(): bool
{
return $this->setupCalled;
}

public function _isTransactionActive(): bool
{
return $this->transactionActive;
return $this->transactionSnapshots !== [];
}

public function _hasPendingChanges(): bool
Expand Down
Loading
Loading