Skip to content

Removed the synchronous Lock method from AsyncLock class - #256

Merged
theRainbird merged 6 commits into
theRainbird:masterfrom
yallie:auth-refactor
Nov 27, 2026
Merged

theRainbird merged 6 commits into
theRainbird:masterfrom
yallie:auth-refactor

Conversation

@yallie

@yallie yallie commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

I'm not sure but it just doesn't feel right to have this method on async locking primitive.
Also, SemaphoreSlim is non-reentrant, so normal lock statement is probably safer to use.
Anyway, both places where Lock is used can be refactored to become async methods.

@danio3xl3

Copy link
Copy Markdown

Thanks, getting rid of the sync-over-async Lock() is a good move. I have one concern and a few small notes.

  1. DisconnectCoreAsync no longer waits for the disconnect handling (RemotingClient.cs, OnDisconnected(); near the end of DisconnectCoreAsync)

OnDisconnected is now async void. Whenever _activeCallsLock is briefly held (e.g. by ProcessRpcResultMessage or InvokeRemoteMethod), it returns before the swap. So DisconnectAsync can complete and raise AfterDisconnect while pending calls are not failed yet, _activeCalls is still set and _goodbyeCompletedEvent isn't set.

The window is small, but I see two ways it can bite:

  • DisposeAsync disposes _activeCallsLock at the end. If OnDisconnectedCore is still queued on the semaphore at that point, the holder's Release() throws ObjectDisposedException and the waiter never runs. Pending calls would then only end via InvocationTimeout.
  • Immediate ConnectAsync() after DisconnectAsync(): ConnectAsync resets _goodbyeCompletedEvent before it takes _activeCallsLock. The delayed OnDisconnectedCore can set the event again afterwards, and ProcessRpcResultMessage would then drop every result on the new connection.

Since DisconnectCoreAsync is already async, I'd suggest awaiting the core method there. The async void wrapper would then only be used for the Disconnected event and the keep-alive timer:

// DisconnectCoreAsync
await OnDisconnectedCore()
    .ConfigureAwait(false);
  1. Swallowed exceptions in OnDisconnected

The empty catch hides any failure in the disconnect path. Previously, on the DisconnectCoreAsync path, such errors reached the caller, or OnError via HandleConnectionLost. Maybe route them to OnError(ex) instead of the TODO?

catch (Exception ex)
{
    OnError(ex);
}
  1. Nit: comment in SimulateDisconnectRace

"not sure if we should even lock here": I think the lock is correct. The helper simulates exactly the _activeCalls swap that OnDisconnectedCore does under _activeCallsLock, so I'd just drop the comment.

  1. Unrelated, already there before this PR

In InvokeRemoteMethod, the cleanup after a failed send calls _activeCalls.Remove(...) without a null check. If a disconnect nulled the dictionary in the meantime, the caller gets a NullReferenceException instead of the actual transport error. _activeCalls?.Remove(...) would fix it. It could go into this PR or a separate one.

@yallie

yallie commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Since DisconnectCoreAsync is already async, I'd suggest awaiting the core method there. The async void wrapper would then only be used for the Disconnected event and the keep-alive timer:

Good catch! 👍

Maybe route them to OnError(ex) instead of the TODO?

Agreed :)

The helper simulates exactly the _activeCalls swap that OnDisconnectedCore does under _activeCallsLock, so I'd just drop the comment.

I still have my doubts... The point is to simulate error condition, so that the worse the better :)
But you're probably right as _activeCalls cannot be reset to null without this lock being held.

the cleanup after a failed send calls _activeCalls.Remove(...) without a null check

Thanks! That's a potential bug for sure.

@danio3xl3

Copy link
Copy Markdown

Thanks for the quick update, looks good to me! 👍

One small thing about the new catch in OnDisconnected: OnError(ex) invokes the user's ErrorHandler directly. If that handler throws, the exception escapes the async void method and takes down the process. Maybe guard it there:

catch (Exception ex)
{
    try
    {
        OnError(ex);
    }
    catch
    {
        // never let a faulty error handler escape async void
    }
}

Alternatively, OnError itself could be made safe, since it's also called from other fire-and-forget paths such as HandleConnectionLost and the auto-reconnect loop. Not a blocker, though.

@danio3xl3

Copy link
Copy Markdown

Thanks, all points are addressed. LGTM! 👍

@theRainbird
theRainbird marked this pull request as draft November 24, 2026 23:18
@theRainbird
theRainbird marked this pull request as ready for review November 26, 2026 11:41
@theRainbird

Copy link
Copy Markdown
Owner

Main concern: late async disconnect handling can corrupt a newly established connection

The PR correctly removes the synchronous AsyncLock.Lock() method and makes the known call sites async. However, OnDisconnected is still an async void handler that mutates shared client state.

Although DisconnectCoreAsync now awaits OnDisconnectedCore(), a disconnect event handler may already have been started and may still be running when the client begins reconnecting. In that case, the delayed OnDisconnectedCore() can still execute after ConnectAsync() has reset _goodbyeCompletedEvent for the new connection.

This is dangerous because ProcessRpcResultMessage contains:

if (_goodbyeCompletedEvent.IsSet)
return;

If a late disconnect handler from the old connection sets _goodbyeCompletedEvent, RPC results for the new connection may be silently dropped. The new connection can then appear broken, with calls hanging until timeout or failing unexpectedly.

A possible sequence is:

  1. The client disconnects.
  2. The transport raises Disconnected.
  3. OnDisconnected starts asynchronously.
  4. DisconnectAsync() returns.
  5. The application immediately calls ConnectAsync().
  6. The new connection is established.
  7. The delayed old disconnect handler finally runs and sets _goodbyeCompletedEvent.
  8. The new connection becomes logically unusable.

The fix should make disconnect handling connection-scoped. For example, introduce a connection generation/epoch and ensure that disconnect handlers carry the generation they belong to. Late handlers from an old generation should be ignored. DisconnectCoreAsync should also await the completion of the disconnect task for the current connection, not merely invoke its own core method.

In short:

Awaiting OnDisconnectedCore() inside DisconnectCoreAsync() is an improvement, but it does not eliminate the race caused by the still-existing async void disconnect handler. Before merging, the disconnect path should be made idempotent per connection generation so that a delayed disconnect from an old connection cannot affect a newly established one.

@danio3xl3

Copy link
Copy Markdown

Uhhhh... I agree with @theRainbird here. My earlier point only covered the direct call in DisconnectCoreAsync, not the event path.

The transports raise Disconnected on their own threads (read loop, WatsonTcp event), where the async void handler starts and can't be awaited. On a manual disconnect, OnDisconnectedCore therefore runs twice: once directly from DisconnectCoreAsync and once via the event. The event one can still be queued on _activeCallsLock when ConnectAsync() runs.

I think the late handler can do more damage than just setting _goodbyeCompletedEvent. When it finally gets the lock, _activeCalls is already the new connection's dictionary. It then:

  • sets it to null, so every new call fails with "Server disconnected",
  • completes the new connection's pending calls with an error,
  • stops the new keep-alive timer (StopKeepSessionAliveTimer runs before the lock).

I haven't reproduced this, it's from reading the code. The race itself isn't new: the old sync handler could also block on the lock from a foreign thread. But this PR doesn't fix it either.

A connection generation seems to be enough, without restructuring the disconnect path:

  1. ConnectAsync increments _connectionGeneration and resets _goodbyeCompletedEvent, both inside the _activeCallsLock block (currently the reset happens before the lock).
  2. OnDisconnected reads the generation synchronously, before its first await. DisconnectCoreAsync reads it at its start. The value is passed to OnDisconnectedCore(generation).
  3. Under the lock, the core checks that the generation is still current and that this generation wasn't handled yet (e.g. Interlocked.Exchange on a per-generation flag). Otherwise it returns. Check and mutation share the lock with ConnectAsync, so a reconnect can't slip in between. This also makes the double invocation harmless.
  4. StopKeepSessionAliveTimer(), _goodbyeCompletedEvent.Set() and EnsureAutoReconnectLoop() move behind that check.

A handler that is raised only after the reconnect would read the new generation and can't be recognized this way. That has to be handled by the transports, and they already do it via IsCurrentReadLoop.

I'm fine with fixing it in this PR if it stays small, or tracking it as a separate issue. @yallie, what do you prefer?

@yallie

yallie commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, I agree with both of you. Thanks for your reviews! :)
Let me think it over.

@yallie

yallie commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

introduce a connection generation/epoch and ensure that disconnect handlers carry the generation they belong to

  1. Implemented a failing unit test reproducing the disconnection race.
  2. Added connection generation to RemotingClient, as suggested.
  3. With the updated RemotingClient, the unit test passes:
using var client = CreateClient(networkPort, AuthenticationRequiredForNegativeTests);
await client.ConnectAsync().ConfigureAwait(false);
var proxy = client.CreateProxy<ITestService>();

// 1. Capture the generation of the initial connection
var oldGeneration = client.ConnectionGenerationForTest;

// 2. Reconnect: this bumps the generation and creates a new _activeCalls dictionary
await client.DisconnectAsync().ConfigureAwait(false);
await client.ConnectAsync().ConfigureAwait(false);

// 3. Simulate a late handler from the OLD connection that just woke up.
// Without the generation check, this would null out the new _activeCalls.
await client.InvokeOnDisconnectedCoreAsync(oldGeneration).ConfigureAwait(false);

// 4. The new connection must be completely unaffected,
// keep-alive still running, RPC works.
Assert.True(client.IsConnected);
Assert.Equal("test", await proxy.EchoAsync("test").ConfigureAwait(false));

Also, rebased this PR onto master.

@theRainbird
theRainbird merged commit 4180fbd into theRainbird:master Nov 27, 2026
4 checks passed
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