Skip to content

fix: make the outbox relay's stop, start, and dispose safe to overlap and repeat#327

Merged
Vulthil merged 1 commit into
mainfrom
fix/outbox-relay-restart-race
Jul 19, 2026
Merged

fix: make the outbox relay's stop, start, and dispose safe to overlap and repeat#327
Vulthil merged 1 commit into
mainfrom
fix/outbox-relay-restart-race

Conversation

@Vulthil

@Vulthil Vulthil commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

Intermittent main CI failure (run 29661863438 on 131e966): both CosmosInboxIntegrationTests passed, then the class fixture threw in DisposeAsyncObjectDisposedException: The CancellationTokenSource has been disposed from inside the host's final StopAsync.

OutboxBackgroundService owns 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:

  • StartAsync disposed the previous stopping source before publishing the new one, so a concurrent stop could observe a disposed source. On a disposed source CancelAsync returns Task.FromException(ObjectDisposedException) — producing exactly the CI stack (thrown at the await, rethrown after the async finally, collected by Host.ForeachService, failing WebApplicationFactory.DisposeAsync as a class cleanup failure while every test passes).
  • StopAsync read 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, Dispose clears that same store, and a second Cancel/CancelAsync returns 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-caller Cancel() 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

  • New regression tests: 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).
  • Full solution Release build: 0 warnings, 0 errors.
  • CosmosInboxIntegrationTests against 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.

… 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.
@Vulthil Vulthil added the backport v1.0 Backport this PR to the v1.0 servicing branch label Jul 19, 2026
@claude

claude Bot commented Jul 19, 2026

Copy link
Copy Markdown

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

@Vulthil
Vulthil merged commit 4f11def into main Jul 19, 2026
7 checks passed
@Vulthil
Vulthil deleted the fix/outbox-relay-restart-race branch July 19, 2026 18:31
@Vulthil

Vulthil commented Jul 19, 2026

Copy link
Copy Markdown
Owner Author

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport v1.0 Backport this PR to the v1.0 servicing branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant