From ea5ce0e9a7dab2a84f0ec19852024c015b402f27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 08:05:58 +0300 Subject: [PATCH 1/6] fix(consumer): keep an in-flight message instead of dropping it as a duplicate With idempotency enabled, a redelivery that found its key claimed by an unfinished handler was acknowledged and discarded. If that handler's worker had died the message was lost, and if the handler outlived the transport's redelivery time and then threw, the discarded duplicate had already deleted the PDO row, so the retry updated nothing. Add CompletionAwareIdempotencyStore (extends IdempotencyStore, adds isCompleted()). When the store implements it, the Dispatcher drops a completed duplicate but releases an in-flight one without counting an attempt, delayed by the new IdempotencyOptions::$inFlightDelaySeconds. Outcome::release() gains an optional delay, which the Worker passes to the transport and follows with a short pause so transports without native delay do not spin. Stores that implement only IdempotencyStore keep the old behaviour. Correct the forget() and contract docblocks and rewrite the idempotent consumption docs. --- CHANGELOG.md | 40 +++ README.md | 91 ++++--- docs/API-Reference.md | 3 +- docs/Core-Concepts.md | 4 +- docs/FAQ.md | 2 +- docs/Idempotent-Consumption.md | 161 +++++++---- docs/Retries-and-Dead-Letters.md | 4 +- docs/The-Worker.md | 4 +- docs/Transport-PDO.md | 7 +- docs/Troubleshooting.md | 18 +- src/Consumer/Dispatcher.php | 53 +++- src/Consumer/IdempotencyOptions.php | 11 + src/Consumer/InMemoryIdempotencyStore.php | 28 +- src/Consumer/Outcome.php | 11 +- src/Consumer/Worker.php | 14 +- .../CompletionAwareIdempotencyStore.php | 38 +++ src/Contracts/IdempotencyStore.php | 28 +- tests/Consumer/InFlightRedeliveryTest.php | 257 ++++++++++++++++++ .../Consumer/InMemoryIdempotencyStoreTest.php | 29 ++ tests/Support/ClaimOnlyIdempotencyStore.php | 42 +++ 20 files changed, 700 insertions(+), 145 deletions(-) create mode 100644 src/Contracts/CompletionAwareIdempotencyStore.php create mode 100644 tests/Consumer/InFlightRedeliveryTest.php create mode 100644 tests/Support/ClaimOnlyIdempotencyStore.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 98a53de..5efa8b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,46 @@ 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\CompletionAwareIdempotencyStore` (extends `IdempotencyStore`) with + `isCompleted(string $key): bool`, which lets the `Dispatcher` tell a key that + was recorded as processed from one that another handler still holds. The bundled + `InMemoryIdempotencyStore` implements it. +- `IdempotencyOptions::$inFlightDelaySeconds` (new optional last argument, + default 5): how long a message waits before it re-checks a key held by another + handler. +- `Outcome::release()` takes an optional `$delaySeconds` and `Outcome` exposes it + as `delaySeconds` (default 0, so existing releases are unchanged). The `Worker` + passes it to the transport and logs it as `delay` on `job.released`. + +### Fixed + +- **A message could be lost with idempotency enabled.** A redelivery that found its + key claimed by a handler that had not finished was acknowledged and discarded as + a `duplicate`. If that handler's worker had died, the message was gone; if the + handler outlived the transport's redelivery time and then threw, the discarded + duplicate had deleted the PDO row, so its retry updated nothing and was lost with + no dead letter. With a `CompletionAwareIdempotencyStore` such a redelivery is now + released back to the queue (`job.released`, reason `in_flight`) without counting + an attempt, so it never moves towards the dead-letter queue by waiting, and it is + re-checked after `inFlightDelaySeconds`. A recorded (completed) duplicate is + still dropped. The `Worker` pauses for `sleepWhenEmpty` after a delayed release so + that RabbitMQ, which has no native delay, does not reserve the message again in a + tight loop. +- Wrong docblocks: `IdempotencyStore::forget()` is called by the dispatcher when a + handler throws, and the contract's description now lists `forget()`. + +### Compatibility + +- `IdempotencyStore` and its signatures are unchanged. A custom store that + implements only `IdempotencyStore` keeps the previous behaviour (any failed claim + is discarded as a duplicate); implement `CompletionAwareIdempotencyStore` to get + the fix. Records written by 2.1/2.2 should be treated as completed by that + method; see the upgrade notes in `docs/Idempotent-Consumption.md`. + ## [2.2.0] - 2026-11-22 ### Changed diff --git a/README.md b/README.md index 1ec2a57..c0f393d 100644 --- a/README.md +++ b/README.md @@ -184,8 +184,8 @@ With no options (the default) deduplication is off and the dispatcher behaves exactly as before — this is fully backward-compatible. > **Deduplication is not exactly-once delivery and does not replace an idempotent -> handler.** It can discard a message whose handler never completed, and it can -> still run a handler twice. Read "What deduplication does not guarantee" below. +> handler.** It can still run a handler twice. Read "What deduplication does not +> guarantee" below. **How it dedupes.** Before running a handler the dispatcher derives a stable dedup key from the message and *claims* it in the store, holding the claim under a @@ -193,42 +193,35 @@ 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, so the normal retry runs it again. -If the claim fails, the dispatcher skips the handler and acknowledges the message, -which discards it (the worker logs `job.dropped` with reason `duplicate`). A -failed claim means one of two things, and the dispatcher cannot tell them apart: - -- the key was **recorded**: the message was handled before, so discarding it is - right; or -- the key is **claimed but not recorded**: another worker is still inside the - handler, or died inside it and its lease has not expired yet. Discarding the - message here means the handler may never complete for it. - -The second case is the one to understand before you turn this on — see -[What deduplication does not guarantee](#what-deduplication-does-not-guarantee). +If the claim fails, the key is either **recorded** (the message was handled before: +it is acknowledged and discarded, `job.dropped` with reason `duplicate`) or +**claimed but not recorded** (another worker is still inside the handler, or died +inside it and its lease has not lapsed). In the second case the message is **not** +discarded: it is put back on the queue (`job.released`, reason `in_flight`) +without counting an attempt, and looked at again after `inFlightDelaySeconds` +(default 5). It ends when the other handler records the key (the message is then +dropped), when that handler fails and releases the claim, or when a dead worker's +lease lapses (the handler then runs). Waiting never moves a message towards the +dead-letter queue, and it is paced rather than a tight loop. + +This needs a store that implements `CompletionAwareIdempotencyStore` +(`InMemoryIdempotencyStore` does). A store that implements only `IdempotencyStore` +cannot tell the two cases apart and keeps the previous behaviour: any failed claim +is discarded. ### What deduplication does not guarantee -The dispatcher treats a claimed-but-unrecorded key (a handler still running, or -one whose worker died) the same as a recorded one: it acknowledges and discards -the message. So: - -1. **A message can be lost.** A worker claims the key and dies inside the handler; - the transport redelivers; the claim is still held, so the redelivery is - discarded and the handler never completes. With the defaults - (`leaseSeconds: 300`) on a `PdoTransport` (`retryAfter: 90`) this is exactly - what happens, and on RabbitMQ a closed connection redelivers immediately. -2. **A handler can still run twice.** A worker that dies after the handler but +1. **A handler can still run twice.** A worker that dies after the handler but before `remember()` leaves no record; once the lease lapses the redelivery runs the handler again. This is not "at most once". -3. **A failed attempt can lose its retry.** If a handler outlives the transport's - redelivery time, the duplicate is discarded; on PDO that deletes the row, so - when the first handler throws there is no row left to retry. - -Set `leaseSeconds` **above your slowest handler** and **below the time the -transport takes to redeliver a dead worker's message** (PDO: below `retryAfter`; -Redis: below your reaper's delay; RabbitMQ: no safe value, since the broker redelivers at once and a redelivery picked up before the lease lapses is discarded). If no value fits, -leave deduplication off and rely on an idempotent handler. The details and the -per-transport table are in the +2. **A handler that outlives its lease can run twice**, because a second worker + then wins the claim. +3. **A claim that never lapses keeps its message waiting.** Give every claim a + lease; `leaseSeconds: 0` holds it until `forget()`. + +Set `leaseSeconds` **above your slowest handler**, and as short as that allows: it +is how long a dead worker's message waits before it is handled again. The +per-transport table and the upgrade notes for 2.1/2.2 are in the [full guide](docs/Idempotent-Consumption.md#choosing-leaseseconds). ### Message keys @@ -251,6 +244,7 @@ new IdempotencyOptions( keyPrefix: 'bq:idemp:', // namespaces keys in a shared store ttl: 86_400, // seconds a processed key is retained (null = forever) leaseSeconds: 60, // in-flight claim lease; see the notes above + inFlightDelaySeconds: 5, // wait before re-checking a key another handler holds keyResolver: static function (ReceivedMessage $message): ?string { $orderId = $message->getData()['order_id'] ?? null; @@ -269,9 +263,9 @@ exactly how the InitPHP ecosystem treats Cache and Database backends as pluggable seams: ```php -use InitPHP\Queue\Contracts\IdempotencyStore; +use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; -final class RedisIdempotencyStore implements IdempotencyStore +final class RedisIdempotencyStore implements CompletionAwareIdempotencyStore { public function __construct(private \Redis $redis) {} @@ -289,14 +283,23 @@ final class RedisIdempotencyStore implements IdempotencyStore $options['EX'] = $leaseSeconds; } - return (bool) $this->redis->set($key, '1', $options); + return (bool) $this->redis->set($key, 'claimed', $options); + } + + public function isCompleted(string $key): bool + { + // 'claimed' is an in-flight claim. Anything else that exists is a record, + // including the '1' that 2.1/2.2 stored for both claims and records. + $value = $this->redis->get($key); + + return $value !== false && $value !== 'claimed'; } public function remember(string $key, ?int $ttl = null): void { $ttl !== null && $ttl > 0 - ? $this->redis->set($key, '1', ['EX' => $ttl]) - : $this->redis->set($key, '1'); + ? $this->redis->set($key, 'done', ['EX' => $ttl]) + : $this->redis->set($key, 'done'); } public function forget(string $key): void @@ -306,6 +309,10 @@ final class RedisIdempotencyStore implements IdempotencyStore } ``` +`CompletionAwareIdempotencyStore` extends `IdempotencyStore`; the one method it adds, +`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. + 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 @@ -316,8 +323,12 @@ when the insert affected a row (a unique-key violation means `false`). The same effect in one statement is `INSERT … ON CONFLICT (dedup_key) DO UPDATE SET expires_at = excluded.expires_at WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), again checking the affected-row count. `remember()` upserts the row with -`expires_at = now + ttl` (or `NULL` to keep it), `forget()` deletes it, and -`seen()` ignores rows whose `expires_at` has passed. +`expires_at = now + ttl` (or `NULL` to keep it) and marks it completed, `forget()` +deletes it, and `seen()` ignores rows whose `expires_at` has passed. For +`isCompleted()` add a `completed` flag column: `claim()` inserts it as `0`, +`remember()` sets it to `1`, and `isCompleted()` returns true for a live row whose +flag is `1`. Give the column a default of `1`, so rows written before you added it +read as completed. Full guide: [docs/Idempotent-Consumption.md](docs/Idempotent-Consumption.md). diff --git a/docs/API-Reference.md b/docs/API-Reference.md index b35af93..71c781f 100644 --- a/docs/API-Reference.md +++ b/docs/API-Reference.md @@ -100,12 +100,13 @@ An unknown strategy string throws `ConfigurationException`. public readonly OutcomeKind $kind; public readonly string $reason; // '' | 'failed' | 'unknown_urn' | a validator reason public readonly ?\Throwable $exception; +public readonly int $delaySeconds; // 0 unless a release is delayed public static function ack(): self public static function retry(?\Throwable $exception = null, string $reason = 'failed'): self public static function deadLetter(string $reason, ?\Throwable $exception = null): self public static function drop(string $reason): self -public static function release(string $reason): self +public static function release(string $reason, int $delaySeconds = 0): self ``` `InitPHP\Queue\Consumer\OutcomeKind` is an enum: `Ack`, `Retry`, `DeadLetter`, diff --git a/docs/Core-Concepts.md b/docs/Core-Concepts.md index ab1a085..89425db 100644 --- a/docs/Core-Concepts.md +++ b/docs/Core-Concepts.md @@ -93,8 +93,8 @@ Delivery is **at-least-once**. A message reserved by a worker that then crashes becomes reservable again (the PDO visibility timeout; the Redis processing list). A handler may therefore run more than once for the same message, so **handlers must be idempotent**. The dispatcher's optional deduplication can skip some -redeliveries but does not replace that, and it has a message-loss window of its -own — see [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). +redeliveries but does not replace that, and it can still run a handler twice — +see [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). ## Error handling diff --git a/docs/FAQ.md b/docs/FAQ.md index 43d3eb5..87ab09d 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -48,7 +48,7 @@ installed. See [Retries & Dead-Letters](Retries-and-Dead-Letters.md). No — it is **at-least-once**. A message can be delivered more than once (e.g. a worker crashes after handling but before acking). Make handlers **idempotent**. The dispatcher's optional deduplication can skip some redeliveries, but it is not -a substitute: it can also discard a message whose handler never completed — see +a substitute: it can still run a handler twice — see [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). ### Can a Go / Python / Node service consume what PHP produces (and vice-versa)? diff --git a/docs/Idempotent-Consumption.md b/docs/Idempotent-Consumption.md index b956e6b..66e70a7 100644 --- a/docs/Idempotent-Consumption.md +++ b/docs/Idempotent-Consumption.md @@ -20,74 +20,113 @@ With no options (the default) deduplication is off and the dispatcher behaves exactly as before — this is fully backward-compatible. > **Deduplication is not exactly-once delivery, and it is not a replacement for an -> idempotent handler.** It removes some redundant executions; it can also discard -> a message whose handler never completed, and it can still run a handler twice. -> Read [What deduplication does not guarantee](#what-deduplication-does-not-guarantee) +> idempotent handler.** It removes some redundant executions, but it can still run +> a handler twice. Read [What deduplication does not guarantee](#what-deduplication-does-not-guarantee) > before enabling it. **How it dedupes.** Before running a handler the dispatcher derives a stable 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, so the normal retry runs it again. +the claim is released (`forget()`), so the normal retry runs it again. -If the claim fails, the dispatcher skips the handler and acknowledges the message, -which discards it (the worker logs `job.dropped` with reason `duplicate`). A -failed claim means one of two things, and the dispatcher cannot tell them apart: +If the claim fails, one of two things is true: -- the key was **recorded**: the message was handled before, so discarding it is - right; or +- the key was **recorded**: the message was handled before, so the dispatcher + acknowledges and discards it (the worker logs `job.dropped` with reason + `duplicate`); or - the key is **claimed but not recorded**: another worker is still inside the - handler, or died inside it and its lease has not expired yet. Discarding the - message here means the handler may never complete for it. - -The second case is the one to understand before you turn this on — see -[What deduplication does not guarantee](#what-deduplication-does-not-guarantee). + handler, or died inside it and its lease has not expired yet. The dispatcher + does **not** discard the message, because that handler may still fail and then + nothing would be left to retry. It puts the message back on the queue + (`job.released`, reason `in_flight`, with the `delay` in the log context), + without counting an attempt, and looks again after `inFlightDelaySeconds` + (default 5). + +A waiting message therefore ends one of three ways: the other handler records the +key and the next look drops the message as a duplicate; the other handler throws +and releases its claim, so the next look runs the handler; or the other worker +died, its lease lapses, and the next look runs the handler. + +A waiting message consumes **no retry attempt**: it is released verbatim, with +`attempts` unchanged, so it is never moved to the dead-letter queue merely for +waiting, and the worker's `maxAttempts` and `backoff` apply only to real failures. +It is not a tight loop either: the message is paced by `inFlightDelaySeconds` +(honoured natively by PDO and Redis), and the worker pauses for `sleepWhenEmpty` +after each deferral, which keeps RabbitMQ (which has no native delay) from +reserving the same message again at once. + +This needs a store that can tell a recorded key from a claimed one: one that +implements `InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore` +(`InMemoryIdempotencyStore` does; see [Bring your own store](#bring-your-own-store)). +A store that implements only `IdempotencyStore` cannot, and keeps the previous +behaviour: every failed claim is treated as a recorded duplicate and discarded. ## What deduplication does not guarantee -Because an in-flight claim is treated like a recorded key, three situations turn -out differently from what "dedupe" suggests. All three were reproduced against a -real `PdoTransport`, a shared store with a lease, and worker processes killed with -`SIGKILL`. - -1. **A message can be lost.** A worker claims the key and dies inside the handler. - The transport redelivers the message, but the claim is still held, so the - redelivery is acknowledged and discarded as a duplicate. The handler never - completes for that message, and nothing is retried or dead-lettered. With the - defaults (`leaseSeconds: 300`) on a `PdoTransport` (`retryAfter: 90`), the - redelivery arrives after 90 seconds, while the claim lives for 300. -2. **A handler can still run twice.** A worker finishes the handler and dies - before `remember()`. The key is not recorded, so once the lease lapses the - redelivery runs the handler again. The "processed at most once" reading does - not hold; handlers must stay idempotent. -3. **A failed attempt can lose its retry.** A handler outlives the transport's - redelivery time, so a second worker receives the same message, finds the claim - held, and discards it. On PDO that deletes the row, so when the first handler - then throws, its retry has no row to update and is silently lost: no retry and - no dead letter. +A message is no longer lost because its first handler failed or its worker died; +these remain. Reproduced against a real `PdoTransport`, a shared store with a +lease, and worker processes killed with `SIGKILL`. + +1. **A handler can still run twice.** A worker finishes the handler and dies + before `remember()`. The key is not recorded, so once the lease lapses the redelivery runs the + handler again. The "processed at most once" reading does not hold; handlers + 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. +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. ### Choosing `leaseSeconds` -The lease has to be **longer than your slowest handler** (otherwise a second -worker can start the same message while the first is running) and **shorter than -the time your transport takes to redeliver a message from a dead worker** (so the -redelivery finds the claim gone and runs the handler). +The lease has to be **longer than your slowest handler**, otherwise a second worker +can start the same message while the first is running. It also sets how long a +dead worker's message waits before it is handled again, so keep it as short as the +first rule allows. It no longer has to be shorter than the transport's redelivery +time: a redelivery that arrives while the lease is still held now waits instead of +being discarded. -| Transport | When a dead worker's message comes back | A safe `leaseSeconds` | +| Transport | When a dead worker's message comes back | Effect of the lease | | --- | --- | --- | -| PDO | after `retryAfter` (default 90 s) | below `retryAfter`, above the slowest handler — for example `retryAfter: 120`, `leaseSeconds: 90` for handlers under a minute | -| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | below the reaper's delay | -| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | no value is safe: a redelivery that is picked up before the lease lapses is discarded, and the broker redelivers at once | +| PDO | after `retryAfter` (default 90 s) | the redelivery is released and re-checked every `inFlightDelaySeconds` until the lease lapses, then handled | +| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | the same: it waits until the lease lapses | +| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | the same, re-checked about every `sleepWhenEmpty` seconds, because RabbitMQ has no native delay | `leaseSeconds: 0` is not "no lease": the bundled `InMemoryIdempotencyStore` and the 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. -If no value satisfies both bounds for your transport, leave deduplication off and -rely on an idempotent handler. An idempotent handler is the only guarantee that -holds on every transport, crash timing and store. +## Upgrading from 2.1 and 2.2 + +Nothing has to change: `IdempotencyStore`, its method signatures and the +`Dispatcher` and `IdempotencyOptions` constructors are unchanged, and +`inFlightDelaySeconds` is a new optional last argument. + +- **A custom store written for 2.1/2.2** keeps working with its old behaviour (a + failed claim is discarded as a duplicate). To get the fix, also implement + `CompletionAwareIdempotencyStore` and its single method + `isCompleted(string $key): bool`. +- **Records written by 2.1/2.2 in a durable store** do not distinguish a claim from + a recorded key (both were a plain row or a `1`). When you add `isCompleted()`, + treat such a legacy record as **completed**. That is what 2.2 did, so every + message deduped before the upgrade is still deduped. The only exposure is a + claim held by a handler that was already running during the upgrade: its + redelivery is discarded as before until that lease lapses, which is at most + `leaseSeconds` (default 300 s), after which new claims are the in-flight kind. + Messages that need no care across the upgrade can be left alone; to be exact, + drain the workers before deploying. +- **`InMemoryIdempotencyStore`** keeps nothing across a restart, so it has no + legacy records. +- **`Outcome::release()`** takes an optional second argument, `$delaySeconds`, and + `Outcome` has a new `delaySeconds` property (default `0`); a `release` without + it behaves as before. ## Message keys @@ -121,6 +160,7 @@ new IdempotencyOptions( keyPrefix: 'bq:idemp:', // namespaces keys in a shared store ttl: 86_400, // seconds a processed key is retained (null = forever) leaseSeconds: 60, // in-flight claim lease: see "Choosing leaseSeconds" + inFlightDelaySeconds: 5, // wait before re-checking a key another handler holds keyResolver: static function (ReceivedMessage $message): ?string { $orderId = $message->getData()['order_id'] ?? null; @@ -140,9 +180,9 @@ exactly how the InitPHP ecosystem treats Cache and Database backends as pluggable seams: ```php -use InitPHP\Queue\Contracts\IdempotencyStore; +use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; -final class RedisIdempotencyStore implements IdempotencyStore +final class RedisIdempotencyStore implements CompletionAwareIdempotencyStore { public function __construct(private \Redis $redis) {} @@ -160,14 +200,23 @@ final class RedisIdempotencyStore implements IdempotencyStore $options['EX'] = $leaseSeconds; } - return (bool) $this->redis->set($key, '1', $options); + return (bool) $this->redis->set($key, 'claimed', $options); + } + + public function isCompleted(string $key): bool + { + // 'claimed' is an in-flight claim. Anything else that exists is a record, + // including the '1' that 2.1/2.2 stored for both claims and records. + $value = $this->redis->get($key); + + return $value !== false && $value !== 'claimed'; } public function remember(string $key, ?int $ttl = null): void { $ttl !== null && $ttl > 0 - ? $this->redis->set($key, '1', ['EX' => $ttl]) - : $this->redis->set($key, '1'); + ? $this->redis->set($key, 'done', ['EX' => $ttl]) + : $this->redis->set($key, 'done'); } public function forget(string $key): void @@ -177,6 +226,10 @@ final class RedisIdempotencyStore implements IdempotencyStore } ``` +`CompletionAwareIdempotencyStore` extends `IdempotencyStore`; the one method it adds, +`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. + 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 @@ -187,8 +240,12 @@ when the insert affected a row (a unique-key violation means `false`). The same effect in one statement is `INSERT … ON CONFLICT (dedup_key) DO UPDATE SET expires_at = excluded.expires_at WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), again checking the affected-row count. `remember()` upserts the row with -`expires_at = now + ttl` (or `NULL` to keep it), `forget()` deletes it, and -`seen()` ignores rows whose `expires_at` has passed. +`expires_at = now + ttl` (or `NULL` to keep it) and marks it completed, `forget()` +deletes it, and `seen()` ignores rows whose `expires_at` has passed. For +`isCompleted()` add a `completed` flag column: `claim()` inserts it as `0`, +`remember()` sets it to `1`, and `isCompleted()` returns true for a live row whose +flag is `1`. Give the column a default of `1`, so rows written before you added it +read as completed. See also [Retries & Dead-Letters](Retries-and-Dead-Letters.md) and [Core Concepts › Delivery guarantee](Core-Concepts.md#delivery-guarantee). diff --git a/docs/Retries-and-Dead-Letters.md b/docs/Retries-and-Dead-Letters.md index 45edf42..deaa802 100644 --- a/docs/Retries-and-Dead-Letters.md +++ b/docs/Retries-and-Dead-Letters.md @@ -116,6 +116,6 @@ from `orders:failed`; for RabbitMQ, consume `orders.failed`. rather than retrying them. See [Handlers & Routing](Handlers-and-Routing.md#unknown-urn-strategies). - Make handlers **idempotent** — at-least-once delivery means a handler can run again for a message that actually succeeded but whose ack was lost. The - dispatcher's optional deduplication is not a replacement: it can discard a - message whose handler never completed — see + dispatcher's optional deduplication is not a replacement: it can still run a + handler twice — see [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). diff --git a/docs/The-Worker.md b/docs/The-Worker.md index ca1a7a2..be7630b 100644 --- a/docs/The-Worker.md +++ b/docs/The-Worker.md @@ -125,8 +125,8 @@ $worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(), | `job.ack` | A handler succeeded. | | `job.retry` | A failure was re-queued (context has `attempt`, `delay`). | | `job.dead_letter` | A message was quarantined (context has `reason`, `attempts`, `error`). | -| `job.dropped` | The message was acked-and-discarded: an unknown URN (`DELETE` strategy) or, with deduplication on, a duplicate (`reason` `duplicate`). | -| `job.released` | An unknown URN was put back (`RELEASE` strategy). | +| `job.dropped` | The message was acked-and-discarded: an unknown URN (`DELETE` strategy) or, with deduplication on, a duplicate whose handler already finished (`reason` `duplicate`). | +| `job.released` | A message was put back without counting an attempt: an unknown URN (`RELEASE` strategy), or, with deduplication on, a key another handler still holds (`reason` `in_flight`, context has `delay`). | | `reserve.failed` | The transport threw while reserving (loop continues). | | `process.failed` | The transport threw while acting on a message (loop continues). | diff --git a/docs/Transport-PDO.md b/docs/Transport-PDO.md index 9ef793c..8bc3527 100644 --- a/docs/Transport-PDO.md +++ b/docs/Transport-PDO.md @@ -106,9 +106,10 @@ and becomes reservable again, so the message is delivered again (at-least-once) instead of staying stuck. Set it comfortably above your slowest handler's runtime. If you also enable the dispatcher's [deduplication](Idempotent-Consumption.md), -keep its `leaseSeconds` **below** `retryAfter`: with the defaults (`retryAfter` 90, -`leaseSeconds` 300) the redelivery of a dead worker's message arrives while its -claim is still held, and it is discarded as a duplicate — see +a redelivery that arrives while another handler's claim is still held (a dead +worker's, or a handler that outlived `retryAfter`) is put back on the queue and +re-checked, not discarded, so the row survives until that claim is recorded, +released or lapses. Keep `leaseSeconds` above your slowest handler — see [Idempotent Consumption](Idempotent-Consumption.md#choosing-leaseseconds). ## Lifecycle in SQL terms diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index afec1f0..91e9e73 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -77,13 +77,17 @@ the cause is at-least-once redelivery (a reservation that lapsed after `retryAfter`), which is expected — make handlers idempotent. Raise `retryAfter` above your slowest handler's runtime if jobs are being reclaimed mid-flight. -## A message was dropped as a duplicate but its handler never finished - -With deduplication on, a redelivery that finds its key still claimed is -acknowledged and discarded (`job.dropped`, reason `duplicate`), even when the -worker that took the claim died inside the handler. Lower `leaseSeconds` below -the transport's redelivery time (PDO `retryAfter`) and above your slowest handler; -on RabbitMQ no value is safe. See +## A message keeps being released with reason `in_flight` + +With deduplication on, a redelivery that finds its key claimed by a handler that +has not finished is put back on the queue (`job.released`, reason `in_flight`) +and re-checked after `inFlightDelaySeconds`; it costs no retry attempt. It stops +when the other handler records the key (the message is dropped as a duplicate), +releases its claim after a failure, or when the claim's lease lapses. If it goes on +for much longer than `leaseSeconds`, the claim never lapses: the store holds it +without an expiry (`leaseSeconds: 0`) or does not honour the lease, so call +`forget()` on the key. A store that implements only `IdempotencyStore` never +releases a message this way; it discards it. See [Idempotent Consumption](Idempotent-Consumption.md#what-deduplication-does-not-guarantee). ## A message produced by another language is rejected diff --git a/src/Consumer/Dispatcher.php b/src/Consumer/Dispatcher.php index 9a228e2..2474ffa 100644 --- a/src/Consumer/Dispatcher.php +++ b/src/Consumer/Dispatcher.php @@ -7,6 +7,7 @@ use BabelQueue\Exceptions\UnknownUrnException; use BabelQueue\Routing\UnknownUrnStrategy; use BabelQueue\Validation\EnvelopeValidator; +use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; use InitPHP\Queue\Contracts\Handler; use InitPHP\Queue\Contracts\HandlerResolver; use InitPHP\Queue\Exceptions\ConfigurationException; @@ -26,8 +27,11 @@ * When an {@see IdempotencyOptions} is supplied the pipeline gains a * deduplication step: a redelivered message whose key is already recorded is * dropped without re-running the handler, and a key is only recorded *after* - * the handler succeeds — so a throwing handler stays retryable. With no options - * (the default) the dispatcher behaves exactly as before. + * the handler succeeds — so a throwing handler stays retryable. A redelivery + * whose key is only claimed by a handler that has not finished is not dropped + * (when the store is a {@see CompletionAwareIdempotencyStore}): it is put back + * on the queue, so the message survives that handler failing or its worker + * dying. With no options (the default) the dispatcher behaves exactly as before. */ final class Dispatcher { @@ -77,18 +81,17 @@ public function dispatch(ReceivedMessage $message): Outcome * Run the resolved handler, guarded by the idempotency layer when enabled. * * The dedup key is claimed *before* the handler runs (so a concurrent - * redelivery is skipped) and only committed with {@see IdempotencyStore::remember()} + * redelivery is not run twice) and only committed with {@see IdempotencyStore::remember()} * *after* the handler returns — a throwing handler leaves the key * uncommitted, so the at-least-once redelivery is retried as normal. */ private function runHandler(Handler $handler, ReceivedMessage $message): Outcome { - $key = $this->idempotency?->keyFor($message); + $idempotency = $this->idempotency; + $key = $idempotency?->keyFor($message); - // A duplicate that is already recorded: it was processed before, so - // acknowledge and discard rather than running the handler again. - if ($key !== null && ! $this->idempotency->store->claim($key, $this->idempotency->leaseSeconds)) { - return Outcome::drop('duplicate'); + if ($idempotency !== null && $key !== null && ! $idempotency->store->claim($key, $idempotency->leaseSeconds)) { + return $this->onClaimLost($idempotency, $key); } try { @@ -96,20 +99,46 @@ private function runHandler(Handler $handler, ReceivedMessage $message): Outcome } catch (Throwable $e) { // Release the in-flight claim so the redelivery can re-run; leaving // it set would suppress a legitimate retry. - if ($key !== null) { - $this->idempotency->store->forget($key); + if ($idempotency !== null && $key !== null) { + $idempotency->store->forget($key); } return Outcome::retry($e, 'failed'); } - if ($key !== null) { - $this->idempotency->store->remember($key, $this->idempotency->ttl); + if ($idempotency !== null && $key !== null) { + $idempotency->store->remember($key, $idempotency->ttl); } return Outcome::ack(); } + /** + * The claim failed: the key is recorded as processed, or another worker holds + * it while its handler runs. + * + * A processed message is acknowledged and discarded. A message whose handler + * has not finished is *not*: that handler may still throw or its worker may + * have died, and discarding the only copy would lose the message. It is + * released verbatim instead (no attempt counted, so waiting never walks it + * towards the dead-letter queue) and not offered again for + * {@see IdempotencyOptions::$inFlightDelaySeconds}; once the other handler + * records the key the redelivery is dropped, and once its claim is released or + * its lease lapses the redelivery runs the handler. + * + * A store that cannot tell the two apart keeps the original behaviour. + */ + private function onClaimLost(IdempotencyOptions $idempotency, string $key): Outcome + { + $store = $idempotency->store; + + if ($store instanceof CompletionAwareIdempotencyStore && ! $store->isCompleted($key)) { + return Outcome::release('in_flight', $idempotency->inFlightDelaySeconds); + } + + return Outcome::drop('duplicate'); + } + private function onUnknownUrn(ReceivedMessage $message): Outcome { return match ($this->unknownUrnStrategy) { diff --git a/src/Consumer/IdempotencyOptions.php b/src/Consumer/IdempotencyOptions.php index 2ab1782..dcb75ea 100644 --- a/src/Consumer/IdempotencyOptions.php +++ b/src/Consumer/IdempotencyOptions.php @@ -45,6 +45,12 @@ final class IdempotencyOptions * may be reclaimed should the worker die mid-handler. * @param (callable(ReceivedMessage): ?string)|null $keyResolver Optional * custom key derivation; return null/'' to fall back to meta.id/trace_id. + * @param int $inFlightDelaySeconds When a redelivery finds its key claimed + * by a handler that has not finished (and the store is a + * {@see \InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore}), the + * message is put back and not offered again for this many seconds. + * The redelivery consumes no attempt, so this only paces the checks; + * it must be at least 1 so a waiting message cannot spin. * * @throws ConfigurationException When a numeric option is out of range. */ @@ -54,6 +60,7 @@ public function __construct( public readonly ?int $ttl = 86_400, public readonly int $leaseSeconds = 300, ?callable $keyResolver = null, + public readonly int $inFlightDelaySeconds = 5, ) { if ($ttl !== null && $ttl < 0) { throw new ConfigurationException('Idempotency ttl must be null or zero/positive.'); @@ -63,6 +70,10 @@ public function __construct( throw new ConfigurationException('Idempotency leaseSeconds must be zero or positive.'); } + if ($inFlightDelaySeconds < 1) { + throw new ConfigurationException('Idempotency inFlightDelaySeconds must be at least 1.'); + } + $this->keyResolver = $keyResolver !== null ? $keyResolver(...) : null; } diff --git a/src/Consumer/InMemoryIdempotencyStore.php b/src/Consumer/InMemoryIdempotencyStore.php index 8f3ee02..6263ca7 100644 --- a/src/Consumer/InMemoryIdempotencyStore.php +++ b/src/Consumer/InMemoryIdempotencyStore.php @@ -4,28 +4,30 @@ namespace InitPHP\Queue\Consumer; -use InitPHP\Queue\Contracts\IdempotencyStore; +use InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore; /** - * The bundled reference {@see IdempotencyStore}: an in-process array of seen + * The bundled reference {@see \InitPHP\Queue\Contracts\IdempotencyStore}: an in-process array of seen * keys with monotonic-clock expiry. * * It is correct for a **single-process** worker — it makes a redelivered * message processed at most once for as long as the process lives — and is the * store the test-suite drives. It is **not** shared across processes and does * not survive a restart, so it cannot dedupe across the whole fleet: for that, - * back {@see IdempotencyStore} with Redis, a database table or `initphp/cache`. + * back {@see \InitPHP\Queue\Contracts\IdempotencyStore} with Redis, a database table or `initphp/cache`. * See the README "Idempotent consumption" section for the BYO pattern. * * Expiry uses {@see hrtime()} (a monotonic clock) so it is immune to wall-clock * jumps; a null expiry means "remembered forever". */ -final class InMemoryIdempotencyStore implements IdempotencyStore +final class InMemoryIdempotencyStore implements CompletionAwareIdempotencyStore { /** - * key => expiry in nanoseconds on the monotonic clock, or null for never. + * key => entry. `expiry` is nanoseconds on the monotonic clock, or null for + * never; `completed` is true once the key was recorded with remember() and + * false while it is only an in-flight claim. * - * @var array + * @var array */ private array $entries = []; @@ -37,7 +39,7 @@ public function seen(string $key): bool return false; } - $expiry = $this->entries[$key]; + $expiry = $this->entries[$key]['expiry']; if ($expiry !== null && hrtime(true) >= $expiry) { unset($this->entries[$key]); @@ -55,14 +57,22 @@ public function claim(string $key, int $leaseSeconds = 0): bool // Hold the claim under a short lease so a crash mid-handler frees it for // the redelivery, rather than blocking the key forever. - $this->entries[$key] = $this->expiryFor($leaseSeconds > 0 ? $leaseSeconds : null); + $this->entries[$key] = [ + 'expiry' => $this->expiryFor($leaseSeconds > 0 ? $leaseSeconds : null), + 'completed' => false, + ]; return true; } + public function isCompleted(string $key): bool + { + return $this->seen($key) && $this->entries[$key]['completed']; + } + public function remember(string $key, ?int $ttl = null): void { - $this->entries[$key] = $this->expiryFor($ttl); + $this->entries[$key] = ['expiry' => $this->expiryFor($ttl), 'completed' => true]; } public function forget(string $key): void diff --git a/src/Consumer/Outcome.php b/src/Consumer/Outcome.php index bade6c7..c019296 100644 --- a/src/Consumer/Outcome.php +++ b/src/Consumer/Outcome.php @@ -22,6 +22,7 @@ private function __construct( public readonly OutcomeKind $kind, public readonly string $reason = '', public readonly ?Throwable $exception = null, + public readonly int $delaySeconds = 0, ) {} /** Handled successfully. */ @@ -48,9 +49,13 @@ public static function drop(string $reason): self return new self(OutcomeKind::Drop, $reason); } - /** Put back verbatim, no attempt counted. */ - public static function release(string $reason): self + /** + * Put back verbatim, no attempt counted. A positive `$delaySeconds` keeps the + * message from becoming reservable again until it has elapsed (best-effort on + * transports without native delay support). + */ + public static function release(string $reason, int $delaySeconds = 0): self { - return new self(OutcomeKind::Release, $reason); + return new self(OutcomeKind::Release, $reason, null, max(0, $delaySeconds)); } } diff --git a/src/Consumer/Worker.php b/src/Consumer/Worker.php index 631160c..bde958b 100644 --- a/src/Consumer/Worker.php +++ b/src/Consumer/Worker.php @@ -150,8 +150,18 @@ private function process(ReceivedMessage $message): void break; case OutcomeKind::Release: - $this->transport->release($message, $message->rawBody(), 0); - $this->log('notice', 'job.released', $this->context($message, ['reason' => $outcome->reason])); + $this->transport->release($message, $message->rawBody(), $outcome->delaySeconds); + $this->log('notice', 'job.released', $this->context($message, [ + 'reason' => $outcome->reason, + ...($outcome->delaySeconds > 0 ? ['delay' => $outcome->delaySeconds] : []), + ])); + + // A delayed release is a message that is waiting on something else. + // Transports without native delay (RabbitMQ) hand it straight back, + // so pause briefly rather than reserving it again in a tight loop. + if ($outcome->delaySeconds > 0) { + $this->sleep($this->options->sleepWhenEmpty); + } break; diff --git a/src/Contracts/CompletionAwareIdempotencyStore.php b/src/Contracts/CompletionAwareIdempotencyStore.php new file mode 100644 index 0000000..55a2c6f --- /dev/null +++ b/src/Contracts/CompletionAwareIdempotencyStore.php @@ -0,0 +1,38 @@ +`), a database row, or the * `initphp/cache` PSR-16 pool. Bring your own by implementing this interface - * over that backend; the {@see \InitPHP\Queue\Consumer\Dispatcher} only ever - * calls {@see claim()} and {@see remember()}. + * over that backend. The {@see \InitPHP\Queue\Consumer\Dispatcher} calls + * {@see claim()} before a handler, then {@see remember()} when it succeeds or + * {@see forget()} when it throws. + * + * To let the dispatcher tell a *finished* message from one another worker is + * still handling (and so not discard the latter), implement + * {@see CompletionAwareIdempotencyStore} as well. A store that only implements + * this interface keeps the original behaviour: any failed claim is treated as + * an already-processed duplicate. * * Contract — the dedup lifecycle the dispatcher relies on: * * 1. Before running a handler the dispatcher calls {@see claim()}. If it * returns `false` the key is already known (processed, or in flight on - * another worker) and the handler is skipped. - * 2. The handler runs. If it **throws**, the key must remain *unremembered* - * so the redelivery is retryable — implementations that mark a key inside - * {@see claim()} must therefore give it only a short in-flight lease, not a - * permanent record. + * another worker) and the handler is skipped. A processed key is + * acknowledged and discarded; an in-flight key is discarded too unless the + * store is a {@see CompletionAwareIdempotencyStore}, in which case the + * message is put back on the queue to be retried later. + * 2. The handler runs. If it **throws**, the dispatcher calls {@see forget()} + * to release the claim so the redelivery is retryable — implementations + * that mark a key inside {@see claim()} must also give it only a short + * in-flight lease, not a permanent record, in case the worker dies instead. * 3. On success the dispatcher calls {@see remember()} to record the key * permanently (for `$ttl` seconds, or forever when `$ttl` is null). * @@ -75,8 +85,8 @@ public function remember(string $key, ?int $ttl = null): void; /** * Drop any record (processed or in-flight) for `$key`, making it - * processable again. Primarily for tests and operational reset; the - * dispatcher never calls it. + * processable again. The dispatcher calls it to release the in-flight claim + * when a handler throws; it is also the operational reset for a key. */ public function forget(string $key): void; } diff --git a/tests/Consumer/InFlightRedeliveryTest.php b/tests/Consumer/InFlightRedeliveryTest.php new file mode 100644 index 0000000..f97f449 --- /dev/null +++ b/tests/Consumer/InFlightRedeliveryTest.php @@ -0,0 +1,257 @@ + 1], 'orders'); + $envelope['meta']['id'] = $id; + $envelope['attempts'] = $attempts; + + return new ReceivedMessage('orders', EnvelopeCodec::encode($envelope), $envelope, 1); + } + + private function payload(string $id): string + { + $envelope = EnvelopeCodec::make(self::URN, ['order_id' => 1], 'orders'); + $envelope['meta']['id'] = $id; + + return EnvelopeCodec::encode($envelope); + } + + private function dispatcher(RecordingHandler $handler, IdempotencyStore $store, int $delay = 5): Dispatcher + { + return new Dispatcher( + (new HandlerMap())->register(self::URN, $handler), + idempotency: new IdempotencyOptions($store, inFlightDelaySeconds: $delay), + ); + } + + public function test_a_redelivery_of_an_in_flight_key_is_released_not_dropped(): void + { + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); // another worker is inside the handler + $handler = new RecordingHandler(); + + $outcome = $this->dispatcher($handler, $store, delay: 7)->dispatch($this->messageWithId('msg-1')); + + self::assertSame(OutcomeKind::Release, $outcome->kind); + self::assertSame('in_flight', $outcome->reason); + self::assertSame(7, $outcome->delaySeconds); + self::assertSame([], $handler->handled, 'the handler must not run while another worker holds the claim'); + } + + public function test_a_redelivery_of_a_completed_key_is_still_dropped(): void + { + $store = new InMemoryIdempotencyStore(); + $store->remember(self::KEY); + + $outcome = $this->dispatcher(new RecordingHandler(), $store)->dispatch($this->messageWithId('msg-1')); + + self::assertSame(OutcomeKind::Drop, $outcome->kind); + self::assertSame('duplicate', $outcome->reason); + } + + public function test_a_store_that_cannot_tell_in_flight_from_completed_keeps_the_old_behaviour(): void + { + $store = new ClaimOnlyIdempotencyStore(); + $store->claim(self::KEY, 300); + + $outcome = $this->dispatcher(new RecordingHandler(), $store)->dispatch($this->messageWithId('msg-1')); + + self::assertSame(OutcomeKind::Drop, $outcome->kind, 'a pre-2.3 store is treated as before'); + self::assertSame('duplicate', $outcome->reason); + } + + public function test_an_in_flight_message_runs_once_the_claim_is_released(): void + { + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $handler = new RecordingHandler(); + $dispatcher = $this->dispatcher($handler, $store); + + self::assertSame(OutcomeKind::Release, $dispatcher->dispatch($this->messageWithId('msg-1'))->kind); + + $store->forget(self::KEY); // the first worker failed, or its lease lapsed + + self::assertSame(OutcomeKind::Ack, $dispatcher->dispatch($this->messageWithId('msg-1'))->kind); + self::assertCount(1, $handler->handled); + } + + public function test_an_in_flight_message_is_dropped_once_the_other_handler_records_it(): void + { + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $handler = new RecordingHandler(); + $dispatcher = $this->dispatcher($handler, $store); + + self::assertSame(OutcomeKind::Release, $dispatcher->dispatch($this->messageWithId('msg-1'))->kind); + + $store->remember(self::KEY); // the first worker finished + + self::assertSame(OutcomeKind::Drop, $dispatcher->dispatch($this->messageWithId('msg-1'))->kind); + self::assertSame([], $handler->handled, 'the handler already ran on the other worker'); + } + + public function test_waiting_on_an_in_flight_key_never_consumes_an_attempt(): void + { + // Path 1: the first worker died inside the handler and its claim is still held. + $transport = new ArrayTransport(); + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $handler = new RecordingHandler(); + $events = []; + $worker = new Worker( + $transport, + $this->dispatcher($handler, $store), + new WorkerOptions(maxAttempts: 1, sleepWhenEmpty: 0.0), + function (string $level, string $event, array $context) use (&$events): void { + $events[] = [$event, $context['reason'] ?? null, $context['delay'] ?? null]; + }, + ); + + $transport->publish($this->payload('msg-1'), 'orders'); + + for ($i = 0; $i < 20; ++$i) { + $worker->runOnce('orders'); + } + + self::assertSame(1, $transport->readyCount('orders'), 'the message is still queued'); + self::assertSame(0, $transport->deadCount('orders'), 'waiting must not dead-letter it, even with maxAttempts 1'); + self::assertCount(20, $transport->releases); + self::assertSame([['job.released', 'in_flight', 5]], array_slice($events, 0, 1)); + + foreach ($transport->releases as $release) { + self::assertSame(5, $release['delay'], 'a waiting message is paced, not re-offered at once'); + self::assertSame(0, EnvelopeCodec::decode($release['payload'])['attempts']); + } + + // The lease lapses (modelled by forgetting the key): the message is processed. + $store->forget(self::KEY); + $worker->runOnce('orders'); + + self::assertCount(1, $handler->handled, 'the message that the dead worker never completed is handled'); + self::assertSame(0, $transport->readyCount('orders')); + self::assertSame(0, $transport->reservedCount()); + } + + public function test_a_released_in_flight_message_does_not_spin(): void + { + $transport = new ArrayTransport(); + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $worker = new Worker( + $transport, + $this->dispatcher(new RecordingHandler(), $store), + new WorkerOptions(sleepWhenEmpty: 0.2), + ); + $transport->publish($this->payload('msg-1'), 'orders'); + + $startedAt = microtime(true); + $worker->runOnce('orders'); + + self::assertGreaterThanOrEqual(0.15, microtime(true) - $startedAt, 'the worker pauses after deferring a message'); + } + + public function test_the_failed_handler_keeps_its_retry_when_a_redelivery_arrives_meanwhile(): void + { + // Path 2: the first handler is slow; the transport hands the message to a + // second worker while it still runs; then the first handler throws. + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $transport = new \InitPHP\Queue\Transport\Pdo\PdoTransport($pdo, 'jobs', null, 'default', 0); // retryAfter 0: a reservation is at once reclaimable + $transport->createSchema(); + $transport->publish($this->payload('msg-1'), 'orders'); + + $store = new InMemoryIdempotencyStore(); + $options = new IdempotencyOptions($store, inFlightDelaySeconds: 5); + $workerOptions = new WorkerOptions(maxAttempts: 3, backoff: [30], sleepWhenEmpty: 0.0); + $secondWorker = null; + $secondWorkerRan = false; + + $handlers = (new HandlerMap())->register(self::URN, function (InboundMessage $message) use (&$secondWorker, &$secondWorkerRan): void { + $secondWorkerRan = $secondWorker->runOnce('orders'); // the redelivery, while we are still in the handler + + throw new RuntimeException('downstream failed'); + }); + $firstWorker = new Worker($transport, new Dispatcher($handlers, idempotency: $options), $workerOptions); + $secondWorker = new Worker($transport, new Dispatcher($handlers, idempotency: $options), $workerOptions); + + $firstWorker->runOnce('orders'); + + self::assertTrue($secondWorkerRan, 'the redelivery was reserved by a second worker'); + + $row = $pdo->query('SELECT attempts FROM jobs')->fetchAll(PDO::FETCH_ASSOC); + self::assertCount(1, $row, 'the message still has a row: neither a retry nor a dead letter was lost'); + self::assertSame(1, (int) $row[0]['attempts'], 'the failed attempt is counted'); + self::assertSame(0, (int) $pdo->query('SELECT COUNT(*) FROM jobs_failed')->fetchColumn()); + self::assertFalse($store->seen(self::KEY), 'the failed handler released its claim'); + } + + public function test_an_in_flight_message_on_a_real_pdo_queue_survives_until_the_claim_lapses(): void + { + // Path 1 end to end: a dead worker's claim is held while the redelivery arrives. + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $transport = new \InitPHP\Queue\Transport\Pdo\PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload('msg-1'), 'orders'); + + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $handler = new RecordingHandler(); + $worker = new Worker($transport, $this->dispatcher($handler, $store), new WorkerOptions(sleepWhenEmpty: 0.0)); + + $worker->runOnce('orders'); + + self::assertSame(1, (int) $pdo->query('SELECT COUNT(*) FROM jobs')->fetchColumn(), 'the row survives the redelivery'); + self::assertSame([], $handler->handled); + + $store->forget(self::KEY); + $pdo->exec("UPDATE jobs SET available_at = '2000-01-01 00:00:00'"); // the delay has passed + $worker->runOnce('orders'); + + self::assertCount(1, $handler->handled); + self::assertSame(0, (int) $pdo->query('SELECT COUNT(*) FROM jobs')->fetchColumn()); + } + + public function test_the_in_flight_delay_must_be_at_least_one_second(): void + { + $this->expectException(ConfigurationException::class); + + new IdempotencyOptions(new InMemoryIdempotencyStore(), inFlightDelaySeconds: 0); + } +} diff --git a/tests/Consumer/InMemoryIdempotencyStoreTest.php b/tests/Consumer/InMemoryIdempotencyStoreTest.php index cb9c949..b43c676 100644 --- a/tests/Consumer/InMemoryIdempotencyStoreTest.php +++ b/tests/Consumer/InMemoryIdempotencyStoreTest.php @@ -65,4 +65,33 @@ public function test_a_zero_ttl_claim_is_held_until_remembered_or_forgotten(): v self::assertTrue($store->claim('k', 0)); self::assertTrue($store->seen('k')); } + + public function test_is_completed_tells_a_recorded_key_from_an_in_flight_claim(): void + { + $store = new InMemoryIdempotencyStore(); + + self::assertFalse($store->isCompleted('k'), 'unknown'); + + $store->claim('k', 300); + self::assertTrue($store->seen('k')); + self::assertFalse($store->isCompleted('k'), 'a claim is in flight, not completed'); + + $store->remember('k'); + self::assertTrue($store->isCompleted('k')); + + $store->forget('k'); + self::assertFalse($store->isCompleted('k')); + } + + public function test_an_expired_record_is_no_longer_completed(): void + { + $store = new InMemoryIdempotencyStore(); + $store->remember('k', 1); + + self::assertTrue($store->isCompleted('k')); + + usleep(1_100_000); + + self::assertFalse($store->isCompleted('k')); + } } diff --git a/tests/Support/ClaimOnlyIdempotencyStore.php b/tests/Support/ClaimOnlyIdempotencyStore.php new file mode 100644 index 0000000..3b17713 --- /dev/null +++ b/tests/Support/ClaimOnlyIdempotencyStore.php @@ -0,0 +1,42 @@ +inner = new InMemoryIdempotencyStore(); + } + + public function seen(string $key): bool + { + return $this->inner->seen($key); + } + + public function claim(string $key, int $leaseSeconds = 0): bool + { + return $this->inner->claim($key, $leaseSeconds); + } + + public function remember(string $key, ?int $ttl = null): void + { + $this->inner->remember($key, $ttl); + } + + public function forget(string $key): void + { + $this->inner->forget($key); + } +} From c7cfb23f688cc583b2ab009e95f6baa15a1dc440 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 09:40:46 +0300 Subject: [PATCH 2/6] fix(transport): make deferring a message safe on RabbitMQ, Redis and PDO Putting a message back to wait for another handler's in-flight key ran through transport steps that could lose or fork it. - AmqpTransport: publish the new copy (waiting for the broker confirm when the channel is in confirm mode) before acking the original, for both release() and deadLetter(). A crash in between leaves a duplicate the dispatcher recognises instead of nothing, and a failed publish leaves the original unacked. nack(requeue) was rejected: it would put the waiting message back at the head and block the queue behind it. - RedisTransport: release(), deadLetter() and the delayed-set migration are Lua scripts, atomic, and act only when the worker's LREM removed its own processing entry, so a worker whose message a reaper already reclaimed no longer forks it into two copies. - PdoTransport: release() updates only a row still held with the reservation stamp it wrote, and a message put back unchanged no longer rewrites payload or attempts. - Worker: a deferral is not counted towards maxJobs or processedCount(), and pauses at least 0.1s even with sleepWhenEmpty 0. Docs: the PDO store recipe resets completed on takeover, rolling-upgrade notes, the reaper requirements on Redis, drain and maxJobs behaviour, and the API reference for the idempotency types. Tests cover AMQP and Redis with fixtures and against real brokers in the integration job. --- CHANGELOG.md | 22 ++++- README.md | 31 ++++-- docs/API-Reference.md | 47 +++++++++ docs/Idempotent-Consumption.md | 84 ++++++++++++---- docs/The-Worker.md | 14 ++- docs/Transport-PDO.md | 11 +++ docs/Transport-RabbitMQ.md | 24 ++++- docs/Transport-Redis.md | 35 ++++++- src/Consumer/IdempotencyOptions.php | 3 +- src/Consumer/Worker.php | 36 +++++-- src/Transport/Amqp/AmqpTransport.php | 31 +++++- src/Transport/Pdo/PdoTransport.php | 48 +++++++-- src/Transport/Redis/RedisTransport.php | 107 ++++++++++++++++----- tests/Consumer/InFlightRedeliveryTest.php | 102 +++++++++++++++++++- tests/Integration/AmqpIntegrationTest.php | 77 +++++++++++++++ tests/Integration/RedisIntegrationTest.php | 92 ++++++++++++++++++ tests/Support/InMemoryRedis.php | 48 ++++++++- tests/Transport/AmqpTransportTest.php | 41 ++++++-- tests/Transport/RedisTransportTest.php | 91 ++++++++++++++++++ 19 files changed, 845 insertions(+), 99 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5efa8b7..c999469 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,9 +30,25 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). released back to the queue (`job.released`, reason `in_flight`) without counting an attempt, so it never moves towards the dead-letter queue by waiting, and it is re-checked after `inFlightDelaySeconds`. A recorded (completed) duplicate is - still dropped. The `Worker` pauses for `sleepWhenEmpty` after a delayed release so - that RabbitMQ, which has no native delay, does not reserve the message again in a - tight loop. + still dropped. After a delayed release the `Worker` pauses for `sleepWhenEmpty` + (at least 0.1 s) so that RabbitMQ, which has no native delay, does not reserve + the message again in a tight loop. +- `RedisTransport::release()`, `deadLetter()` and the delayed-set migration are + single Lua scripts. They act only while the worker still owns the message (its + `LREM` removed one processing entry), so a release or dead-letter from a worker + whose message a reaper already moved back no longer forks it into two copies, and + a crash cannot leave a message on no list. Redis 6.2+ already required Lua. +- `AmqpTransport::release()` and `deadLetter()` publish the new copy (waiting for + the broker's confirm when the channel is in confirm mode) **before** acking the + original, so a crash between the two leaves a duplicate instead of losing the + message, and a failed publish leaves the original unacked. +- `PdoTransport::release()` updates only a row still held with the reservation + stamp it wrote, and a message put back unchanged no longer rewrites `payload` + or `attempts`, so a worker whose reservation was taken over cannot overwrite + another worker's recorded retry or back-off. +- A message deferred to wait for an in-flight key no longer counts towards + `maxJobs` or `processedCount()`, and the worker pauses at least 0.1 s after a + deferral even with `sleepWhenEmpty: 0`. - Wrong docblocks: `IdempotencyStore::forget()` is called by the dispatcher when a handler throws, and the contract's description now lists `forget()`. diff --git a/README.md b/README.md index c0f393d..6d6ebeb 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,14 @@ without counting an attempt, and looked at again after `inFlightDelaySeconds` (default 5). It ends when the other handler records the key (the message is then dropped), when that handler fails and releases the claim, or when a dead worker's lease lapses (the handler then runs). Waiting never moves a message towards the -dead-letter queue, and it is paced rather than a tight loop. +dead-letter queue, and it is paced rather than a tight loop: the message is held +back for `inFlightDelaySeconds` and the worker pauses for `sleepWhenEmpty` (at +least 0.1 s) after each deferral. A deferral is not counted as processing, so it +does not use up `maxJobs`; on RabbitMQ a `stopWhenEmpty` (drain) worker stays +until the other handler finishes or its lease lapses. Each transport puts the +message back without a step that could lose it: PDO in one `UPDATE`, RabbitMQ by +publishing the copy before acking the original (a crash in between leaves a +duplicate, never a gap), Redis in one Lua script. This needs a store that implements `CompletionAwareIdempotencyStore` (`InMemoryIdempotencyStore` does). A store that implements only `IdempotencyStore` @@ -218,10 +225,18 @@ is discarded. then wins the claim. 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. +5. **On Redis a reaper has to count its reclaims.** A message the reaper has moved + back onto the queue is no longer the original worker's, so that worker's later + failure is ignored. Have the reaper increment `attempts` and keep its delay + above your slowest handler. Set `leaseSeconds` **above your slowest handler**, and as short as that allows: it is how long a dead worker's message waits before it is handled again. The -per-transport table and the upgrade notes for 2.1/2.2 are in the +per-transport table and the upgrade notes for 2.1/2.2 (drain the old workers +first) are in the [full guide](docs/Idempotent-Consumption.md#choosing-leaseseconds). ### Message keys @@ -321,14 +336,16 @@ if its lease has lapsed (`DELETE FROM idempotency WHERE dedup_key = ? AND expire then `INSERT` it with `expires_at = now + leaseSeconds` and report `true` only when the insert affected a row (a unique-key violation means `false`). The same effect in one statement is `INSERT … ON CONFLICT (dedup_key) DO UPDATE SET expires_at = -excluded.expires_at WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), +excluded.expires_at, completed = 0 WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), again checking the affected-row count. `remember()` upserts the row with `expires_at = now + ttl` (or `NULL` to keep it) and marks it completed, `forget()` deletes it, and `seen()` ignores rows whose `expires_at` has passed. For -`isCompleted()` add a `completed` flag column: `claim()` inserts it as `0`, -`remember()` sets it to `1`, and `isCompleted()` returns true for a live row whose -flag is `1`. Give the column a default of `1`, so rows written before you added it -read as completed. +`isCompleted()` add a `completed` flag column: `claim()` sets it to `0`, **also when +it takes over a lapsed row** (the one-statement form needs `completed = 0` in its +`DO UPDATE SET` list: a takeover that keeps the old `1` makes the next redelivery +look completed and drops the message), `remember()` sets it to +`1`, and `isCompleted()` returns true for a live row whose flag is `1`. Give the +column a default of `1`, so rows written before you added it read as completed. Full guide: [docs/Idempotent-Consumption.md](docs/Idempotent-Consumption.md). diff --git a/docs/API-Reference.md b/docs/API-Reference.md index 71c781f..41d9a54 100644 --- a/docs/API-Reference.md +++ b/docs/API-Reference.md @@ -92,6 +92,27 @@ public function dispatch(InitPHP\Queue\Message\ReceivedMessage $message): InitPH An unknown strategy string throws `ConfigurationException`. +### IdempotencyOptions / InMemoryIdempotencyStore + +`InitPHP\Queue\Consumer\IdempotencyOptions` (immutable), passed to +`Dispatcher`'s `idempotency:` argument: + +```php +public function __construct( + InitPHP\Queue\Contracts\IdempotencyStore $store, + string $keyPrefix = 'bq:idemp:', + ?int $ttl = 86_400, // seconds a processed key is kept (null = forever) + int $leaseSeconds = 300, // in-flight claim lease + ?callable $keyResolver = null, // fn (ReceivedMessage): ?string + int $inFlightDelaySeconds = 5, // wait before re-checking a key another handler holds (>= 1) +) +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`. + ### Outcome / OutcomeKind `InitPHP\Queue\Consumer\Outcome` — the dispatcher's decision (immutable). @@ -166,6 +187,32 @@ interface HandlerResolver } ``` +### IdempotencyStore + +```php +interface IdempotencyStore +{ + public function seen(string $key): bool; + public function claim(string $key, int $leaseSeconds = 0): bool; + public function remember(string $key, ?int $ttl = null): void; + public function forget(string $key): void; +} +``` + +### CompletionAwareIdempotencyStore + +```php +interface CompletionAwareIdempotencyStore extends IdempotencyStore +{ + public function isCompleted(string $key): bool; // recorded with remember(), still live +} +``` + +Lets the `Dispatcher` tell a recorded key from one another handler still holds: a +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). + ### ConsumerTransport ```php diff --git a/docs/Idempotent-Consumption.md b/docs/Idempotent-Consumption.md index 66e70a7..8862ba8 100644 --- a/docs/Idempotent-Consumption.md +++ b/docs/Idempotent-Consumption.md @@ -52,9 +52,27 @@ A waiting message consumes **no retry attempt**: it is released verbatim, with `attempts` unchanged, so it is never moved to the dead-letter queue merely for waiting, and the worker's `maxAttempts` and `backoff` apply only to real failures. It is not a tight loop either: the message is paced by `inFlightDelaySeconds` -(honoured natively by PDO and Redis), and the worker pauses for `sleepWhenEmpty` -after each deferral, which keeps RabbitMQ (which has no native delay) from -reserving the same message again at once. +(honoured natively by PDO and Redis), and after each deferral the worker pauses +for `sleepWhenEmpty`, but never less than 0.1 s, so RabbitMQ (which has no native +delay and hands the message straight back) is not spun on even with +`sleepWhenEmpty: 0`. On PDO and Redis that pause is the price of a deferral for +the messages queued behind it. + +A deferral is not processing: the worker does not count it towards `maxJobs` or +`processedCount()`. Two consequences follow. A worker run with `stopWhenEmpty: true` +(drain mode) keeps going while a waiting message is still handed back at once, which +on RabbitMQ is until the other handler finishes or its lease lapses, and for good +if the claim has no lease; on PDO and Redis the waiting message is parked with its +delay, so the queue counts as empty and the worker exits. And `maxJobs` is not used +up by waiting, so a worker whose only message is waiting does not restart over and +over. + +How the message is put back is the transport's job, and it is done so that no +step can lose it: PDO is one `UPDATE` of the row, RabbitMQ **publishes the copy +before it acks the original** (a crash in between leaves a duplicate, which this +layer recognises, never a missing message), and Redis does the move in one Lua +script. See [Transport: RabbitMQ](Transport-RabbitMQ.md#why-retries-republish) and +[Transport: Redis](Transport-Redis.md#retry-with-delay). This needs a store that can tell a recorded key from a claimed one: one that implements `InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore` @@ -64,9 +82,11 @@ behaviour: every failed claim is treated as a recorded duplicate and discarded. ## What deduplication does not guarantee -A message is no longer lost because its first handler failed or its worker died; -these remain. Reproduced against a real `PdoTransport`, a shared store with a -lease, and worker processes killed with `SIGKILL`. +A message is no longer lost because its first handler failed or its worker died +(the two loss paths were reproduced against a real `PdoTransport`, a shared store +with a lease, and worker processes killed with `SIGKILL`, and no longer occur); +these remain. Items 3 to 6 follow from how the lease and the transports work and +were not run as separate scenarios. 1. **A handler can still run twice.** A worker finishes the handler and dies before `remember()`. The key is not recorded, so once the lease lapses the redelivery runs the @@ -74,7 +94,8 @@ lease, and worker processes killed with `SIGKILL`. 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. + the same message concurrently. When the first handler then throws, its + `forget()` also frees the newer claim, because a claim carries no owner. 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 @@ -82,6 +103,21 @@ lease, and worker processes killed with `SIGKILL`. `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. +6. **On Redis, a reaper has to count its reclaims.** Redis never redelivers a + message by itself; a reaper moves it from `:processing` back onto the + queue. If the original handler is still running (slower than the reaper's + delay), its eventual failure is ignored, because the message is no longer + its own (see [Transport: Redis](Transport-Redis.md#delivery-semantics)). The + retry then has to come from the reclaimed copy, so have the reaper increment + `attempts` in the envelope it moves back, and keep its delay above your slowest + handler: otherwise a handler that always runs longer than the reaper and always + fails is never counted against `maxAttempts`. ### Choosing `leaseSeconds` @@ -95,8 +131,8 @@ being discarded. | Transport | When a dead worker's message comes back | Effect of the lease | | --- | --- | --- | | PDO | after `retryAfter` (default 90 s) | the redelivery is released and re-checked every `inFlightDelaySeconds` until the lease lapses, then handled | -| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | the same: it waits until the lease lapses | -| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | the same, re-checked about every `sleepWhenEmpty` seconds, because RabbitMQ has no native delay | +| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | the same: it waits until the lease lapses; keep the reaper's delay above your slowest handler and have it count each reclaim as an attempt | +| RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | the same, re-checked about every `sleepWhenEmpty` seconds (at least 0.1 s), because RabbitMQ has no native delay | `leaseSeconds: 0` is not "no lease": the bundled `InMemoryIdempotencyStore` and the Redis store below then hold the claim with no expiry, so a dead worker's claim @@ -116,12 +152,18 @@ Nothing has to change: `IdempotencyStore`, its method signatures and the - **Records written by 2.1/2.2 in a durable store** do not distinguish a claim from a recorded key (both were a plain row or a `1`). When you add `isCompleted()`, treat such a legacy record as **completed**. That is what 2.2 did, so every - message deduped before the upgrade is still deduped. The only exposure is a - claim held by a handler that was already running during the upgrade: its - redelivery is discarded as before until that lease lapses, which is at most - `leaseSeconds` (default 300 s), after which new claims are the in-flight kind. - Messages that need no care across the upgrade can be left alone; to be exact, - drain the workers before deploying. + message deduped before the upgrade is still deduped. +- **Roll the upgrade out by draining first.** Stop every worker that runs 2.1/2.2 + before the first 2.3 worker starts, and deploy the new store schema or value + format before it. While both versions run, the old workers still discard any + message whose claim they cannot get, including a claim the new workers hold + with the new in-flight marker, so a new worker that dies mid-handler can lose + its message to an old one. They also keep writing legacy claim records, which + the new `isCompleted()` reads as completed, so a redelivery meant to wait is + discarded instead. The exposure lasts until the last 2.2 worker has stopped, and + then for as long as the longest lease still on record: `leaseSeconds` (default + 300 s), or forever for a claim written with `leaseSeconds: 0`, which you clear + with `forget()`. - **`InMemoryIdempotencyStore`** keeps nothing across a restart, so it has no legacy records. - **`Outcome::release()`** takes an optional second argument, `$delaySeconds`, and @@ -238,14 +280,16 @@ if its lease has lapsed (`DELETE FROM idempotency WHERE dedup_key = ? AND expire then `INSERT` it with `expires_at = now + leaseSeconds` and report `true` only when the insert affected a row (a unique-key violation means `false`). The same effect in one statement is `INSERT … ON CONFLICT (dedup_key) DO UPDATE SET expires_at = -excluded.expires_at WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), +excluded.expires_at, completed = 0 WHERE idempotency.expires_at <= ?` (SQLite and PostgreSQL), again checking the affected-row count. `remember()` upserts the row with `expires_at = now + ttl` (or `NULL` to keep it) and marks it completed, `forget()` deletes it, and `seen()` ignores rows whose `expires_at` has passed. For -`isCompleted()` add a `completed` flag column: `claim()` inserts it as `0`, -`remember()` sets it to `1`, and `isCompleted()` returns true for a live row whose -flag is `1`. Give the column a default of `1`, so rows written before you added it -read as completed. +`isCompleted()` add a `completed` flag column: `claim()` sets it to `0`, **also when +it takes over a lapsed row** (the one-statement form needs `completed = 0` in its +`DO UPDATE SET` list: a takeover that keeps the old `1` makes the next redelivery +look completed and drops the message), `remember()` sets it to +`1`, and `isCompleted()` returns true for a live row whose flag is `1`. Give the +column a default of `1`, so rows written before you added it read as completed. See also [Retries & Dead-Letters](Retries-and-Dead-Letters.md) and [Core Concepts › Delivery guarantee](Core-Concepts.md#delivery-guarantee). diff --git a/docs/The-Worker.md b/docs/The-Worker.md index be7630b..829d584 100644 --- a/docs/The-Worker.md +++ b/docs/The-Worker.md @@ -43,7 +43,7 @@ new WorkerOptions( maxAttempts: 3, // total delivery attempts before dead-lettering (>= 1) backoff: [0], // per-attempt delay in seconds; the last value repeats reserveTimeout: 5.0, // seconds a blocking transport waits for a message - sleepWhenEmpty: 0.5, // seconds to sleep when the queue is empty + sleepWhenEmpty: 0.5, // seconds to sleep when the queue is empty (also after a deferral) maxJobs: 0, // stop after N messages (0 = unlimited) maxRuntime: 0.0, // stop after N seconds (0 = unlimited) memoryLimitMb: 0, // stop once memory reaches N MB (0 = unlimited) @@ -61,6 +61,12 @@ negative back-off, or a negative limit throws `ConfigurationException`. - **Polling transports** (PDO, RabbitMQ `basic_get`) return immediately when the queue is empty; the worker then sleeps for `sleepWhenEmpty`. Tune that for your latency/load trade-off. +- **A deferred message** — put back with a delay because, with + [deduplication](Idempotent-Consumption.md) on, another handler still holds its + key — also makes the worker sleep for `sleepWhenEmpty`, but at least 0.1 s, so a + transport that ignores the delay (RabbitMQ) is not spun on even with + `sleepWhenEmpty: 0`. A deferral does not count towards `maxJobs` or + `processedCount()`. ### Stopping cleanly @@ -72,7 +78,11 @@ new WorkerOptions(maxJobs: 1000, memoryLimitMb: 128); This is the standard pattern for long-running PHP — the process exits on its own terms and a fresh one starts with clean memory. `stopWhenEmpty: true` instead -drains the queue and returns (useful for batch jobs and tests). +drains the queue and returns (useful for batch jobs and tests). With deduplication +on, a message waiting for another handler's key is not "empty" on RabbitMQ, which +hands it straight back: a drain worker stays until that handler finishes or its +lease lapses (for good if the claim never lapses). On PDO and Redis the waiting +message is parked with its delay and the drain ends. ### Graceful shutdown diff --git a/docs/Transport-PDO.md b/docs/Transport-PDO.md index 8bc3527..dc945f4 100644 --- a/docs/Transport-PDO.md +++ b/docs/Transport-PDO.md @@ -112,6 +112,17 @@ re-checked, not discarded, so the row survives until that claim is recorded, released or lapses. Keep `leaseSeconds` above your slowest handler — see [Idempotent Consumption](Idempotent-Consumption.md#choosing-leaseseconds). +### Releasing a row you no longer hold + +A worker whose reservation has lapsed and been taken over by another worker does +not overwrite the new holder's row. `release()` updates only a row whose +`reserved_at` still has the stamp this transport instance wrote when it reserved +it, or (for a retry that records a new `attempts` and back-off) one that has since +been released; and a message put back **unchanged** (waiting for another handler) +never rewrites `payload` or `attempts`, so it cannot undo a retry another worker has +just recorded. The stamp has one-second resolution, so with `retryAfter: 0` two +reservations within the same second look alike. + ## Lifecycle in SQL terms | Operation | Effect | diff --git a/docs/Transport-RabbitMQ.md b/docs/Transport-RabbitMQ.md index 4b13d10..7019d2d 100644 --- a/docs/Transport-RabbitMQ.md +++ b/docs/Transport-RabbitMQ.md @@ -52,16 +52,30 @@ auto_delete=false`); the body is the canonical envelope JSON. | `publish()` | Declare the queue, `basic_publish` the persistent envelope. | | `reserve()` | Declare the queue, then `basic_get` one message (pull). Returns `null` when empty. | | `ack()` | `basic_ack` on the delivery tag. | -| `release()` | `basic_ack` the original, then **republish** the updated envelope. | -| `deadLetter()` | `basic_ack` the original, then publish the annotated envelope to `.failed`. | +| `release()` | **Republish** the updated envelope, wait for the broker's confirm if the channel is in confirm mode, then `basic_ack` the original. | +| `deadLetter()` | Publish the annotated envelope to `.failed`, wait for the confirm likewise, then `basic_ack` the original. | ### Why retries republish RabbitMQ does not let you mutate a message body in place, and a plain `basic_nack(requeue=true)` would not persist the incremented `attempts` or the -`dead_letter` block. So a retry/dead-letter **acks the original delivery and -publishes a fresh message** carrying the updated envelope. This keeps `attempts` -and dead-letter annotations accurate across redeliveries. +`dead_letter` block. So a retry/dead-letter **publishes a fresh message** +carrying the updated envelope **and only then acks the original delivery**. This +keeps `attempts` and dead-letter annotations accurate across redeliveries. + +The order is deliberate. A worker that dies between the publish and the ack leaves +a duplicate, which RabbitMQ redelivers and the dispatcher's +[deduplication](Idempotent-Consumption.md) recognises; acking first would leave no +message at all. If the publish throws, the original is not acked and RabbitMQ +redelivers it. To also be safe against the broker not accepting the publish, put +the channel in publisher-confirm mode (`$channel->confirm_select()`): the transport +then waits (up to 30 s) for the confirm before it acks, and leaves the original +unacked if none arrives. Without confirm mode that wait returns at once. + +The same path puts back a message that is **waiting for another handler's +in-flight key** (a `release` with a delay). It lands at the tail of the queue, so +other messages are not blocked behind it, and the worker pauses briefly after each +such release because RabbitMQ ignores the delay. ### Delay caveat diff --git a/docs/Transport-Redis.md b/docs/Transport-Redis.md index 6b273ca..dc87d12 100644 --- a/docs/Transport-Redis.md +++ b/docs/Transport-Redis.md @@ -51,19 +51,27 @@ observe a stop signal instead of blocking forever on an empty queue. ### Retry with delay -`release()` removes the in-flight copy, then: +`release()` runs one Lua script that removes the in-flight copy (`LREM`) and, only +if it removed one, then: - delay `0` → `RPUSH orders ` (back onto the ready queue immediately); - delay `> 0` → `ZADD orders:delayed `. -On every `reserve()`, due members of `orders:delayed` (score `<= now`) are migrated -back onto the ready list — each re-enqueued only by the worker that wins its -`ZREM`, so a delayed retry is never duplicated across workers. +Because it is one script, a worker that dies cannot leave the message on no list at +all. And because the write happens only when the `LREM` removed the worker's own +entry, a worker that has **lost the message** (a reaper already moved it back onto +the queue) does not add a second copy: the live copy belongs to whoever reserves it +next, and the stale release is ignored. The same holds for `deadLetter()`. + +On every `reserve()`, due members of `orders:delayed` (score `<= now`, at most 1000 +at a time) are migrated back onto the ready list by another script, each member +removed and pushed in the same step, so a delayed retry is neither lost nor +duplicated across workers. ### Dead-letter `deadLetter()` removes the in-flight copy and `RPUSH`-es the annotated envelope -onto `orders:failed`. +onto `orders:failed`, in one script, and only if the worker still owns the message. ## Delivery semantics @@ -73,6 +81,23 @@ then exit) avoids stranding messages in normal operation; if you run workers tha can be killed mid-job, add a small reaper that moves long-idle `orders:processing` entries back onto `orders`. +A message is identified by its processing entry, so a worker acts on a message +only while that entry is still there. This is what stops a slow handler and a +reaper from splitting one message into two, and it has two consequences for the +reaper you write: + +- **Keep its delay above your slowest handler.** If a handler is still running when + the reaper moves its message back, the handler's later ack, retry or dead-letter + is ignored; the reclaimed copy is the one that carries on. +- **Count each reclaim as an attempt**: increment `attempts` in the envelope it + puts back. A reclaim means one attempt did not finish, and without the count a + handler that always outlives the reaper and always fails would never reach + `maxAttempts`. + +With the dispatcher's [deduplication](Idempotent-Consumption.md), a reclaimed copy +that finds the original handler's key still claimed is parked in `orders:delayed` +and re-checked, not discarded. + ## Using phpredis instead The consume side is written against `Predis\ClientInterface`. If you use the diff --git a/src/Consumer/IdempotencyOptions.php b/src/Consumer/IdempotencyOptions.php index dcb75ea..169e9c7 100644 --- a/src/Consumer/IdempotencyOptions.php +++ b/src/Consumer/IdempotencyOptions.php @@ -50,7 +50,8 @@ final class IdempotencyOptions * {@see \InitPHP\Queue\Contracts\CompletionAwareIdempotencyStore}), the * message is put back and not offered again for this many seconds. * The redelivery consumes no attempt, so this only paces the checks; - * it must be at least 1 so a waiting message cannot spin. + * it must be at least 1. The worker also pauses after each + * deferral, so a transport without native delay does not spin. * * @throws ConfigurationException When a numeric option is out of range. */ diff --git a/src/Consumer/Worker.php b/src/Consumer/Worker.php index bde958b..fdadcd2 100644 --- a/src/Consumer/Worker.php +++ b/src/Consumer/Worker.php @@ -28,6 +28,13 @@ */ final class Worker { + /** + * The shortest pause after putting a message back with a delay, so a + * transport that ignores the delay (RabbitMQ) cannot be spun on even with + * `sleepWhenEmpty: 0`. + */ + private const DEFERRAL_PAUSE_SECONDS = 0.1; + private bool $shouldStop = false; private int $processed = 0; @@ -87,13 +94,17 @@ public function run(string $queue): void continue; } + $counted = true; + try { - $this->process($message); + $counted = $this->process($message); } catch (Throwable $e) { $this->log('error', 'process.failed', $this->context($message, ['error' => $e->getMessage()])); } - ++$this->processed; + if ($counted) { + ++$this->processed; + } $this->dispatchSignals(); } } @@ -110,8 +121,9 @@ public function runOnce(string $queue): bool return false; } - $this->process($message); - ++$this->processed; + if ($this->process($message)) { + ++$this->processed; + } return true; } @@ -125,14 +137,20 @@ public function stop(): void } /** - * Total messages processed across this worker's lifetime. + * Total messages processed across this worker's lifetime. A message put back + * to wait for another handler's in-flight key is not processing and is not + * counted, so waiting never uses up `maxJobs`. */ public function processedCount(): int { return $this->processed; } - private function process(ReceivedMessage $message): void + /** + * Act on one message. Returns false when the message was only deferred (put + * back with a delay to wait for another handler), true when it was handled. + */ + private function process(ReceivedMessage $message): bool { $outcome = $this->dispatcher->dispatch($message); @@ -160,7 +178,9 @@ private function process(ReceivedMessage $message): void // Transports without native delay (RabbitMQ) hand it straight back, // so pause briefly rather than reserving it again in a tight loop. if ($outcome->delaySeconds > 0) { - $this->sleep($this->options->sleepWhenEmpty); + $this->sleep(max(self::DEFERRAL_PAUSE_SECONDS, $this->options->sleepWhenEmpty)); + + return false; } break; @@ -180,6 +200,8 @@ private function process(ReceivedMessage $message): void break; } + + return true; } private function retry(ReceivedMessage $message, int $attempt): void diff --git a/src/Transport/Amqp/AmqpTransport.php b/src/Transport/Amqp/AmqpTransport.php index b0d3c29..5883a60 100644 --- a/src/Transport/Amqp/AmqpTransport.php +++ b/src/Transport/Amqp/AmqpTransport.php @@ -22,8 +22,13 @@ * time with `basic_get`; `ack` is `basic_ack` on the delivery tag. * * Because RabbitMQ does not version a message body in place, a retry/dead-letter - * acks the original delivery and republishes the updated envelope (so `attempts` - * and the `dead_letter` block persist). Per-message delay is not applied — it + * republishes the updated envelope (so `attempts` and the `dead_letter` block + * persist) and only then acks the original delivery. That order is deliberate: a + * worker that dies between the two leaves a duplicate (which the dispatcher's + * idempotency layer recognises), where acking first would leave nothing; and if + * the publish fails the original is not acked and RabbitMQ redelivers it. When the + * caller has put the channel in publisher-confirm mode (`confirm_select()`), the + * ack also waits for the broker to confirm the new copy. Per-message delay is not applied — it * needs the delayed-message exchange plugin; configure that on the broker if you * need back-off windows. * @@ -31,6 +36,9 @@ */ final class AmqpTransport implements Transport, ConsumerTransport { + /** Seconds to wait for publisher confirms before giving up on the ack. */ + private const CONFIRM_TIMEOUT = 30; + private readonly BabelAmqpTransport $publisher; public function __construct( @@ -69,14 +77,27 @@ public function ack(ReceivedMessage $message): void public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void { - $this->channel->basic_ack($this->deliveryTag($message)); - $this->publisher->publish($payload, $message->queue()); + $this->republishThenAck($message, $payload, $message->queue()); } public function deadLetter(ReceivedMessage $message, string $payload): void { + $this->republishThenAck($message, $payload, $message->queue() . $this->failedSuffix); + } + + /** + * Publish the new copy, make sure the broker has it, then ack the original. A + * failure before the ack leaves the original unacked, so it is redelivered. + */ + private function republishThenAck(ReceivedMessage $message, string $payload, string $target): void + { + $this->publisher->publish($payload, $target); + + // Returns at once unless the channel is in publisher-confirm mode, in which + // case it blocks until the broker has confirmed (or throws on timeout). + $this->channel->wait_for_pending_acks(self::CONFIRM_TIMEOUT); + $this->channel->basic_ack($this->deliveryTag($message)); - $this->publisher->publish($payload, $message->queue() . $this->failedSuffix); } private function deliveryTag(ReceivedMessage $message): int diff --git a/src/Transport/Pdo/PdoTransport.php b/src/Transport/Pdo/PdoTransport.php index c0cfb62..c10c103 100644 --- a/src/Transport/Pdo/PdoTransport.php +++ b/src/Transport/Pdo/PdoTransport.php @@ -24,6 +24,13 @@ * reservation older than `$retryAfter` seconds is treated as abandoned and * becomes reservable again, so a crashed worker never loses a message. * + * `release()` is conditional on the reservation this transport instance took: a + * worker whose reservation lapsed and was taken over cannot overwrite the new + * holder's row, and a verbatim release (a message put back unchanged) never + * touches `payload` or `attempts`, so it cannot undo a retry another worker has + * just recorded. The stamp has one-second resolution, so with `$retryAfter` of 0 + * two reservations inside the same second look alike. + * * The whole envelope is stored as JSON in `payload`; `queue`, `urn`, `trace_id` * and `attempts` are denormalised into columns purely for indexing and * inspection. @@ -34,6 +41,9 @@ final class PdoTransport implements Transport, ConsumerTransport { private readonly string $failedTable; + /** @var array row id => the `reserved_at` stamp this instance wrote at reserve() */ + private array $reservations = []; + /** * @param PDO $pdo A connection in exception error mode (PHP 8's default). * @param string $table Main queue table name. @@ -105,6 +115,7 @@ public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage $claim->execute([':reserved' => $now, ':id' => $row['id'], ':stale' => $stale]); if ($claim->rowCount() === 1) { + $this->reservations[(int) $row['id']] = $now; $payload = (string) $row['payload']; return new ReceivedMessage($queue, $payload, EnvelopeCodec::decode($payload), (int) $row['id']); @@ -116,6 +127,8 @@ public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage public function ack(ReceivedMessage $message): void { + unset($this->reservations[(int) $message->receipt()]); + $this->pdo ->prepare("DELETE FROM {$this->table} WHERE id = :id") ->execute([':id' => (int) $message->receipt()]); @@ -123,20 +136,39 @@ public function ack(ReceivedMessage $message): void public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void { - $envelope = EnvelopeCodec::decode($payload); + $id = (int) $message->receipt(); + $stamp = $this->reservations[$id] ?? null; + unset($this->reservations[$id]); - $this->pdo->prepare( - "UPDATE {$this->table} SET payload = :payload, attempts = :attempts, available_at = :available_at, reserved_at = NULL WHERE id = :id", - )->execute([ - ':payload' => $payload, - ':attempts' => $this->attemptsOf($envelope), + $params = [ ':available_at' => $this->at(max(0, $delaySeconds)), - ':id' => (int) $message->receipt(), - ]); + ':id' => $id, + ]; + + if ($payload === $message->rawBody()) { + // Put back unchanged: only reschedule, and only while the reservation + // is still ours; never rewrite a retry another worker recorded. + $set = 'available_at = :available_at, reserved_at = NULL'; + $guard = $stamp !== null ? ' AND reserved_at = :stamp' : ''; + } else { + $set = 'payload = :payload, attempts = :attempts, available_at = :available_at, reserved_at = NULL'; + // A retry applies unless someone else holds the row right now. + $guard = $stamp !== null ? ' AND (reserved_at = :stamp OR reserved_at IS NULL)' : ''; + $params[':payload'] = $payload; + $params[':attempts'] = $this->attemptsOf(EnvelopeCodec::decode($payload)); + } + + if ($stamp !== null) { + $params[':stamp'] = $stamp; + } + + $this->pdo->prepare("UPDATE {$this->table} SET {$set} WHERE id = :id{$guard}")->execute($params); } public function deadLetter(ReceivedMessage $message, string $payload): void { + unset($this->reservations[(int) $message->receipt()]); + $envelope = EnvelopeCodec::decode($payload); $deadLetter = is_array($envelope['dead_letter'] ?? null) ? $envelope['dead_letter'] : []; $now = $this->now(); diff --git a/src/Transport/Redis/RedisTransport.php b/src/Transport/Redis/RedisTransport.php index 68b98c1..5da6412 100644 --- a/src/Transport/Redis/RedisTransport.php +++ b/src/Transport/Redis/RedisTransport.php @@ -23,10 +23,62 @@ * Delayed retries use a `:delayed` sorted set drained on each reserve, and * dead-letters go to a `:failed` list. * - * Requires Redis 6.2+ (for `BLMOVE`). Optional dependency: `predis/predis`. + * `release()`, `deadLetter()` and the delayed-set migration each run as one Lua + * script, so they are atomic: a worker that dies half way cannot leave a message + * on no list at all. `release()` and `deadLetter()` also act only while the + * message is still **this worker's** (its `LREM` from the processing list removes + * one entry); if a reaper has already moved the message back onto the queue, the + * live copy belongs to whoever reserves it next and the stale write is ignored, + * which keeps one message from forking into two copies. + * + * Requires Redis 6.2+ (for `BLMOVE`; Lua scripting is built in). Optional + * dependency: `predis/predis`. */ final class RedisTransport implements Transport, ConsumerTransport { + /** + * KEYS: processing, queue, delayed. ARGV: receipt, payload, due time (0 = now). + * Re-queues only when this worker still owns the processing entry. + */ + private const RELEASE_SCRIPT = <<<'LUA' + -- queue:release + if redis.call('LREM', KEYS[1], 1, ARGV[1]) < 1 then + return 0 + end + if tonumber(ARGV[3]) > 0 then + redis.call('ZADD', KEYS[3], ARGV[3], ARGV[2]) + else + redis.call('RPUSH', KEYS[2], ARGV[2]) + end + return 1 + LUA; + + /** + * KEYS: processing, failed. ARGV: receipt, payload. + */ + private const DEAD_LETTER_SCRIPT = <<<'LUA' + -- queue:dead-letter + if redis.call('LREM', KEYS[1], 1, ARGV[1]) < 1 then + return 0 + end + redis.call('RPUSH', KEYS[2], ARGV[2]) + return 1 + LUA; + + /** + * KEYS: delayed, queue. ARGV: now. Moves due members, each removed and + * pushed in the same step, so none can be lost or duplicated. + */ + private const MIGRATE_SCRIPT = <<<'LUA' + -- queue:migrate + local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, 1000) + for _, member in ipairs(due) do + redis.call('ZREM', KEYS[1], member) + redis.call('RPUSH', KEYS[2], member) + end + return #due + LUA; + private readonly BabelRedisTransport $publisher; public function __construct( @@ -74,39 +126,46 @@ public function ack(ReceivedMessage $message): void public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void { - $this->client->lrem($message->queue() . $this->processingSuffix, 1, (string) $message->receipt()); - - if ($delaySeconds > 0) { - $this->client->zadd($message->queue() . $this->delayedSuffix, [$payload => time() + $delaySeconds]); - - return; - } + $queue = $message->queue(); - $this->client->rpush($message->queue(), [$payload]); + $this->client->eval( + self::RELEASE_SCRIPT, + 3, + $queue . $this->processingSuffix, + $queue, + $queue . $this->delayedSuffix, + (string) $message->receipt(), + $payload, + (string) ($delaySeconds > 0 ? time() + $delaySeconds : 0), + ); } public function deadLetter(ReceivedMessage $message, string $payload): void { - $this->client->lrem($message->queue() . $this->processingSuffix, 1, (string) $message->receipt()); - $this->client->rpush($message->queue() . $this->failedSuffix, [$payload]); + $queue = $message->queue(); + + $this->client->eval( + self::DEAD_LETTER_SCRIPT, + 2, + $queue . $this->processingSuffix, + $queue . $this->failedSuffix, + (string) $message->receipt(), + $payload, + ); } /** - * Move any delayed messages whose time has come back onto the main queue. A - * member is re-enqueued only by the worker that wins its `ZREM`, so a delayed - * retry is not duplicated across concurrent workers. + * Move any delayed messages whose time has come back onto the main queue, in + * one atomic script so concurrent workers cannot duplicate or drop them. */ private function migrateDueDelayed(string $queue): void { - $key = $queue . $this->delayedSuffix; - - /** @var list $due */ - $due = $this->client->zrangebyscore($key, '-inf', (string) time()); - - foreach ($due as $payload) { - if ((int) $this->client->zrem($key, $payload) > 0) { - $this->client->rpush($queue, [$payload]); - } - } + $this->client->eval( + self::MIGRATE_SCRIPT, + 2, + $queue . $this->delayedSuffix, + $queue, + (string) time(), + ); } } diff --git a/tests/Consumer/InFlightRedeliveryTest.php b/tests/Consumer/InFlightRedeliveryTest.php index f97f449..142074b 100644 --- a/tests/Consumer/InFlightRedeliveryTest.php +++ b/tests/Consumer/InFlightRedeliveryTest.php @@ -19,6 +19,7 @@ use InitPHP\Queue\Tests\Support\ArrayTransport; use InitPHP\Queue\Tests\Support\ClaimOnlyIdempotencyStore; use InitPHP\Queue\Tests\Support\RecordingHandler; +use InitPHP\Queue\Transport\Pdo\PdoTransport; use PDO; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -145,13 +146,13 @@ function (string $level, string $event, array $context) use (&$events): void { $transport->publish($this->payload('msg-1'), 'orders'); - for ($i = 0; $i < 20; ++$i) { + for ($i = 0; $i < 6; ++$i) { $worker->runOnce('orders'); } self::assertSame(1, $transport->readyCount('orders'), 'the message is still queued'); self::assertSame(0, $transport->deadCount('orders'), 'waiting must not dead-letter it, even with maxAttempts 1'); - self::assertCount(20, $transport->releases); + self::assertCount(6, $transport->releases); self::assertSame([['job.released', 'in_flight', 5]], array_slice($events, 0, 1)); foreach ($transport->releases as $release) { @@ -192,9 +193,10 @@ public function test_the_failed_handler_keeps_its_retry_when_a_redelivery_arrive // second worker while it still runs; then the first handler throws. $pdo = new PDO('sqlite::memory:'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $transport = new \InitPHP\Queue\Transport\Pdo\PdoTransport($pdo, 'jobs', null, 'default', 0); // retryAfter 0: a reservation is at once reclaimable + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); // retryAfter 0: a reservation is at once reclaimable $transport->createSchema(); $transport->publish($this->payload('msg-1'), 'orders'); + $otherTransport = new PdoTransport($pdo, 'jobs', null, 'default', 0); // the second worker's own connection $store = new InMemoryIdempotencyStore(); $options = new IdempotencyOptions($store, inFlightDelaySeconds: 5); @@ -208,7 +210,7 @@ public function test_the_failed_handler_keeps_its_retry_when_a_redelivery_arrive throw new RuntimeException('downstream failed'); }); $firstWorker = new Worker($transport, new Dispatcher($handlers, idempotency: $options), $workerOptions); - $secondWorker = new Worker($transport, new Dispatcher($handlers, idempotency: $options), $workerOptions); + $secondWorker = new Worker($otherTransport, new Dispatcher($handlers, idempotency: $options), $workerOptions); $firstWorker->runOnce('orders'); @@ -217,6 +219,7 @@ public function test_the_failed_handler_keeps_its_retry_when_a_redelivery_arrive $row = $pdo->query('SELECT attempts FROM jobs')->fetchAll(PDO::FETCH_ASSOC); self::assertCount(1, $row, 'the message still has a row: neither a retry nor a dead letter was lost'); self::assertSame(1, (int) $row[0]['attempts'], 'the failed attempt is counted'); + self::assertGreaterThan(time() + 20, strtotime((string) $pdo->query('SELECT available_at FROM jobs')->fetchColumn()), 'the retry keeps its back-off, the wait did not shorten it'); self::assertSame(0, (int) $pdo->query('SELECT COUNT(*) FROM jobs_failed')->fetchColumn()); self::assertFalse($store->seen(self::KEY), 'the failed handler released its claim'); } @@ -226,7 +229,7 @@ public function test_an_in_flight_message_on_a_real_pdo_queue_survives_until_the // Path 1 end to end: a dead worker's claim is held while the redelivery arrives. $pdo = new PDO('sqlite::memory:'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $transport = new \InitPHP\Queue\Transport\Pdo\PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); $transport->createSchema(); $transport->publish($this->payload('msg-1'), 'orders'); @@ -248,6 +251,95 @@ public function test_an_in_flight_message_on_a_real_pdo_queue_survives_until_the self::assertSame(0, (int) $pdo->query('SELECT COUNT(*) FROM jobs')->fetchColumn()); } + public function test_waiting_does_not_count_as_processing_or_use_up_max_jobs(): void + { + $transport = new ArrayTransport(); + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $handler = new RecordingHandler(); + $worker = new Worker( + $transport, + $this->dispatcher($handler, $store), + new WorkerOptions(maxJobs: 1, sleepWhenEmpty: 0.0, reserveTimeout: 0.0, maxRuntime: 1.0), + ); + $transport->publish($this->payload('msg-1'), 'orders'); + $transport->publish($this->payload('msg-2'), 'orders'); // an ordinary message behind the waiting one + + $worker->run('orders'); + + self::assertCount(1, $handler->handled, 'maxJobs 1 was still available for the ordinary message'); + self::assertSame(1, $worker->processedCount(), 'only the handled message is counted'); + self::assertGreaterThan(0, count($transport->releases), 'the waiting message was deferred'); + } + + public function test_a_deferral_pauses_even_when_sleep_when_empty_is_zero(): void + { + $transport = new ArrayTransport(); + $store = new InMemoryIdempotencyStore(); + $store->claim(self::KEY, 300); + $worker = new Worker( + $transport, + $this->dispatcher(new RecordingHandler(), $store), + new WorkerOptions(sleepWhenEmpty: 0.0), + ); + $transport->publish($this->payload('msg-1'), 'orders'); + + $startedAt = microtime(true); + $worker->runOnce('orders'); + + self::assertGreaterThanOrEqual(0.09, microtime(true) - $startedAt, 'a transport that ignores the delay must not be spun on'); + } + + public function test_a_stale_holder_cannot_overwrite_a_retry_recorded_by_another_worker(): void + { + // A and B both hold the row (B took over A's lapsed reservation). B records + // a retry; A then puts the message back unchanged. + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $a = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $a->createSchema(); + $b = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $a->publish($this->payload('msg-1'), 'orders'); + + $first = $a->reserve('orders'); + $second = $b->reserve('orders'); + self::assertNotNull($first); + self::assertNotNull($second); + + $envelope = $second->envelope(); + $envelope['attempts'] = 1; + $b->release($second, EnvelopeCodec::encode($envelope), 60); + $a->release($first, $first->rawBody(), 5); + + $row = $pdo->query('SELECT attempts, payload FROM jobs')->fetch(PDO::FETCH_ASSOC); + self::assertSame(1, (int) $row['attempts'], 'the recorded retry survives'); + self::assertSame(1, EnvelopeCodec::decode($row['payload'])['attempts']); + self::assertGreaterThan(time() + 30, strtotime((string) $pdo->query('SELECT available_at FROM jobs')->fetchColumn())); + } + + public function test_a_release_does_not_touch_a_row_another_worker_holds_now(): void + { + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload('msg-1'), 'orders'); + + $message = $transport->reserve('orders'); + self::assertNotNull($message); + + // Another worker took the row over later: a different reservation stamp. + $pdo->exec("UPDATE jobs SET reserved_at = '2999-01-01 00:00:00'"); + + $envelope = $message->envelope(); + $envelope['attempts'] = 1; + $transport->release($message, EnvelopeCodec::encode($envelope), 30); + + $row = $pdo->query('SELECT attempts, reserved_at FROM jobs')->fetch(PDO::FETCH_ASSOC); + self::assertSame(0, (int) $row['attempts'], 'the new holder keeps its row'); + self::assertSame('2999-01-01 00:00:00', $row['reserved_at']); + } + public function test_the_in_flight_delay_must_be_at_least_one_second(): void { $this->expectException(ConfigurationException::class); diff --git a/tests/Integration/AmqpIntegrationTest.php b/tests/Integration/AmqpIntegrationTest.php index 93b5052..4e4ffe0 100644 --- a/tests/Integration/AmqpIntegrationTest.php +++ b/tests/Integration/AmqpIntegrationTest.php @@ -5,6 +5,13 @@ namespace InitPHP\Queue\Tests\Integration; use BabelQueue\Codec\EnvelopeCodec; +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\IdempotencyOptions; +use InitPHP\Queue\Consumer\InMemoryIdempotencyStore; +use InitPHP\Queue\Consumer\Worker; +use InitPHP\Queue\Consumer\WorkerOptions; +use InitPHP\Queue\Routing\HandlerMap; +use InitPHP\Queue\Tests\Support\RecordingHandler; use InitPHP\Queue\Transport\Amqp\AmqpTransport; use PhpAmqpLib\Channel\AMQPChannel; use PhpAmqpLib\Connection\AMQPStreamConnection; @@ -73,4 +80,74 @@ public function test_full_publish_reserve_ack_cycle(): void // Nothing left to consume after the ack. self::assertNull($this->transport->reserve(self::QUEUE, 1.0)); } + + public function test_release_republishes_the_updated_envelope_and_acks_the_original(): void + { + $this->transport->publish( + EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['order_id' => 1], self::QUEUE)), + self::QUEUE, + ); + + $message = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($message); + + $envelope = $message->envelope(); + $envelope['attempts'] = 1; + $this->transport->release($message, EnvelopeCodec::encode($envelope), 0); + + $again = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($again, 'the republished copy is there'); + self::assertSame(1, $again->attempts()); + $this->transport->ack($again); + + self::assertNull($this->transport->reserve(self::QUEUE, 1.0), 'exactly one copy existed: the original was acked'); + } + + public function test_release_and_dead_letter_work_with_publisher_confirms(): void + { + $this->channel->confirm_select(); + + $this->transport->publish( + EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['order_id' => 1], self::QUEUE)), + self::QUEUE, + ); + + $message = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($message); + $this->transport->release($message, $message->rawBody(), 0); + + $again = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($again); + $this->transport->deadLetter($again, $again->rawBody()); + + self::assertNull($this->transport->reserve(self::QUEUE, 1.0)); + $this->channel->queue_purge(self::QUEUE . '.failed'); + } + + public function test_a_message_waiting_on_an_in_flight_key_stays_on_the_queue(): void + { + $envelope = EnvelopeCodec::make('urn:babel:orders:created', ['order_id' => 1], self::QUEUE); + $envelope['meta']['id'] = 'msg-1'; + $this->transport->publish(EnvelopeCodec::encode($envelope), self::QUEUE); + + $store = new InMemoryIdempotencyStore(); + $store->claim('bq:idemp:msg-1', 300); // another worker holds the key + $handler = new RecordingHandler(); + $worker = new Worker( + $this->transport, + new Dispatcher( + (new HandlerMap())->register('urn:babel:orders:created', $handler), + idempotency: new IdempotencyOptions($store), + ), + new WorkerOptions(sleepWhenEmpty: 0.0), + ); + + $worker->runOnce(self::QUEUE); + self::assertSame([], $handler->handled); + + $store->forget('bq:idemp:msg-1'); // the other worker failed + self::assertTrue($worker->runOnce(self::QUEUE), 'the message was still there'); + self::assertCount(1, $handler->handled); + self::assertNull($this->transport->reserve(self::QUEUE, 1.0)); + } } diff --git a/tests/Integration/RedisIntegrationTest.php b/tests/Integration/RedisIntegrationTest.php index eb68ab1..ec8147e 100644 --- a/tests/Integration/RedisIntegrationTest.php +++ b/tests/Integration/RedisIntegrationTest.php @@ -5,6 +5,13 @@ namespace InitPHP\Queue\Tests\Integration; use BabelQueue\Codec\EnvelopeCodec; +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\IdempotencyOptions; +use InitPHP\Queue\Consumer\InMemoryIdempotencyStore; +use InitPHP\Queue\Consumer\Worker; +use InitPHP\Queue\Consumer\WorkerOptions; +use InitPHP\Queue\Routing\HandlerMap; +use InitPHP\Queue\Tests\Support\RecordingHandler; use InitPHP\Queue\Transport\Redis\RedisTransport; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; @@ -70,4 +77,89 @@ public function test_release_requeues_and_dead_letter_quarantines(): void $this->transport->deadLetter($again, $again->rawBody()); self::assertSame(1, (int) $this->client->llen(self::QUEUE . ':failed')); } + + private function copies(): int + { + return (int) $this->client->llen(self::QUEUE) + + (int) $this->client->llen(self::QUEUE . ':processing') + + (int) $this->client->llen(self::QUEUE . ':failed') + + (int) $this->client->zcard(self::QUEUE . ':delayed'); + } + + private function publishAndReserve(): \InitPHP\Queue\Message\ReceivedMessage + { + $payload = EnvelopeCodec::encode(EnvelopeCodec::make('urn:babel:orders:created', ['n' => 1], self::QUEUE)); + $this->transport->publish($payload, self::QUEUE); + + $message = $this->transport->reserve(self::QUEUE, 2.0); + self::assertNotNull($message); + + return $message; + } + + /** A reaper moving the message off the processing list and back onto the queue. */ + private function reap(\InitPHP\Queue\Message\ReceivedMessage $message): void + { + $this->client->lrem(self::QUEUE . ':processing', 1, $message->rawBody()); + $this->client->rpush(self::QUEUE, [$message->rawBody()]); + } + + public function test_a_delayed_release_parks_the_message_and_migrates_it_when_due(): void + { + $message = $this->publishAndReserve(); + + $this->transport->release($message, $message->rawBody(), 60); + + self::assertSame(0, (int) $this->client->llen(self::QUEUE)); + self::assertSame(0, (int) $this->client->llen(self::QUEUE . ':processing')); + self::assertSame(1, (int) $this->client->zcard(self::QUEUE . ':delayed')); + + // Make it due and let reserve() migrate it. + $this->client->zadd(self::QUEUE . ':delayed', [$message->rawBody() => time() - 1]); + $again = $this->transport->reserve(self::QUEUE, 2.0); + + self::assertNotNull($again); + self::assertSame(0, (int) $this->client->zcard(self::QUEUE . ':delayed')); + self::assertSame(1, $this->copies()); + } + + public function test_a_release_or_dead_letter_from_a_worker_that_lost_the_message_does_not_fork_it(): void + { + $message = $this->publishAndReserve(); + $this->reap($message); + + $retry = $message->envelope(); + $retry['attempts'] = 1; + $this->transport->release($message, EnvelopeCodec::encode($retry), 30); + $this->transport->deadLetter($message, $message->rawBody()); + + self::assertSame(1, $this->copies(), 'only the reaped copy is live'); + self::assertSame(1, (int) $this->client->llen(self::QUEUE)); + } + + public function test_a_message_waiting_on_an_in_flight_key_is_parked_not_lost(): void + { + $envelope = EnvelopeCodec::make('urn:babel:orders:created', ['n' => 1], self::QUEUE); + $envelope['meta']['id'] = 'msg-1'; + $this->transport->publish(EnvelopeCodec::encode($envelope), self::QUEUE); + + $store = new InMemoryIdempotencyStore(); + $store->claim('bq:idemp:msg-1', 300); + $handler = new RecordingHandler(); + $worker = new Worker( + $this->transport, + new Dispatcher( + (new HandlerMap())->register('urn:babel:orders:created', $handler), + idempotency: new IdempotencyOptions($store), + ), + new WorkerOptions(sleepWhenEmpty: 0.0, reserveTimeout: 1.0), + ); + + $worker->runOnce(self::QUEUE); + + self::assertSame([], $handler->handled); + self::assertSame(1, $this->copies()); + self::assertSame(1, (int) $this->client->zcard(self::QUEUE . ':delayed')); + self::assertSame(0, (int) $this->client->llen(self::QUEUE . ':processing')); + } } diff --git a/tests/Support/InMemoryRedis.php b/tests/Support/InMemoryRedis.php index 5aab327..26c3c53 100644 --- a/tests/Support/InMemoryRedis.php +++ b/tests/Support/InMemoryRedis.php @@ -11,7 +11,10 @@ /** * A tiny in-memory stand-in for a Predis client implementing just the list and * sorted-set commands {@see \InitPHP\Queue\Transport\Redis\RedisTransport} uses - * (`BLMOVE`, `RPUSH`, `LREM`, `ZADD`, `ZRANGEBYSCORE`, `ZREM`). The remaining + * (`BLMOVE`, `RPUSH`, `LREM`, `ZADD`, `ZRANGEBYSCORE`, `ZREM`) plus an `eval()` + * that recognises the transport's three scripts by their leading marker comment + * and applies the same steps atomically (the real scripts run against Redis in + * the integration test). The remaining * {@see ClientInterface} methods are not exercised by the transport and throw. */ final class InMemoryRedis implements ClientInterface @@ -115,6 +118,49 @@ public function zrem(string $key, string $member): int return 1; } + /** + * Emulates EVAL for the transport's scripts only. + * + * @return int + */ + public function eval(string $script, int $numKeys, string ...$args): mixed + { + $keys = array_slice($args, 0, $numKeys); + $argv = array_slice($args, $numKeys); + + if (str_contains($script, '-- queue:release')) { + if ($this->lrem($keys[0], 1, $argv[0]) < 1) { + return 0; + } + (float) $argv[2] > 0 + ? $this->zadd($keys[2], [$argv[1] => (float) $argv[2]]) + : $this->rpush($keys[1], [$argv[1]]); + + return 1; + } + + if (str_contains($script, '-- queue:dead-letter')) { + if ($this->lrem($keys[0], 1, $argv[0]) < 1) { + return 0; + } + $this->rpush($keys[1], [$argv[1]]); + + return 1; + } + + if (str_contains($script, '-- queue:migrate')) { + $due = array_slice($this->zrangebyscore($keys[0], '-inf', $argv[0]), 0, 1000); + foreach ($due as $member) { + $this->zrem($keys[0], $member); + $this->rpush($keys[1], [$member]); + } + + return count($due); + } + + throw new BadMethodCallException('InMemoryRedis cannot evaluate this script.'); + } + /** * @return list */ diff --git a/tests/Transport/AmqpTransportTest.php b/tests/Transport/AmqpTransportTest.php index 9d2386c..7360a9b 100644 --- a/tests/Transport/AmqpTransportTest.php +++ b/tests/Transport/AmqpTransportTest.php @@ -63,23 +63,52 @@ public function test_ack_acknowledges_the_delivery_tag(): void (new AmqpTransport($channel))->ack($this->reserved($this->envelope())); } - public function test_release_acks_the_original_and_republishes(): void + public function test_release_publishes_the_new_copy_before_it_acks_the_original(): void { $channel = Mockery::mock(AMQPChannel::class); - $channel->shouldReceive('basic_ack')->once()->with(42); $channel->shouldReceive('queue_declare'); - $channel->shouldReceive('basic_publish')->once(); + $channel->shouldReceive('basic_publish')->once()->ordered(); + $channel->shouldReceive('wait_for_pending_acks')->once()->ordered(); + $channel->shouldReceive('basic_ack')->once()->with(42)->ordered(); $raw = $this->envelope(); (new AmqpTransport($channel))->release($this->reserved($raw), $raw, 0); } - public function test_dead_letter_acks_and_publishes_to_the_failed_queue(): void + public function test_a_failed_publish_leaves_the_original_unacked(): void { $channel = Mockery::mock(AMQPChannel::class); - $channel->shouldReceive('basic_ack')->once()->with(42); - $channel->shouldReceive('queue_declare')->once()->with('orders.failed', false, true, false, false); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_publish')->once()->andThrow(new \RuntimeException('connection lost')); + $channel->shouldNotReceive('basic_ack'); + + $raw = $this->envelope(); + + $this->expectException(\RuntimeException::class); + (new AmqpTransport($channel))->release($this->reserved($raw), $raw, 0); + } + + public function test_an_unconfirmed_publish_leaves_the_original_unacked(): void + { + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); $channel->shouldReceive('basic_publish')->once(); + $channel->shouldReceive('wait_for_pending_acks')->once()->andThrow(new \RuntimeException('confirm timeout')); + $channel->shouldNotReceive('basic_ack'); + + $raw = $this->envelope(); + + $this->expectException(\RuntimeException::class); + (new AmqpTransport($channel))->deadLetter($this->reserved($raw), $raw); + } + + public function test_dead_letter_publishes_to_the_failed_queue_before_it_acks(): void + { + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare')->once()->with('orders.failed', false, true, false, false); + $channel->shouldReceive('basic_publish')->once()->ordered(); + $channel->shouldReceive('wait_for_pending_acks')->once()->ordered(); + $channel->shouldReceive('basic_ack')->once()->with(42)->ordered(); $raw = $this->envelope(); (new AmqpTransport($channel))->deadLetter($this->reserved($raw), $raw); diff --git a/tests/Transport/RedisTransportTest.php b/tests/Transport/RedisTransportTest.php index b78094c..2da6aa6 100644 --- a/tests/Transport/RedisTransportTest.php +++ b/tests/Transport/RedisTransportTest.php @@ -114,4 +114,95 @@ public function test_dead_letter_pushes_onto_the_failed_list(): void self::assertSame([], $this->redis->list('orders:processing')); self::assertSame([$message->rawBody()], $this->redis->list('orders:failed')); } + + /** + * Messages the transport still holds anywhere, whichever list they are on. + */ + private function copies(string $queue = 'orders'): int + { + return count($this->redis->list($queue)) + + count($this->redis->list($queue . ':processing')) + + count($this->redis->list($queue . ':failed')) + + $this->redis->zcard($queue . ':delayed'); + } + + /** + * What a reaper does to a message whose worker looks dead: take it off the + * processing list and put it back on the queue. + */ + private function reap(ReceivedMessage $message): void + { + $this->redis->lrem('orders:processing', 1, (string) $message->receipt()); + $this->redis->rpush('orders', [$message->rawBody()]); + } + + public function test_a_release_from_a_worker_that_lost_the_message_does_not_fork_it(): void + { + $this->transport->publish($this->envelope(), 'orders'); + $message = $this->transport->reserve('orders', 1.0); + self::assertNotNull($message); + + $this->reap($message); + self::assertSame(1, $this->copies()); + + // The original worker finally fails and releases a retry it no longer owns. + $this->transport->release($message, $this->withAttempts($message, 1), 30); + + self::assertSame(1, $this->copies(), 'the reaped copy is the only live one'); + self::assertSame(0, $this->redis->zcard('orders:delayed')); + } + + public function test_a_dead_letter_from_a_worker_that_lost_the_message_is_ignored(): void + { + $this->transport->publish($this->envelope(), 'orders'); + $message = $this->transport->reserve('orders', 1.0); + self::assertNotNull($message); + + $this->reap($message); + $this->transport->deadLetter($message, $message->rawBody()); + + self::assertSame([], $this->redis->list('orders:failed')); + self::assertSame(1, $this->copies()); + } + + public function test_an_in_flight_wait_followed_by_the_first_worker_failing_leaves_one_copy(): void + { + // A handler outlives the reaper, a second worker waits on the in-flight + // key, then the first handler throws. The message must not become two. + $this->transport->publish($this->envelope(), 'orders'); + $first = $this->transport->reserve('orders', 1.0); + self::assertNotNull($first); + + $this->reap($first); + $second = $this->transport->reserve('orders', 1.0); + self::assertNotNull($second); + $this->transport->release($second, $second->rawBody(), 5); // in-flight wait + $this->transport->release($first, $this->withAttempts($first, 1), 30); // first handler fails + + self::assertSame(1, $this->copies()); + self::assertSame(1, $this->redis->zcard('orders:delayed')); + self::assertSame([], $this->redis->list('orders:processing')); + } + + public function test_migration_moves_each_due_member_exactly_once(): void + { + $due = $this->envelope('urn:babel:orders:due'); + $later = $this->envelope('urn:babel:orders:later'); + $this->redis->zadd('orders:delayed', [$due => time() - 1, $later => time() + 3600]); + + // The first reserve migrates the due one and reserves it; a second migrates nothing. + self::assertNotNull($this->transport->reserve('orders', 1.0)); + self::assertNull($this->transport->reserve('orders', 1.0)); + + self::assertSame([$due], $this->redis->list('orders:processing')); + self::assertSame(1, $this->redis->zcard('orders:delayed')); + } + + private function withAttempts(ReceivedMessage $message, int $attempts): string + { + $envelope = $message->envelope(); + $envelope['attempts'] = $attempts; + + return EnvelopeCodec::encode($envelope); + } } From c1e475cfeec02e2162fd3f849c04f65fbc535f45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 10:10:16 +0300 Subject: [PATCH 3/6] fix(transport): count a failure whoever holds the message, and never trust a nack A failure reported by a worker that no longer holds its message was dropped on PDO and Redis, so a handler slower than the reservation or the reaper never reached maxAttempts, and the consume path started to need EVAL. RabbitMQ in confirm mode acked the original after a broker nack. - PdoTransport: a retry from a worker whose reservation was taken over records attempts, payload and back-off without touching the holder's reservation. attempts never moves back and an unchanged release never shortens a back-off. - RedisTransport: a worker that lost its processing entry replaces the live copy (delayed set, then queue) instead of being ignored, for release and dead-letter, so attempts climb and maxAttempts ends the message without forking it. A client that cannot EVAL falls back to the same steps as separate commands; reserve, ack and publish never need scripting. - AmqpTransport: a broker nack or returned copy requeues the original with basic_nack and throws QueueException instead of acking. The caller's own nack handler and return listener are wrapped and put back. Docs state the guarantees of the scripted and command-by-command Redis paths separately, the confirm-mode behaviour, and the PDO release rules. --- CHANGELOG.md | 27 +++- README.md | 10 +- docs/Idempotent-Consumption.md | 21 +-- docs/Transport-PDO.md | 24 ++- docs/Transport-RabbitMQ.md | 21 ++- docs/Transport-Redis.md | 67 +++++--- src/Transport/Amqp/AmqpTransport.php | 86 +++++++++- src/Transport/Pdo/PdoTransport.php | 100 +++++++++--- src/Transport/Redis/RedisTransport.php | 176 ++++++++++++++++----- tests/Consumer/InFlightRedeliveryTest.php | 95 ++++++++++- tests/Integration/RedisIntegrationTest.php | 35 +++- tests/Support/InMemoryRedis.php | 33 +++- tests/Transport/AmqpTransportTest.php | 96 ++++++++++- tests/Transport/RedisTransportTest.php | 132 ++++++++++++++-- 14 files changed, 782 insertions(+), 141 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c999469..3a09f73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,17 +35,28 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). the message again in a tight loop. - `RedisTransport::release()`, `deadLetter()` and the delayed-set migration are single Lua scripts. They act only while the worker still owns the message (its - `LREM` removed one processing entry), so a release or dead-letter from a worker - whose message a reaper already moved back no longer forks it into two copies, and - a crash cannot leave a message on no list. Redis 6.2+ already required Lua. + `LREM` removed one processing entry), so a crash cannot leave a message on no + list. A release or dead-letter from a worker whose message a reaper already moved + back replaces the live copy (in the delayed set, or on the queue) instead of + adding a second one, so `attempts` still climbs and `maxAttempts` still ends the + message. A client that cannot `EVAL` (an adapter without `eval`, or a Redis user + without scripting permission) falls back to the same steps as separate commands + with the same rules, without atomicity; `reserve()`, `ack()` and `publish()` need + no scripting. - `AmqpTransport::release()` and `deadLetter()` publish the new copy (waiting for the broker's confirm when the channel is in confirm mode) **before** acking the original, so a crash between the two leaves a duplicate instead of losing the - message, and a failed publish leaves the original unacked. -- `PdoTransport::release()` updates only a row still held with the reservation - stamp it wrote, and a message put back unchanged no longer rewrites `payload` - or `attempts`, so a worker whose reservation was taken over cannot overwrite - another worker's recorded retry or back-off. + message, and a failed publish leaves the original unacked. In confirm mode a + broker `nack` or a returned copy requeues the original (`basic_nack`, requeue) + and throws a `QueueException` instead of acking; the channel's own nack handler + and return listener keep running. +- `PdoTransport::release()` no longer overwrites a reservation another worker took + over, and a message put back unchanged no longer rewrites `payload` or `attempts` + or shortens a recorded back-off. A failure reported by a worker whose reservation + was taken over still counts (the new `attempts`, payload and back-off are + recorded without touching the holder's reservation, and `attempts` never goes + back), so a handler slower than `retryAfter` that always fails still reaches + `maxAttempts` and the dead-letter table. - A message deferred to wait for an in-flight key no longer counts towards `maxJobs` or `processedCount()`, and the worker pauses at least 0.1 s after a deferral even with `sleepWhenEmpty: 0`. diff --git a/README.md b/README.md index 6d6ebeb..5464bc4 100644 --- a/README.md +++ b/README.md @@ -228,10 +228,12 @@ is discarded. 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. -5. **On Redis a reaper has to count its reclaims.** A message the reaper has moved - back onto the queue is no longer the original worker's, so that worker's later - failure is ignored. Have the reaper increment `attempts` and keep its delay - above your slowest handler. +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 + the body the handler was given. Keep the reaper's delay above your slowest + handler and move the body back unchanged. A Redis client without `EVAL` keeps the + same rules, but a crash in the middle of a retry can lose the message. Set `leaseSeconds` **above your slowest handler**, and as short as that allows: it is how long a dead worker's message waits before it is handled again. The diff --git a/docs/Idempotent-Consumption.md b/docs/Idempotent-Consumption.md index 8862ba8..fff61e4 100644 --- a/docs/Idempotent-Consumption.md +++ b/docs/Idempotent-Consumption.md @@ -109,15 +109,16 @@ were not run as separate scenarios. 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. -6. **On Redis, a reaper has to count its reclaims.** Redis never redelivers a - message by itself; a reaper moves it from `:processing` back onto the - queue. If the original handler is still running (slower than the reaper's - delay), its eventual failure is ignored, because the message is no longer - its own (see [Transport: Redis](Transport-Redis.md#delivery-semantics)). The - retry then has to come from the reclaimed copy, so have the reaper increment - `attempts` in the envelope it moves back, and keep its delay above your slowest - handler: otherwise a handler that always runs longer than the reaper and always - fails is never counted against `maxAttempts`. +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 + `:processing` back onto the queue. If the original handler is still + running, its eventual failure replaces the reclaimed copy, so `attempts` keeps + climbing and `maxAttempts` still ends the message (see + [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. ### Choosing `leaseSeconds` @@ -131,7 +132,7 @@ being discarded. | Transport | When a dead worker's message comes back | Effect of the lease | | --- | --- | --- | | PDO | after `retryAfter` (default 90 s) | the redelivery is released and re-checked every `inFlightDelaySeconds` until the lease lapses, then handled | -| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | the same: it waits until the lease lapses; keep the reaper's delay above your slowest handler and have it count each reclaim as an attempt | +| Redis | when your reaper moves it from `:processing` back onto the queue (there is no automatic reclaim) | the same: it waits until the lease lapses; keep the reaper's delay above your slowest handler | | RabbitMQ | as soon as the broker sees the connection or channel close, typically immediately | the same, re-checked about every `sleepWhenEmpty` seconds (at least 0.1 s), because RabbitMQ has no native delay | `leaseSeconds: 0` is not "no lease": the bundled `InMemoryIdempotencyStore` and the diff --git a/docs/Transport-PDO.md b/docs/Transport-PDO.md index dc945f4..9a5be82 100644 --- a/docs/Transport-PDO.md +++ b/docs/Transport-PDO.md @@ -115,13 +115,23 @@ released or lapses. Keep `leaseSeconds` above your slowest handler — see ### Releasing a row you no longer hold A worker whose reservation has lapsed and been taken over by another worker does -not overwrite the new holder's row. `release()` updates only a row whose -`reserved_at` still has the stamp this transport instance wrote when it reserved -it, or (for a retry that records a new `attempts` and back-off) one that has since -been released; and a message put back **unchanged** (waiting for another handler) -never rewrites `payload` or `attempts`, so it cannot undo a retry another worker has -just recorded. The stamp has one-second resolution, so with `retryAfter: 0` two -reservations within the same second look alike. +not overwrite the new holder's reservation, but its failure still counts. +`release()` for a retry has two outcomes: + +- while the row is still reserved with the stamp this transport instance wrote (or + has been released since), it records `attempts`, the payload and the back-off and + frees the row. `attempts` only ever moves forward; +- if another worker holds the row now, it records the new `attempts` and payload and + extends the back-off, **without touching the holder's reservation**. So a handler + that always runs longer than `retryAfter` and always fails still reaches + `maxAttempts` and `jobs_failed`, as before. The holder's own outcome then + completes the job; this can take until its handler ends, so such a message is + dead-lettered later than a worker that cleared the other's reservation would have. + +A message put back **unchanged** (waiting for another handler) only reschedules the +row, only while the reservation is still its own, and never shortens a back-off +another worker recorded. The stamp has one-second resolution, so with +`retryAfter: 0` two reservations within the same second look alike. ## Lifecycle in SQL terms diff --git a/docs/Transport-RabbitMQ.md b/docs/Transport-RabbitMQ.md index 7019d2d..7893574 100644 --- a/docs/Transport-RabbitMQ.md +++ b/docs/Transport-RabbitMQ.md @@ -67,10 +67,23 @@ The order is deliberate. A worker that dies between the publish and the ack leav a duplicate, which RabbitMQ redelivers and the dispatcher's [deduplication](Idempotent-Consumption.md) recognises; acking first would leave no message at all. If the publish throws, the original is not acked and RabbitMQ -redelivers it. To also be safe against the broker not accepting the publish, put -the channel in publisher-confirm mode (`$channel->confirm_select()`): the transport -then waits (up to 30 s) for the confirm before it acks, and leaves the original -unacked if none arrives. Without confirm mode that wait returns at once. +redelivers it once the channel closes. To also be safe against the broker not +accepting the publish, put the channel in publisher-confirm mode +(`$channel->confirm_select()`). The transport then waits (up to 30 s) for the +confirm before it acks: + +- a broker **`nack`** or a **returned** message means the new copy is not on the + queue (a full queue with `x-overflow: reject-publish`, for example). The original + is requeued with `basic_nack(requeue: true)`, not acked, and a `QueueException` + is thrown; the worker logs `process.failed` and the message is tried again. Your + own `set_nack_handler()` and `set_return_listener()` callbacks still run: the + transport wraps them for the wait and puts them back. +- a **timeout** leaves the original unacked (it comes back when the channel + closes) and throws. The channel's pending confirms are then in an unknown state, + so restart the worker; until then every release waits for the lost confirm again. + +Without confirm mode that wait returns at once and a refused publish goes +unnoticed, so enable confirms if the queue can refuse messages. The same path puts back a message that is **waiting for another handler's in-flight key** (a `release` with a delay). It lands at the tail of the queue, so diff --git a/docs/Transport-Redis.md b/docs/Transport-Redis.md index dc87d12..87110c3 100644 --- a/docs/Transport-Redis.md +++ b/docs/Transport-Redis.md @@ -58,10 +58,14 @@ if it removed one, then: - delay `> 0` → `ZADD orders:delayed `. Because it is one script, a worker that dies cannot leave the message on no list at -all. And because the write happens only when the `LREM` removed the worker's own -entry, a worker that has **lost the message** (a reaper already moved it back onto -the queue) does not add a second copy: the live copy belongs to whoever reserves it -next, and the stale release is ignored. The same holds for `deadLetter()`. +all. A worker that has **lost the message** (a reaper already moved it back onto the +queue, so the `LREM` finds nothing) does not add a second copy either: it looks for +the live copy, first in `orders:delayed`, then on `orders`, and **replaces** it with +the new envelope. The failed attempt's `attempts` and back-off are carried onto the +one copy that exists. If no copy with the same body is found (a reaper that +rewrote the body, or the message already finished), the call changes nothing. The +same holds for `deadLetter()`: a worker that has lost the message quarantines the +live copy. On every `reserve()`, due members of `orders:delayed` (score `<= now`, at most 1000 at a time) are migrated back onto the ready list by another script, each member @@ -70,8 +74,8 @@ duplicated across workers. ### Dead-letter -`deadLetter()` removes the in-flight copy and `RPUSH`-es the annotated envelope -onto `orders:failed`, in one script, and only if the worker still owns the message. +`deadLetter()` removes the in-flight copy (or, failing that, the live copy, as +above) and `RPUSH`-es the annotated envelope onto `orders:failed`, in one script. ## Delivery semantics @@ -81,22 +85,43 @@ then exit) avoids stranding messages in normal operation; if you run workers tha can be killed mid-job, add a small reaper that moves long-idle `orders:processing` entries back onto `orders`. -A message is identified by its processing entry, so a worker acts on a message -only while that entry is still there. This is what stops a slow handler and a -reaper from splitting one message into two, and it has two consequences for the -reaper you write: +A message is identified by the body it was reserved with. A worker that finishes +after the reaper has moved its message back is not ignored: its retry or +dead-letter replaces the live copy (see above), so `attempts` still climbs and a +message that always fails reaches `maxAttempts` and `orders:failed`, whether or not +the reaper is faster than the handler. Two things are worth knowing when you write +the reaper: -- **Keep its delay above your slowest handler.** If a handler is still running when - the reaper moves its message back, the handler's later ack, retry or dead-letter - is ignored; the reclaimed copy is the one that carries on. -- **Count each reclaim as an attempt**: increment `attempts` in the envelope it - puts back. A reclaim means one attempt did not finish, and without the count a - handler that always outlives the reaper and always fails would never reach - `maxAttempts`. +- **Keep its delay above your slowest handler.** Moving a message back while its + handler is still running makes a second worker run it concurrently. +- **If it rewrites the envelope** (to add `attempts`, say), the late worker's retry + can no longer find the copy by its old body and is ignored; the reaper's own + increment is then the only count. Moving the body back unchanged lets both + count. With the dispatcher's [deduplication](Idempotent-Consumption.md), a reclaimed copy that finds the original handler's key still claimed is parked in `orders:delayed` -and re-checked, not discarded. +and re-checked, not discarded; the original handler's later failure then replaces +that parked copy. + +### Two paths, two guarantees + +The transport uses Lua scripts (`EVAL`) for `release()`, `deadLetter()` and the +delayed-set migration, and falls back to the same steps as separate commands when +the client cannot evaluate scripts: + +| | With `EVAL` (Predis, scripting allowed) | Without (adapter lacks `eval`, or the Redis user has no scripting permission) | +| --- | --- | --- | +| Ownership and live-copy replacement | yes | yes, the same rules | +| A crash between the steps | cannot lose the message: each operation is one script | can lose it: the processing entry is removed before the message is re-added | +| Concurrent workers on the delayed set | each member moves exactly once | each member is moved only by the worker whose `ZREM` wins, which is also exactly once | + +The fallback is chosen the first time `eval` fails as unavailable (no such method, a +different signature, `NOPERM`/unknown command); any other failure, a lost connection +for instance, is thrown as before. `reserve()`, `ack()` and `publish()` never need +scripting, so a client that implements only the commands listed below keeps +consuming. Run with scripting allowed if you can: it is what makes a crash during a +retry harmless. ## Using phpredis instead @@ -105,7 +130,11 @@ The consume side is written against `Predis\ClientInterface`. If you use the - install `predis/predis` (pure PHP, no extension needed — the supported path), or - wrap phpredis in a thin adapter exposing the same `blmove` / `rpush` / `lrem` / - `zadd` / `zrangebyscore` / `zrem` methods. + `zadd` / `zrangebyscore` / `zrem` methods. `eval` is optional: leave it out (let + the call throw `BadMethodCallException`) and the transport uses the + [command-by-command path](#two-paths-two-guarantees). If the adapter does provide + `eval`, it must accept Predis's argument order, `eval($script, $numKeys, ...$keysAndArgs)` + (phpredis takes `$script, $args, $numKeys`), or throw. For **publish-only** producers, the SDK's one-method `Transport` is just an `RPUSH` and is trivial to implement over phpredis directly. diff --git a/src/Transport/Amqp/AmqpTransport.php b/src/Transport/Amqp/AmqpTransport.php index 5883a60..0d854d7 100644 --- a/src/Transport/Amqp/AmqpTransport.php +++ b/src/Transport/Amqp/AmqpTransport.php @@ -8,8 +8,11 @@ use BabelQueue\Contracts\Transport; use BabelQueue\Transport\AmqpTransport as BabelAmqpTransport; use InitPHP\Queue\Contracts\ConsumerTransport; +use InitPHP\Queue\Exceptions\QueueException; use InitPHP\Queue\Message\ReceivedMessage; use PhpAmqpLib\Channel\AMQPChannel; +use ReflectionException; +use ReflectionProperty; /** * A RabbitMQ transport that completes the SDK's publish-only @@ -26,9 +29,11 @@ * persist) and only then acks the original delivery. That order is deliberate: a * worker that dies between the two leaves a duplicate (which the dispatcher's * idempotency layer recognises), where acking first would leave nothing; and if - * the publish fails the original is not acked and RabbitMQ redelivers it. When the - * caller has put the channel in publisher-confirm mode (`confirm_select()`), the - * ack also waits for the broker to confirm the new copy. Per-message delay is not applied — it + * the publish fails the original is not acked and RabbitMQ redelivers it once the + * channel closes. When the caller has put the channel in publisher-confirm mode + * (`confirm_select()`), the ack also waits for the broker to confirm the new copy, + * and a broker `nack` or a returned message counts as a failure: the original is + * requeued, not acked, and a {@see QueueException} is thrown. Per-message delay is not applied — it * needs the delayed-message exchange plugin; configure that on the broker if you * need back-off windows. * @@ -87,19 +92,86 @@ public function deadLetter(ReceivedMessage $message, string $payload): void /** * Publish the new copy, make sure the broker has it, then ack the original. A - * failure before the ack leaves the original unacked, so it is redelivered. + * failure before the ack leaves the original unacked (redelivered when the + * channel closes); a broker `nack` or a returned copy requeues it at once. + * + * @throws QueueException When the broker refused the new copy. */ private function republishThenAck(ReceivedMessage $message, string $payload, string $target): void { $this->publisher->publish($payload, $target); - // Returns at once unless the channel is in publisher-confirm mode, in which - // case it blocks until the broker has confirmed (or throws on timeout). - $this->channel->wait_for_pending_acks(self::CONFIRM_TIMEOUT); + $refusal = $this->awaitConfirmation(); + if ($refusal !== null) { + // The copy is not on the queue: keep the original by putting it back. + $this->channel->basic_nack($this->deliveryTag($message), false, true); + + throw new QueueException(sprintf( + 'RabbitMQ %s the republished message for "%s"; the original was requeued, not acked.', + $refusal, + $target, + )); + } $this->channel->basic_ack($this->deliveryTag($message)); } + /** + * Wait for the broker to settle every pending publish. Returns at once unless + * the channel is in publisher-confirm mode. Returns `'nacked'` or `'returned'` + * when the broker refused one, null when all were confirmed. + * + * The channel's own nack handler and return listener are wrapped, not replaced: + * the caller's still run, and are put back afterwards. A timeout throws and + * leaves the original unacked; the channel's pending confirms are then in an + * unknown state, so restart the worker. + */ + private function awaitConfirmation(): ?string + { + $refusal = null; + $userNack = $this->channelCallback('nack_handler'); + $userReturn = $this->channelCallback('basic_return_callback'); + + $this->channel->set_nack_handler(static function (mixed ...$arguments) use (&$refusal, $userNack): void { + $refusal ??= 'nacked'; + if ($userNack !== null) { + $userNack(...$arguments); + } + }); + $this->channel->set_return_listener(static function (mixed ...$arguments) use (&$refusal, $userReturn): void { + $refusal ??= 'returned'; + if ($userReturn !== null) { + $userReturn(...$arguments); + } + }); + + try { + $this->channel->wait_for_pending_acks_returns(self::CONFIRM_TIMEOUT); + } finally { + // amqplib cannot unset a handler; a no-op behaves exactly like none. + $this->channel->set_nack_handler($userNack ?? static function (): void {}); + $this->channel->set_return_listener($userReturn ?? static function (): void {}); + } + + return $refusal; + } + + /** + * Read a callback php-amqplib keeps in a private property (it has no getter), so + * that it can be wrapped instead of overwritten. Null when none is set or the + * installed version stores it differently. + */ + private function channelCallback(string $property): ?callable + { + try { + $callback = (new ReflectionProperty(AMQPChannel::class, $property))->getValue($this->channel); + } catch (ReflectionException) { + return null; + } + + return is_callable($callback) ? $callback : null; + } + private function deliveryTag(ReceivedMessage $message): int { return (int) $message->receipt(); diff --git a/src/Transport/Pdo/PdoTransport.php b/src/Transport/Pdo/PdoTransport.php index c10c103..3529cdd 100644 --- a/src/Transport/Pdo/PdoTransport.php +++ b/src/Transport/Pdo/PdoTransport.php @@ -24,12 +24,14 @@ * reservation older than `$retryAfter` seconds is treated as abandoned and * becomes reservable again, so a crashed worker never loses a message. * - * `release()` is conditional on the reservation this transport instance took: a + * `release()` is conditional on the reservation this transport instance took. A * worker whose reservation lapsed and was taken over cannot overwrite the new - * holder's row, and a verbatim release (a message put back unchanged) never - * touches `payload` or `attempts`, so it cannot undo a retry another worker has - * just recorded. The stamp has one-second resolution, so with `$retryAfter` of 0 - * two reservations inside the same second look alike. + * holder's reservation, but a retry it reports still counts: the new `attempts` + * and payload are recorded without touching the reservation, so `maxAttempts` is + * reached whoever holds the row. A verbatim release (a message put back + * unchanged) never touches `payload` or `attempts` and never shortens a back-off. + * The stamp has one-second resolution, so with `$retryAfter` of 0 two + * reservations inside the same second look alike. * * The whole envelope is stored as JSON in `payload`; `queue`, `urn`, `trace_id` * and `attempts` are denormalised into columns purely for indexing and @@ -140,29 +142,87 @@ public function release(ReceivedMessage $message, string $payload, int $delaySec $stamp = $this->reservations[$id] ?? null; unset($this->reservations[$id]); - $params = [ - ':available_at' => $this->at(max(0, $delaySeconds)), - ':id' => $id, - ]; + $availableAt = $this->at(max(0, $delaySeconds)); if ($payload === $message->rawBody()) { - // Put back unchanged: only reschedule, and only while the reservation - // is still ours; never rewrite a retry another worker recorded. - $set = 'available_at = :available_at, reserved_at = NULL'; - $guard = $stamp !== null ? ' AND reserved_at = :stamp' : ''; - } else { - $set = 'payload = :payload, attempts = :attempts, available_at = :available_at, reserved_at = NULL'; - // A retry applies unless someone else holds the row right now. - $guard = $stamp !== null ? ' AND (reserved_at = :stamp OR reserved_at IS NULL)' : ''; - $params[':payload'] = $payload; - $params[':attempts'] = $this->attemptsOf(EnvelopeCodec::decode($payload)); + $this->putBackUnchanged($id, $stamp, $availableAt); + + return; + } + + $attempts = $this->attemptsOf(EnvelopeCodec::decode($payload)); + + if ($stamp === null) { + // A message this instance did not reserve: no stamp to compare. + $this->pdo->prepare( + "UPDATE {$this->table} SET payload = :payload, attempts = :attempts, available_at = :available_at, reserved_at = NULL WHERE id = :id", + )->execute([':payload' => $payload, ':attempts' => $attempts, ':available_at' => $availableAt, ':id' => $id]); + + return; + } + + // A retry. Applies in full while the reservation is still ours, or the row + // has been released since. `attempts` only ever moves forward, so two + // workers recording the same failure cannot lower it. (payload comes first + // because MySQL evaluates the assignments left to right.) + $owned = $this->pdo->prepare( + "UPDATE {$this->table} SET" + . ' payload = CASE WHEN attempts > :attempts_a THEN payload ELSE :payload END,' + . ' attempts = CASE WHEN attempts > :attempts_b THEN attempts ELSE :attempts_c END,' + . ' available_at = :available_at, reserved_at = NULL' + . ' WHERE id = :id AND (reserved_at = :stamp OR reserved_at IS NULL)', + ); + $owned->execute([ + ':attempts_a' => $attempts, + ':attempts_b' => $attempts, + ':attempts_c' => $attempts, + ':payload' => $payload, + ':available_at' => $availableAt, + ':id' => $id, + ':stamp' => $stamp, + ]); + + if ($owned->rowCount() > 0) { + return; } + // Another worker holds the row now (our reservation lapsed and was taken + // over). The failure still counts: record the attempt and its back-off + // without touching the holder's reservation, so a handler that always runs + // longer than `retryAfter` still reaches `maxAttempts` and the dead-letter + // table, as it did before. A delay is only ever extended, never shortened. + $this->pdo->prepare( + "UPDATE {$this->table} SET payload = :payload, attempts = :attempts," + . ' available_at = CASE WHEN available_at > :available_a THEN available_at ELSE :available_b END' + . ' WHERE id = :id AND attempts < :attempts_guard', + )->execute([ + ':payload' => $payload, + ':attempts' => $attempts, + ':available_a' => $availableAt, + ':available_b' => $availableAt, + ':id' => $id, + ':attempts_guard' => $attempts, + ]); + } + + /** + * Put a message back unchanged: only reschedule it, and only while the + * reservation is still ours, so it can neither undo a retry another worker has + * recorded nor shorten its back-off. + */ + private function putBackUnchanged(int $id, ?string $stamp, string $availableAt): void + { + $guard = $stamp !== null ? ' AND reserved_at = :stamp' : ''; + $params = [':available_a' => $availableAt, ':available_b' => $availableAt, ':id' => $id]; if ($stamp !== null) { $params[':stamp'] = $stamp; } - $this->pdo->prepare("UPDATE {$this->table} SET {$set} WHERE id = :id{$guard}")->execute($params); + $this->pdo->prepare( + "UPDATE {$this->table} SET" + . ' available_at = CASE WHEN available_at > :available_a THEN available_at ELSE :available_b END,' + . " reserved_at = NULL WHERE id = :id{$guard}", + )->execute($params); } public function deadLetter(ReceivedMessage $message, string $payload): void diff --git a/src/Transport/Redis/RedisTransport.php b/src/Transport/Redis/RedisTransport.php index 5da6412..79a2fdf 100644 --- a/src/Transport/Redis/RedisTransport.php +++ b/src/Transport/Redis/RedisTransport.php @@ -7,9 +7,13 @@ use BabelQueue\Codec\EnvelopeCodec; use BabelQueue\Contracts\Transport; use BabelQueue\Transport\RedisTransport as BabelRedisTransport; +use BadMethodCallException; +use Error; use InitPHP\Queue\Contracts\ConsumerTransport; use InitPHP\Queue\Message\ReceivedMessage; use Predis\ClientInterface; +use Predis\Response\ServerException; +use Throwable; /** * A reliable-queue Redis transport that completes the SDK's publish-only @@ -24,12 +28,19 @@ * dead-letters go to a `:failed` list. * * `release()`, `deadLetter()` and the delayed-set migration each run as one Lua - * script, so they are atomic: a worker that dies half way cannot leave a message - * on no list at all. `release()` and `deadLetter()` also act only while the - * message is still **this worker's** (its `LREM` from the processing list removes - * one entry); if a reaper has already moved the message back onto the queue, the - * live copy belongs to whoever reserves it next and the stale write is ignored, - * which keeps one message from forking into two copies. + * script when the client can `EVAL`, so they are atomic: a worker that dies half + * way cannot leave a message on no list at all. `release()` and `deadLetter()` + * also never fork a message. They act on the worker's own processing entry + * (`LREM` removes one); when a reaper has already moved the message back, they + * replace the live copy instead (still on the queue, or parked in the delayed + * set, with the same body), so the failure's `attempts` and back-off are carried + * onto the one copy that exists. If the live copy cannot be found (a reaper that + * rewrote the body, or the message already finished) the call is ignored. + * + * A client without `EVAL` (an adapter that only implements the commands listed in + * the docs, or a Redis user without scripting permission) is not an error: the + * transport falls back to issuing the same steps as separate commands, with the + * same ownership rules but without atomicity. * * Requires Redis 6.2+ (for `BLMOVE`; Lua scripting is built in). Optional * dependency: `predis/predis`. @@ -38,12 +49,15 @@ final class RedisTransport implements Transport, ConsumerTransport { /** * KEYS: processing, queue, delayed. ARGV: receipt, payload, due time (0 = now). - * Re-queues only when this worker still owns the processing entry. + * Takes the worker's own processing entry, or else the live copy (parked in + * the delayed set, or on the queue), and puts the new payload in its place. */ private const RELEASE_SCRIPT = <<<'LUA' -- queue:release if redis.call('LREM', KEYS[1], 1, ARGV[1]) < 1 then - return 0 + if redis.call('ZREM', KEYS[3], ARGV[1]) < 1 and redis.call('LREM', KEYS[2], 1, ARGV[1]) < 1 then + return 0 + end end if tonumber(ARGV[3]) > 0 then redis.call('ZADD', KEYS[3], ARGV[3], ARGV[2]) @@ -54,12 +68,14 @@ final class RedisTransport implements Transport, ConsumerTransport LUA; /** - * KEYS: processing, failed. ARGV: receipt, payload. + * KEYS: processing, failed, delayed, queue. ARGV: receipt, payload. */ private const DEAD_LETTER_SCRIPT = <<<'LUA' -- queue:dead-letter if redis.call('LREM', KEYS[1], 1, ARGV[1]) < 1 then - return 0 + if redis.call('ZREM', KEYS[3], ARGV[1]) < 1 and redis.call('LREM', KEYS[4], 1, ARGV[1]) < 1 then + return 0 + end end redis.call('RPUSH', KEYS[2], ARGV[2]) return 1 @@ -81,6 +97,9 @@ final class RedisTransport implements Transport, ConsumerTransport private readonly BabelRedisTransport $publisher; + /** Whether the client can EVAL; cleared the first time it proves it cannot. */ + private bool $scripting = true; + public function __construct( private readonly ClientInterface $client, private readonly string $defaultQueue = 'default', @@ -127,45 +146,128 @@ public function ack(ReceivedMessage $message): void public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void { $queue = $message->queue(); + $processing = $queue . $this->processingSuffix; + $delayed = $queue . $this->delayedSuffix; + $receipt = (string) $message->receipt(); + $due = $delaySeconds > 0 ? time() + $delaySeconds : 0; - $this->client->eval( - self::RELEASE_SCRIPT, - 3, - $queue . $this->processingSuffix, - $queue, - $queue . $this->delayedSuffix, - (string) $message->receipt(), - $payload, - (string) ($delaySeconds > 0 ? time() + $delaySeconds : 0), - ); + if ($this->evaluate(self::RELEASE_SCRIPT, [$processing, $queue, $delayed], [$receipt, $payload, (string) $due])) { + return; + } + + // Without scripting: the same steps, one command at a time. + if (! $this->takeOwnership($processing, $delayed, $queue, $receipt)) { + return; + } + + if ($due > 0) { + $this->client->zadd($delayed, [$payload => $due]); + + return; + } + + $this->client->rpush($queue, [$payload]); } public function deadLetter(ReceivedMessage $message, string $payload): void { $queue = $message->queue(); + $processing = $queue . $this->processingSuffix; + $failed = $queue . $this->failedSuffix; + $delayed = $queue . $this->delayedSuffix; + $receipt = (string) $message->receipt(); - $this->client->eval( - self::DEAD_LETTER_SCRIPT, - 2, - $queue . $this->processingSuffix, - $queue . $this->failedSuffix, - (string) $message->receipt(), - $payload, - ); + if ($this->evaluate(self::DEAD_LETTER_SCRIPT, [$processing, $failed, $delayed, $queue], [$receipt, $payload])) { + return; + } + + if ($this->takeOwnership($processing, $delayed, $queue, $receipt)) { + $this->client->rpush($failed, [$payload]); + } + } + + /** + * Run one of the scripts. Returns false (without having done anything) when the + * client cannot evaluate scripts, so the caller can take the command-by-command + * path; any other failure, such as a lost connection, is rethrown. + * + * @param list $keys + * @param list $args + */ + private function evaluate(string $script, array $keys, array $args): bool + { + if (! $this->scripting) { + return false; + } + + try { + $this->client->eval($script, count($keys), ...$keys, ...$args); + + return true; + } catch (Throwable $e) { + if (! $this->isScriptingUnavailable($e)) { + throw $e; + } + + $this->scripting = false; + + return false; + } + } + + /** + * Whether `$e` means "this client cannot EVAL" (no such method, a different + * signature, or a server that refuses the command) rather than a real failure. + */ + private function isScriptingUnavailable(Throwable $e): bool + { + if ($e instanceof BadMethodCallException || $e instanceof Error) { + return true; + } + + if ($e instanceof ServerException) { + $reason = strtolower($e->getMessage()); + + return str_contains($reason, 'noperm') + || str_contains($reason, 'unknown command') + || str_contains($reason, 'not allowed'); + } + + return false; } /** - * Move any delayed messages whose time has come back onto the main queue, in - * one atomic script so concurrent workers cannot duplicate or drop them. + * The non-scripted twin of the ownership rule: take the worker's own processing + * entry, or else the live copy; false when there is nothing to act on. + */ + private function takeOwnership(string $processing, string $delayed, string $queue, string $receipt): bool + { + return (int) $this->client->lrem($processing, 1, $receipt) > 0 + || (int) $this->client->zrem($delayed, $receipt) > 0 + || (int) $this->client->lrem($queue, 1, $receipt) > 0; + } + + /** + * Move any delayed messages whose time has come back onto the main queue. With + * scripting this is one atomic script, so concurrent workers cannot duplicate or + * drop a member; without it each member is re-enqueued only by the worker that + * wins its `ZREM`. */ private function migrateDueDelayed(string $queue): void { - $this->client->eval( - self::MIGRATE_SCRIPT, - 2, - $queue . $this->delayedSuffix, - $queue, - (string) time(), - ); + $delayed = $queue . $this->delayedSuffix; + + if ($this->evaluate(self::MIGRATE_SCRIPT, [$delayed, $queue], [(string) time()])) { + return; + } + + /** @var list $due */ + $due = $this->client->zrangebyscore($delayed, '-inf', (string) time()); + + foreach ($due as $payload) { + if ((int) $this->client->zrem($delayed, $payload) > 0) { + $this->client->rpush($queue, [$payload]); + } + } } } diff --git a/tests/Consumer/InFlightRedeliveryTest.php b/tests/Consumer/InFlightRedeliveryTest.php index 142074b..c9fb41f 100644 --- a/tests/Consumer/InFlightRedeliveryTest.php +++ b/tests/Consumer/InFlightRedeliveryTest.php @@ -317,7 +317,7 @@ public function test_a_stale_holder_cannot_overwrite_a_retry_recorded_by_another self::assertGreaterThan(time() + 30, strtotime((string) $pdo->query('SELECT available_at FROM jobs')->fetchColumn())); } - public function test_a_release_does_not_touch_a_row_another_worker_holds_now(): void + public function test_a_failure_still_counts_when_another_worker_holds_the_row(): void { $pdo = new PDO('sqlite::memory:'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); @@ -333,11 +333,96 @@ public function test_a_release_does_not_touch_a_row_another_worker_holds_now(): $envelope = $message->envelope(); $envelope['attempts'] = 1; - $transport->release($message, EnvelopeCodec::encode($envelope), 30); + $transport->release($message, EnvelopeCodec::encode($envelope), 60); - $row = $pdo->query('SELECT attempts, reserved_at FROM jobs')->fetch(PDO::FETCH_ASSOC); - self::assertSame(0, (int) $row['attempts'], 'the new holder keeps its row'); - self::assertSame('2999-01-01 00:00:00', $row['reserved_at']); + $row = $pdo->query('SELECT attempts, reserved_at, available_at, payload FROM jobs')->fetch(PDO::FETCH_ASSOC); + self::assertSame(1, (int) $row['attempts'], 'the failed attempt is counted'); + self::assertSame(1, EnvelopeCodec::decode($row['payload'])['attempts']); + self::assertSame('2999-01-01 00:00:00', $row['reserved_at'], 'the holder keeps its reservation'); + self::assertGreaterThan(time() + 30, strtotime((string) $row['available_at']), 'the back-off is recorded'); + } + + public function test_a_holders_unchanged_release_does_not_shorten_a_recorded_back_off(): void + { + // A holds the row; B (its reservation lapsed) fails and records a 60 s back-off; + // A then puts the message back unchanged with a 5 s wait. + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $a = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $a->createSchema(); + $b = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $a->publish($this->payload('msg-1'), 'orders'); + + $held = $a->reserve('orders'); + $lapsed = $b->reserve('orders'); + self::assertNotNull($held); + self::assertNotNull($lapsed); + $pdo->exec("UPDATE jobs SET reserved_at = '2999-01-01 00:00:00'"); // A's stamp differs from B's + + $envelope = $lapsed->envelope(); + $envelope['attempts'] = 1; + $b->release($lapsed, EnvelopeCodec::encode($envelope), 60); + + $pdo->exec("UPDATE jobs SET reserved_at = '" . date('Y-m-d H:i:s') . "'"); // A's reservation again + $a->release($held, $held->rawBody(), 5); + + $row = $pdo->query('SELECT attempts, available_at FROM jobs')->fetch(PDO::FETCH_ASSOC); + self::assertSame(1, (int) $row['attempts']); + self::assertGreaterThan(time() + 30, strtotime((string) $row['available_at']), 'the 60 s back-off was not cut to 5 s'); + } + + public function test_a_recorded_attempt_count_never_goes_back(): void + { + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 0); + $transport->createSchema(); + $transport->publish($this->payload('msg-1'), 'orders'); + + $message = $transport->reserve('orders'); + self::assertNotNull($message); + $pdo->exec('UPDATE jobs SET attempts = 3'); + + $envelope = $message->envelope(); + $envelope['attempts'] = 1; + $transport->release($message, EnvelopeCodec::encode($envelope), 0); + + self::assertSame(3, (int) $pdo->query('SELECT attempts FROM jobs')->fetchColumn()); + self::assertNull($pdo->query('SELECT reserved_at FROM jobs')->fetchColumn() ?: null, 'the reservation is still released'); + } + + public function test_a_handler_slower_than_the_reservation_still_reaches_the_dead_letter_table_without_idempotency(): void + { + // No idempotency. Every time the handler throws, the row has meanwhile been + // taken over by another worker (a different reservation stamp). + $pdo = new PDO('sqlite::memory:'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $transport = new PdoTransport($pdo, 'jobs', null, 'default', 90); + $transport->createSchema(); + $transport->publish($this->payload('msg-1'), 'orders'); + + $handlers = (new HandlerMap())->register(self::URN, function () use ($pdo): void { + $pdo->exec("UPDATE jobs SET reserved_at = '2999-01-01 00:00:00'"); // taken over while we run + + throw new RuntimeException('downstream failed'); + }); + $worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(maxAttempts: 3, backoff: [0])); + + $seen = []; + for ($i = 0; $i < 6; ++$i) { + $pdo->exec("UPDATE jobs SET reserved_at = NULL, available_at = '2000-01-01 00:00:00'"); // the other worker let go + if (! $worker->runOnce('orders')) { + break; + } + $attempts = $pdo->query('SELECT attempts FROM jobs')->fetchColumn(); + if ($attempts !== false) { + $seen[] = (int) $attempts; + } + } + + self::assertSame([1, 2], $seen, 'attempts climb on every failure'); + self::assertSame(0, (int) $pdo->query('SELECT COUNT(*) FROM jobs')->fetchColumn()); + self::assertSame(1, (int) $pdo->query('SELECT COUNT(*) FROM jobs_failed')->fetchColumn(), 'the message is dead-lettered at maxAttempts'); } public function test_the_in_flight_delay_must_be_at_least_one_second(): void diff --git a/tests/Integration/RedisIntegrationTest.php b/tests/Integration/RedisIntegrationTest.php index ec8147e..e16c2a5 100644 --- a/tests/Integration/RedisIntegrationTest.php +++ b/tests/Integration/RedisIntegrationTest.php @@ -123,7 +123,7 @@ public function test_a_delayed_release_parks_the_message_and_migrates_it_when_du self::assertSame(1, $this->copies()); } - public function test_a_release_or_dead_letter_from_a_worker_that_lost_the_message_does_not_fork_it(): void + public function test_a_release_from_a_worker_that_lost_the_message_replaces_the_live_copy(): void { $message = $this->publishAndReserve(); $this->reap($message); @@ -131,10 +131,39 @@ public function test_a_release_or_dead_letter_from_a_worker_that_lost_the_messag $retry = $message->envelope(); $retry['attempts'] = 1; $this->transport->release($message, EnvelopeCodec::encode($retry), 30); + + self::assertSame(1, $this->copies(), 'still one copy'); + self::assertSame(0, (int) $this->client->llen(self::QUEUE), 'the reaped copy was taken off the queue'); + $parked = $this->client->zrange(self::QUEUE . ':delayed', 0, -1); + self::assertCount(1, $parked); + self::assertSame(1, EnvelopeCodec::decode($parked[0])['attempts'], 'the failed attempt is carried onto it'); + } + + public function test_a_dead_letter_from_a_worker_that_lost_the_message_quarantines_the_live_copy(): void + { + $message = $this->publishAndReserve(); + $this->reap($message); + $this->transport->deadLetter($message, $message->rawBody()); - self::assertSame(1, $this->copies(), 'only the reaped copy is live'); - self::assertSame(1, (int) $this->client->llen(self::QUEUE)); + self::assertSame(1, $this->copies()); + self::assertSame(0, (int) $this->client->llen(self::QUEUE)); + self::assertSame(1, (int) $this->client->llen(self::QUEUE . ':failed')); + } + + public function test_a_release_for_a_message_that_is_gone_is_ignored(): void + { + $message = $this->publishAndReserve(); + $this->client->lrem(self::QUEUE . ':processing', 1, $message->rawBody()); + $rewritten = $message->envelope(); + $rewritten['attempts'] = 1; + $this->client->rpush(self::QUEUE, [EnvelopeCodec::encode($rewritten)]); // a reaper that counted the reclaim + + $this->transport->release($message, $message->rawBody(), 0); + $this->transport->deadLetter($message, $message->rawBody()); + + self::assertSame(1, $this->copies()); + self::assertSame(0, (int) $this->client->llen(self::QUEUE . ':failed')); } public function test_a_message_waiting_on_an_in_flight_key_is_parked_not_lost(): void diff --git a/tests/Support/InMemoryRedis.php b/tests/Support/InMemoryRedis.php index 26c3c53..62c3320 100644 --- a/tests/Support/InMemoryRedis.php +++ b/tests/Support/InMemoryRedis.php @@ -25,6 +25,12 @@ final class InMemoryRedis implements ClientInterface /** @var array> member => score */ private array $zsets = []; + /** + * @param bool $scripting False models a client without EVAL (the documented + * adapter surface, or a user without scripting rights). + */ + public function __construct(private readonly bool $scripting = true) {} + public function blmove(string $source, string $destination, string $from, string $to, int $timeout): ?string { if (empty($this->lists[$source])) { @@ -119,17 +125,22 @@ public function zrem(string $key, string $member): int } /** - * Emulates EVAL for the transport's scripts only. + * Emulates EVAL for the transport's scripts only. With `$scripting` false it + * behaves like an adapter that does not implement `eval` at all. * * @return int */ public function eval(string $script, int $numKeys, string ...$args): mixed { + if (! $this->scripting) { + throw new BadMethodCallException('InMemoryRedis does not implement "eval".'); + } + $keys = array_slice($args, 0, $numKeys); $argv = array_slice($args, $numKeys); if (str_contains($script, '-- queue:release')) { - if ($this->lrem($keys[0], 1, $argv[0]) < 1) { + if (! $this->takeOwnership($keys[0], $keys[2], $keys[1], $argv[0])) { return 0; } (float) $argv[2] > 0 @@ -140,7 +151,7 @@ public function eval(string $script, int $numKeys, string ...$args): mixed } if (str_contains($script, '-- queue:dead-letter')) { - if ($this->lrem($keys[0], 1, $argv[0]) < 1) { + if (! $this->takeOwnership($keys[0], $keys[2], $keys[3], $argv[0])) { return 0; } $this->rpush($keys[1], [$argv[1]]); @@ -161,6 +172,14 @@ public function eval(string $script, int $numKeys, string ...$args): mixed throw new BadMethodCallException('InMemoryRedis cannot evaluate this script.'); } + /** The processing entry, else the live copy in the delayed set, else on the queue. */ + private function takeOwnership(string $processing, string $delayed, string $queue, string $receipt): bool + { + return $this->lrem($processing, 1, $receipt) > 0 + || $this->zrem($delayed, $receipt) > 0 + || $this->lrem($queue, 1, $receipt) > 0; + } + /** * @return list */ @@ -169,6 +188,14 @@ public function list(string $key): array return $this->lists[$key] ?? []; } + /** + * @return list the members of a sorted set, by score + */ + public function members(string $key): array + { + return $this->zrangebyscore($key, '-inf', '+inf'); + } + public function zcard(string $key): int { return count($this->zsets[$key] ?? []); diff --git a/tests/Transport/AmqpTransportTest.php b/tests/Transport/AmqpTransportTest.php index 7360a9b..a91034c 100644 --- a/tests/Transport/AmqpTransportTest.php +++ b/tests/Transport/AmqpTransportTest.php @@ -5,6 +5,7 @@ namespace InitPHP\Queue\Tests\Transport; use BabelQueue\Codec\EnvelopeCodec; +use InitPHP\Queue\Exceptions\QueueException; use InitPHP\Queue\Message\ReceivedMessage; use InitPHP\Queue\Transport\Amqp\AmqpTransport; use Mockery; @@ -68,7 +69,9 @@ public function test_release_publishes_the_new_copy_before_it_acks_the_original( $channel = Mockery::mock(AMQPChannel::class); $channel->shouldReceive('queue_declare'); $channel->shouldReceive('basic_publish')->once()->ordered(); - $channel->shouldReceive('wait_for_pending_acks')->once()->ordered(); + $channel->shouldReceive('set_nack_handler'); + $channel->shouldReceive('set_return_listener'); + $channel->shouldReceive('wait_for_pending_acks_returns')->once()->ordered(); $channel->shouldReceive('basic_ack')->once()->with(42)->ordered(); $raw = $this->envelope(); @@ -93,7 +96,9 @@ public function test_an_unconfirmed_publish_leaves_the_original_unacked(): void $channel = Mockery::mock(AMQPChannel::class); $channel->shouldReceive('queue_declare'); $channel->shouldReceive('basic_publish')->once(); - $channel->shouldReceive('wait_for_pending_acks')->once()->andThrow(new \RuntimeException('confirm timeout')); + $channel->shouldReceive('set_nack_handler'); + $channel->shouldReceive('set_return_listener'); + $channel->shouldReceive('wait_for_pending_acks_returns')->once()->andThrow(new \RuntimeException('confirm timeout')); $channel->shouldNotReceive('basic_ack'); $raw = $this->envelope(); @@ -107,10 +112,95 @@ public function test_dead_letter_publishes_to_the_failed_queue_before_it_acks(): $channel = Mockery::mock(AMQPChannel::class); $channel->shouldReceive('queue_declare')->once()->with('orders.failed', false, true, false, false); $channel->shouldReceive('basic_publish')->once()->ordered(); - $channel->shouldReceive('wait_for_pending_acks')->once()->ordered(); + $channel->shouldReceive('set_nack_handler'); + $channel->shouldReceive('set_return_listener'); + $channel->shouldReceive('wait_for_pending_acks_returns')->once()->ordered(); $channel->shouldReceive('basic_ack')->once()->with(42)->ordered(); $raw = $this->envelope(); (new AmqpTransport($channel))->deadLetter($this->reserved($raw), $raw); } + + public function test_a_broker_nack_requeues_the_original_instead_of_acking_it(): void + { + $nackHandler = null; + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_publish')->once(); + $channel->shouldReceive('set_nack_handler')->andReturnUsing(function (callable $handler) use (&$nackHandler): void { + $nackHandler ??= $handler; // the first one is the transport's wrapper + }); + $channel->shouldReceive('set_return_listener'); + // The broker refuses the publish while the transport waits for confirms. + $channel->shouldReceive('wait_for_pending_acks_returns')->once()->andReturnUsing(function () use (&$nackHandler): void { + $nackHandler(new AMQPMessage('body')); + }); + $channel->shouldReceive('basic_nack')->once()->with(42, false, true); + $channel->shouldNotReceive('basic_ack'); + + $raw = $this->envelope(); + + $this->expectException(QueueException::class); + $this->expectExceptionMessage('nacked'); + (new AmqpTransport($channel))->release($this->reserved($raw), $raw, 0); + } + + public function test_a_returned_message_requeues_the_original_instead_of_acking_it(): void + { + $returnListener = null; + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_publish')->once(); + $channel->shouldReceive('set_nack_handler'); + $channel->shouldReceive('set_return_listener')->andReturnUsing(function (callable $listener) use (&$returnListener): void { + $returnListener ??= $listener; + }); + $channel->shouldReceive('wait_for_pending_acks_returns')->once()->andReturnUsing(function () use (&$returnListener): void { + $returnListener(312, 'NO_ROUTE', '', 'orders.failed', new AMQPMessage('body')); + }); + $channel->shouldReceive('basic_nack')->once()->with(42, false, true); + $channel->shouldNotReceive('basic_ack'); + + $raw = $this->envelope(); + + $this->expectException(QueueException::class); + $this->expectExceptionMessage('returned'); + (new AmqpTransport($channel))->deadLetter($this->reserved($raw), $raw); + } + + public function test_the_callers_own_nack_handler_still_runs_and_is_put_back(): void + { + $seen = []; + $own = static function (AMQPMessage $message) use (&$seen): void { + $seen[] = $message->getBody(); + }; + + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_publish')->once(); + + // Give the (mock) channel the handler the caller installed earlier. + $property = new \ReflectionProperty(AMQPChannel::class, 'nack_handler'); + $property->setValue($channel, $own); + + $installed = []; + $channel->shouldReceive('set_nack_handler')->andReturnUsing(function (callable $handler) use (&$installed): void { + $installed[] = $handler; + }); + $channel->shouldReceive('set_return_listener'); + $channel->shouldReceive('wait_for_pending_acks_returns')->once()->andReturnUsing(function () use (&$installed): void { + $installed[0](new AMQPMessage('nacked-body')); + }); + $channel->shouldReceive('basic_nack')->once(); + + $raw = $this->envelope(); + try { + (new AmqpTransport($channel))->release($this->reserved($raw), $raw, 0); + self::fail('a nack must fail the release'); + } catch (QueueException) { + } + + self::assertSame(['nacked-body'], $seen, "the caller's handler was still called"); + self::assertSame($own, $installed[1], "the caller's handler is put back afterwards"); + } } diff --git a/tests/Transport/RedisTransportTest.php b/tests/Transport/RedisTransportTest.php index 2da6aa6..9294c60 100644 --- a/tests/Transport/RedisTransportTest.php +++ b/tests/Transport/RedisTransportTest.php @@ -5,13 +5,24 @@ namespace InitPHP\Queue\Tests\Transport; use BabelQueue\Codec\EnvelopeCodec; +use InitPHP\Queue\Consumer\Dispatcher; +use InitPHP\Queue\Consumer\Worker; +use InitPHP\Queue\Consumer\WorkerOptions; use InitPHP\Queue\Message\ReceivedMessage; +use InitPHP\Queue\Routing\HandlerMap; use InitPHP\Queue\Tests\Support\InMemoryRedis; use InitPHP\Queue\Transport\Redis\RedisTransport; +use Mockery; +use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration; use PHPUnit\Framework\TestCase; +use Predis\ClientInterface; +use Predis\Response\ServerException; +use RuntimeException; final class RedisTransportTest extends TestCase { + use MockeryPHPUnitIntegration; + private InMemoryRedis $redis; private RedisTransport $transport; @@ -136,7 +147,7 @@ private function reap(ReceivedMessage $message): void $this->redis->rpush('orders', [$message->rawBody()]); } - public function test_a_release_from_a_worker_that_lost_the_message_does_not_fork_it(): void + public function test_a_release_from_a_worker_that_lost_the_message_replaces_the_live_copy(): void { $this->transport->publish($this->envelope(), 'orders'); $message = $this->transport->reserve('orders', 1.0); @@ -145,30 +156,52 @@ public function test_a_release_from_a_worker_that_lost_the_message_does_not_fork $this->reap($message); self::assertSame(1, $this->copies()); - // The original worker finally fails and releases a retry it no longer owns. + // The original worker finally fails and reports a retry it no longer owns. $this->transport->release($message, $this->withAttempts($message, 1), 30); - self::assertSame(1, $this->copies(), 'the reaped copy is the only live one'); - self::assertSame(0, $this->redis->zcard('orders:delayed')); + self::assertSame(1, $this->copies(), 'still one copy'); + self::assertSame([], $this->redis->list('orders'), 'the reaped copy was taken off the queue'); + $parked = $this->redis->members('orders:delayed'); + self::assertCount(1, $parked); + self::assertSame(1, EnvelopeCodec::decode($parked[0])['attempts'], 'the failed attempt is carried onto the live copy'); } - public function test_a_dead_letter_from_a_worker_that_lost_the_message_is_ignored(): void + public function test_a_dead_letter_from_a_worker_that_lost_the_message_quarantines_the_live_copy(): void { $this->transport->publish($this->envelope(), 'orders'); $message = $this->transport->reserve('orders', 1.0); self::assertNotNull($message); $this->reap($message); - $this->transport->deadLetter($message, $message->rawBody()); + $this->transport->deadLetter($message, $this->withAttempts($message, 3)); + + self::assertSame(1, $this->copies()); + self::assertSame([], $this->redis->list('orders')); + self::assertCount(1, $this->redis->list('orders:failed')); + } + + public function test_a_release_for_a_message_that_is_gone_is_ignored(): void + { + // A reaper that rewrote the body (say, to count the reclaim) leaves nothing + // that matches the late worker's receipt; the reaper's copy stays as it is. + $this->transport->publish($this->envelope(), 'orders'); + $message = $this->transport->reserve('orders', 1.0); + self::assertNotNull($message); + + $this->redis->lrem('orders:processing', 1, $message->rawBody()); + $this->redis->rpush('orders', [$this->withAttempts($message, 1)]); + + $this->transport->release($message, $this->withAttempts($message, 1), 0); + $this->transport->deadLetter($message, $this->withAttempts($message, 1)); - self::assertSame([], $this->redis->list('orders:failed')); self::assertSame(1, $this->copies()); + self::assertSame([], $this->redis->list('orders:failed')); } - public function test_an_in_flight_wait_followed_by_the_first_worker_failing_leaves_one_copy(): void + public function test_an_in_flight_wait_followed_by_the_first_worker_failing_leaves_one_copy_with_the_attempt(): void { - // A handler outlives the reaper, a second worker waits on the in-flight - // key, then the first handler throws. The message must not become two. + // A handler outlives the reaper, a second worker waits on the in-flight key, + // then the first handler throws. One copy remains, and it has the attempt. $this->transport->publish($this->envelope(), 'orders'); $first = $this->transport->reserve('orders', 1.0); self::assertNotNull($first); @@ -180,8 +213,85 @@ public function test_an_in_flight_wait_followed_by_the_first_worker_failing_leav $this->transport->release($first, $this->withAttempts($first, 1), 30); // first handler fails self::assertSame(1, $this->copies()); - self::assertSame(1, $this->redis->zcard('orders:delayed')); self::assertSame([], $this->redis->list('orders:processing')); + $parked = $this->redis->members('orders:delayed'); + self::assertCount(1, $parked); + self::assertSame(1, EnvelopeCodec::decode($parked[0])['attempts']); + } + + public function test_a_handler_slower_than_the_reaper_still_reaches_the_dead_letter_list_without_idempotency(): void + { + $handlers = (new HandlerMap())->register('urn:babel:orders:created', function (): void { + // The reaper moves the message back while the handler is still running. + $raw = $this->redis->list('orders:processing')[0]; + $this->redis->lrem('orders:processing', 1, $raw); + $this->redis->rpush('orders', [$raw]); + + throw new RuntimeException('downstream failed'); + }); + $worker = new Worker($this->transport, new Dispatcher($handlers), new WorkerOptions(maxAttempts: 3, backoff: [0])); + $this->transport->publish($this->envelope(), 'orders'); + + $seen = []; + for ($i = 0; $i < 6 && $worker->runOnce('orders'); ++$i) { + $live = array_merge($this->redis->list('orders'), $this->redis->members('orders:delayed')); + if ($live !== []) { + $seen[] = EnvelopeCodec::decode($live[0])['attempts']; + } + } + + self::assertSame([1, 2], $seen, 'every failure is counted'); + self::assertSame(1, count($this->redis->list('orders:failed')), 'the message reaches the dead-letter list at maxAttempts'); + self::assertSame(1, $this->copies(), 'one copy in total'); + self::assertSame([], $this->redis->list('orders:processing')); + } + + public function test_a_client_without_eval_gets_the_same_results_command_by_command(): void + { + $redis = new InMemoryRedis(scripting: false); + $transport = new RedisTransport($redis, 'default'); + $transport->publish($this->envelope(), 'orders'); + $message = $transport->reserve('orders', 1.0); + self::assertNotNull($message); + + // A lapsed reaper hands the message back; the late failure replaces it. + $redis->lrem('orders:processing', 1, $message->rawBody()); + $redis->rpush('orders', [$message->rawBody()]); + $transport->release($message, $this->withAttempts($message, 1), 30); + + self::assertSame([], $redis->list('orders')); + self::assertCount(1, $redis->members('orders:delayed')); + + $redis->zadd('orders:delayed', [$message->rawBody() => time() - 1]); + self::assertNotNull($transport->reserve('orders', 1.0), 'a due delayed message is migrated and reserved'); + } + + public function test_a_client_that_refuses_eval_falls_back_and_keeps_working(): void + { + $client = Mockery::mock(ClientInterface::class); + $client->shouldReceive('eval')->once()->andThrow(new ServerException('NOPERM this user has no permissions to run the \'eval\' command')); + $client->shouldReceive('lrem')->with('orders:processing', 1, 'raw')->once()->andReturn(1); + $client->shouldReceive('rpush')->with('orders', ['payload'])->once(); + + $transport = new RedisTransport($client, 'default'); + $transport->release(new ReceivedMessage('orders', 'raw', [], 'raw'), 'payload', 0); + + // Later calls go straight to the commands: eval is not tried again. + $client->shouldReceive('lrem')->with('orders:processing', 1, 'raw')->once()->andReturn(1); + $client->shouldReceive('rpush')->with('orders', ['payload'])->once(); + $transport->release(new ReceivedMessage('orders', 'raw', [], 'raw'), 'payload', 0); + + self::addToAssertionCount(1); + } + + public function test_a_real_failure_of_eval_is_not_swallowed(): void + { + $client = Mockery::mock(ClientInterface::class); + $client->shouldReceive('eval')->once()->andThrow(new RuntimeException('connection lost')); + $client->shouldNotReceive('lrem'); + + $this->expectException(RuntimeException::class); + (new RedisTransport($client, 'default'))->release(new ReceivedMessage('orders', 'raw', [], 'raw'), 'payload', 0); } public function test_migration_moves_each_due_member_exactly_once(): void From 6957b5b2fb74c04b87d2d2c393c4ba563b44df78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 10:34:40 +0300 Subject: [PATCH 4/6] fix(consumer): pause after a message the transport could not settle When RabbitMQ nacked a republish, the original was requeued and the worker took it straight back, re-running its handler in a tight loop without counting an attempt or applying a back-off. The worker now pauses after a process failure: the larger of 0.1s, sleepWhenEmpty and the back-off for the message's next attempt, capped at 5s and taken in short slices that a stop signal ends at once. Attempts cannot advance while the broker refuses the new copy; the RabbitMQ docs state that limit and advise a separate channel for a handler's own publishes. The Redis fallback now treats only NOPERM and unknown command as "scripting unavailable". --- CHANGELOG.md | 6 + docs/The-Worker.md | 2 +- docs/Transport-RabbitMQ.md | 17 ++- src/Consumer/Worker.php | 34 +++++ src/Transport/Redis/RedisTransport.php | 4 +- tests/Consumer/WorkerFailurePauseTest.php | 153 ++++++++++++++++++++++ 6 files changed, 209 insertions(+), 7 deletions(-) create mode 100644 tests/Consumer/WorkerFailurePauseTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a09f73..203c24b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). recorded without touching the holder's reservation, and `attempts` never goes back), so a handler slower than `retryAfter` that always fails still reaches `maxAttempts` and the dead-letter table. +- The `Worker` pauses after the transport fails to act on a message + (`process.failed`): the larger of 0.1 s, `sleepWhenEmpty` and the back-off for the + message's next attempt, at most 5 s, in short slices that a stop signal ends at + once. A message RabbitMQ keeps refusing (a nacked republish) no longer re-runs its + handler in a tight loop. Its `attempts` still do not advance while the broker + refuses the copy; see the RabbitMQ page. - A message deferred to wait for an in-flight key no longer counts towards `maxJobs` or `processedCount()`, and the worker pauses at least 0.1 s after a deferral even with `sleepWhenEmpty: 0`. diff --git a/docs/The-Worker.md b/docs/The-Worker.md index 829d584..1541212 100644 --- a/docs/The-Worker.md +++ b/docs/The-Worker.md @@ -138,7 +138,7 @@ $worker = new Worker($transport, new Dispatcher($handlers), new WorkerOptions(), | `job.dropped` | The message was acked-and-discarded: an unknown URN (`DELETE` strategy) or, with deduplication on, a duplicate whose handler already finished (`reason` `duplicate`). | | `job.released` | A message was put back without counting an attempt: an unknown URN (`RELEASE` strategy), or, with deduplication on, a key another handler still holds (`reason` `in_flight`, context has `delay`). | | `reserve.failed` | The transport threw while reserving (loop continues). | -| `process.failed` | The transport threw while acting on a message (loop continues). | +| `process.failed` | The transport threw while acting on a message (loop continues after a pause: the larger of 0.1 s, `sleepWhenEmpty` and the back-off for the message's next attempt, at most 5 s, ended at once by a stop signal). | ## The CLI diff --git a/docs/Transport-RabbitMQ.md b/docs/Transport-RabbitMQ.md index 7893574..2a50379 100644 --- a/docs/Transport-RabbitMQ.md +++ b/docs/Transport-RabbitMQ.md @@ -75,9 +75,20 @@ confirm before it acks: - a broker **`nack`** or a **returned** message means the new copy is not on the queue (a full queue with `x-overflow: reject-publish`, for example). The original is requeued with `basic_nack(requeue: true)`, not acked, and a `QueueException` - is thrown; the worker logs `process.failed` and the message is tried again. Your - own `set_nack_handler()` and `set_return_listener()` callbacks still run: the - transport wraps them for the wait and puts them back. + is thrown; the worker logs `process.failed`, **pauses** (see below) and the + message is tried again. Your own `set_nack_handler()` and `set_return_listener()` + callbacks still run: the transport wraps them for the wait and puts them back. + The requeued message is the original, so its `attempts` do not advance and no + back-off is recorded on it: RabbitMQ cannot take the new copy, so there is + nothing to carry the new count. The handler runs again on every retry of that + message, paced only by the worker's failure pause (the larger of 0.1 s, + `sleepWhenEmpty` and the back-off for its next attempt, at most 5 s), until the + broker accepts the copy: a queue that stays full keeps the message cycling, so + fix or drain it, and give the handler idempotent effects. +- confirms are tracked per channel: a nack for **another publish on the same channel** + (say your own handler's) also counts against the message being settled, and + requeues it although its copy was confirmed, which only costs a duplicate. Publish + from a handler on a separate channel. - a **timeout** leaves the original unacked (it comes back when the channel closes) and throws. The channel's pending confirms are then in an unknown state, so restart the worker; until then every release waits for the lost confirm again. diff --git a/src/Consumer/Worker.php b/src/Consumer/Worker.php index fdadcd2..e67bfa5 100644 --- a/src/Consumer/Worker.php +++ b/src/Consumer/Worker.php @@ -35,6 +35,13 @@ final class Worker */ private const DEFERRAL_PAUSE_SECONDS = 0.1; + /** + * The longest pause after a message could not be acted on (the transport threw + * while acking, releasing or dead-lettering it). Kept short so a connection that + * needs heartbeats is not left idle for long. + */ + private const FAILURE_PAUSE_CAP_SECONDS = 5.0; + private bool $shouldStop = false; private int $processed = 0; @@ -100,6 +107,7 @@ public function run(string $queue): void $counted = $this->process($message); } catch (Throwable $e) { $this->log('error', 'process.failed', $this->context($message, ['error' => $e->getMessage()])); + $this->pauseAfterFailure($message); } if ($counted) { @@ -295,6 +303,32 @@ private function dispatchSignals(): void } } + /** + * Wait before the next reservation after the transport failed to act on a + * message. Without it a message the broker keeps refusing (RabbitMQ rejecting a + * republish, a database that cannot be updated) comes straight back and its + * handler runs again at once. The wait is the larger of 0.1 s, `sleepWhenEmpty` + * and the back-off for the message's next attempt, capped at 5 s, and it is + * taken in short slices so a stop signal ends it at once. + */ + private function pauseAfterFailure(ReceivedMessage $message): void + { + $seconds = min( + self::FAILURE_PAUSE_CAP_SECONDS, + max( + self::DEFERRAL_PAUSE_SECONDS, + $this->options->sleepWhenEmpty, + (float) $this->options->delayForAttempt($message->attempts() + 1), + ), + ); + $until = microtime(true) + $seconds; + + while (! $this->shouldStop && ($left = $until - microtime(true)) > 0) { + $this->sleep(min($left, 0.25)); + $this->dispatchSignals(); + } + } + private function sleep(float $seconds): void { if ($seconds > 0) { diff --git a/src/Transport/Redis/RedisTransport.php b/src/Transport/Redis/RedisTransport.php index 79a2fdf..ac90259 100644 --- a/src/Transport/Redis/RedisTransport.php +++ b/src/Transport/Redis/RedisTransport.php @@ -228,9 +228,7 @@ private function isScriptingUnavailable(Throwable $e): bool if ($e instanceof ServerException) { $reason = strtolower($e->getMessage()); - return str_contains($reason, 'noperm') - || str_contains($reason, 'unknown command') - || str_contains($reason, 'not allowed'); + return str_contains($reason, 'noperm') || str_contains($reason, 'unknown command'); } return false; diff --git a/tests/Consumer/WorkerFailurePauseTest.php b/tests/Consumer/WorkerFailurePauseTest.php new file mode 100644 index 0000000..4c048db --- /dev/null +++ b/tests/Consumer/WorkerFailurePauseTest.php @@ -0,0 +1,153 @@ + 1], 'orders'); + $envelope['attempts'] = $attempts; + + return EnvelopeCodec::encode($envelope); + } + + /** + * A transport that always hands the same message back and refuses to settle it. + */ + private function refusingTransport(string $raw): ConsumerTransport + { + return new class ($raw) implements ConsumerTransport { + public function __construct(private readonly string $raw) {} + + public function reserve(string $queue, float $timeout = 5.0): ?ReceivedMessage + { + return new ReceivedMessage($queue, $this->raw, EnvelopeCodec::decode($this->raw), 1); + } + + public function ack(ReceivedMessage $message): void + { + throw new QueueException('refused'); + } + + public function release(ReceivedMessage $message, string $payload, int $delaySeconds = 0): void + { + throw new QueueException('refused'); + } + + public function deadLetter(ReceivedMessage $message, string $payload): void + { + throw new QueueException('refused'); + } + }; + } + + public function test_a_message_the_transport_keeps_refusing_does_not_spin_its_handler(): void + { + $handler = new RecordingHandler(); + $worker = new Worker( + $this->refusingTransport($this->raw()), + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(sleepWhenEmpty: 0.0, maxRuntime: 0.65), + ); + + $worker->run('orders'); + + self::assertGreaterThanOrEqual(1, count($handler->handled)); + self::assertLessThanOrEqual(8, count($handler->handled), 'about one run per 0.1 s pause, not thousands'); + } + + public function test_the_pause_follows_the_back_off_and_a_stop_ends_it_at_once(): void + { + $worker = null; + $runs = 0; + $handlers = (new HandlerMap())->register(self::URN, function () use (&$worker, &$runs): void { + ++$runs; + $worker->stop(); // a stop signal arrives while the failure pause would start + }); + $worker = new Worker( + $this->refusingTransport($this->raw()), + new Dispatcher($handlers), + new WorkerOptions(backoff: [30], sleepWhenEmpty: 0.0), + ); + + $startedAt = microtime(true); + $worker->run('orders'); + + self::assertSame(1, $runs); + self::assertLessThan(1.0, microtime(true) - $startedAt, 'the 5 s pause is skipped once a stop is requested'); + } + + public function test_a_rabbitmq_nack_of_the_dead_letter_republish_does_not_spin_the_handler(): void + { + // The dead-letter queue refuses publishes (x-overflow reject-publish) and the + // message is at maxAttempts, so every run ends in a nack and a requeue. + $body = $this->raw(attempts: 2); + $nackHandler = null; + + $delivered = Mockery::mock(AMQPMessage::class); + $delivered->shouldReceive('getBody')->andReturn($body); + $delivered->shouldReceive('getDeliveryTag')->andReturn(7); + + $channel = Mockery::mock(AMQPChannel::class); + $channel->shouldReceive('queue_declare'); + $channel->shouldReceive('basic_get')->andReturn($delivered); + $channel->shouldReceive('basic_publish'); + $channel->shouldReceive('set_return_listener'); + $channel->shouldReceive('set_nack_handler')->andReturnUsing(function (callable $handler) use (&$nackHandler): void { + $nackHandler = $handler; + }); + $channel->shouldReceive('wait_for_pending_acks_returns')->andReturnUsing(function () use (&$nackHandler): void { + $nackHandler(new AMQPMessage('refused')); + }); + $channel->shouldReceive('basic_nack')->with(7, false, true); + $channel->shouldNotReceive('basic_ack'); + + $handler = new class implements \InitPHP\Queue\Contracts\Handler { + public int $calls = 0; + + public function handle(\BabelQueue\Contracts\InboundMessage $message): void + { + ++$this->calls; + + throw new \RuntimeException('always fails'); + } + }; + $worker = new Worker( + new AmqpTransport($channel), + new Dispatcher((new HandlerMap())->register(self::URN, $handler)), + new WorkerOptions(maxAttempts: 3, backoff: [0], sleepWhenEmpty: 0.0, maxRuntime: 0.45), + ); + + $worker->run('orders'); + + self::assertGreaterThanOrEqual(1, $handler->calls); + self::assertLessThanOrEqual(8, $handler->calls, 'paced by the failure pause, not a tight loop'); + } +} From 01617c3579317962968821d33381f9421016685d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 20:38:23 +0300 Subject: [PATCH 5/6] fix(consumer): keep the failure pause from throwing and from drifting The pause after a failed message computed its back-off outside the failure handling, so a message with attempts of PHP_INT_MAX overflowed into a float and escaped run() with a TypeError. Cap the attempt used for the lookup. Time the pause with the monotonic clock so a wall-clock step cannot stretch the 5s cap, and test the floor, the idle sleep, the back-off and the cap. --- src/Consumer/Worker.php | 29 +++++++++---- tests/Consumer/WorkerFailurePauseTest.php | 53 +++++++++++++++++++++++ 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/src/Consumer/Worker.php b/src/Consumer/Worker.php index e67bfa5..1a4c79e 100644 --- a/src/Consumer/Worker.php +++ b/src/Consumer/Worker.php @@ -313,20 +313,33 @@ private function dispatchSignals(): void */ private function pauseAfterFailure(ReceivedMessage $message): void { - $seconds = min( + // A monotonic clock, so a wall-clock step cannot stretch the 5 s cap. + $until = hrtime(true) + (int) ($this->failurePauseSeconds($message) * 1_000_000_000); + + while (! $this->shouldStop && ($left = ($until - hrtime(true)) / 1_000_000_000) > 0) { + $this->sleep(min($left, 0.25)); + $this->dispatchSignals(); + } + } + + /** + * How long to wait after a failure on `$message`: the larger of 0.1 s, + * `sleepWhenEmpty` and the back-off for its next attempt, at most 5 s. + */ + private function failurePauseSeconds(ReceivedMessage $message): float + { + // Capped so an `attempts` of PHP_INT_MAX (a foreign or damaged message) cannot + // overflow into a float here, outside the failure handling that called us. + $nextAttempt = min($message->attempts(), PHP_INT_MAX - 1) + 1; + + return min( self::FAILURE_PAUSE_CAP_SECONDS, max( self::DEFERRAL_PAUSE_SECONDS, $this->options->sleepWhenEmpty, - (float) $this->options->delayForAttempt($message->attempts() + 1), + (float) $this->options->delayForAttempt($nextAttempt), ), ); - $until = microtime(true) + $seconds; - - while (! $this->shouldStop && ($left = $until - microtime(true)) > 0) { - $this->sleep(min($left, 0.25)); - $this->dispatchSignals(); - } } private function sleep(float $seconds): void diff --git a/tests/Consumer/WorkerFailurePauseTest.php b/tests/Consumer/WorkerFailurePauseTest.php index 4c048db..db06818 100644 --- a/tests/Consumer/WorkerFailurePauseTest.php +++ b/tests/Consumer/WorkerFailurePauseTest.php @@ -12,6 +12,7 @@ use InitPHP\Queue\Exceptions\QueueException; use InitPHP\Queue\Message\ReceivedMessage; use InitPHP\Queue\Routing\HandlerMap; +use InitPHP\Queue\Tests\Support\ArrayTransport; use InitPHP\Queue\Tests\Support\RecordingHandler; use InitPHP\Queue\Transport\Amqp\AmqpTransport; use Mockery; @@ -150,4 +151,56 @@ public function handle(\BabelQueue\Contracts\InboundMessage $message): void self::assertGreaterThanOrEqual(1, $handler->calls); self::assertLessThanOrEqual(8, $handler->calls, 'paced by the failure pause, not a tight loop'); } + + /** + * @return float the failure pause for a message with `$attempts` + */ + private function pauseFor(WorkerOptions $options, int $attempts): float + { + $worker = new Worker($this->refusingTransport($this->raw()), new Dispatcher(new HandlerMap()), $options); + $message = new ReceivedMessage('orders', $this->raw($attempts), EnvelopeCodec::decode($this->raw($attempts)), 1); + + return (new \ReflectionMethod($worker, 'failurePauseSeconds'))->invoke($worker, $message); + } + + public function test_the_pause_is_the_larger_of_the_floor_the_idle_sleep_and_the_back_off(): void + { + self::assertSame(0.1, $this->pauseFor(new WorkerOptions(backoff: [0], sleepWhenEmpty: 0.0), 0), 'the floor'); + self::assertSame(2.0, $this->pauseFor(new WorkerOptions(backoff: [0], sleepWhenEmpty: 2.0), 0), 'sleepWhenEmpty'); + self::assertSame(3.0, $this->pauseFor(new WorkerOptions(backoff: [1, 3], sleepWhenEmpty: 0.5), 1), 'the back-off for the next attempt'); + self::assertSame(1.0, $this->pauseFor(new WorkerOptions(backoff: [1, 3], sleepWhenEmpty: 0.5), 0), 'attempt 1 uses the first back-off'); + } + + public function test_the_pause_is_capped_at_five_seconds(): void + { + self::assertSame(5.0, $this->pauseFor(new WorkerOptions(backoff: [30], sleepWhenEmpty: 0.0), 0)); + self::assertSame(5.0, $this->pauseFor(new WorkerOptions(backoff: [0], sleepWhenEmpty: 60.0), 0)); + } + + public function test_a_message_with_the_largest_possible_attempts_does_not_crash_the_worker(): void + { + $transport = new ArrayTransport(); + $envelope = EnvelopeCodec::make(self::URN, ['order_id' => 1], 'orders'); + $envelope['attempts'] = PHP_INT_MAX; // a foreign or damaged message + $transport->publish(EnvelopeCodec::encode($envelope), 'orders'); + $transport->publish($this->raw(), 'orders'); + + $handler = new RecordingHandler(); + $handlers = (new HandlerMap()) + ->register(self::URN, static function (\BabelQueue\Contracts\InboundMessage $message) use ($handler): void { + if ($message->attempts() === PHP_INT_MAX) { + throw new \RuntimeException('poison'); + } + $handler->handle($message); + }); + $worker = new Worker( + $transport, + new Dispatcher($handlers), + new WorkerOptions(sleepWhenEmpty: 0.0, stopWhenEmpty: true, maxRuntime: 3.0), + ); + + $worker->run('orders'); + + self::assertCount(1, $handler->handled, 'the next message was still processed'); + } } From 016a50f57a0c94e9f94082954af9b5a746a6e95a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 20:42:47 +0300 Subject: [PATCH 6/6] fix(consumer): keep the failure pause from throwing on an odd back-off backoff is documented as a list of ints, but a map or floats can reach the worker. The pause after a failed message read it through delayForAttempt(), whose int return type throws on a float, so the error escaped run() where 2.2 logged process.failed and carried on. Read the back-off defensively in the pause: a map is read as its values, a float is kept, anything else is no back-off. --- src/Consumer/Worker.php | 24 +++++++++++--- tests/Consumer/WorkerFailurePauseTest.php | 38 +++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/Consumer/Worker.php b/src/Consumer/Worker.php index 1a4c79e..31d326e 100644 --- a/src/Consumer/Worker.php +++ b/src/Consumer/Worker.php @@ -334,14 +334,28 @@ private function failurePauseSeconds(ReceivedMessage $message): float return min( self::FAILURE_PAUSE_CAP_SECONDS, - max( - self::DEFERRAL_PAUSE_SECONDS, - $this->options->sleepWhenEmpty, - (float) $this->options->delayForAttempt($nextAttempt), - ), + max(self::DEFERRAL_PAUSE_SECONDS, $this->options->sleepWhenEmpty, $this->backoffFor($nextAttempt)), ); } + /** + * The configured back-off for `$attempt`, read defensively: `backoff` is + * documented as a list of ints, but a map (`[1 => 5]`) or floats (`[0.5]`) can + * reach it, and the pause runs outside the failure handling, so it must not + * throw. Anything that is not a number counts as no back-off. + */ + private function backoffFor(int $attempt): float + { + $delays = array_values($this->options->backoff); + if ($delays === []) { + return 0.0; + } + + $delay = $delays[min(max($attempt, 1) - 1, count($delays) - 1)]; + + return is_int($delay) || is_float($delay) ? (float) $delay : 0.0; + } + private function sleep(float $seconds): void { if ($seconds > 0) { diff --git a/tests/Consumer/WorkerFailurePauseTest.php b/tests/Consumer/WorkerFailurePauseTest.php index db06818..1c7eb47 100644 --- a/tests/Consumer/WorkerFailurePauseTest.php +++ b/tests/Consumer/WorkerFailurePauseTest.php @@ -203,4 +203,42 @@ public function test_a_message_with_the_largest_possible_attempts_does_not_crash self::assertCount(1, $handler->handled, 'the next message was still processed'); } + + public function test_an_undocumented_back_off_shape_does_not_crash_the_worker(): void + { + // `backoff` is documented as list; a map or floats must still not make + // the failure pause throw (2.2 logged process.failed and carried on). + self::assertSame(5.0, $this->pauseFor(new WorkerOptions(backoff: [1 => 5], sleepWhenEmpty: 0.0), 0), 'a map is read as its values'); + self::assertSame(0.5, $this->pauseFor(new WorkerOptions(backoff: [0.5], sleepWhenEmpty: 0.0), 0), 'a float is kept'); + + // End to end with floats (a map also triggers a PHP warning in the retry path itself, as in 2.2). + foreach ([[0.5]] as $backoff) { + $transport = new ArrayTransport(); + $transport->publish($this->raw(), 'orders'); + $transport->publish($this->raw(), 'orders'); + $events = []; + $handler = new RecordingHandler(); + $failing = true; + $handlers = (new HandlerMap())->register(self::URN, static function (\BabelQueue\Contracts\InboundMessage $message) use ($handler, &$failing): void { + if ($failing) { + $failing = false; + throw new \RuntimeException('first one fails'); + } + $handler->handle($message); + }); + $worker = new Worker( + $transport, + new Dispatcher($handlers), + new WorkerOptions(backoff: $backoff, sleepWhenEmpty: 0.0, stopWhenEmpty: true, maxRuntime: 4.0), + function (string $level, string $event) use (&$events): void { + $events[] = $event; + }, + ); + + $worker->run('orders'); + + self::assertSame(1, count($handler->handled), 'the next message was still processed'); + self::assertContains('process.failed', $events, 'the failure is logged, as in 2.2'); + } + } }