From 329eb0a7851f1ad372ae18fd9a84d58a5285ddbb Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 18:21:36 +0000 Subject: [PATCH 01/10] Test that idle AMQP connections keep heartbeating A process holding more than one AMQP connection, from one provider's connection modes or from several providers, should keep every connection alive while it is idle. These tests fail: only the connection touched last has a heartbeat sender, so the others miss their heartbeats. Co-Authored-By: Claude Opus 5.5 --- tests/Provider/AmqpTest.php | 64 ++++++++++++++++++++++++ tests/Provider/Mock/AmqpMockProvider.php | 8 +++ 2 files changed, 72 insertions(+) diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index bd8ca42..9abb9d3 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -85,6 +85,70 @@ public function testHeartbeatAfterMissed() self::assertGreaterThan($disconnectsBefore, $q->getDisconnectCount()); } + public function testHeartbeatKeepsEveryConnectionOfAProviderAlive() + { + $q = $this->_getProvider('test_heartbeat_all_modes'); + $q->declareExchange() + ->declareQueue() + ->bindQueue(); + $q->push('open the push connection'); + $q->getQueueInfo(); + + $this->_idlePastHeartbeatTimeout($q); + + $this->_assertConnectionOpen($q, AmqpMockProvider::CONN_PUSH); + $this->_assertConnectionOpen($q, AmqpMockProvider::CONN_OTHER); + } + + public function testHeartbeatKeepsConnectionsOfEveryProviderAlive() + { + $first = $this->_getProvider('test_heartbeat_first_provider'); + $first->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the first provider push connection'); + $second = $this->_getProvider('test_heartbeat_second_provider'); + $second->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the second provider push connection'); + + $this->_idlePastHeartbeatTimeout($first); + + $this->_assertConnectionOpen($first, AmqpMockProvider::CONN_PUSH); + $this->_assertConnectionOpen($second, AmqpMockProvider::CONN_PUSH); + } + + /** + * Sleep with no AMQP traffic for long enough that the broker closes any connection that sent no heartbeats. + * SIGALRM interrupts sleep(), so keep sleeping for the remainder. + */ + private function _idlePastHeartbeatTimeout(AmqpMockProvider $q) + { + $timeLeft = (int)$q->config()->getItem('heartbeat') * 3; + while($timeLeft > 0) + { + $timeLeft = sleep($timeLeft); + } + } + + private function _assertConnectionOpen(AmqpMockProvider $q, string $connectionMode) + { + try + { + // Opening a channel is a round trip, so it fails if the broker has closed the connection. + $q->getOpenConnection($connectionMode)->channel()->close(); + } + catch(\Exception $e) + { + self::fail(sprintf( + 'The %s connection stopped heartbeating while idle: %s: %s', + $connectionMode, get_class($e), $e->getMessage() + )); + } + $this->addToAssertionCount(1); + } + public function testAmqp() { $q = $this->_getProvider('test', 'testexchange'); diff --git a/tests/Provider/Mock/AmqpMockProvider.php b/tests/Provider/Mock/AmqpMockProvider.php index 4259362..253970c 100644 --- a/tests/Provider/Mock/AmqpMockProvider.php +++ b/tests/Provider/Mock/AmqpMockProvider.php @@ -30,6 +30,14 @@ public function unregisterHeartbeat() return $this; } + /** + * The connection already open for this mode, without reconnecting. + */ + public function getOpenConnection($connectionMode) + { + return $this->_connections[$connectionMode]; + } + public function getDisconnectCount() { return $this->_disconnectCount; From afbb3d80012ac06872c4d268d10ed429e4b83458 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 18:24:08 +0000 Subject: [PATCH 02/10] Heartbeat every open AMQP connection from one SIGALRM handler AmqpHeartbeat holds every open connection in the process and, on each alarm, sends a heartbeat on any that has been quiet for half its heartbeat interval and is not mid-write. A provider registers a connection when it opens it and unregisters it when it disconnects that connection mode. This replaces the per-provider PCNTLHeartbeatSender, which was re-registered on every _getConnection() call and shared the process's single SIGALRM handler with every other provider, so only the last connection touched was heartbeated. The protected $_heartbeatSender property is removed. Co-Authored-By: Claude Opus 5.5 --- src/Provider/Amqp/AmqpHeartbeat.php | 117 +++++++++++++++++++++++ src/Provider/Amqp/AmqpQueueProvider.php | 34 +------ tests/Provider/Mock/AmqpMockProvider.php | 12 ++- 3 files changed, 128 insertions(+), 35 deletions(-) create mode 100644 src/Provider/Amqp/AmqpHeartbeat.php diff --git a/src/Provider/Amqp/AmqpHeartbeat.php b/src/Provider/Amqp/AmqpHeartbeat.php new file mode 100644 index 0000000..19701ba --- /dev/null +++ b/src/Provider/Amqp/AmqpHeartbeat.php @@ -0,0 +1,117 @@ +getHeartbeat() < 1) + { + return; + } + self::$_connections[spl_object_id($connection)] = $connection; + self::_arm(); + } + + public static function unregister(AbstractConnection $connection): void + { + if(!isset(self::$_connections[spl_object_id($connection)])) + { + return; + } + unset(self::$_connections[spl_object_id($connection)]); + self::_arm(); + } + + public static function isRegistered(AbstractConnection $connection): bool + { + return isset(self::$_connections[spl_object_id($connection)]); + } + + /** + * Heartbeat each idle connection. Runs inside the SIGALRM handler. + */ + public static function beat(): void + { + foreach(self::$_connections as $id => $connection) + { + if(!$connection->isConnected()) + { + unset(self::$_connections[$id]); + continue; + } + // A heartbeat frame written in the middle of another frame would corrupt the stream. + if($connection->isWriting()) + { + continue; + } + $interval = (int)ceil($connection->getHeartbeat() / 2); + if(time() > $connection->getLastActivity() + $interval) + { + try + { + $connection->checkHeartBeat(); + } + catch(\Throwable $e) + { + // Throwing here would unwind whatever code the signal interrupted. + // The connection's next read or write raises the failure where it can be handled. + unset(self::$_connections[$id]); + } + } + } + self::_arm(); + } + + private static function _arm(): void + { + $interval = 0; + foreach(self::$_connections as $connection) + { + $connectionInterval = (int)ceil($connection->getHeartbeat() / 2); + if($interval === 0 || $connectionInterval < $interval) + { + $interval = $connectionInterval; + } + } + + if($interval === 0) + { + if(self::$_interval !== 0) + { + pcntl_alarm(0); + pcntl_signal(SIGALRM, SIG_IGN); + self::$_interval = 0; + } + return; + } + + if(self::$_interval === 0) + { + pcntl_async_signals(true); + pcntl_signal(SIGALRM, [self::class, 'beat'], true); + } + self::$_interval = $interval; + pcntl_alarm($interval); + } +} diff --git a/src/Provider/Amqp/AmqpQueueProvider.php b/src/Provider/Amqp/AmqpQueueProvider.php index 00ec832..f30c761 100644 --- a/src/Provider/Amqp/AmqpQueueProvider.php +++ b/src/Provider/Amqp/AmqpQueueProvider.php @@ -11,10 +11,8 @@ use PhpAmqpLib\Channel\AMQPChannel; use PhpAmqpLib\Connection\AbstractConnection; use PhpAmqpLib\Connection\AMQPStreamConnection; -use PhpAmqpLib\Connection\Heartbeat\PCNTLHeartbeatSender; use PhpAmqpLib\Exception\AMQPHeartbeatMissedException; use PhpAmqpLib\Exception\AMQPProtocolChannelException; -use PhpAmqpLib\Exception\AMQPRuntimeException; use PhpAmqpLib\Exception\AMQPTimeoutException; use PhpAmqpLib\Message\AMQPMessage; use PhpAmqpLib\Wire\AMQPTable; @@ -88,11 +86,6 @@ class AmqpQueueProvider extends AbstractQueueProvider */ private $_slowPushThreshold = 0; - /** - * @var ?PCNTLHeartbeatSender - */ - protected $_heartbeatSender; - protected function _construct() { $this->_fixedConsumerCallback = [$this, 'consumerCallback']; @@ -582,20 +575,10 @@ protected function _getConnection($connectionMode) } $this->_persistentDefault = ValueAs::bool($config->getItem('persistent', false)); $this->_lastConnectTimes[$connectionMode] = time(); - } - - try - { - if($this->_heartbeatSender) + if(!empty($this->_connections[$connectionMode])) { - $this->_heartbeatSender->unregister(); + AmqpHeartbeat::register($this->_connections[$connectionMode]); } - $this->_heartbeatSender = new PCNTLHeartbeatSender($this->_connections[$connectionMode]); - $this->_heartbeatSender->register(); - } - catch(AMQPRuntimeException $e) - { - Log::error('Unable to start heartbeat sender. ' . $e->getMessage()); } return $this->_connections[$connectionMode]; @@ -709,22 +692,11 @@ private function _disconnect($connectionMode) } $this->_channels[$connectionMode] = null; - if($this->_heartbeatSender) - { - try - { - $this->_heartbeatSender->unregister(); - } - catch(\Throwable $e) - { - } - } - $this->_heartbeatSender = null; - if((!empty($this->_connections[$connectionMode])) && ($this->_connections[$connectionMode] instanceof AbstractConnection) ) { + AmqpHeartbeat::unregister($this->_connections[$connectionMode]); try { $this->_connections[$connectionMode]->close(); diff --git a/tests/Provider/Mock/AmqpMockProvider.php b/tests/Provider/Mock/AmqpMockProvider.php index 253970c..b882a4f 100644 --- a/tests/Provider/Mock/AmqpMockProvider.php +++ b/tests/Provider/Mock/AmqpMockProvider.php @@ -2,6 +2,7 @@ namespace Packaged\Queue\Tests\Provider\Mock; +use Packaged\Queue\Provider\Amqp\AmqpHeartbeat; use Packaged\Queue\Provider\Amqp\AmqpQueueProvider; class AmqpMockProvider extends AmqpQueueProvider @@ -13,9 +14,9 @@ class AmqpMockProvider extends AmqpQueueProvider protected function _getConnection($connectionMode) { $conn = parent::_getConnection($connectionMode); - if($this->_unregisterHeartbeat && $this->_heartbeatSender) + if($this->_unregisterHeartbeat) { - $this->_heartbeatSender->unregister(); + AmqpHeartbeat::unregister($conn); } return $conn; } @@ -23,9 +24,12 @@ protected function _getConnection($connectionMode) public function unregisterHeartbeat() { $this->_unregisterHeartbeat = true; - if($this->_unregisterHeartbeat && $this->_heartbeatSender) + foreach($this->_connections as $conn) { - $this->_heartbeatSender->unregister(); + if($conn) + { + AmqpHeartbeat::unregister($conn); + } } return $this; } From 54758a3787ae16cc3fb958728dac71a98fa9cf36 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 19:59:00 +0000 Subject: [PATCH 03/10] Test heartbeat registry edge cases from review - An idle connection stays alive while other connections open and close more often than the heartbeat interval. - A push after a process pause long enough to miss the broker heartbeat reconnects instead of writing to the closed socket. - A provider that has consumed is garbage collected once released. - AMQP_WITHOUT_SIGNALS leaves the SIGALRM handler untouched. Co-Authored-By: Claude Opus 5.5 --- tests/Provider/AmqpTest.php | 88 +++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index 9abb9d3..ad658cb 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -119,6 +119,94 @@ public function testHeartbeatKeepsConnectionsOfEveryProviderAlive() $this->_assertConnectionOpen($second, AmqpMockProvider::CONN_PUSH); } + public function testHeartbeatKeepsIdleConnectionAliveWhileOtherConnectionsChurn() + { + $idle = $this->_getProvider('test_heartbeat_idle_beside_churn'); + $idle->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the idle provider push connection'); + $churn = $this->_getProvider('test_heartbeat_churn'); + $churn->declareExchange() + ->declareQueue() + ->bindQueue(); + + // Open and close a connection every second, more often than the heartbeat interval. + $until = time() + (int)$idle->config()->getItem('heartbeat') * 3; + while(time() < $until) + { + $churn->push('churn'); + $churn->disconnect(); + $timeLeft = 1; + while($timeLeft > 0) + { + $timeLeft = sleep($timeLeft); + } + } + + $this->_assertConnectionOpen($idle, AmqpMockProvider::CONN_PUSH); + } + + public function testPushReconnectsAfterHeartbeatFailedDuringProcessPause() + { + $q = $this->_getProvider('test_heartbeat_after_pause'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('before pause'); + + // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is already missed. + pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]); + try + { + $this->_idlePastHeartbeatTimeout($q); + } + finally + { + pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]); + } + + $disconnectsBefore = $q->getDisconnectCount(); + $q->push('after pause'); + self::assertGreaterThan($disconnectsBefore, $q->getDisconnectCount()); + } + + public function testReleasedConsumerProviderIsCollected() + { + $q = $this->_getProvider('test_heartbeat_released_consumer'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('consume me'); + $q->consume( + function ($message, $deliveryTag) use ($q) { + $q->ack($deliveryTag); + } + ); + + $released = \WeakReference::create($q); + unset($q); + gc_collect_cycles(); + + self::assertNull($released->get(), 'The provider is still referenced after it was released.'); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testWithoutSignalsLeavesSigalrmAlone() + { + define('AMQP_WITHOUT_SIGNALS', true); + $q = $this->_getProvider('test_heartbeat_without_signals'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open a connection'); + + self::assertSame(SIG_DFL, pcntl_signal_get_handler(SIGALRM)); + } + /** * Sleep with no AMQP traffic for long enough that the broker closes any connection that sent no heartbeats. * SIGALRM interrupts sleep(), so keep sleeping for the remainder. From a1e969307a766bfdd0a2b0d42e4e7e81cd535af9 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 20:23:59 +0000 Subject: [PATCH 04/10] Keep heartbeat registry from leaking, stalling or hiding failures - Hold connections by WeakReference, so a released provider (which a consumer channel references through its callback) can be collected. - Only ever bring the pending alarm forward. Registering or removing a connection no longer postpones it, so churn cannot starve idle connections of heartbeats. - When a heartbeat fails inside the signal handler, flag the connection. The provider disconnects it on its next push or consume and reconnects. - Honour AMQP_WITHOUT_SIGNALS, as PCNTLHeartbeatSender did. Co-Authored-By: Claude Opus 5.5 --- src/Provider/Amqp/AmqpHeartbeat.php | 114 +++++++++++++++++------- src/Provider/Amqp/AmqpQueueProvider.php | 6 +- 2 files changed, 89 insertions(+), 31 deletions(-) diff --git a/src/Provider/Amqp/AmqpHeartbeat.php b/src/Provider/Amqp/AmqpHeartbeat.php index 19701ba..72d951b 100644 --- a/src/Provider/Amqp/AmqpHeartbeat.php +++ b/src/Provider/Amqp/AmqpHeartbeat.php @@ -8,15 +8,25 @@ * * A process has a single SIGALRM handler, so one sender per connection would leave every * connection but the last registered without heartbeats. + * + * Connections are held by weak reference, so the registry never keeps a provider alive. */ final class AmqpHeartbeat { - /** @var AbstractConnection[] keyed by spl_object_id */ + /** @var \WeakReference[] keyed by spl_object_id */ private static $_connections = []; - private static $_interval = 0; + /** @var bool[] connections whose heartbeat failed, keyed by spl_object_id */ + private static $_failed = []; + private static $_handlerInstalled = false; + /** Unix time the pending alarm fires, or 0 when none is pending */ + private static $_nextBeat = 0; public static function isSupported(): bool { + if(defined('AMQP_WITHOUT_SIGNALS') && AMQP_WITHOUT_SIGNALS) + { + return false; + } return function_exists('pcntl_async_signals') && function_exists('pcntl_signal') && function_exists('pcntl_alarm') @@ -29,23 +39,34 @@ public static function register(AbstractConnection $connection): void { return; } - self::$_connections[spl_object_id($connection)] = $connection; - self::_arm(); + $id = spl_object_id($connection); + self::$_connections[$id] = \WeakReference::create($connection); + unset(self::$_failed[$id]); + self::_schedule(); } public static function unregister(AbstractConnection $connection): void { - if(!isset(self::$_connections[spl_object_id($connection)])) + $id = spl_object_id($connection); + if(!self::_holds($id, $connection)) { return; } - unset(self::$_connections[spl_object_id($connection)]); - self::_arm(); + unset(self::$_connections[$id], self::$_failed[$id]); + if(!self::$_connections) + { + self::_cancel(); + } } - public static function isRegistered(AbstractConnection $connection): bool + /** + * Whether a heartbeat on this connection failed in the signal handler. + * The connection is unusable, so its owner should disconnect and reconnect. + */ + public static function hasFailed(AbstractConnection $connection): bool { - return isset(self::$_connections[spl_object_id($connection)]); + $id = spl_object_id($connection); + return isset(self::$_failed[$id]) && self::_holds($id, $connection); } /** @@ -53,20 +74,21 @@ public static function isRegistered(AbstractConnection $connection): bool */ public static function beat(): void { - foreach(self::$_connections as $id => $connection) + self::$_nextBeat = 0; + foreach(self::$_connections as $id => $reference) { - if(!$connection->isConnected()) + $connection = $reference->get(); + if($connection === null || !$connection->isConnected()) { - unset(self::$_connections[$id]); + unset(self::$_connections[$id], self::$_failed[$id]); continue; } // A heartbeat frame written in the middle of another frame would corrupt the stream. - if($connection->isWriting()) + if(isset(self::$_failed[$id]) || $connection->isWriting()) { continue; } - $interval = (int)ceil($connection->getHeartbeat() / 2); - if(time() > $connection->getLastActivity() + $interval) + if(time() > $connection->getLastActivity() + self::_interval($connection)) { try { @@ -75,20 +97,40 @@ public static function beat(): void catch(\Throwable $e) { // Throwing here would unwind whatever code the signal interrupted. - // The connection's next read or write raises the failure where it can be handled. - unset(self::$_connections[$id]); + // The owning provider sees the failure on its next push or consume and reconnects. + self::$_failed[$id] = true; } } } - self::_arm(); + self::_schedule(); } - private static function _arm(): void + private static function _holds(int $id, AbstractConnection $connection): bool + { + return isset(self::$_connections[$id]) && self::$_connections[$id]->get() === $connection; + } + + private static function _interval(AbstractConnection $connection): int + { + return (int)ceil($connection->getHeartbeat() / 2); + } + + /** + * Arm the alarm for the shortest interval among live connections. + * A pending alarm is only ever brought forward, so registry changes cannot postpone it. + */ + private static function _schedule(): void { $interval = 0; - foreach(self::$_connections as $connection) + foreach(self::$_connections as $id => $reference) { - $connectionInterval = (int)ceil($connection->getHeartbeat() / 2); + $connection = $reference->get(); + if($connection === null) + { + unset(self::$_connections[$id], self::$_failed[$id]); + continue; + } + $connectionInterval = self::_interval($connection); if($interval === 0 || $connectionInterval < $interval) { $interval = $connectionInterval; @@ -97,21 +139,33 @@ private static function _arm(): void if($interval === 0) { - if(self::$_interval !== 0) - { - pcntl_alarm(0); - pcntl_signal(SIGALRM, SIG_IGN); - self::$_interval = 0; - } + self::_cancel(); return; } - if(self::$_interval === 0) + if(!self::$_handlerInstalled) { pcntl_async_signals(true); pcntl_signal(SIGALRM, [self::class, 'beat'], true); + self::$_handlerInstalled = true; + } + + $due = time() + $interval; + if(self::$_nextBeat === 0 || $due < self::$_nextBeat) + { + pcntl_alarm($interval); + self::$_nextBeat = $due; + } + } + + private static function _cancel(): void + { + if(self::$_handlerInstalled) + { + pcntl_alarm(0); + pcntl_signal(SIGALRM, SIG_IGN); + self::$_handlerInstalled = false; } - self::$_interval = $interval; - pcntl_alarm($interval); + self::$_nextBeat = 0; } } diff --git a/src/Provider/Amqp/AmqpQueueProvider.php b/src/Provider/Amqp/AmqpQueueProvider.php index f30c761..114dd38 100644 --- a/src/Provider/Amqp/AmqpQueueProvider.php +++ b/src/Provider/Amqp/AmqpQueueProvider.php @@ -487,10 +487,14 @@ protected function _refreshConnection($connectionMode) $channel = isset($this->_channels[$connectionMode]) ? $this->_channels[$connectionMode] : null; + $connection = isset($this->_connections[$connectionMode]) + ? $this->_connections[$connectionMode] : null; // Disconnect if the channel exists but the connection is broken, + // if a background heartbeat on the connection failed, // or if the connection has been open for too long - if(($channel && + if(($connection instanceof AbstractConnection && AmqpHeartbeat::hasFailed($connection)) + || ($channel && ((!$channel->getConnection()) || (!$channel->getConnection()->isConnected()) ) From d19b6cc057e0aeeb799f31d77f16800559e3acde Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 20:29:22 +0000 Subject: [PATCH 05/10] Collect twice before checking the released provider is freed PHP runs the destructors of a garbage cycle on the first collection and frees the cycle on the next one. Co-Authored-By: Claude Opus 5.5 --- tests/Provider/AmqpTest.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index ad658cb..7b572ba 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -186,6 +186,8 @@ function ($message, $deliveryTag) use ($q) { $released = \WeakReference::create($q); unset($q); + // The first collection runs the cycle's destructors; the second frees it. + gc_collect_cycles(); gc_collect_cycles(); self::assertNull($released->get(), 'The provider is still referenced after it was released.'); From 62fee4bde2fa7f529baee870e842adcfd9aec050 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 21:02:00 +0000 Subject: [PATCH 06/10] Test paused consumer callbacks and single-mode disconnects - A consumer callback paused past the broker heartbeat timeout should leave its message for redelivery: its ack must not throw, consume() returns false, and the next consume receives the message again. - Disconnecting one connection mode keeps the provider's other connection heartbeating. Co-Authored-By: Claude Opus 5.5 --- tests/Provider/AmqpTest.php | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index 7b572ba..f9e61af 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -171,6 +171,56 @@ public function testPushReconnectsAfterHeartbeatFailedDuringProcessPause() self::assertGreaterThan($disconnectsBefore, $q->getDisconnectCount()); } + public function testDisconnectingOneModeKeepsTheOtherHeartbeating() + { + $q = $this->_getProvider('test_heartbeat_disconnect_one_mode'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('open the push connection'); + $q->getQueueInfo(); + $q->disconnect(AmqpMockProvider::CONN_OTHER); + + $this->_idlePastHeartbeatTimeout($q); + + $this->_assertConnectionOpen($q, AmqpMockProvider::CONN_PUSH); + } + + public function testConsumerCallbackPausedPastHeartbeatLeavesMessageForRedelivery() + { + $q = $this->_getProvider('test_heartbeat_paused_callback'); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('slow message'); + + $consumed = $q->consume( + function ($message, $deliveryTag) use ($q) { + // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is missed. + pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]); + try + { + $this->_idlePastHeartbeatTimeout($q); + } + finally + { + pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]); + } + $q->ack($deliveryTag); + } + ); + self::assertFalse($consumed, 'consume() should report the batch as not consumed.'); + + $redelivered = null; + $q->consume( + function ($message, $deliveryTag) use ($q, &$redelivered) { + $redelivered = $message; + $q->ack($deliveryTag); + } + ); + self::assertSame('slow message', $redelivered); + } + public function testReleasedConsumerProviderIsCollected() { $q = $this->_getProvider('test_heartbeat_released_consumer'); From 9700c8403af9b1eff02d5670e40074fed50bf98f Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Fri, 20 Nov 2026 21:05:26 +0000 Subject: [PATCH 07/10] Leave deliveries for redelivery when the consumer heartbeat failed A heartbeat that fails in the signal handler during a consumer callback closes the socket. ack, nack and batchAck now skip settling on a flagged consume connection, since its delivery tags are void and replaying them on a new channel would settle unrelated messages. consume() then disconnects and returns false, and the broker redelivers the messages. Co-Authored-By: Claude Opus 5.5 --- src/Provider/Amqp/AmqpQueueProvider.php | 27 ++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Provider/Amqp/AmqpQueueProvider.php b/src/Provider/Amqp/AmqpQueueProvider.php index 114dd38..15bf8ad 100644 --- a/src/Provider/Amqp/AmqpQueueProvider.php +++ b/src/Provider/Amqp/AmqpQueueProvider.php @@ -306,9 +306,26 @@ public function consume(callable $callback) { return false; } + if($this->_consumeHeartbeatFailed()) + { + // The broker requeues the deliveries of the lost connection. + $this->disconnect(self::CONN_CONSUME); + return false; + } return true; } + /** + * Whether a background heartbeat failed on the consume connection. + * Its delivery tags are void, so settling them on a new channel would ack or reject unrelated messages. + */ + private function _consumeHeartbeatFailed(): bool + { + $connection = isset($this->_connections[self::CONN_CONSUME]) + ? $this->_connections[self::CONN_CONSUME] : null; + return $connection instanceof AbstractConnection && AmqpHeartbeat::hasFailed($connection); + } + protected function _processBatchMessage($msg, $tag = null) { $this->_batchData[$tag] = $msg; @@ -397,6 +414,10 @@ public static function create( public function ack($deliveryTag) { + if($this->_consumeHeartbeatFailed()) + { + return; + } try { $this->_getChannel(self::CONN_CONSUME) @@ -411,6 +432,10 @@ public function ack($deliveryTag) public function nack($deliveryTag, $requeueFailures = false) { + if($this->_consumeHeartbeatFailed()) + { + return; + } try { $this->_getChannel(self::CONN_CONSUME) @@ -425,7 +450,7 @@ public function nack($deliveryTag, $requeueFailures = false) public function batchAck(array $tagResults, $requeueFailures = false) { - if(count($tagResults) < 1) + if(count($tagResults) < 1 || $this->_consumeHeartbeatFailed()) { return; } From bc000b483706b1ccb1f5b528bc523f9f2c4d13c9 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Sat, 21 Nov 2026 11:30:40 +0000 Subject: [PATCH 08/10] Test that a batch drops deliveries from a lost consume connection A heartbeat failure part way through batchConsume() replaces the consume connection. The batch should then hold only deliveries from the new connection, not the lost delivery whose tag is void. Co-Authored-By: Claude Opus 5.5 --- tests/Provider/AmqpTest.php | 41 ++++++++++++++++++++++++ tests/Provider/Mock/AmqpMockProvider.php | 18 +++++++++++ 2 files changed, 59 insertions(+) diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index f9e61af..dd0acc6 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -221,6 +221,47 @@ function ($message, $deliveryTag) use ($q, &$redelivered) { self::assertSame('slow message', $redelivered); } + public function testBatchDropsDeliveriesFromAConsumeConnectionLostMidBatch() + { + $q = $this->_getProvider('test_heartbeat_batch_lost_connection'); + $q->configure(new ConfigSection('', ['heartbeat' => 4, 'read_write_timeout' => 3, 'wait_time' => 2])); + $q->declareExchange() + ->declareQueue() + ->bindQueue() + ->push('first'); + // Use up delivery tag 1, so the lost delivery's tag differs from its redelivery's. + $q->consume( + function ($message, $deliveryTag) use ($q) { + $q->ack($deliveryTag); + } + ); + $q->push('second'); + + $q->afterNextBatchMessage = function () use ($q) { + // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is missed. + pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]); + try + { + $this->_idlePastHeartbeatTimeout($q); + } + finally + { + pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]); + } + }; + + $batch = []; + $q->batchConsume( + function (array $messages) use (&$batch) { + $batch = $messages; + }, + 2 + ); + + self::assertSame(['second'], array_values($batch), 'The batch should hold only the redelivery.'); + $q->batchAck(array_fill_keys(array_keys($batch), true)); + } + public function testReleasedConsumerProviderIsCollected() { $q = $this->_getProvider('test_heartbeat_released_consumer'); diff --git a/tests/Provider/Mock/AmqpMockProvider.php b/tests/Provider/Mock/AmqpMockProvider.php index b882a4f..afc1bfa 100644 --- a/tests/Provider/Mock/AmqpMockProvider.php +++ b/tests/Provider/Mock/AmqpMockProvider.php @@ -34,6 +34,24 @@ public function unregisterHeartbeat() return $this; } + /** + * Runs once, after the next message is added to a batch. + * + * @var callable|null + */ + public $afterNextBatchMessage; + + protected function _processBatchMessage($msg, $tag = null) + { + parent::_processBatchMessage($msg, $tag); + if($this->afterNextBatchMessage) + { + $hook = $this->afterNextBatchMessage; + $this->afterNextBatchMessage = null; + $hook(); + } + } + /** * The connection already open for this mode, without reconnecting. */ From 72ac06c879ec5f89c49e828208d370df0912ea48 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Sat, 21 Nov 2026 11:39:58 +0000 Subject: [PATCH 09/10] Sleep to a deadline in heartbeat tests; fix the mid-batch assertion SIGALRM from the shared heartbeat handler interrupts sleep(), and its whole-second remainder can lose part of a second per interruption, so a 12s idle could fall under the 9s missed-heartbeat threshold. This made testHeartbeatAfterMissed fail intermittently. Every test now sleeps to a microtime deadline. When a heartbeat fails during the first delivery of a batch, consume() returns false and batchConsume() hands the stale delivery to the callback. The test now expects no stale delivery in that batch and the redelivery in the next. Co-Authored-By: Claude Opus 5.5 --- tests/Provider/AmqpTest.php | 57 ++++++++++++++----------------------- 1 file changed, 22 insertions(+), 35 deletions(-) diff --git a/tests/Provider/AmqpTest.php b/tests/Provider/AmqpTest.php index dd0acc6..9d5ad41 100644 --- a/tests/Provider/AmqpTest.php +++ b/tests/Provider/AmqpTest.php @@ -26,12 +26,7 @@ public function testFailHeartbeat() self::assertEquals(0, $q->getDisconnectCount()); $q->consume( function ($msg, $tag) use ($q) { - - $timeLeft = (int)$msg * 3; - while($timeLeft > 0) - { - $timeLeft = sleep($timeLeft); - } + self::_sleepFor((int)$msg * 3); $q->ack($tag); // expect one reconnect @@ -71,11 +66,7 @@ public function testHeartbeatAfterMissed() $q->push('trigger'); // sleep past the heartbeat interval to cause a missed heartbeat - $timeLeft = (int)$q->config()->getItem('heartbeat') * 3; - while($timeLeft > 0) - { - $timeLeft = sleep($timeLeft); - } + $this->_idlePastHeartbeatTimeout($q); $checksBefore = $q->getHeartbeatCheckCount(); $disconnectsBefore = $q->getDisconnectCount(); @@ -137,11 +128,7 @@ public function testHeartbeatKeepsIdleConnectionAliveWhileOtherConnectionsChurn( { $churn->push('churn'); $churn->disconnect(); - $timeLeft = 1; - while($timeLeft > 0) - { - $timeLeft = sleep($timeLeft); - } + self::_sleepFor(1); } $this->_assertConnectionOpen($idle, AmqpMockProvider::CONN_PUSH); @@ -228,14 +215,7 @@ public function testBatchDropsDeliveriesFromAConsumeConnectionLostMidBatch() $q->declareExchange() ->declareQueue() ->bindQueue() - ->push('first'); - // Use up delivery tag 1, so the lost delivery's tag differs from its redelivery's. - $q->consume( - function ($message, $deliveryTag) use ($q) { - $q->ack($deliveryTag); - } - ); - $q->push('second'); + ->push('second'); $q->afterNextBatchMessage = function () use ($q) { // Hold SIGALRM through the pause, so the heartbeat handler first runs once the broker heartbeat is missed. @@ -251,14 +231,14 @@ function ($message, $deliveryTag) use ($q) { }; $batch = []; - $q->batchConsume( - function (array $messages) use (&$batch) { - $batch = $messages; - }, - 2 - ); + $collect = function (array $messages) use (&$batch) { + $batch = $messages; + }; + $q->batchConsume($collect, 2); + self::assertSame([], $batch, 'The batch held a delivery from the lost connection.'); - self::assertSame(['second'], array_values($batch), 'The batch should hold only the redelivery.'); + $q->batchConsume($collect, 2); + self::assertSame(['second'], array_values($batch), 'The lost delivery should be redelivered.'); $q->batchAck(array_fill_keys(array_keys($batch), true)); } @@ -302,14 +282,21 @@ public function testWithoutSignalsLeavesSigalrmAlone() /** * Sleep with no AMQP traffic for long enough that the broker closes any connection that sent no heartbeats. - * SIGALRM interrupts sleep(), so keep sleeping for the remainder. */ private function _idlePastHeartbeatTimeout(AmqpMockProvider $q) { - $timeLeft = (int)$q->config()->getItem('heartbeat') * 3; - while($timeLeft > 0) + self::_sleepFor((int)$q->config()->getItem('heartbeat') * 3); + } + + /** + * Sleep for the full duration. SIGALRM from the heartbeat handler interrupts usleep(), so sleep to a deadline. + */ + private static function _sleepFor(float $seconds) + { + $deadline = microtime(true) + $seconds; + while(($left = $deadline - microtime(true)) > 0) { - $timeLeft = sleep($timeLeft); + usleep((int)ceil(min($left, 1) * 1000000)); } } From 822e6253c243d5590cb37c3cb08a22548ed654a1 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Sat, 21 Nov 2026 11:43:31 +0000 Subject: [PATCH 10/10] Clear the pending batch when the consume connection disconnects Deliveries collected by batchConsume() carry tags of the channel they arrived on. Once that connection is gone the broker requeues them, so the batch callback must not see them and batchAck() must not settle their tags on a replacement channel. Co-Authored-By: Claude Opus 5.5 --- src/Provider/Amqp/AmqpQueueProvider.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Provider/Amqp/AmqpQueueProvider.php b/src/Provider/Amqp/AmqpQueueProvider.php index 15bf8ad..daf7d98 100644 --- a/src/Provider/Amqp/AmqpQueueProvider.php +++ b/src/Provider/Amqp/AmqpQueueProvider.php @@ -721,6 +721,12 @@ private function _disconnect($connectionMode) } $this->_channels[$connectionMode] = null; + if($connectionMode === self::CONN_CONSUME) + { + // Delivery tags belong to the lost channel. The broker requeues those deliveries. + $this->_batchData = []; + } + if((!empty($this->_connections[$connectionMode])) && ($this->_connections[$connectionMode] instanceof AbstractConnection) )