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
65 changes: 65 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,71 @@ All notable changes to `initphp/queue` are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- `Contracts\OwnershipAwareIdempotencyStore` (extends `IdempotencyStore`, optional,
independent of `CompletionAwareIdempotencyStore`): `claimOwned()` returns a token
for the claim it took, `forgetOwned()` releases a claim only while that token
still owns the key. The `Dispatcher` uses them when the store implements the
interface; a store that does not keeps `claim()` and `forget()` exactly as before.
The bundled `InMemoryIdempotencyStore` implements it.
- `ReceivedMessage` has a new optional last constructor argument `$abandoned` and
`wasAbandoned()`: the transport has handed the message out again after a delivery
that never ended in an ack, release or dead-letter, and has already counted that
delivery in `attempts()`.
- `RedisTransport` has a new optional last constructor argument `$startedSuffix`
(default `:started`).

### Fixed

- **A handler that kills its process now counts as an attempt.** A handler killed by
out-of-memory, `exit` or `SIGKILL` never reports a failure, so its message used to
come back with the same `attempts` for ever. The transport now counts the
unfinished delivery when it hands the message out again, and the `Worker`
dead-letters it (reason `failed`) once `attempts` reaches `maxAttempts`, without
running the handler again. PDO: a row taken over after its reservation lapsed gets
`attempts` (column and envelope) raised in the same `UPDATE` that takes it, so one
worker counts it; no schema change. Redis: `reserve()` records each delivery in a
`<queue>:started` sorted set (SHA-1 of the body) that `ack()`, `release()` and
`deadLetter()` clear, and a body that returns with its entry still there is
counted, in the body and in the processing entry, so the count survives the next
crash; the body format is unchanged and a client without the sorted-set commands
switches the counting off. RabbitMQ: the broker's `redelivered` flag counts one
attempt (a classic queue keeps no delivery count, so repeated crashes are not
bounded there). Waiting for another handler's in-flight key is a release and is
never counted, so `inFlightDelaySeconds` waits still use no attempts.
- **A handler that outlived its lease no longer deletes the new holder's claim.** On
a store that implements `OwnershipAwareIdempotencyStore`, the late failure releases
only its own claim, so the claim or completed record of the worker that took over
stays.
- An abandoned message that is out of attempts is checked against the idempotency
store before it is dead-lettered: a key recorded as processed drops it as a
`duplicate` (the handler finished, only its ack was lost) and a key still claimed
releases it as `in_flight`. `Dispatcher::dispatch()` has a new optional second
argument, `$exhausted`, for this; the `Worker` passes it. A message that is put
back this way is treated as exhausted when it returns: any message that arrives
with `attempts` at or above `maxAttempts` and no `dead_letter` block is, so a
handler that kills its process every time reaches the dead-letter queue even when
`leaseSeconds` is longer than the transport's redelivery time. A store that cannot
tell a recorded key from a claimed one now dead-letters such a message instead of
discarding it.
- `RedisTransport` counting never fails a reservation: a `NOPERM`/unknown-command
refusal of `ZREMRANGEBYSCORE`, `LINSERT` or the other commands it adds switches the
counting off, and any other failure while counting hands the message out
uncounted, instead of leaving it on `<queue>:processing`.
- `PdoTransport::release()` for a worker whose reservation was taken over records
the back-off even when the stored `attempts` already equals the one it reports
(the take-over counted it); `attempts` still never goes back.

### Notes

- Nothing changes for existing stores, transports or message bodies; see
`docs/Idempotent-Consumption.md` (Upgrading from 2.3) for rolling deploys. A
handler that outlives `retryAfter` (PDO) or your Redis reaper's delay while its
worker is alive looks like a dead one and its second delivery is counted.

## [2.3.0] - 2026-11-25

### Added
Expand Down
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,17 @@ is discarded.
before `remember()` leaves no record; once the lease lapses the redelivery runs
the handler again. This is not "at most once".
2. **A handler that outlives its lease can run twice**, because a second worker
then wins the claim.
then wins the claim. With a store that implements `OwnershipAwareIdempotencyStore`
its later failure releases only its own claim; with one that does not, the
failure's `forget()` can delete the newer claim or the completed record.
3. **A claim that never lapses keeps its message waiting.** Give every claim a
lease; `leaseSeconds: 0` holds it until `forget()`.
4. **A handler that kills its process never counts as failed**, so its `attempts`
does not rise and it never reaches the dead-letter queue; it is picked up again
each time the lease lapses.
4. **A handler that kills its process is counted by the transport.** It never
reports a failure, so when the transport hands the message out again it counts
that unfinished delivery as one attempt, and the worker dead-letters the message
at `maxAttempts` without running the handler. PDO and Redis count every one;
RabbitMQ counts one (no delivery count on a classic queue). Waiting for an
in-flight key is never counted. See `docs/Retries-and-Dead-Letters.md`.
5. **On Redis, a reaper that rewrites the envelope hides the late failure.** A
handler that outlives the reaper still has its failure counted (it replaces the
reclaimed copy, so `maxAttempts` ends the message), but only while the copy has
Expand Down
24 changes: 22 additions & 2 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ public function keyFor(InitPHP\Queue\Message\ReceivedMessage $message): ?string

A negative `ttl` or `leaseSeconds`, or an `inFlightDelaySeconds` below 1, throws
`ConfigurationException`. `InitPHP\Queue\Consumer\InMemoryIdempotencyStore`
implements `CompletionAwareIdempotencyStore` and adds `count(): int`.
implements `CompletionAwareIdempotencyStore` and `OwnershipAwareIdempotencyStore` and
adds `count(): int`.

### Outcome / OutcomeKind

Expand Down Expand Up @@ -213,6 +214,23 @@ failed claim on a completed key is dropped, on an in-flight key the message is
released. A store that implements only `IdempotencyStore` keeps the previous
behaviour (always dropped). See [Idempotent Consumption](Idempotent-Consumption.md).

### OwnershipAwareIdempotencyStore

```php
interface OwnershipAwareIdempotencyStore extends IdempotencyStore
{
public function claimOwned(string $key, int $leaseSeconds = 0): ?string; // token, or null when not won
public function forgetOwned(string $key, string $token): void; // releases only the claim the token owns
}
```

Optional and independent of `CompletionAwareIdempotencyStore`. When the store
implements it, the `Dispatcher` takes the claim with `claimOwned()` and releases a
failed handler's claim with `forgetOwned()`, so a handler that outlived its lease
cannot delete the claim or the completed record of the worker that took over. A store
without it keeps `claim()` and `forget()`. `InMemoryIdempotencyStore` implements it.
See [Claim ownership](Idempotent-Consumption.md#claim-ownership).

### ConsumerTransport

```php
Expand All @@ -234,7 +252,7 @@ interface ConsumerTransport
`InitPHP\Queue\Message\ReceivedMessage implements BabelQueue\Contracts\InboundMessage`.

```php
public function __construct(string $queue, string $rawBody, array $envelope, mixed $receipt)
public function __construct(string $queue, string $rawBody, array $envelope, mixed $receipt, bool $abandoned = false)

// InboundMessage:
public function getUrn(): string
Expand All @@ -248,6 +266,7 @@ public function rawBody(): string
public function envelope(): array
public function attempts(): int
public function receipt(): mixed
public function wasAbandoned(): bool // a previous delivery never ended; the transport counted it in attempts()
```

---
Expand Down Expand Up @@ -286,6 +305,7 @@ public function __construct(
string $processingSuffix = ':processing',
string $failedSuffix = ':failed',
string $delayedSuffix = ':delayed',
string $startedSuffix = ':started',
)
```

Expand Down
127 changes: 116 additions & 11 deletions docs/Idempotent-Consumption.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ exactly as before — this is fully backward-compatible.
dedup key from the message and *claims* it in the store, holding the claim under a
lease (`leaseSeconds`). If the claim succeeds the handler runs; when it returns,
the key is **recorded** (`remember()`, kept for `ttl` seconds); when it throws,
the claim is released (`forget()`), so the normal retry runs it again.
the claim is released (`forget()`, or `forgetOwned()` with the claim's token on a
store that [tracks ownership](#claim-ownership)), so the normal retry runs it again.

If the claim fails, one of two things is true:

Expand Down Expand Up @@ -94,21 +95,30 @@ were not run as separate scenarios.
must stay idempotent.
2. **A handler that outlives its lease can run twice.** If the lease lapses while
the first handler is still running, the next redelivery wins the claim and runs
the same message concurrently. When the first handler then throws, its
`forget()` also frees the newer claim, because a claim carries no owner.
the same message concurrently. On a store that implements
`OwnershipAwareIdempotencyStore` the first handler's later failure releases only
its own claim, so the newer claim and a completed record stay. On a store that
does not, its `forget()` also frees the newer claim, or deletes the completed
record, because the claim carries no owner (see [Claim ownership](#claim-ownership)).
3. **A key stuck in flight keeps its message waiting.** With a lease that never
lapses (`leaseSeconds: 0` on a store that then holds the claim forever) a dead
worker's claim is never released, and the message is deferred again and again
without being handled. The message is not lost and not dead-lettered, but only
`forget()` on the key (or a lease) frees it, so give every claim a lease.
4. **A store without `isCompleted()` still discards.** See above: such a store
keeps the pre-2.3 behaviour, including the message loss it had.
5. **A handler that kills its process never counts as failed.** A message whose
handler is killed each time (out of memory, a fatal error) never reaches the
retry path, so its `attempts` stays the same and it never reaches the
dead-letter queue. Without deduplication it simply crashed the worker again on
every redelivery; with it, the message is picked up again each time the lease
lapses. Watch for a message that keeps appearing.
5. **A handler that kills its process is counted by the transport, not by the
worker.** A handler that is killed (out of memory, `exit`, `SIGKILL`) never
reports a failure. When the transport hands such a message out again, it counts
that unfinished delivery as one attempt, and the worker dead-letters the message
(reason `failed`) once the count reaches `maxAttempts`, without running the
handler again, after checking the store: a key recorded as processed drops the
message as a duplicate, and a key still claimed releases it as `in_flight` (it
stays out of attempts and is dead-lettered once the claim has lapsed). This
does not touch waiting: a message put back for an in-flight
key is released, not abandoned, and is never counted. PDO and Redis count every
unfinished delivery, RabbitMQ counts one (it keeps no delivery count on a classic
queue); see [Retries & Dead-Letters](Retries-and-Dead-Letters.md#a-handler-that-kills-its-process).
6. **On Redis, a reaper that rewrites the envelope hides the late failure.** Redis
never redelivers a message by itself; a reaper moves it from
`<queue>:processing` back onto the queue. If the original handler is still
Expand All @@ -117,8 +127,11 @@ were not run as separate scenarios.
[Transport: Redis](Transport-Redis.md#delivery-semantics)). That only works while
the copy still has the body the handler was given: a reaper that rewrites it
(to increment `attempts`, say) makes the late failure unmatchable, and only the
reaper's own count applies. A client without `EVAL` keeps the same rules but can
lose a message to a crash in the middle of a retry.
reaper's own count applies. The same holds for the count of a delivery that never
finished (item 5): the transport raises `attempts` in the body it hands out, and
that count is kept only while the reaper moves the body back unchanged. A client
without `EVAL` keeps the same rules but can lose a message to a crash in the
middle of a retry.

### Choosing `leaseSeconds`

Expand All @@ -140,6 +153,62 @@ Redis store below then hold the claim with no expiry, so a dead worker's claim
never lapses. `InMemoryIdempotencyStore` lives and dies with its worker, so it
has no orphaned claim, but it also remembers nothing across a restart.

## Claim ownership

`forget()` removes whatever is stored under the key. A handler that outlives its
lease and then throws would therefore delete the claim, or the completed record, of
the worker that took the key over, and the message would run again. A store that
implements `InitPHP\Queue\Contracts\OwnershipAwareIdempotencyStore` avoids this:

- `claimOwned(string $key, int $leaseSeconds = 0): ?string` takes the claim like
`claim()` and returns an opaque token that identifies it (`null` when the claim was
not won);
- `forgetOwned(string $key, string $token): void` releases the claim **only if** the
token still owns the key, in one atomic step. A claim another worker took over, or
a key that has since been recorded, is left alone.

The dispatcher uses these two instead of `claim()` and `forget()` when the store
implements the interface, and only for releasing a failed handler's claim:
`remember()` is unchanged. The interface is optional and independent of
`CompletionAwareIdempotencyStore`; a store may implement either or both, and a store
that implements neither keeps using `claim()` and `forget()` exactly as before.
`claim()`, `remember()` and `forget()` must keep working on a store that adds it.
`InMemoryIdempotencyStore` implements it. A durable example is in
[Bring your own store](#bring-your-own-store).

## Upgrading from 2.3

Nothing has to change: no signature of `IdempotencyStore`,
`CompletionAwareIdempotencyStore`, `ConsumerTransport` or `Handler` changed, the
message body format is unchanged, and `ReceivedMessage` has a new optional last
constructor argument.

- **Ownership is opt-in.** A custom store keeps `claim()` and `forget()` until you
implement `OwnershipAwareIdempotencyStore`. For a Redis store, store the token as
the claim's value and release with a compare-and-delete script. For a PDO store,
add a nullable `claim_token` column that `claim()` sets (also when it takes over a
lapsed row), that `remember()` clears, and `DELETE … WHERE dedup_key = ? AND
claim_token = ?` in `forgetOwned()`.
- **The count of unfinished deliveries needs no schema change.** PDO reuses
`reserved_at`, Redis adds a `<queue>:started` sorted set, RabbitMQ reads the
broker's `redelivered` flag. Rows and messages left by 2.3 are counted like any
other the first time a 2.4 worker takes them over.
- **Rolling deploys are safe in both directions.** A 2.3 worker does not count an
unfinished delivery, so such a delivery is only counted while a 2.4 worker is the
one that takes it over (on Redis, only if a 2.4 worker reserved it first and left
its started entry). A 2.3 worker reading a row or message that a 2.4 worker
counted sees an ordinary `attempts` and the usual body. Deploying all workers gives
the full behaviour; none has to be drained.
- **A late 2.3 worker can lose a back-off.** While 2.3 and 2.4 workers run side by
side, a 2.3 worker whose PDO reservation was taken over by a 2.4 worker still uses
the old rule and skips recording its back-off when the stored `attempts` already
equals its own. The count is right; only that one delay is lost, and only until
the last 2.3 worker has stopped.
- **`retryAfter` and your Redis reaper now matter for `attempts`.** A handler that
runs longer than `retryAfter` (PDO) or than your reaper's delay (Redis) while its
worker is alive is indistinguishable from one that died, so the second delivery is
counted. Keep both above your slowest handler, as before.

## Upgrading from 2.1 and 2.2

Nothing has to change: `IdempotencyStore`, its method signatures and the
Expand Down Expand Up @@ -273,6 +342,42 @@ final class RedisIdempotencyStore implements CompletionAwareIdempotencyStore
`isCompleted()`, is what lets the dispatcher keep an in-flight message instead of
discarding it. Without it a store still works, with the 2.2 behaviour.

To also stop a late failure from releasing a claim that is no longer yours, add
`OwnershipAwareIdempotencyStore` (see [Claim ownership](#claim-ownership)). On Redis,
keep the token as the claim's value and compare it in a script:

```php
use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore;
use InitPHP\Queue\Contracts\OwnershipAwareIdempotencyStore;

final class OwnedRedisIdempotencyStore implements CompletionAwareIdempotencyStore, OwnershipAwareIdempotencyStore
{
// seen(), claim(), isCompleted(), remember() and forget() as above, with one
// change: isCompleted() must treat a value that starts with 'claimed:' as in flight.

public function claimOwned(string $key, int $leaseSeconds = 0): ?string
{
$token = bin2hex(random_bytes(16));
$options = ['NX'];
if ($leaseSeconds > 0) {
$options['EX'] = $leaseSeconds;
}

return $this->redis->set($key, 'claimed:' . $token, $options) ? $token : null;
}

public function forgetOwned(string $key, string $token): void
{
// Compare and delete in one step: only the claim that carries our token goes.
$this->redis->eval(
"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0",
[$key, 'claimed:' . $token],
1,
);
}
}
```

A PDO-backed store needs one more step than the Redis one, because a unique
constraint does not expire rows by itself. Redis `EX` frees a lapsed claim on its
own; with a table, `claim()` must free it explicitly or a dead worker's key stays
Expand Down
Loading
Loading