diff --git a/AGENTS.md b/AGENTS.md index e885d7439..49a8d69e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,8 +29,8 @@ pwsh ./build.ps1 -StartServers # Start the Redis test servers in the background (preferred; see "Testing topology") docker compose --file tests/RedisConfigs/docker-compose.yml up -d --wait -# Run the main test suite against one target framework (fastest inner loop) -dotnet test --project tests/StackExchange.Redis.Tests/StackExchange.Redis.Tests.csproj -c Release -f net10.0 +# Run the main test suite against one target framework (fastest inner loop; Debug locally, see below) +dotnet test --project tests/StackExchange.Redis.Tests/StackExchange.Redis.Tests.csproj -c Debug -f net10.0 # Run a single test class / method (xUnit v3 on Microsoft.Testing.Platform; names are fully qualified, '*' allowed at either end) dotnet test --project tests/StackExchange.Redis.Tests/StackExchange.Redis.Tests.csproj -f net10.0 --filter-class StackExchange.Redis.Tests.ClassName @@ -43,6 +43,7 @@ dotnet test --solution StackExchange.Redis.slnx -c Release --no-build dotnet pack src/StackExchange.Redis/StackExchange.Redis.csproj --no-build -c Release /p:Packing=true ``` +- **Test locally in Debug.** CI builds and tests Release, so DEBUG-only checks never run there: `Debug.Assert`s, the buffer leak-tracking finalizers in RESPite, and instrumentation that some tests read (e.g. `RespRequest.HashComputations`, which pins "a request is hashed once"; those tests skip in Release). Use Release for benchmarks and when reproducing a CI failure. - SDK is pinned (`global.json`, `allowPrerelease: false`); CI installs the 6/8/10 runtimes. `LangVersion` is 14. - `TreatWarningsAsErrors=true` everywhere and `Features=strict` — warnings fail the build. Analyzers (StyleCop + the custom `eng` analyzer + PublicApiAnalyzers) run as part of the build. - Analyzers run on **one TFM per project** — the newest it builds (see `Directory.Build.targets`), because they cost ~40% of a clean build otherwise and every rule is TFM-agnostic. Source generators still run on every TFM. If you touch code inside a down-level `#if`, build it with `/p:RunAnalyzers=true` to get the full per-TFM sweep. StyleCop applies to `src/` only, not `tests/` or `toys/`. diff --git a/docs/Configuration.md b/docs/Configuration.md index 59b6a2034..0728afef2 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -169,6 +169,7 @@ Additional code-only options: - Whether exceptions include performance counter details (CPU usage, etc); note that this can be problematic on some platforms - RequestBufferPool (`MemoryPool`) - Default: `null` - The buffer pool to use when buffering requests; when `null`, a shared default pool is used + - Covers the socket's write buffers and the copy a request is held in until it is written (requests too large for the client's small inline buffer). Short-lived scratch space used while a request is being composed is not rented from it. A write buffer that is in use when a connection is torn down is left to the garbage collector rather than returned, so a pool that counts outstanding rentals can see one per closed connection. - ResponseBufferPool (`MemoryPool`) - Default: `null` - The buffer pool to use when buffering responses (and for allocating `Lease` results); when `null`, a shared default pool is used - CircuitBreaker (`CircuitBreaker`) - Default: `null` diff --git a/src/StackExchange.Redis/Caching/RespClientCache.cs b/src/StackExchange.Redis/Caching/RespClientCache.cs index 65d34b678..e3a0e4d19 100644 --- a/src/StackExchange.Redis/Caching/RespClientCache.cs +++ b/src/StackExchange.Redis/Caching/RespClientCache.cs @@ -1066,7 +1066,7 @@ public bool TryBeginFill(ref RespRequestFrame frame, int database, CommandFlags if (_doorkeeper is not null && (flags & CommandFlags.CacheOptIn) == 0 && !byPrefix - && !_doorkeeper.SeenBefore((frame.AsLookupKey().GetHashCode() * 397) ^ database)) + && !_doorkeeper.SeenBefore((frame.Hash * 397) ^ database)) { Interlocked.Increment(ref _refusedNotAdmitted); fill = default; diff --git a/src/StackExchange.Redis/Contexts/RespConnectionManager.cs b/src/StackExchange.Redis/Contexts/RespConnectionManager.cs index 708f253d3..8c0ddbac3 100644 --- a/src/StackExchange.Redis/Contexts/RespConnectionManager.cs +++ b/src/StackExchange.Redis/Contexts/RespConnectionManager.cs @@ -930,6 +930,7 @@ private RespEndpointExecutor Endpoint(EndPoint endpoint) () => ModelledServer(endpoint)) { RerouteSubscription = operation => TryRerouteSubscription(endpoint, operation), + ConfiguredRequestBufferPool = _multiplexer.RawConfig.RequestBufferPool, HeartbeatDriven = true, SyncTimeoutMilliseconds = () => _multiplexer.TimeoutMilliseconds, }; diff --git a/src/StackExchange.Redis/Contexts/RespDatabaseExecutor.cs b/src/StackExchange.Redis/Contexts/RespDatabaseExecutor.cs index 1d7b0ec8d..a42c05b46 100644 --- a/src/StackExchange.Redis/Contexts/RespDatabaseExecutor.cs +++ b/src/StackExchange.Redis/Contexts/RespDatabaseExecutor.cs @@ -115,6 +115,9 @@ internal override ValueTask SendTypedAsync( /// internal override bool CopiesRequestOnSend => true; // a view over an endpoint executor, which does + /// + internal override System.Buffers.MemoryPool? RequestBufferPool => _inner.RequestBufferPool; + /// internal override ValueTask SendVoidAsync(RespRequest request, IRespHandler handler, CancellationToken cancellationToken) => _inner.SendVoidAsync(request, handler, Database, cancellationToken); diff --git a/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs b/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs index 13a8d2411..b47c2b03d 100644 --- a/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs +++ b/src/StackExchange.Redis/Contexts/RespEndpointExecutor.cs @@ -466,6 +466,18 @@ internal RespPayload WaitBlocking(RespPayloadOperation operation) /// internal override ConnectionMultiplexer? Multiplexer => Server?.Multiplexer; + /// + /// Set once by the owner, from configuration; null for an executor built directly in tests. + internal override System.Buffers.MemoryPool? RequestBufferPool => _requestBufferPool; + + private System.Buffers.MemoryPool? _requestBufferPool; + + /// Supplied by the owner; see . + internal System.Buffers.MemoryPool? ConfiguredRequestBufferPool + { + init => _requestBufferPool = value; + } + /// /// /// A view over this connection, which is the whole point of . @@ -955,7 +967,7 @@ internal override RespPayload Send(RespRequest preamble, RespRequest request, IR pre.Database = Database; var body = RespPayloadOperation.Rent(); - body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix); + body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix, _requestBufferPool); body.Slot = request.Slot; body.Command = request.Command; body.Observer = this; @@ -2155,7 +2167,7 @@ private RespPayloadOperation Dispatch( Validate(in request, database); var operation = rented ?? RespPayloadOperation.Rent(); - operation.Attach(in request, cancellationToken); + operation.Attach(in request, cancellationToken, _requestBufferPool); operation.Database = database; operation.Command = request.Command; operation.Observer = this; diff --git a/src/StackExchange.Redis/Contexts/RespExecutor.cs b/src/StackExchange.Redis/Contexts/RespExecutor.cs index 03cecbc84..80487b90c 100644 --- a/src/StackExchange.Redis/Contexts/RespExecutor.cs +++ b/src/StackExchange.Redis/Contexts/RespExecutor.cs @@ -60,6 +60,13 @@ internal abstract class RespExecutorBase /// internal virtual ConnectionMultiplexer? Multiplexer => null; + /// Where a large request's own copy is rented from: the configured RequestBufferPool, or null. + /// + /// Null means , as before. Only what an operation holds until + /// it is written comes from here; see RespPayloadOperation.Attach for which requests that is. + /// + internal virtual System.Buffers.MemoryPool? RequestBufferPool => null; + /// The multiplexer a context reports publicly, as . /// /// @@ -1334,7 +1341,7 @@ public static ValueTask SendAsync( // Not under CacheNoLocalServe: the in-flight reply answers a question asked before this // one, and the wait resolves by re-probing the cache - both are what that flag declines. if ((flags & CommandFlags.CacheNoLocalServe) == 0 - && cache.TryAwaitInFlight(request.AsLookupKey(), executor.Database, out var pending)) + && cache.TryAwaitInFlight(request.AsHashedLookupKey(), executor.Database, out var pending)) { return AwaitShared(executor, request.Detach(flags), pending, handler, cache, context.CachePolicy, cancellationToken); } @@ -1662,7 +1669,7 @@ private static bool TryServeFromCache( return false; } - if (!cache.TryGet(request.AsLookupKey(), executor.Database, policy, out var hit, out var refresh, out var reuse)) + if (!cache.TryGet(request.AsHashedLookupKey(), executor.Database, policy, out var hit, out var refresh, out var reuse)) { result = default; return false; diff --git a/src/StackExchange.Redis/Contexts/RespOperationBatch.cs b/src/StackExchange.Redis/Contexts/RespOperationBatch.cs index 613737adb..3b9e3c3a1 100644 --- a/src/StackExchange.Redis/Contexts/RespOperationBatch.cs +++ b/src/StackExchange.Redis/Contexts/RespOperationBatch.cs @@ -91,6 +91,9 @@ internal RespOperationBatchExecutor(RespExecutorBase inner, bool reusable = fals /// public override int Database => _inner.Database; + /// + internal override System.Buffers.MemoryPool? RequestBufferPool => _inner.RequestBufferPool; + /// internal override IConnectionMultiplexer? ExposedMultiplexer => _inner.ExposedMultiplexer; @@ -215,7 +218,7 @@ internal override ValueTask SendVoidAsync(RespRequest request, IRespHandlerFalse if the command is fire-and-forget, and so already answered. private bool Enqueue(RespPayloadOperation operation, in RespRequest request, CancellationToken cancellationToken) { - operation.Attach(request.Span, request.Flags, cancellationToken, request.Prefix); + operation.Attach(request.Span, request.Flags, cancellationToken, request.Prefix, RequestBufferPool); operation.Diagnostics.Status = RespCommandStatus.WaitingInBacklog; operation.Slot = request.Slot; operation.Database = Database; // read if it is ever re-sent on its own, after a redirect @@ -280,7 +283,7 @@ public override ValueTask SendAsync( head.Database = Database; var body = RespPayloadOperation.Rent(); - body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix); + body.Attach(request.Span, request.Flags, cancellationToken, request.Prefix, RequestBufferPool); body.Diagnostics.Status = RespCommandStatus.WaitingInBacklog; body.Slot = request.Slot; body.Database = Database; diff --git a/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs b/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs index f4b74fa48..71840729f 100644 --- a/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs +++ b/src/StackExchange.Redis/Contexts/RespPayloadOperation.cs @@ -605,7 +605,7 @@ protected override void OnReset() /// protected override void OnRecyclable() => Return(this); - /// The operation's own request buffer, kept across pooled lives; see . + /// The operation's own request buffer, kept across pooled lives; see . private byte[]? _requestBuffer; /// Requests up to this size are copied into the operation; larger ones share the caller's buffer. @@ -628,7 +628,7 @@ protected override void OnReset() /// is neither copied nor retained by a pooled operation; a borrowed large one is copied into a rented array. /// /// - internal void Attach(in RespRequest request, CancellationToken cancellationToken) + internal void Attach(in RespRequest request, CancellationToken cancellationToken, MemoryPool? pool = null) { var span = request.Span; if (span.Length <= InlineRequestLimit) @@ -646,7 +646,10 @@ internal void Attach(in RespRequest request, CancellationToken cancellationToken return; } - if (request.TryShare(out var memory, out var owner)) + // Shared only when no pool was configured: sharing keeps the builder's ArrayPool array alive until the + // write, and a caller who configured RequestBufferPool asked for that memory to be theirs. Copying costs + // one memcpy of a large request, and only for them; everyone else keeps the zero-copy hand-off. + if (pool is null && request.TryShare(out var memory, out var owner)) { _flags = request.Flags; SetRequest(memory, owner, cancellationToken); @@ -654,7 +657,7 @@ internal void Attach(in RespRequest request, CancellationToken cancellationToken return; } - Attach(request.Span, request.Flags, cancellationToken, request.Prefix); + Attach(request.Span, request.Flags, cancellationToken, request.Prefix, pool); } /// Begin a life for a request given as raw bytes, which are copied. @@ -662,13 +665,30 @@ internal void Attach(in RespRequest request, CancellationToken cancellationToken /// The request's flags. /// Cancels the request. /// A frame the connection writes ahead of the request, or null; see . - internal void Attach(ReadOnlySpan request, CommandFlags flags, CancellationToken cancellationToken, byte[]? prefix = null) + /// + /// The configured RequestBufferPool, or null for . A caller who configured + /// one asked to own the memory requests are buffered in, as v3 honoured it for every request it wrote; this is the + /// copy that lives until the request is written, so it is the one that has to come from there. The owner is + /// released through IDisposable when the last reference to the request goes, exactly once. + /// + internal void Attach(ReadOnlySpan request, CommandFlags flags, CancellationToken cancellationToken, byte[]? prefix = null, MemoryPool? pool = null) { _flags = flags; - var pool = ArrayPool.Shared; - var buffer = pool.Rent(request.Length); - request.CopyTo(buffer); - SetRequest(new ReadOnlyMemory(buffer, 0, request.Length), pool, cancellationToken); + if (pool is not null && request.Length <= pool.MaxBufferSize) + { + var owner = pool.Rent(request.Length); + var memory = owner.Memory.Slice(0, request.Length); + request.CopyTo(memory.Span); + SetRequest(memory, owner, cancellationToken); + } + else + { + var arrays = ArrayPool.Shared; + var buffer = arrays.Rent(request.Length); + request.CopyTo(buffer); + SetRequest(new ReadOnlyMemory(buffer, 0, request.Length), arrays, cancellationToken); + } + Prefix = prefix; } diff --git a/src/StackExchange.Redis/Contexts/RespTransaction.cs b/src/StackExchange.Redis/Contexts/RespTransaction.cs index 7ce0ddd51..f8b6a9a05 100644 --- a/src/StackExchange.Redis/Contexts/RespTransaction.cs +++ b/src/StackExchange.Redis/Contexts/RespTransaction.cs @@ -98,6 +98,9 @@ internal RespTransactionExecutor(RespExecutorBase inner, RespContext? context = /// public override int Database => _inner.Database; + /// + internal override System.Buffers.MemoryPool? RequestBufferPool => _inner.RequestBufferPool; + /// internal override IConnectionMultiplexer? ExposedMultiplexer => _inner.ExposedMultiplexer; @@ -200,7 +203,7 @@ internal override ValueTask SendVoidAsync(RespRequest request, IRespHandlerFalse if the command is fire-and-forget, and so already answered. private bool Enqueue(RespPayloadOperation operation, in RespRequest request, CancellationToken cancellationToken) { - operation.Attach(request.Span, request.Flags, cancellationToken); + operation.Attach(request.Span, request.Flags, cancellationToken, pool: RequestBufferPool); operation.Diagnostics.Status = RespCommandStatus.WaitingInBacklog; operation.Slot = request.Slot; operation.Command = request.Command; // RoutingFlags asks whether any queued command is primary-only diff --git a/src/StackExchange.Redis/Protocol/RespRequest.cs b/src/StackExchange.Redis/Protocol/RespRequest.cs index b9a18faa9..993f1e417 100644 --- a/src/StackExchange.Redis/Protocol/RespRequest.cs +++ b/src/StackExchange.Redis/Protocol/RespRequest.cs @@ -1,6 +1,8 @@ using System; using System.Buffers; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using RESPite; using RESPite.Buffers; using RESPite.Messages; @@ -39,13 +41,16 @@ namespace StackExchange.Redis.Protocol private readonly RefCountedBuffer? _lease; // null => BORROWED: this key owns no reference private readonly int _offset; private readonly int _length; - private readonly int _hash; // carried over from the frame, because an executor decorator sees only a request. Routing needs the // slot; a cache needs the key marks to register dependencies; retry and cacheability need the flags. // Without these a decorator can ask nothing about what it is sending. private readonly ulong _keyMarks; + // The content hash, or 0 while nobody has asked: see GetHashCode. Never 0 once known (ComputeHash), so 0 can + // mean "not yet". Carried to every request derived from this one, and from the frame it was rendered in. + private readonly int _hash; + internal RespRequest( byte[] array, RefCountedBuffer? lease, @@ -57,15 +62,16 @@ internal RespRequest( CommandFlags flags = CommandFlags.None, RedisCommand command = RedisCommand.UNKNOWN, int database = -1, - byte[]? prefix = null) + byte[]? prefix = null, + int hash = 0) { _array = array; Prefix = prefix; _lease = lease; _offset = offset; _length = length; - _hash = RedisValue.GetHashCode(array.AsSpan(offset, length)); _keyMarks = keyMarks; + _hash = hash; Slot = slot; ArgCount = argCount; Flags = flags; @@ -144,8 +150,7 @@ public ReadOnlySpan GetKey(in KeyRange range) internal RespRequest WithFlags(CommandFlags flags) => flags == Flags ? this : new RespRequest(this, flags); - // the same bytes, lease and metadata - including the hash, which there is no reason to recompute - with - // different flags; a struct copy, so the lease is shared exactly as passing the request by value shares it + // the same bytes, lease and metadata with different flags; a struct copy, so the lease is shared exactly as passing the request by value shares it private RespRequest(in RespRequest source, CommandFlags flags) { _array = source._array; @@ -153,8 +158,8 @@ private RespRequest(in RespRequest source, CommandFlags flags) _lease = source._lease; _offset = source._offset; _length = source._length; - _hash = source._hash; _keyMarks = source._keyMarks; + _hash = source._hash; Slot = source.Slot; ArgCount = source.ArgCount; Flags = flags; @@ -173,7 +178,7 @@ internal RespRequest ToOwned() var array = ArrayPool.Shared.Rent(Math.Max(span.Length, 1)); span.CopyTo(array); return new RespRequest( - array, RefCountedBuffer.Adopt(array, array.Length), 0, span.Length, _keyMarks, Slot, ArgCount, Flags, Command, Database, Prefix); + array, RefCountedBuffer.Adopt(array, array.Length), 0, span.Length, _keyMarks, Slot, ArgCount, Flags, Command, Database, Prefix, _hash); } /// Take a reference of our own on these bytes, rather than copying them. @@ -238,7 +243,7 @@ internal RespRequest CopyForCacheKey() { var span = Span; var array = span.ToArray(); - return new RespRequest(array, lease: null, 0, array.Length, _keyMarks, Slot, ArgCount, Flags, Command, Database); + return new RespRequest(array, lease: null, 0, array.Length, _keyMarks, Slot, ArgCount, Flags, Command, Database, hash: _hash); } /// @@ -251,7 +256,7 @@ internal RespRequest CopyForCacheKey(byte[] into, int offset) { var span = Span; span.CopyTo(into.AsSpan(offset)); - return new RespRequest(into, lease: null, offset, span.Length, _keyMarks, Slot, ArgCount, Flags, Command, Database); + return new RespRequest(into, lease: null, offset, span.Length, _keyMarks, Slot, ArgCount, Flags, Command, Database, hash: _hash); } /// @@ -292,14 +297,67 @@ public bool TryRetain(out RespRequest retained) /// the same command with different are asking the same question. /// public bool Equals(RespRequest other) - => _hash == other._hash && _length == other._length && Span.SequenceEqual(other.Span); + => _length == other._length && Span.SequenceEqual(other.Span); /// public override bool Equals(object? obj) => obj is RespRequest other && Equals(other); /// - /// Computed once, when the key is detached, while the bytes are already in cache. - public override int GetHashCode() => _hash; + /// + /// + /// Computed once, and only when asked. Only the client-side cache asks, and every request used to pay + /// for it at construction - a pass over the whole payload, so a large SET hashed its value on every + /// send, cached or not, and a cache miss hashed once per copy it made of the key. + /// + /// + /// So the hash lives on the , the one instance the cache path passes by + /// reference: the cache asks the frame (), and every request + /// derived from it afterwards - lookup views, the detached fill key, the stored copy - carries the answer. + /// A request that arrives without one (built some other way) computes it here; the write-back keeps it for + /// that copy's later calls, and is a benign race, since every thread writes the same value. + /// + /// + /// does not compare hashes first: a dictionary calls it only once the hash + /// codes it stored already match. + /// + /// + public override int GetHashCode() + { + var hash = _hash; + if (hash == 0) Unsafe.AsRef(in _hash) = hash = ComputeHash(Span); + return hash; + } + + /// The hash, if it is already known; 0 otherwise. For passing on to a derived request. + internal int KnownHash => _hash; + + /// The one place a request's content is hashed. Never 0, so 0 can mean "not computed". + internal static int ComputeHash(ReadOnlySpan span) + { + CountHash(); + var hash = RedisValue.GetHashCode(span); + return hash == 0 ? 1 : hash; + } + + /// How many times this thread has hashed request content: lets tests pin "once per request". + /// + /// Per thread, so concurrent tests cannot see each other's work. Counted in DEBUG builds only (see + /// ): always zero in Release, so tests that read it skip there. + /// + internal static long HashComputations => t_hashComputations; + + /// Whether is maintained by this build. +#if DEBUG + internal static bool CountsHashes => true; +#else + internal static bool CountsHashes => false; +#endif + + [Conditional("DEBUG")] + private static void CountHash() => t_hashComputations++; + + [ThreadStatic] + private static long t_hashComputations; /// /// diff --git a/src/StackExchange.Redis/Protocol/RespRequestFrame.cs b/src/StackExchange.Redis/Protocol/RespRequestFrame.cs index d9b77fbf1..b2bf9bf83 100644 --- a/src/StackExchange.Redis/Protocol/RespRequestFrame.cs +++ b/src/StackExchange.Redis/Protocol/RespRequestFrame.cs @@ -32,6 +32,7 @@ public struct RespRequestFrame : IDisposable private readonly int _start; private readonly int _length; private readonly ulong _keyMarks; + private int _hash; // 0 until the cache first asks; see AsHashedLookupKey internal RespRequestFrame(byte[] buffer, int start, int length, int argCount, int slot, ulong keyMarks, RedisCommand command, int database = -1) { @@ -329,7 +330,8 @@ internal RespRequest Detach(CommandFlags flags, byte[]? prefix) flags, Command, Database, - prefix); + prefix, + _hash); } /// @@ -368,7 +370,43 @@ internal RespRequest AsLookupKey(CommandFlags flags, byte[]? prefix) flags, Command, Database, - prefix); + prefix, + _hash); + } + + /// + /// As , with the content hash computed now - once, on this frame - so that + /// every request derived from the frame from here on carries it rather than hashing again. + /// + /// + /// For the client-side cache, which is the only thing that hashes a request, and hashes it repeatedly on a miss: + /// the lookup, the in-flight probe, the doorkeeper, registering the fill, storing it, removing the in-flight + /// marker. Each of those used to see a different copy of the key, and copies of a readonly struct cannot share a + /// lazily computed field; the frame, passed by reference throughout, can. + /// + internal RespRequest AsHashedLookupKey() + { + EnsureHash(); + return AsLookupKey(CommandFlags.None, prefix: null); + } + + /// The content hash, computed on first use; see . + internal int Hash + { + get + { + EnsureHash(); + return _hash; + } + } + + private void EnsureHash() + { + if (_hash == 0) + { + var buffer = _buffer ?? throw new ObjectDisposedException(nameof(RespRequestFrame)); + _hash = RespRequest.ComputeHash(buffer.AsSpan(_start, _length)); + } } /// Return the underlying buffer to the pool; safe to call more than once. diff --git a/tests/StackExchange.Redis.Tests/RequestBufferPoolTests.cs b/tests/StackExchange.Redis.Tests/RequestBufferPoolTests.cs new file mode 100644 index 000000000..0f6e99a14 --- /dev/null +++ b/tests/StackExchange.Redis.Tests/RequestBufferPoolTests.cs @@ -0,0 +1,132 @@ +using System; +using System.Buffers; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace StackExchange.Redis.Tests; + +/// +/// : v3 buffered every request in it, and v4 staged requests in +/// regardless (raised on #3364). The copy an operation holds until it is written +/// comes from the configured pool, and every rental goes back to it exactly once. +/// +[RunPerProtocol] +public class RequestBufferPoolTests(ITestOutputHelper log) +{ + private sealed class CountingPool : MemoryPool + { + private int _rented, _returned, _doubleReturns, _requestSized, _requestSizedReturned; + private readonly int _requestMin, _requestMax; + + public CountingPool(int requestMin, int requestMax) + { + _requestMin = requestMin; + _requestMax = requestMax; + } + + public int Rented => Volatile.Read(ref _rented); + + public int Returned => Volatile.Read(ref _returned); + + public int DoubleReturns => Volatile.Read(ref _doubleReturns); + + // rentals sized like the large request itself, rather than like a transport buffer block + public int RequestSized => Volatile.Read(ref _requestSized); + + public int RequestSizedReturned => Volatile.Read(ref _requestSizedReturned); + + private bool IsRequestSized(int size) => size >= _requestMin && size <= _requestMax; + + public override int MaxBufferSize => int.MaxValue; + + public override IMemoryOwner Rent(int minBufferSize = -1) + { + Interlocked.Increment(ref _rented); + if (IsRequestSized(minBufferSize)) Interlocked.Increment(ref _requestSized); + var owner = new Owner(this, Shared.Rent(minBufferSize), minBufferSize); + lock (_outstanding) _outstanding.Add(owner); + return owner; + } + + protected override void Dispose(bool disposing) { } + + private readonly System.Collections.Generic.HashSet _outstanding = new(); + + public string Outstanding() + { + lock (_outstanding) + { + var sb = new System.Text.StringBuilder(); + foreach (var o in _outstanding) sb.Append(o.Requested).Append(' '); + return sb.ToString(); + } + } + + private sealed class Owner(CountingPool pool, IMemoryOwner inner, int requested) : IMemoryOwner + { + private int _disposed; + + public int Requested => requested; + + public Memory Memory => inner.Memory; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + Interlocked.Increment(ref pool._returned); + if (pool.IsRequestSized(requested)) Interlocked.Increment(ref pool._requestSizedReturned); + lock (pool._outstanding) pool._outstanding.Remove(this); + inner.Dispose(); + } + else + { + Interlocked.Increment(ref pool._doubleReturns); + } + } + } + } + + [Fact] + public async Task LargeRequestsAreBufferedInTheConfiguredPoolAndReturnedOnce() + { + const int ValueLength = 10_000; // well past the operation's inline limit, so the request needs a buffer of its own + var pool = new CountingPool(ValueLength, ValueLength + 128); + + using var server = new InProcessTestServer(log); + var config = server.GetClientConfig(); + config.RequestBufferPool = pool; + var conn = await ConnectionMultiplexer.ConnectAsync(config); + try + { + var db = conn.GetDatabase(); + var key = Me(); + var value = new byte[ValueLength]; + new Random(42).NextBytes(value); + + for (var i = 0; i < 5; i++) + { + Assert.True(await db.StringSetAsync(key, value)); + db.StringSet(key, value); // the sync surface too + } + + Assert.Equal(value, (byte[]?)await db.StringGetAsync(key)); + Assert.True(pool.RequestSized >= 10, $"expected each large SET to stage in the configured pool; saw {pool.RequestSized} request-sized rentals of {pool.Rented}"); + } + finally + { + await conn.DisposeAsync(); + } + + // every request copy went back, and nothing - request or transport block - went back twice. The transport's + // write buffer is deliberately NOT returned on teardown (BufferedStreamWriter recycles only on a clean exit, + // rather than risk returning memory a write may still touch), so it is not part of the "all back" check. + Assert.True( + await Poll.UntilAsync(() => pool.RequestSizedReturned == pool.RequestSized), + $"request copies: rented {pool.RequestSized}, returned {pool.RequestSizedReturned}; outstanding sizes: {pool.Outstanding()}"); + Assert.Equal(0, pool.DoubleReturns); + } + + private static string Me([System.Runtime.CompilerServices.CallerMemberName] string caller = "") => caller; +} diff --git a/tests/StackExchange.Redis.Tests/RequestHashTests.cs b/tests/StackExchange.Redis.Tests/RequestHashTests.cs new file mode 100644 index 000000000..1f2342374 --- /dev/null +++ b/tests/StackExchange.Redis.Tests/RequestHashTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using StackExchange.Redis.Caching; +using StackExchange.Redis.Protocol; +using Xunit; + +namespace StackExchange.Redis.Tests; + +/// +/// A request's content hash is computed when the client-side cache first needs it, and once: never for a request +/// the cache does not look up (an uncached read, any write), and once - not once per copy of the key - across a +/// lookup, the in-flight probe, the doorkeeper, registering the fill, storing it and clearing the in-flight marker. +/// +/// +/// Counted with , which is per thread; the fake executor answers inline, +/// so the whole round trip - fill and store included - runs on the test's thread. The counter exists in DEBUG builds +/// of the library only, so the counting tests skip in Release - which is what CI builds; run them locally in Debug. +/// +public class RequestHashTests +{ + private const CommandFlags Readable = CommandFlags.CommandRetryReadOnly; + + private sealed class InlineExecutor(string reply) : RespExecutorBase + { + public int Sends; + + public override int Database => 0; + + public override RespPayload Send(in RespRequest request) + { + Sends++; + return (request.Flags & CommandFlags.FireAndForget) != 0 ? null! : RespPayload.Create(Encoding.UTF8.GetBytes(reply)); + } + + public override ValueTask SendAsync(RespRequest request, CancellationToken cancellationToken = default) + => new(Send(request)); + } + + private static (RespDatabaseContext Context, RespClientCache Cache, InlineExecutor Executor) Create(CacheAdmission admission, string reply = "$1\r\na\r\n") + { + var cache = new RespClientCache(new CacheOptions { Admission = admission }); + var executor = new InlineExecutor(reply); + return (new RespDatabaseContext(new RespContext().WithExecutor(executor).WithCache(cache)), cache, executor); + } + + private static async Task HashesDuring(Func action) + { + Assert.SkipUnless(RespRequest.CountsHashes, "hash counting exists in DEBUG builds of the library only"); + var before = RespRequest.HashComputations; + await action(); + return RespRequest.HashComputations - before; + } + + [Fact] + public async Task MissAndStoreHashOnce_HitHashesOnce() + { + var (context, cache, executor) = Create(CacheAdmission.OnFirstMiss); + using (cache) + { + // miss: lookup, in-flight probe, fill registration, store, in-flight removal - one hash between them + Assert.Equal(1, await HashesDuring(async () => Assert.Equal("a", await context.SendAsync($"{RedisCommand.GET}{(RedisKey)"k"}", Readable)))); + Assert.Equal(1, cache.Count); + + // hit + Assert.Equal(1, await HashesDuring(async () => Assert.Equal("a", await context.SendAsync($"{RedisCommand.GET}{(RedisKey)"k"}", Readable)))); + Assert.Equal(1, executor.Sends); + + // invalidated, then re-filled over the dead entry: still one + Assert.True(cache.OnInvalidate("k"u8)); + Assert.Equal(1, await HashesDuring(async () => Assert.Equal("a", await context.SendAsync($"{RedisCommand.GET}{(RedisKey)"k"}", Readable)))); + Assert.Equal(2, executor.Sends); + } + } + + [Fact] + public async Task TheDoorkeeperReusesTheLookupHash() + { + var (context, cache, _) = Create(CacheAdmission.OnRepeatedMiss); + using (cache) + { + // first miss: remembered by the doorkeeper, not stored + Assert.Equal(1, await HashesDuring(async () => await context.SendAsync($"{RedisCommand.GET}{(RedisKey)"k"}", Readable))); + Assert.Equal(0, cache.Count); + + // second miss: admitted and stored + Assert.Equal(1, await HashesDuring(async () => await context.SendAsync($"{RedisCommand.GET}{(RedisKey)"k"}", Readable))); + Assert.Equal(1, cache.Count); + } + } + + [Fact] + public async Task RequestsTheCacheNeverLooksUpAreNeverHashed() + { + var (context, cache, _) = Create(CacheAdmission.OnFirstMiss, "+OK\r\n"); + using (cache) + { + var value = new byte[100_000]; + + // a large write, with caching on: invalidation reads the key, never the value + Assert.Equal(0, await HashesDuring(async () => await context.SendAsync($"{RedisCommand.SET}{(RedisKey)"k"}{(RedisValue)value}", CommandFlags.None))); + + // a read that opted out + Assert.Equal(0, await HashesDuring(async () => await context.SendAsync($"{RedisCommand.GET}{(RedisKey)"k"}", Readable | CommandFlags.CacheOptOut))); + } + } + + [Fact] + public void RequestsCompareAndHashByContent() + { + var bytes = "*2\r\n$3\r\nGET\r\n$3\r\nfoo\r\n"u8.ToArray(); + var copy = (byte[])bytes.Clone(); + var other = "*2\r\n$3\r\nGET\r\n$3\r\nbar\r\n"u8.ToArray(); + + // different arrays, offsets and flags: identity is the rendered bytes only + var padded = new byte[bytes.Length + 7]; + bytes.CopyTo(padded, 7); + var a = new RespRequest(bytes, null, 0, bytes.Length); + var b = new RespRequest(padded, null, 7, bytes.Length, flags: CommandFlags.PreferReplica); + var c = new RespRequest(copy, null, 0, copy.Length).WithFlags(CommandFlags.DemandMaster); + var d = new RespRequest(other, null, 0, other.Length); + + Assert.True(a.Equals(b)); + Assert.True(a.Equals(c)); + Assert.False(a.Equals(d)); + Assert.Equal(a.GetHashCode(), b.GetHashCode()); + Assert.Equal(a.GetHashCode(), c.GetHashCode()); + Assert.Equal(a.GetHashCode(), a.GetHashCode()); // computed on demand, so it must be stable across calls + Assert.NotEqual(0, default(RespRequest).GetHashCode()); // 0 means "not computed", so it is never a result + } + +}