Fix transactions after lost connections, failed DISCARD and protocol errors (#1758)

* Fail a transaction whose connection was lost until it is discarded

A connection error released the connection holding the transaction, so a
caller that caught the error and kept using the same MultiExec sent the
next commands on a new connection, outside of the transaction. In CAS
mode, MULTI and EXEC then ran on a connection that watched nothing and
overwrote a change made after WATCH. The lost connection now stays held,
and every command fails until discard() or unwatch(). discard() sends
nothing to it, since closing the connection already ended the
transaction on the server.

discard() now always ends the transaction: the strategy closes the
connection when DISCARD fails, so that it cannot stay in MULTI, and
MultiExec resets its state even when the strategy throws. Before, a
failed DISCARD after a queue error reset MultiExec while the strategy
still held the lost connection, and every later transaction failed.
discard() also unwatches the keys when MULTI was never sent, for example
when the connection was lost between WATCH and MULTI.

Cluster transactions built with the fluent interface are aborted after a
cross-slot error too, instead of committing the remaining commands.

The StreamInitException handling is removed: a held connection that is
not open is never reconnected, so it cannot be thrown there. Also drops
the isAborted() check in unwatch(), the inline comments added in #1756,
and merges the changelog into a single Unreleased section.

* Merge overlapping transaction tests

The tests for a queue error with the fluent interface (discarded, not
reusable, unwatch() and watch() while aborted) become one test, and the
one for a failed DISCARD is covered by the recovery test, which now also
covers a connection lost between WATCH and MULTI. The strategy tests for
commands not being retried after WATCH or MULTI fold into the tests for
a lost connection, and the connected tests for a connection lost after
WATCH share one helper.

The persistence data provider is renamed, since it is not only used by
cluster tests.

* Report protocol errors in transactions on the node holding them

With replication, Sentinel or cluster, MultiExec passed the aggregate
connection to ProtocolException, which requires a node connection, so an
unexpected reply inside MULTI or an EXEC reply with the wrong number of
items threw a TypeError. The exception is now built with the node the
transaction's commands are routed to, which is also the connection that
gets closed.

* Remove unreachable branches from the transaction retry callback

A CommunicationException always carries a node connection, so the
callback only ever disconnected it: the branches removing the node from
a replication or handling timeouts never ran.

* Align the comment of MultiExecState::ABORTED with the other flags

* Only realign the comment of MultiExecState::ABORTED

* Shorten the transaction changelog entries

* Cover the remaining branches of the changed transaction methods

Adds tests for discard() in CAS mode before MULTI, a non-callable
argument to execute(), RESP3 replies to EXEC, and server errors from a
node or Relay connection in executeBypassingTransaction().

* Retry transaction commands after a failed connect

The retry callback only accepted a CommunicationException, so retrying
after a StreamInitException failed with a TypeError.

* Reset a transaction once Redis replies to EXEC

execute() kept the transaction state after EXEC, so a transaction that
Redis had already ended still looked open. discard() then sent DISCARD
outside of MULTI, and since a failed DISCARD closes the connection, it
dropped a healthy connection. Reusing the transaction sent the next
command without MULTI, outside of any transaction.

The state is now reset once EXEC replies, whether it succeeded, reported
a failed command, was aborted by a watched key or was rejected. It is
kept when EXEC fails on a lost connection, so that discard() still
releases that connection.

* Close the connection when Redis rejects EXEC but keeps MULTI open

Since MultiExec resets once EXEC replies, discard() no longer sends
DISCARD after a rejected EXEC. Redis 6.0.6 and later discard the
transaction when they reject EXEC and reply with EXECABORT, but older
versions reject it with BUSY, LOADING or MASTERDOWN and keep the
connection in MULTI, so later commands on it were queued.

The strategy now closes the connection when EXEC fails with any error
other than EXECABORT. Relay is excluded, since it reports a transaction
aborted by WATCH as an error.

* Skip UNWATCH on a transaction connection that was lost

unwatch() reconnected to send UNWATCH after the connection holding the
WATCH was lost, although closing that connection already dropped the
watched keys on the server. With the server still down, discard() of a
transaction in CAS mode, or of one that lost its connection between
WATCH and MULTI, then failed although there was nothing left to clean
up. unwatch() now releases a lost connection without sending anything,
as discard() already does.

* Keep a rejected command before MULTI from aborting a transaction

In CAS mode commands run on their own until multi(), so an error there
does not affect the transaction, as in Redis. A fluent cluster
transaction still treated a cross-slot error before multi() like a
rejected queued command, discarding the transaction and failing every
later command until discard(). Only errors after MULTI abort it now.

* Cover the Relay, replication and server-down transaction paths

No test failed when the Relay exception or the choice of connection in
the rejected EXEC handling was removed, or when discard() of a CAS
transaction failed while the server stayed down. New tests check that a
transaction aborted by WATCH under Relay keeps its connection, that a
rejected EXEC with replication closes only the node holding the
transaction, and that discard() succeeds while the server is down after
the connection was lost. The docblock now says that the connection is
closed on any EXEC error but EXECABORT, as the code does.

* Send nothing from unwatch() on an aborted transaction

Aborting the transaction already discarded it and released the
connection holding it, so the UNWATCH that unwatch() sent was a wasted
round trip. Restores the isAborted() check from #1755.
This commit is contained in:
Till Krüss
2026-11-18 01:23:57 -07:00
committed by GitHub
parent d764a3c514
commit 897b238c7e
6 changed files with 970 additions and 378 deletions
@@ -19,7 +19,10 @@ use Predis\Command\Redis\SET;
use Predis\Connection\ConnectionException;
use Predis\Connection\NodeConnectionInterface;
use Predis\Connection\Parameters;
use Predis\Connection\RelayConnection;
use Predis\Connection\Resource\Exception\StreamInitException;
use Predis\Response\Error;
use Predis\Response\ServerException;
use Predis\Retry\Retry;
use Predis\Retry\Strategy\ExponentialBackoff;
use Predis\TimeoutException;
@@ -133,86 +136,6 @@ class NodeConnectionStrategyTest extends TestCase
$this->assertEquals('OK', $strategy->unwatch());
}
/**
* @return void
*/
public function testCommandsAfterMultiAreNotRetried(): void
{
$sent = [];
$this->mockConnection
->expects($this->exactly(2))
->method('executeCommand')
->willReturnCallback(function (CommandInterface $command) use (&$sent) {
$sent[] = $command->getId();
if ($command->getId() === 'MULTI') {
return 'OK';
}
throw new ConnectionException($this->mockConnection, 'Connection lost');
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)]));
$this->mockConnection
->expects($this->once())
->method('disconnect');
$strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState());
$this->assertTrue($strategy->initializeTransaction());
try {
$strategy->executeCommand(new SET());
$this->fail('Expected the connection error to reach the caller.');
} catch (ConnectionException $exception) {
$this->assertSame(['MULTI', 'SET'], $sent);
}
}
/**
* @return void
*/
public function testCommandsAfterWatchAreNotRetried(): void
{
$sent = [];
$this->mockConnection
->expects($this->exactly(2))
->method('executeCommand')
->willReturnCallback(function (CommandInterface $command) use (&$sent) {
$sent[] = $command->getId();
if ($command->getId() === 'WATCH') {
return 'OK';
}
throw new TimeoutException($this->mockConnection);
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)]));
$this->mockConnection
->expects($this->once())
->method('disconnect');
$state = new MultiExecState();
$state->flag(MultiExecState::CAS);
$strategy = new NodeConnectionStrategy($this->mockConnection, $state);
$strategy->watch(['foo']);
try {
$strategy->executeCommand(new GET());
$this->fail('Expected the connection error to reach the caller.');
} catch (TimeoutException $exception) {
$this->assertSame(['WATCH', 'GET'], $sent);
}
}
/**
* @return void
*/
@@ -242,6 +165,35 @@ class NodeConnectionStrategyTest extends TestCase
$this->assertTrue($strategy->initializeTransaction());
}
/**
* @return void
*/
public function testMultiIsRetriedAfterAFailedConnect(): void
{
$failed = false;
$this->mockConnection
->expects($this->exactly(2))
->method('executeCommand')
->willReturnCallback(function () use (&$failed) {
if (!$failed) {
$failed = true;
throw new StreamInitException('Connection refused');
}
return 'OK';
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)]));
$strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState());
$this->assertTrue($strategy->initializeTransaction());
}
/**
* @dataProvider transactionEnds
* @return void
@@ -281,13 +233,6 @@ class NodeConnectionStrategyTest extends TestCase
case 'UNWATCH':
$strategy->unwatch();
break;
case 'connection error':
try {
$strategy->executeCommand(new SET());
} catch (ConnectionException $exception) {
// NOOP
}
break;
}
$failMulti = true;
@@ -300,14 +245,13 @@ class NodeConnectionStrategyTest extends TestCase
return [
'DISCARD' => ['DISCARD'],
'UNWATCH' => ['UNWATCH'],
'connection error' => ['connection error'],
];
}
/**
* @return void
*/
public function testCommandsAfterWatchFailWhenTheConnectionIsNoLongerOpen(): void
public function testCommandsAfterWatchFailUntilUnwatchOnceTheConnectionIsLost(): void
{
$sent = [];
$this->mockConnection
@@ -316,60 +260,20 @@ class NodeConnectionStrategyTest extends TestCase
->willReturnCallback(function (CommandInterface $command) use (&$sent) {
$sent[] = $command->getId();
return 'OK';
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)]));
$state = new MultiExecState();
$state->flag(MultiExecState::CAS);
$strategy = new NodeConnectionStrategy($this->mockConnection, $state);
$strategy->watch(['foo']);
// e.g. after MultiExec::onProtocolError() disconnected it
$this->connected = false;
try {
$strategy->executeCommand(new GET());
$this->fail('Expected the lost connection to reach the caller.');
} catch (ConnectionException $exception) {
$this->assertSame(['WATCH'], $sent);
}
// The transaction no longer holds the connection, so commands go through retries again.
$this->connected = true;
$this->assertSame('OK', $strategy->executeCommand(new GET())->getResponse());
$this->assertSame('OK', $strategy->executeCommand(new GET())->getResponse());
$this->assertSame(['WATCH', 'GET', 'GET'], $sent);
}
/**
* @return void
*/
public function testAFailedReconnectReleasesTheConnection(): void
{
$calls = 0;
$this->mockConnection
->expects($this->exactly(4))
->method('executeCommand')
->willReturnCallback(function (CommandInterface $command) use (&$calls) {
++$calls;
if ($calls === 2) {
throw new StreamInitException('Connection refused');
}
// Only a released connection retries this one.
if ($calls === 3) {
if ($sent === ['WATCH', 'GET']) {
throw new TimeoutException($this->mockConnection);
}
return 'OK';
});
$this->mockConnection
->expects($this->once())
->method('disconnect')
->willReturnCallback(function () {
$this->connected = false;
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
@@ -382,10 +286,249 @@ class NodeConnectionStrategyTest extends TestCase
try {
$strategy->executeCommand(new GET());
$this->fail('Expected the stream error to reach the caller.');
} catch (StreamInitException $exception) {
$this->fail('Expected the connection error to reach the caller.');
} catch (TimeoutException $exception) {
// NOOP
}
try {
$strategy->executeCommand(new GET());
$this->fail('Expected the lost connection to reach the caller.');
} catch (ConnectionException $exception) {
$this->assertSame('The connection holding the transaction was lost.', $exception->getMessage());
}
$this->assertSame(['WATCH', 'GET'], $sent);
$this->assertEquals('OK', $strategy->unwatch());
$this->assertSame('OK', $strategy->executeCommand(new GET())->getResponse());
$this->assertSame(['WATCH', 'GET', 'GET'], $sent);
}
/**
* @return void
*/
public function testDiscardEndsATransactionWhoseConnectionWasLost(): void
{
$sent = [];
$this->mockConnection
->expects($this->exactly(3))
->method('executeCommand')
->willReturnCallback(function (CommandInterface $command) use (&$sent) {
$sent[] = $command->getId();
if ($command->getId() === 'SET') {
throw new ConnectionException($this->mockConnection, 'Connection lost');
}
return 'OK';
});
$this->mockConnection
->expects($this->once())
->method('disconnect')
->willReturnCallback(function () {
$this->connected = false;
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters(['retry' => new Retry(new ExponentialBackoff(1, 10), 3)]));
$strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState());
$strategy->initializeTransaction();
try {
$strategy->executeCommand(new SET());
$this->fail('Expected the connection error to reach the caller.');
} catch (ConnectionException $exception) {
// NOOP
}
try {
$strategy->executeTransaction();
$this->fail('Expected EXEC to fail on the lost connection.');
} catch (ConnectionException $exception) {
$this->assertSame('The connection holding the transaction was lost.', $exception->getMessage());
}
$this->assertEquals('OK', $strategy->discard());
$this->assertSame(['MULTI', 'SET'], $sent);
$this->assertTrue($strategy->initializeTransaction());
$this->assertSame(['MULTI', 'SET', 'MULTI'], $sent);
}
/**
* @return void
*/
public function testServerExceptionFromNodeConnectionIsRethrown(): void
{
$this->mockConnection
->method('executeCommand')
->willReturnCallback(static function (CommandInterface $command) {
if ($command->getId() === 'EXEC') {
throw new ServerException('ERR RELAY_ERR_REDIS simulated');
}
return 'OK';
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters());
$strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState());
$strategy->initializeTransaction();
$this->expectException(ServerException::class);
$this->expectExceptionMessage('ERR RELAY_ERR_REDIS simulated');
$strategy->executeTransaction();
}
/**
* @dataProvider rejectedExecReplies
* @return void
*/
public function testRejectedExecClosesTheConnectionUnlessTheTransactionWasDiscarded(string $error, bool $closed): void
{
$this->mockConnection
->method('executeCommand')
->willReturnCallback(static function (CommandInterface $command) use ($error) {
return $command->getId() === 'EXEC' ? new Error($error) : 'OK';
});
$this->mockConnection
->expects($closed ? $this->once() : $this->never())
->method('disconnect')
->willReturnCallback(function () {
$this->connected = false;
});
$this->mockConnection
->expects($this->any())
->method('getParameters')
->willReturn(new Parameters());
$strategy = new NodeConnectionStrategy($this->mockConnection, new MultiExecState());
$strategy->initializeTransaction();
try {
$strategy->executeTransaction();
$this->fail('Expected EXEC to fail.');
} catch (ServerException $exception) {
$this->assertSame($error, $exception->getMessage());
}
$this->assertTrue($strategy->initializeTransaction());
}
public function rejectedExecReplies(): array
{
return [
'transaction discarded' => [
'EXECABORT Transaction discarded because of previous errors.',
false,
],
'EXEC rejected while MULTI stays open' => [
'BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.',
true,
],
];
}
/**
* @requires extension relay
* @return void
*/
public function testExecAbortedByWatchKeepsTheRelayConnection(): void
{
$relay = $this->getMockBuilder(RelayConnection::class)->disableOriginalConstructor()->getMock();
$relay
->method('executeCommand')
->willReturnCallback(static function (CommandInterface $command) {
return $command->getId() === 'EXEC'
? new Error('Transaction failed (RELAY_ERR_REDIS; commands.c:16733)')
: 'OK';
});
$relay
->method('isConnected')
->willReturn(true);
$relay
->expects($this->never())
->method('disconnect');
$relay
->method('getParameters')
->willReturn(new Parameters());
$state = new MultiExecState();
$state->flag(MultiExecState::CAS);
$strategy = new NodeConnectionStrategy($relay, $state);
$strategy->watch(['foo']);
$strategy->multi();
try {
$strategy->executeTransaction();
$this->fail('Expected Relay to report the aborted transaction as an error.');
} catch (ServerException $exception) {
$this->assertStringStartsWith('Transaction failed (RELAY_ERR_REDIS', $exception->getMessage());
}
$this->assertTrue($strategy->initializeTransaction());
}
/**
* @requires extension relay
* @dataProvider relayServerErrors
* @return void
*/
public function testServerExceptionFromRelay(string $failing, string $message, bool $aborted): void
{
$relay = $this->getMockBuilder(RelayConnection::class)->disableOriginalConstructor()->getMock();
$relay
->method('executeCommand')
->willReturnCallback(static function (CommandInterface $command) use ($failing, $message) {
if ($command->getId() === $failing) {
throw new ServerException($message);
}
return 'OK';
});
$relay
->method('isConnected')
->willReturn(true);
$relay
->method('getParameters')
->willReturn(new Parameters());
$state = new MultiExecState();
$state->flag(MultiExecState::CAS);
$strategy = new NodeConnectionStrategy($relay, $state);
$strategy->watch(['foo']);
$strategy->multi();
if ($aborted) {
$this->assertNull($strategy->executeTransaction());
return;
}
$this->expectException(ServerException::class);
$this->expectExceptionMessage($message);
$failing === 'EXEC' ? $strategy->executeTransaction() : $strategy->executeCommand(new GET());
}
public function relayServerErrors(): array
{
return [
'aborted EXEC' => ['EXEC', 'ERR RELAY_ERR_REDIS simulated', true],
'other EXEC error' => ['EXEC', 'ERR simulated', false],
'error on another command' => ['GET', 'ERR RELAY_ERR_REDIS simulated', false],
];
}
}