Skip to content

Stop waiting on Redis operations when cancelled - #740

Merged
sburmanoctopus merged 7 commits into
mainfrom
orion/redis-cancelling
Nov 19, 2026
Merged

sburmanoctopus merged 7 commits into
mainfrom
orion/redis-cancelling

Conversation

@borland

@borland borland commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Claude (with tweaks from 👨 Orion)

Background

StackExchange.Redis doesn't accept a CancellationToken on commands like StringGetAsync.
There's no other available token either (for example how aspnet core has HttpContext.RequestAborted as a proxy cancellation token).

A stuck command only ends when Redis responds, or when AsyncTimeout expires.
AsyncTimeout falls back to SyncTimeout (5s) and is only checked once per 1s heartbeat.

While the connection is down, backlogged commands time out using SyncTimeout. As a result, cancelling a caller of RedisFacade didn't take effect until roughly 5–6s later, once for each retry attempt.

Changes

  • ExecuteWithRetry (both versions) awaits each Redis operation with WaitAsync using the combined token (caller's token plus the facade's lifetime token). Cancellation now takes effect immediately. The abandoned Redis task has its exceptions observed, so its later timeout doesn't surface as an unobserved task exception.
    • The exception is ListLeftPopAsync and the delete in TryGetAndDeleteFromHash. These still wait for Redis to respond, because if we abandoned them and Redis applied them anyway, the popped or deleted item would be lost. They can still take up to the Redis timeout to return after cancellation.
  • SubscribeToChannel also stops waiting on cancellation. If the abandoned SubscribeAsync completes later, it is unsubscribed, so no orphaned subscription is left behind. Cancellation is no longer caught and logged as "Failed to subscribe… retrying in 2 seconds". A Redis error that coincides with cancellation now propagates as itself rather than as an OperationCanceledException, matching ExecuteWithRetry.
  • Adds a net48-only polyfill of Task.WaitAsync(CancellationToken) in TaskExtensionMethods. net10.0 uses the built-in version.
  • IgnoreUnobservedExceptions now passes TaskScheduler.Default explicitly, instead of picking up TaskScheduler.Current.

Notes

  • Cancelling stops the wait, not the command. A write such as SetString or ListRightPushAsync can still be applied in Redis after the caller has given up. The retry loop already had a similar risk.

👨 Orion: This is not a new problem, in any network-based system there is always a race condition where you

  • Send the command to change something

  • The remote server receives and applies the change

  • The remote server is sending it's response back but you haven't got it yet

  • CANCEL
    This just extends the timing on the same behaviour

  • No timing-based test was added, because it would be flaky on slow CI agents.

🤖 Generated with Claude Code

StackExchange.Redis does not accept a CancellationToken, so a stuck command
only ends when the AsyncTimeout (default 5s, checked once per heartbeat)
expires. RedisFacade now uses Task.WaitAsync (with a net48 polyfill) so
callers stop waiting as soon as their token or the facade's lifetime token
is cancelled. The abandoned Redis task has its exceptions observed.

SubscribeToChannel also stops waiting on cancellation, unsubscribes if the
abandoned subscription completes later, and no longer logs a misleading
"retrying" message when cancelled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@borland
borland requested a review from a team as a code owner November 17, 2026 22:47
- Remove the "when (!task.IsCompleted)" filters on the cancellation catches.
  The operation can complete between WaitAsync cancelling and the filter
  running, which left its exception unobserved, or in SubscribeToChannel
  left a successful subscription that was never unsubscribed.
- ListLeftPopAsync and the delete in TryGetAndDeleteFromHash wait for
  Redis even when cancelled, so an item removed on the server is not lost.
- Drop ExecuteSynchronously on the abandoned-subscription cleanup, and pass
  TaskScheduler.Default explicitly in IgnoreUnobservedExceptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
/// StackExchange.Redis does not accept a CancellationToken; commands only end when redis responds
/// or the AsyncTimeout (default 5s, checked once per heartbeat) expires. This lets callers stop
/// waiting as soon as they are cancelled. The redis command itself is abandoned, not cancelled,
/// so it may still take effect on the server. Destructive reads (e.g. pops) should not use this,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Destructive reads (e.g. pops) should not use this,

All comms with redis are not atomic. You can only know if it completed and you can't know if it failed (within a single call). The queue has to work on this assumption, throughout. So I don't think this comment is of value its just more of the same which could be called out again. e.g. "Cancellation may not stop the operation from occurring on Redis".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per above, maybe we shouldn't attempt to treat mutations differently

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated accordingly

}

async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken)
async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken, bool stopWaitingOnCancellation = true)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should make stopWaitingOnCancellation required. If we use this for a destructive read later, it will silently give up while waiting.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude was keen on treating writes differently from reads, but per @LukeButters comment below and my "this is not a new problem" in the PR description, on second thought maybe we shouldn't do that at all, because you can always cancel just after the mutation has already taken place

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Resolved. Commit 6e6dc65 removed stopWaitingOnCancellation entirely. Every operation now stops waiting on cancellation, as agreed in this thread, so no carve-out can be forgotten later. The stale comments that still mention a carve-out (the WaitForOperation doc and the pop comment) are tracked in their own threads.

public async Task<string?> ListLeftPopAsync(string key, CancellationToken cancellationToken)
{
var listKey = ToListKey(key);
// Wait for the pop even if cancelled: if it succeeds on the server, abandoning it would lose the item.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude found that waiting for the pop doesn't save the item.

TryRemoveNextItemFromQueue passes the popped ID to TryGetAndRemoveRequest with the same cancelled token, which throws straight away, so the request is still lost.

This isn't new, but the comment suggests otherwise.

We could either finish the read and delete under their own token, or reword the comment?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the comment, it was wrong.

// if it succeeds on the server, abandoning it would lose the item.

Claude is losing sight of the fact that if cancelled, there's almost certainly going to be a TaskCancelledException thrown, and we'd lose it regardless

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude-Round2: This comment ("Wait for the pop even if cancelled...") is still on line 434 at 6e6dc65, which matches origin/orion/redis-cancelling. The WaitForOperation doc comment on lines 181-182 is also unchanged: it still says "Destructive reads (e.g. pops) should not use this", but ListLeftPopAsync now uses it. Maybe the edit is local and not pushed yet? The PR description has the same problem: it still says ListLeftPopAsync and the delete in TryGetAndDeleteFromHash keep waiting for Redis.

@LukeButters LukeButters left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is safe.

Failed comms with Redis is like Dr Pepper; we must remain agnostic about what happened.

Cancellation, I think, already means we don't know if it arrived or not.

And the queue must already work under that assumption.

So I think making all calls respect the CT is ok.

The downside here is that it probably adds CPU load to the queue by having all these extra tasks for every single call. I think this shouldn't matter, and instead we ought to make use of k8s scaling.

@borland

borland commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

having all these extra tasks for every single call

@LukeButters the CPU and memory overhead of task.Wait(CancellationToken) is basically zero. It's a small C# object with minimal state, we're talking 100 bytes or less, and they only exist while the network call is in place.

Put it this way, serilog logging costs about 1000x what this would add

return await operation();
return stopWaitingOnCancellation
? await WaitForOperation(operation(), combinedToken)
: await operation();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The operation will likely have a call to the lazy `Connection, which is a blocking operation. This will get hit the first time we use it, and could block this thread (it's one of the reasons for blocking Claude found for the original test flakiness).

We could replace the Lazy with a one-time async connect that callers can stop waiting for.

We can do that later if we want.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmm ok, may as well kill that one too, I'll get on it

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Resolved in dd359fe. The blocking Lazy<ConnectionMultiplexer> + ConnectionMultiplexer.Connect has been replaced by AsyncLazy + ConnectAsync. No operation path blocks a thread on the connect now. (IsConnected still calls GetResult(), but only after HasValue is true, when the task has already completed.) There's one leftover edge case: the caller that runs the factory doesn't stop waiting when cancelled. It's covered in the thread on the old line 437 and in a new comment on SubscribeToChannel.


async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken)
async Task<T> ExecuteWithRetry<T>(Func<Task<T>> operation, CancellationToken cancellationToken, bool stopWaitingOnCancellation = true)
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add some tests?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Partially addressed. a0e35fb adds AsyncLazyFixture, which covers the lazy-init semantics well: failure not cached, waiter cancellation, and factory-holder cancellation. There are still no RedisFacade tests for the behaviour this PR is about:

  • a cancelled caller returns promptly while Redis is unresponsive;
  • a cancelled first connect doesn't break later calls;
  • no command is sent after cancellation.

The existing PortForwarder setup in RedisFacadeWhenRedisGoesDownAwayTests could drive these without depending on timing: pause the forwarder, call GetString with a token you then cancel, resume the forwarder, and check that a call with a fresh token succeeds.

@sburmanoctopus sburmanoctopus left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice.

Some comments to consider.

@borland borland left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude-Round2: The per-call WaitAsync approach from round 1 looks fine to me now. The new async GetConnection in 6e6dc65 has a blocker, though, so I would not approve until it's fixed. If the first caller to connect is cancelled while the connection is being made, the facade caches a cancelled task forever and every later Redis call fails. I reproduced the exact ContinueWith/token pattern in a small console app.

Findings (inline):

  1. Blocker, RedisFacade.cs:60: a cancelled first connect is never cleared, so the facade stays broken until disposed. ExecuteWithRetry retries for 30s and then throws TaskCanceledException, and SubscribeToChannel retries every 2s forever.
  2. Major, RedisFacade.cs:79: the cleanup path for an abandoned connect never runs, because multiplexer is still null when WaitAsync throws. The multiplexer that ConnectAsync creates later is never disposed, and with AbortOnConnectFail = false it keeps reconnecting in the background.
  3. Major, RedisFacade.cs:437 (affects every lambda): callers that join an in-progress connect wait on the first caller's task, not their own token. If they're cancelled, the abandoned lambda still sends its command (pop, push, delete) once the connection arrives, after the caller has already returned.

One fix covers all three: start the connect without any caller's token, cache it, decide at read time whether a faulted/cancelled task should be replaced, and give each caller cachedTask.WaitAsync(callerToken). Snippet on the first comment.

Earlier threads:

  • Stop-waiting carve-out: resolved. stopWaitingOnCancellation was removed in 6e6dc65, and every operation now stops waiting on cancellation, as Luke and Orion agreed.
  • The stale pop comment (line 434) and the WaitForOperation doc (lines 181-182): the replies say these were removed or updated, but both are still there at 6e6dc65, which matches origin. Maybe not pushed yet? The PR description also still says ListLeftPopAsync and the delete in TryGetAndDeleteFromHash keep waiting for Redis. That's no longer true.
  • Blocking Lazy connect: addressed by 6e6dc65, apart from the issues above.
  • Tests: still none. Finding 1 can get a deterministic test with the existing PortForwarder support (see RedisFacadeWhenRedisGoesDownAwayTests): pause the forwarder, call GetString with a token cancelled after ~100ms, resume, then check that a call with a fresh token succeeds. It doesn't depend on timing, because the bug is a cached task state.

Not checked: I did not build the branch or run the Redis test suite. The poisoning behaviour was confirmed with a stand-alone repro of the same ContinueWith pattern, not against real Redis.

ConnectionMultiplexer? multiplexer = null;
try
{
multiplexer = await ConnectionMultiplexer.ConnectAsync(redisOptions).WaitAsync(ct);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude-Round2: Major: the abandoned multiplexer leaks, and the cleanup in the catch block can never run.

When WaitAsync(ct) throws, the assignment to multiplexer hasn't happened, so multiplexer is always null in the catch (OperationCanceledException) block. The dispose branch is dead code. My repro hit that catch with multiplexer == null.

Meanwhile the real ConnectAsync task keeps running and returns a ConnectionMultiplexer that nothing references or disposes. Because AbortOnConnectFail = false, that multiplexer keeps its sockets, heartbeat timer and reconnect loop alive for the life of the process. Its exception is also never observed if it faults.

Scenarios:

  • DisposeAsync cancels objectLifetimeCts while a connect is in progress. That cancels combinedToken, which is the token this connect was started with.
  • Any first caller is cancelled during the connect.

If this happens repeatedly, for example caller cancellations while Redis is unreachable, each attempt leaks another multiplexer.

Suggestion: let the shared connect run to completion, as in the snippet on line 60, so DisposeAsync always gets a multiplexer it can dispose. If you do want to abandon the connect, attach the cleanup to the ConnectAsync task itself, not to a local that's never assigned:

var connectTask = ConnectionMultiplexer.ConnectAsync(redisOptions);
try { multiplexer = await connectTask.WaitAsync(ct); }
catch (OperationCanceledException)
{
    _ = connectTask.ContinueWith(t => Try.IgnoringError(async () => await t.Result.DisposeAsync()),
        CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
    connectTask.IgnoreUnobservedExceptions();
    throw;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Partially fixed in dd359fe. When a caller is cancelled, the multiplexer no longer leaks. The factory now always awaits ConnectAsync to completion and caches the result, so DisposeAsync can dispose it.

Still open: the first scenario above, where DisposeAsync runs while the connect is in progress. connectionMultiplexer.HasValue is still false at that point (RedisFacade.cs:179), so DisposeAsync skips the dispose. When ConnectAsync finishes, the factory caches the new multiplexer, and nothing ever disposes it. With AbortOnConnectFail = false, it keeps reconnecting in the background for the life of the process. Also, SubscribeToChannel doesn't use objectLifeTimeCancellationToken, so calling it after dispose can still start a brand-new connect.

Possible fix: in the factory, after ConnectAsync returns, check objectLifeTimeCancellationToken.IsCancellationRequested. If it's set, dispose the multiplexer and throw ObjectDisposedException. That still leaves a very small window. To close it completely, DisposeAsync would need to wait for an in-progress factory call without starting a new one, for example through a method on AsyncLazy that waits on the semaphore but never runs the factory.

return await ExecuteWithRetry<string?>(async ct =>
{
var database = Connection.GetDatabase();
var connection = await GetConnection(ct);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude-Round2: Major: commands can be sent after the caller was cancelled and has returned. This applies to every ExecuteWithRetry lambda. It matters most here because a pop is destructive.

GetConnection(ct) only respects ct for the caller that created connectionSource. Any other caller that arrives while the connect is in progress gets the first caller's task, which doesn't watch its token. When that second caller is cancelled, WaitForOperation stops waiting and ExecuteWithRetry throws OperationCanceledException, which is correct. But the abandoned lambda is still waiting on the shared connect. When the connect finishes, it carries on and runs database.ListLeftPopAsync(listKey). The item is popped on the server and the result is thrown away.

The round-1 discussion accepted that a command in flight when cancellation happens may still be applied. This case is different. The command hasn't been sent when the caller gives up, and it can be sent up to ConnectTimeout (seconds) later. Pushes, deletes and TTL changes are affected the same way.

Scenario: on startup, several TryRemoveNextItemFromQueue loops for different tentacles call ListLeftPopAsync while the first connect is still running. One of those tentacles disconnects (its token is cancelled). When the connection comes up, its pending pop still runs, and a queued request is dequeued with nobody to receive it.

Suggestion: have GetConnection return sharedTask.WaitAsync(cancellationToken) (see line 60). Each lambda then throws at the await GetConnection(ct) line and never sends the command after cancellation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Partially fixed in dd359fe. Callers that join an in-progress connect now wait on semaphore.WaitAsync(ct) with their own token. When cancelled, they throw at await connectionMultiplexer.Value(ct) and never send their command.

Still open, but now for the other caller: the caller that runs the factory. AsyncLazy.Value awaits factoryFunc(ct) directly, and the factory only checks ct before ConnectAsync, which takes no token. If that caller is cancelled during the connect, WaitForOperation stops waiting and ExecuteWithRetry returns. The lambda is still waiting inside Value(), though. When ConnectAsync finishes (up to ConnectTimeout, 5s by default), Value() returns and the lambda goes on to send ListLeftPopAsync (or a push or delete). The popped item is then discarded.

Scenario: a dequeue loop is the first Redis user after startup, Redis is slow to connect, and that tentacle's token is cancelled. One queued request is popped and lost.

Fix: ExecuteWithRetry disposes its CancelOnDisposeCancellationToken on the way out, so ct is always cancelled by the time this happens. A check after getting the connection is therefore enough. The cleanest place is AsyncLazy.Value, after the factory has finished, so the value is still cached:

value = await factoryFunc(cancellationToken);
hasValue = true;
cancellationToken.ThrowIfCancellationRequested(); // value is cached; this caller just doesn't use it
return value;

(Alternatively, add ct.ThrowIfCancellationRequested(); after each await connectionMultiplexer.Value(ct) in the lambdas.)

{
// NitoEx.AsyncLazy doesn't allow us to pass a CancellationToken to the GetValue method; we build our own
// equivalent here.
lock (this)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use a Lock object. If we put that next to connectionSource, it makes it clear that accessing connectionSource should be done using that lock.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

net48 doesn't have System.Threading.Lock

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Now moot. dd359fe removed the lock (this) / connectionSource code. AsyncLazy guards initialisation with a private SemaphoreSlim.

connection = new Lazy<ConnectionMultiplexer>(() =>

connectionMultiplexer = new AsyncLazy<ConnectionMultiplexer>(async ct =>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Prior issue, now fixed. There was a blocker here: a cancelled first connect (ContinueWith with the caller's token) left a cancelled task cached in connectionSource, which broke the facade until it was disposed.

Fixed in dd359fe by AsyncLazy<ConnectionMultiplexer>. A failed or cancelled factory call is not cached: hasValue stays false and the semaphore is released in finally, so the next caller runs the factory again. AsyncLazyFixture.WhenTheFactoryThrows_TheFailureIsNotCached... and ...WhenTheCallerRunningTheFactoryCancels... cover this. Because the factory awaits ConnectAsync directly, callers also see the real exception instead of AggregateException, and the old continuation ordering race is gone.

{
// This can throw if we are unable to connect to redis.
var channel = await Connection.GetSubscriber()
var connection = await this.connectionMultiplexer.Value(cancellationToken);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Minor: SubscribeToChannel doesn't stop waiting when its caller runs the connect.

ExecuteWithRetry wraps the whole lambda in WaitForOperation. This Value(cancellationToken) call is awaited directly. If this call is the one running the AsyncLazy factory, the factory checks ct once and then awaits ConnectAsync, which takes no token. Cancelling the token therefore has no effect until the connect finishes, which can take up to ConnectTimeout (5s by default). That's the delay this PR is meant to remove. Callers that are waiting on the semaphore are fine, because semaphore.WaitAsync(ct) stops waiting when they're cancelled.

Scenario: a subscription is the first thing that touches Redis, Redis is slow or unreachable, and the subscriber is cancelled (for example, during shutdown or when a request is abandoned). The cancellation takes several seconds to take effect.

Suggestion: stop waiting here the same way the other paths do, and observe the abandoned task:

var connectionTask = connectionMultiplexer.Value(cancellationToken);
ConnectionMultiplexer connection;
try { connection = await connectionTask.WaitAsync(cancellationToken); }
catch (OperationCanceledException) { connectionTask.IgnoreUnobservedExceptions(); throw; }

(Or fix it once in AsyncLazy by keeping the in-progress factory task and having each caller WaitAsync(ct) on it, so that no caller's cancellation is tied to the factory.)

/// <summary>
/// A Lazy implementation with CancellationToken support.
/// </summary>
public class AsyncLazy<T>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Nit: AsyncLazy<T> is public, so it becomes part of the Halibut NuGet package's public API. Its sibling in this folder, TaskExtensions, is internal, and Halibut.Tests already has InternalsVisibleTo, so AsyncLazyFixture would still compile. If it's public, consumers can start depending on it, and later changes (for example, to fix the cancellation behaviour in the SubscribeToChannel comment) become breaking changes. Suggest internal class AsyncLazy<T>.

}
}

public bool IsConnected => connectionMultiplexer.HasValue && connectionMultiplexer.Value(CancellationToken.None).GetAwaiter().GetResult().IsConnected;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Nit: sync-over-async that is only safe because of how AsyncLazy is currently written. GetResult() never blocks today, because Value takes the if (hasValue) return value; fast path and returns a completed task. If Value changes later (for example, an await before the check), IsConnected could block a thread or deadlock. A synchronous accessor on AsyncLazy, such as bool TryGetValue(out T value), would make that guarantee explicit:

public bool IsConnected => connectionMultiplexer.TryGetValue(out var conn) && conn.IsConnected;

DisposeAsync (lines 179-183) could use the same accessor.

@borland

borland commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Claude: Round 3 review (dd359fe). Moving to AsyncLazy fixes the round-2 blocker: a failed or cancelled connect is no longer cached. It also removes the blocking Lazy connect. I would not approve yet, though. Two gaps can still send a Redis command, or leak a multiplexer, after cancellation or dispose. Both are small fixes.

Status of earlier comments:

  • Fixed: cancelled first connect breaking the facade (round-2 blocker). I deleted the original comment and posted a replacement on line 49. The round-2 review summary also describes this blocker as open, but review bodies can't be deleted. Treat that item as resolved.
  • Fixed: making stopWaitingOnCancellation required (the parameter was removed), the blocking Lazy connect, and Lock vs lock (this) (moot now). I replied in those threads rather than deleting them, because they aren't my comments.
  • Partially fixed: the abandoned multiplexer leak. A cancelled caller no longer leaks one, but dispose during an in-progress connect still leaks it.
  • Partially fixed: commands sent after cancellation. Callers that join an in-progress connect are fixed, but the caller running the factory still sends its command (for example, a pop) once ConnectAsync finishes. A one-line ThrowIfCancellationRequested() in AsyncLazy.Value, after the value is cached, fixes it. Details in the thread.
  • Partially fixed: tests. AsyncLazyFixture is good, but there are still no RedisFacade-level cancellation tests.
  • Not fixed: the stale comments. The WaitForOperation doc (lines 140-141, "Destructive reads (e.g. pops) should not use this") and the pop comment on line 393 ("Wait for the pop even if cancelled") are still in dd359fe, which matches origin. The replies say they were removed, so the edit may not have been pushed. The PR description also still says ListLeftPopAsync and the delete in TryGetAndDeleteFromHash keep waiting on Redis.

New findings (inline):

  1. Minor, RedisFacade.cs:207: if SubscribeToChannel's caller is the one running the connect, cancellation doesn't take effect until ConnectAsync finishes (up to ConnectTimeout).
  2. Nit, AsyncLazy.cs:10: the type is public, so it joins the NuGet package's public API. It could be internal.
  3. Nit, RedisFacade.cs:173: IsConnected uses GetResult(), which is only safe because of how AsyncLazy is currently written. A TryGetValue accessor would be clearer.

Cross-cutting: a note on the AsyncLazy design. The factory receives the first caller's token, and it holds the semaphore for the whole connect. Every remaining issue comes from the caller that runs the factory being handled differently from the callers that wait. In practice that's fine here, because the factory ignores ct after starting. Each caller that gets the connection still needs to check its own token before it sends anything.

Not checked: I didn't build or run the tests (AsyncLazyFixture or the Redis suites). The findings come from reading the code and tracing it, including the fact that ExecuteWithRetry's CancelOnDisposeCancellationToken cancels combinedToken on exit.

@sburmanoctopus
sburmanoctopus enabled auto-merge (squash) November 19, 2026 06:04
@sburmanoctopus
sburmanoctopus merged commit f7893f2 into main Nov 19, 2026
13 checks passed
@sburmanoctopus
sburmanoctopus deleted the orion/redis-cancelling branch November 19, 2026 06:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants