fix: make the outbox relay's stop, start, and dispose safe to overlap and repeat#327
Merged
Conversation
… and repeat A stop overlapping a restart, or running after disposal, could await CancelAsync on a disposed stopping source and fail the host's final StopAsync with an ObjectDisposedException at test-factory teardown, or pair one loop generation's cancellation with another generation's wait and stall. A lock now guards every transition, the stopping source and execute task swap together as a matched generation, restarts retire the previous generation by canceling it, and disposal makes later stop and start calls benign no-ops. Retired sources are canceled but never disposed, because disposing a source whose queued cancellation notification has not yet run drops the pending callbacks and strands the loop.
Code reviewNo issues found. Checked for bugs and CLAUDE.md compliance. |
Owner
Author
|
Successfully created backport PR for |
Vulthil
added a commit
that referenced
this pull request
Jul 19, 2026
… and repeat (#327) (#328) A stop overlapping a restart, or running after disposal, could await CancelAsync on a disposed stopping source and fail the host's final StopAsync with an ObjectDisposedException at test-factory teardown, or pair one loop generation's cancellation with another generation's wait and stall. A lock now guards every transition, the stopping source and execute task swap together as a matched generation, restarts retire the previous generation by canceling it, and disposal makes later stop and start calls benign no-ops. Retired sources are canceled but never disposed, because disposing a source whose queued cancellation notification has not yet run drops the pending callbacks and strands the loop. (cherry picked from commit 4f11def)
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.
Summary
Intermittent main CI failure (run 29661863438 on 131e966): both
CosmosInboxIntegrationTestspassed, then the class fixture threw inDisposeAsync—ObjectDisposedException: The CancellationTokenSource has been disposedfrom inside the host's finalStopAsync.OutboxBackgroundServiceowns its stopping source and execute task, but its lifecycle methods assumed strictly sequential calls. The test harness stops and restarts the relay after every test and the host stops it once more at teardown, and nothing serializes those flows. Under overlap or reordering:StartAsyncdisposed the previous stopping source before publishing the new one, so a concurrent stop could observe a disposed source. On a disposed sourceCancelAsyncreturnsTask.FromException(ObjectDisposedException)— producing exactly the CI stack (thrown at the await, rethrown after the asyncfinally, collected byHost.ForeachService, failingWebApplicationFactory.DisposeAsyncas a class cleanup failure while every test passes).StopAsyncread the source and the execute task non-atomically, so it could cancel one loop generation while awaiting another — a silent stall bounded only by the caller's token.Dispose()left the disposed source in place with the execute task still set, making any later stop fail deterministically.The fix serializes every transition behind a lock, swaps the stopping source and execute task together (a stop always cancels the generation it awaits), retires the previous generation on restart by canceling it (also releasing a loop left behind by a timed-out stop, which previously kept running unstoppably), and marks disposal so a later stop merely awaits the already-canceled loop and a later start is a no-op.
Retired sources are canceled but never disposed: disposing a source whose cancellation notification is still queued silently drops the pending callbacks (callback execution claims the registration store with an atomic exchange,
Disposeclears that same store, and a secondCancel/CancelAsyncreturns without waiting for in-flight callbacks), which strands the retired loop in a wait that never ends — stress testing caught an earlier revision of this fix doing exactly that. They hold no timer or kernel handle, so garbage collection reclaims them;Dispose()only disposes a source whose cancellation it requested itself, after the synchronous first-callerCancel()has run the callbacks to completion.Sequential stop→start cycles — the only choreography the harness intends — were verified safe as-is with a 3000-cycle stress run including timed-out stops; the failure required a teardown-time overlap, which is why it was rare.
Verification
StoppingAfterDisposeCompletesGracefully(reproduces the exact CI exception against the previous code),DisposingTwiceIsSafe(also failed before),StoppingTwiceCompletesGracefully,StoppingAndRestartingConcurrentlyConvergesCleanly(300 barrier-synchronized overlapped stop/start iterations, all waits 10-second-bounded so a regression fails fast instead of hanging; failed before via timeout).Vulthil.SharedKernel.Outbox.Tests: 22/22 on net9.0 and net10.0 (Release).CosmosInboxIntegrationTestsagainst the real Cosmos emulator: 6 consecutive runs, zero cleanup failures.Backport to v1.0: yes — v1.0 received the relay-ownership change (#312, backport of #310) and has the same lifecycle code.