From d90ea1bd3ee89d5bd59210a18e35c9456b8ed662 Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Thu, 3 Dec 2026 15:18:14 +0000 Subject: [PATCH] Transactions honour the caller's replica preference, escalate for primary-only work, and are profiled as EXEC Port of main #3381 by intent. RespTransaction resolved its target with no flags, so every transaction went to the primary: a read-only transaction sent with PreferReplica never reached a replica. It now routes with the caller's preference, and goes to the primary when any queued command is primary-only (DemandReplica is left alone, as in main). Queued operations now record their command, which the escalation reads. The transaction is also profiled again, as one EXEC record, which is what the v3 core reported; the v4 run was unprofiled. RespExecOperation carries the record the way RespPayloadOperation does, through a small IProfiledOperation view of Diagnostics.HostState. --- .../Contexts/RespClientConnection.cs | 4 ++ .../Contexts/RespConnectionManager.cs | 4 +- .../Contexts/RespEndpointExecutor.cs | 22 ++++--- .../Contexts/RespPayloadOperation.cs | 13 +++- .../Contexts/RespTransaction.cs | 55 ++++++++++++++++- .../TransactionTests.cs | 60 +++++++++++++++++++ 6 files changed, 146 insertions(+), 12 deletions(-) diff --git a/src/StackExchange.Redis/Contexts/RespClientConnection.cs b/src/StackExchange.Redis/Contexts/RespClientConnection.cs index 5c7a2bc35..54dccf29e 100644 --- a/src/StackExchange.Redis/Contexts/RespClientConnection.cs +++ b/src/StackExchange.Redis/Contexts/RespClientConnection.cs @@ -431,6 +431,10 @@ protected override bool TryHandOff(ReadOnlySpan frame, IRespMessage messag return true; } } + else if (message is RespExecOperation exec) + { + exec.Profile?.SetResponseReceived(); + } // one byte of work for every reply that is not an error, which is nearly all of them if (!RespRedirect.TryParse(frame, out var redirect)) return false; diff --git a/src/StackExchange.Redis/Contexts/RespConnectionManager.cs b/src/StackExchange.Redis/Contexts/RespConnectionManager.cs index 93dd886d4..2d3ec9ffc 100644 --- a/src/StackExchange.Redis/Contexts/RespConnectionManager.cs +++ b/src/StackExchange.Redis/Contexts/RespConnectionManager.cs @@ -1630,7 +1630,7 @@ private async Task SubscribeToConfigurationChannelAsync( /// the answer would profile the wrong session, or keep profiling after someone stopped. /// private object? StartProfile( - RespPayloadOperation operation, RedisCommand command, CommandFlags flags, int database, EndPoint? endpoint) + IProfiledOperation operation, RedisCommand command, CommandFlags flags, int database, EndPoint? endpoint) { if (endpoint is null) return null; @@ -1658,7 +1658,7 @@ private async Task SubscribeToConfigurationChannelAsync( // Claiming "interactive" would be right most of the time, which is not the same as right. profile.SetEnqueued(null); - operation.Profile = profile; + operation.Diagnostics.HostState = profile; // RespPayloadOperation.Profile, RespExecOperation.Profile return profile; } diff --git a/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs b/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs index 74924c5d4..13a8d2411 100644 --- a/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs +++ b/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs @@ -38,7 +38,7 @@ internal sealed class RespEndpointExecutor : RespExecutorBase, IAsyncDisposable, { private readonly Func> _connect; private readonly Func? _features; - private readonly Func? _startProfile; + private readonly Func? _startProfile; private readonly EndPoint? _endpoint; private readonly bool _queueWhileDisconnected; @@ -226,7 +226,7 @@ internal RespEndpointExecutor( EndPoint? endpoint = null, bool queueWhileDisconnected = true, Func? features = null, - Func? startProfile = null, + Func? startProfile = null, SelectPreamble? select = null, int connectTimeoutMilliseconds = 0, Func? retryPolicy = null, @@ -1254,11 +1254,13 @@ internal override bool TryWriteRun(RespConnection connection, RespRunEntry[] run /// Write a run, preceded by a SELECT if this connection is on another database. /// - /// Only a batch asks for profiling (): its commands are ordinary commands - /// that happen to travel together, and a batch used to skip profiling altogether because it bypasses - /// Dispatch, where single sends start their records (#2175). A transaction's run stays - /// unprofiled here, as it always was - its operations answer QUEUED and then answer again - /// inside EXEC, which is not the shape a ProfiledCommand describes. + /// Only a batch asks for its commands to be profiled (): they are ordinary + /// commands that happen to travel together, and a batch used to skip profiling altogether because it + /// bypasses Dispatch, where single sends start their records (#2175). A transaction's queued + /// commands stay unprofiled - they answer QUEUED and then answer again inside EXEC, which + /// is not the shape a ProfiledCommand describes - but the transaction itself is profiled, as + /// ONE record named EXEC, which is what the v3 core reported for it (its transaction was a + /// single message whose command was EXEC). /// internal bool SendRun(RespConnection connection, RespRunEntry[] run, int count, int database, bool profile = false) { @@ -1286,6 +1288,12 @@ internal bool SendRun(RespConnection connection, RespRunEntry[] run, int count, _endpoint); } } + else if (run[i].Message is RespExecOperation exec && _startProfile is { } startExec) + { + // the transaction's own record (see the remarks): named EXEC, with the caller's flags + // and the run's database, as the v3 core's transaction message reported it + startExec(exec, RedisCommand.EXEC, exec.Flags, database, _endpoint); + } } if (_select is null || database < 0) return connection.Send(run, count); diff --git a/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs b/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs index d94ec5278..f4b74fa48 100644 --- a/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs +++ b/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs @@ -9,6 +9,17 @@ namespace StackExchange.Redis { + /// An operation that can carry a profiling record: a single command, or a transaction's EXEC. + /// + /// The record lives in Diagnostics.HostState; this is only the common view of where that is, because + /// the operations share no non-generic base that exposes it. + /// + internal interface IProfiledOperation + { + /// The operation's diagnostics, whose HostState holds the profiling record. + ref RespOperationDiagnostics Diagnostics { get; } + } + /// An operation whose result is the reply frame itself. /// /// @@ -23,7 +34,7 @@ namespace StackExchange.Redis /// of the receive buffer instead is a real win and a separate piece of work. /// /// - internal class RespPayloadOperation : RespMessageBase, IFaultSubject + internal class RespPayloadOperation : RespMessageBase, IFaultSubject, IProfiledOperation { /// /// Recycled operations, so a steady-state send allocates no operation at all. diff --git a/src/StackExchange.Redis/Contexts/RespTransaction.cs b/src/StackExchange.Redis/Contexts/RespTransaction.cs index 486f37239..7ce0ddd51 100644 --- a/src/StackExchange.Redis/Contexts/RespTransaction.cs +++ b/src/StackExchange.Redis/Contexts/RespTransaction.cs @@ -203,6 +203,7 @@ private bool Enqueue(RespPayloadOperation operation, in RespRequest request, Can operation.Attach(request.Span, request.Flags, cancellationToken); operation.Diagnostics.Status = RespCommandStatus.WaitingInBacklog; operation.Slot = request.Slot; + operation.Command = request.Command; // RoutingFlags asks whether any queued command is primary-only operation.Database = Database; // its first reply will be the +QUEUED receipt; the real result arrives from EXEC @@ -323,7 +324,7 @@ public async Task ExecuteAsync(CommandFlags flags = CommandFlags.None) var empty = queue is null || queue.Count == 0; if (empty && conditions is null) return true; // an empty transaction trivially succeeds - var target = _inner.ResolveForSlot(SlotOf(queue), RedisCommand.MULTI, CommandFlags.None); + var target = _inner.ResolveForSlot(SlotOf(queue), RedisCommand.MULTI, RoutingFlags(flags, queue)); // waits for a connection rather than declining when one is merely not up yet; a transaction // that arrived before the first connect is early, not unservable @@ -553,6 +554,38 @@ private async Task CheckAsync( /// transaction as cross-slot. Wrong error, not wrong data. /// /// + /// The primary/replica preference the transaction is routed with. + /// + /// + /// The caller's preference, as for any command. This routed with no flags at all, so every + /// transaction went to the primary: harmless for writes, but a read-only transaction sent with + /// PreferReplica never reached a replica, unlike the v3 core. + /// + /// + /// Primary-only work takes the whole transaction to the primary. It runs on one server, so if + /// any queued command is primary-only the transaction must go where that command can run - the rule + /// EndpointForAny applies to a single command, and that the v3 core applied to a transaction + /// (main #3381: the LockExtend/LockRelease fallback, sent with PreferReplica, + /// went to a replica that rejected the queued EXPIRE/DEL). DemandReplica is left + /// alone, so that it still fails the same way. + /// + /// + private static CommandFlags RoutingFlags(CommandFlags flags, List? queue) + { + var preference = CommandFlagsInternal.GetPrimaryReplicaFlags(flags); + if (preference == CommandFlags.DemandReplica || queue is null) return preference; + + foreach (var (operation, _) in queue) + { + if (operation.Command.IsPrimaryOnly()) + { + return CommandFlags.DemandMaster; + } + } + + return preference; + } + private static int SlotOf(List? queue) { var slot = ServerSelectionStrategy.NoSlot; @@ -716,12 +749,29 @@ internal void Abandon(Exception fault) /// alternative is pinning a potentially large array. /// /// - internal sealed class RespExecOperation : RespMessageBase + internal sealed class RespExecOperation : RespMessageBase, IProfiledOperation { private List? _queued; private Action? _onAborted; private CommandFlags _flags; + /// The caller's flags for the transaction, which its profiling record reports. + internal CommandFlags Flags => _flags; + + /// The transaction's profiling record, when anyone is profiling. + /// Held where holds a single command's. + internal Profiling.ProfiledCommand? Profile + { + get => Diagnostics.HostState as Profiling.ProfiledCommand; + set => Diagnostics.HostState = value; + } + + /// + protected override void OnSent() => Profile?.SetRequestSent(); + + /// + protected override void OnFinished(Exception? fault) => Profile?.SetCompleted(); + internal void Attach( ReadOnlySpan request, List queued, @@ -743,6 +793,7 @@ protected override void OnReset() _queued = null; _onAborted = null; _flags = CommandFlags.None; + Profile = null; } /// diff --git a/tests/StackExchange.Redis.Tests/TransactionTests.cs b/tests/StackExchange.Redis.Tests/TransactionTests.cs index 8a4340308..243fc3706 100644 --- a/tests/StackExchange.Redis.Tests/TransactionTests.cs +++ b/tests/StackExchange.Redis.Tests/TransactionTests.cs @@ -1,5 +1,7 @@ using System; +using System.Linq; using System.Threading.Tasks; +using StackExchange.Redis.Profiling; using Xunit; namespace StackExchange.Redis.Tests; @@ -67,6 +69,64 @@ public async Task NestedTransactionThrows() Assert.Throws(() => ((IDatabaseAsync)tran).CreateTransaction(null)); } + [Fact] + public async Task PrimaryOnlyWorkWithPreferReplicaRunsOnThePrimary() + { + await using var conn = Create(configuration: TestConfig.Current.PrimaryServerAndPort + "," + TestConfig.Current.ReplicaServerAndPort); + Assert.SkipUnless( + conn.GetEndPoints().Any(ep => conn.GetServer(ep).IsReplica), + "No replica in this configuration"); + + var db = conn.GetDatabase(); + RedisKey key = Me(); + db.StringSet(key, "abc"); + + var session = new ProfilingSession(); + conn.RegisterProfiler(() => session); + + // this is what LockExtend / LockRelease fall back to on servers without SET IFEQ / DELEX + var tran = db.CreateTransaction(); + tran.AddCondition(Condition.StringEqual(key, "abc")); + var expire = tran.KeyExpireAsync(key, TimeSpan.FromMinutes(1)); + Assert.True(tran.Execute(CommandFlags.PreferReplica)); + Assert.True(await expire); + + tran = db.CreateTransaction(); + tran.AddCondition(Condition.StringEqual(key, "abc")); + var set = tran.StringSetAsync(key, "def"); + Assert.True(await tran.ExecuteAsync(CommandFlags.PreferReplica)); + Assert.True(await set); + + Assert.Equal("def", db.StringGet(key, CommandFlags.DemandMaster)); + var execs = session.FinishProfiling().Where(cmd => cmd.Command == "EXEC").ToList(); + Assert.Equal(2, execs.Count); + Assert.All(execs, exec => Assert.False(conn.GetServer(exec.EndPoint).IsReplica)); + } + + [Fact] + public async Task ReadOnlyWorkWithPreferReplicaStillRunsOnTheReplica() + { + await using var conn = Create(configuration: TestConfig.Current.PrimaryServerAndPort + "," + TestConfig.Current.ReplicaServerAndPort); + Assert.SkipUnless( + conn.GetEndPoints().Any(ep => conn.GetServer(ep).IsReplica), + "No replica in this configuration"); + + var db = conn.GetDatabase(); + RedisKey key = Me(); + + var session = new ProfilingSession(); + conn.RegisterProfiler(() => session); + + var tran = db.CreateTransaction(); + tran.AddCondition(Condition.KeyNotExists(key)); + var get = tran.StringGetAsync(key); + Assert.True(await tran.ExecuteAsync(CommandFlags.PreferReplica)); + Assert.True((await get).IsNull); + + var exec = Assert.Single(session.FinishProfiling(), cmd => cmd.Command == "EXEC"); + Assert.True(conn.GetServer(exec.EndPoint).IsReplica); + } + [Theory] [InlineData(false, false, true)] [InlineData(false, true, false)]