Repository navigation
fix: prevent ObjectDisposedException when StopAsync races disposal - #172
Merged
Merged
Conversation
StopAsync checked the disposed flag without holding the lock and then waited on stateLock, while DisposeAsync disposed stateLock without waiting for StopAsync. At host shutdown this could throw ObjectDisposedException from SemaphoreSlim. - Count StopAsync, StartAsync, TryAcquireLeadershipAsync, ReleaseLeadershipAsync and timer callbacks as in-progress operations. Each operation increments the counter before it checks the disposed flag, so DisposeAsync either waits for it or the operation backs out. - Set the disposed flag atomically so only the first dispose call runs. - StopAsync returns quietly after disposal and treats an ObjectDisposedException after the dispose timeout as stopped. - Take timers out of their fields atomically before disposing them, and dispose any timer started by an operation that disposal waited for. - Add StopDisposeRaceTests, run in a non-parallel collection. Fixes #171
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #172 +/- ##
==========================================
+ Coverage 72.53% 73.16% +0.62%
==========================================
Files 65 65
Lines 4974 4982 +8
Branches 607 603 -4
==========================================
+ Hits 3608 3645 +37
+ Misses 1155 1133 -22
+ Partials 211 204 -7
... and 1 file with indirect coverage changes Continue to review full report in Codecov by Harness.
🚀 New features to boost your workflow:
|
Codecov reported 81% patch coverage on the fix for #171. The largest gap was the path where DisposeAsync stops waiting after its timeout, which had no test because the timeout was a fixed 10 seconds. - Add an internal DisposeWaitTimeout (default 10 s) so tests can use a short timeout. Behaviour is unchanged. - Simplify EnterOperationOrThrow to a single ThrowIf call, which removes an unreachable line. - Test that StopAsync does not throw when DisposeAsync times out and disposes the lock while StopAsync still holds it. - Test StopAsync when the provider fails to release leadership, ReleaseLeadershipAsync when not leader, and loss of leadership after a failed heartbeat.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #171
Problem
LeaderElectionService.StopAsynccould throwObjectDisposedExceptionfromSemaphoreSlimwhenDispose/DisposeAsyncran at the same time, for example when aWebApplicationFactoryis disposed at the end of an integration test.StopAsyncchecked the disposed flag without holding the lock, andDisposeAsyncdisposedstateLockwithout waiting forStopAsync.StartAsync,TryAcquireLeadershipAsyncandReleaseLeadershipAsynchad the same gap.Changes
activeCallbacks, nowactiveOperations) also coversStopAsync,StartAsync,TryAcquireLeadershipAsyncandReleaseLeadershipAsync, not only timer callbacks.TryEnterOperationincrements the counter before it checks the disposed flag.DisposeAsyncsets the flag withInterlocked.Exchange. Both are full fences, so either the operation sees the flag and backs out, or disposal sees the counter and waits. The atomic flag also means that only the first of several concurrent dispose calls runs the disposal body.StopAsyncnever throws on shutdown. After disposal it returns without doing anything. If disposal gives up after its 10-second timeout and disposes the lock or the cancellation token source,StopAsynccatches theObjectDisposedExceptionand treats the service as stopped.ObjectDisposedException, but it now namesLeaderElectionService, not the internalSemaphoreSlim.StopAsyncandDisposeAsynccould both dispose the same timer field and set it to null, which could cause aNullReferenceException.DisposeTimerAsyncnow takes the timer out of its field withInterlocked.Exchangebefore disposing it.ReleaseLeadershipAsyncrestarts the election timer), and nothing disposed it. Disposal now clears both timers again after the wait.Tests
New
StopDisposeRaceTests:StopAsyncandDisposeAsyncrun at the same time, 50 iterations, alternating which starts first. The same test with syncDispose().DisposeAsyncwaits for aStopAsyncthat is releasing leadership.StopAsyncafter disposal does not throw.ObjectDisposedExceptionnaming the service.Against the original code, all four race tests fail. The two
StopAsync/dispose tests fail with the stack trace from the issue, fromSemaphoreSlim.ReleaseinStopAsync. With the fix, all 613 unit tests passed in 16 of 16 runs across net8.0 and net10.0.Notes for reviewers
MultiInstanceLeaderElectionTests.LeaderFailover_ShouldElectNewLeaderfail in about 1 of 3 full runs. That test passed every time without the new tests, on both the original and the fixed code, so the failures did not come from the fix.