Skip to content

ObjectDisposedException from StopAllAsync when a second Pause/Stop fans out over disposed daemons (marten#5055) #574

Description

@jeremydmiller

Upstream report: JasperFx/marten#5055

At Kubernetes pod shutdown, users see repeated Error while trying to stop daemon agents logs:

System.ObjectDisposedException: The CancellationTokenSource has been disposed.
   at System.Threading.CancellationTokenSource.get_Token()
   at JasperFx.Events.Daemon.JasperFxAsyncDaemon`3.StopAllAsync()
   at JasperFx.Events.Daemon.ProjectionCoordinatorBase.PauseAsync()

Root cause

  • JasperFxAsyncDaemon.StopAllAsync() begins with await _semaphore.WaitAsync(_cancellation.Token). If Dispose() already ran (_cancellation?.Dispose()), reading .Token throws ObjectDisposedException.
  • ProjectionCoordinatorBase.StopAsync() calls PauseAsync() then daemon.SafeDispose() on every resolved daemon, but the subclass daemon caches (e.g. Marten's ProjectionCoordinator._daemons) are never cleared. Any second Pause/Stop — double AddAsyncDaemon hosted-service registration, user pause + host stop, Wolverine quiesce + host stop — fans StopAllAsync() out over disposed daemons, and PauseAsync() logs each one at Error level.
  • Latent second bug: after StopAsync, ResumeAsync and the daemon accessors hand back disposed daemons from the stale cache.

Fix

  1. JasperFxAsyncDaemon: _disposed flag, idempotent Dispose(), StopAllAsync() no-ops when disposed (including the Dispose-races-an-in-flight-stop window).
  2. ProjectionCoordinatorBase.PauseAsync: catch ObjectDisposedException and log at Debug — same philosophy as the ProjectionCoordinatorBase.executeAsync: terminate on cancellation / disposed data source instead of re-polling (shutdown drain race) #499/#499: terminate coordinator loop on disposed data source / wrapped cancellation #500 handling in executeAsync.
  3. ProjectionCoordinatorBase.StopAsync: new ClearResolvedDaemons() seam so subclass caches are purged after disposal; ResumeAsync then rebuilds fresh daemons.

Marten/Polecat need to implement the new seam when they bump (Marten side also wants AddAsyncDaemon idempotence — tracked separately on marten#5055).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions