fix(centralui): no timers/subscriptions created after a mid-load dispose (UI-4, WP5 task 5.3)

A navigation while an awaited load was still running disposed the component
first; the continuation then created a timer / added a singleton handler that
nothing ever disposed, rooting the dead circuit for the life of the process.

- Health: refresh timer created under _timerLock only if not disposed.
- DataConnections: same for the health-poll timer; also stops before touching
  the disposed CTS when disposed during the first load.
- Deployments: subscribe to IDeploymentStatusNotifier BEFORE the first load
  (the handler only schedules a reload; the generation guard orders flights).
- PendingUpdatesHealthTiles: the Invalidated subscription and the poll timer are
  both created under a lifetime lock after a disposed check; Dispose unsubscribes
  only what was subscribed (covers a dispose during the auth-state await too).
- AlarmSummary: StartTimer/StopTimer/Dispose atomic under _timerLock; StartTimer
  refuses after dispose (Topology.StartLiveUpdatesTimer idiom).

Tests (each fails on the pre-fix component): HealthPageTests, DataConnectionsPageTests,
DeploymentsPerFlightScopeTests, PendingUpdatesHealthTilesTests (x2),
AlarmSummaryRenderTests - dispose mid-load, release the load, assert no timer and
no handler left.
This commit is contained in:
Joseph Doherty
2026-12-03 10:00:36 -05:00
parent 2969ee44e5
commit 7addd846a1
10 changed files with 312 additions and 33 deletions
@@ -53,6 +53,8 @@
private Timer? _timer;
private volatile bool _disposed;
private bool _subscribed;
private readonly object _lifetimeLock = new();
private bool _visible;
private IReadOnlySet<int>? _scopedSiteIds;
private PendingUpdatesSnapshot? _snapshot;
@@ -85,9 +87,23 @@
var (isSystemWide, sites) = SiteScopeService.Resolve(user);
_scopedSiteIds = isSystemWide ? null : sites;
PendingUpdates.Invalidated += OnInvalidated;
// UI-4: the component may have been disposed during an await above or below;
// Dispose() has then already run and must not be followed by a subscription to the
// process-singleton cache or a new timer (both would root this dead component).
// Subscribe/create and dispose are atomic under _lifetimeLock.
lock (_lifetimeLock)
{
if (_disposed) return;
PendingUpdates.Invalidated += OnInvalidated;
_subscribed = true;
}
await LoadAsync();
_timer = new Timer(_ => _ = ReloadAsync(), null, PollInterval, PollInterval);
lock (_lifetimeLock)
{
if (_disposed) return;
_timer = new Timer(_ => _ = ReloadAsync(), null, PollInterval, PollInterval);
}
}
private void OnInvalidated() => _ = ReloadAsync();
@@ -131,12 +147,17 @@
public void Dispose()
{
_disposed = true;
if (_visible)
lock (_lifetimeLock)
{
PendingUpdates.Invalidated -= OnInvalidated;
}
_disposed = true;
if (_subscribed)
{
PendingUpdates.Invalidated -= OnInvalidated;
_subscribed = false;
}
_timer?.Dispose();
_timer?.Dispose();
_timer = null;
}
}
}
@@ -343,8 +343,13 @@
protected override async Task OnInitializedAsync()
{
await LoadDataAsync();
// UI-4: subscribe BEFORE the first load. Subscribing after it meant a navigation
// during the load ran Dispose() first (unsubscribing a handler that was not yet
// added), and the continuation then added a dead component to the process-singleton
// notifier's invocation list for good. A push during the initial load is harmless:
// the handler only schedules a reload, and the generation guard orders the flights.
DeploymentStatusNotifier.StatusChanged += OnDeploymentStatusChanged;
await LoadDataAsync();
}
// ── Push coalescing (arch-review WP2.4) ───────────────────────────────────
@@ -233,6 +233,7 @@
// DebugView.razor. The CTS is used to cancel the in-flight health query when
// the component is disposed.
private volatile bool _disposed;
private readonly object _timerLock = new();
private bool _healthTickInFlight;
private readonly CancellationTokenSource _disposeCts = new();
@@ -241,17 +242,24 @@
protected override async Task OnInitializedAsync()
{
await LoadDataAsync();
if (_disposed) return;
await LoadConnectionHealthAsync(_disposeCts.Token);
// Poll the live health map on the same cadence as the Health dashboard.
// Best-effort: a failed query leaves the prior map in place rather than
// disturbing the tree.
// CentralUI-022 pattern: guard against dispose race — see _disposed field.
_healthTimer = new Timer(_ =>
// UI-4: a navigation during the loads above has already run Dispose(), which found
// no timer; create-vs-dispose is atomic under _timerLock so none is leaked.
lock (_timerLock)
{
if (_disposed) return;
_ = DispatchHealthTickAsync();
}, null, TimeSpan.FromSeconds(HealthRefreshSeconds), TimeSpan.FromSeconds(HealthRefreshSeconds));
_healthTimer = new Timer(_ =>
{
if (_disposed) return;
_ = DispatchHealthTickAsync();
}, null, TimeSpan.FromSeconds(HealthRefreshSeconds), TimeSpan.FromSeconds(HealthRefreshSeconds));
}
}
/// <summary>
@@ -479,9 +487,13 @@
// CentralUI-022 pattern: set the guard FIRST so any tick already in flight
// on the thread-pool no-ops, then cancel the in-flight health query, then
// stop the timer. Mirrors Deployments.razor and DebugView.razor.
_disposed = true;
lock (_timerLock)
{
_disposed = true;
_healthTimer?.Dispose();
_healthTimer = null;
}
_disposeCts.Cancel();
_disposeCts.Dispose();
_healthTimer?.Dispose();
}
}
@@ -327,6 +327,7 @@
// seed-then-stream) starts warming while the initial poll runs.
SubscribeLive(siteId);
await RefreshAsync();
if (_disposed) return;
StartTimer();
// If another circuit already warmed the cache for this site, the initial
// poll may be staler than what's live — apply the live snapshot on top.
@@ -393,24 +394,45 @@
}
}
// UI-4: StartTimer runs after OnSiteChangedAsync's awaited fan-out, which can take
// seconds against an unreachable site. If the operator navigated away meanwhile,
// Dispose() has already run; creating the timer then would leak it (rooting this dead
// component) for the life of the process. Create / stop / dispose are atomic under
// _timerLock and creation is refused once disposed.
private readonly object _timerLock = new();
private void StartTimer()
{
StopTimer();
_refreshTimer = new Timer(_ =>
Timer? old;
lock (_timerLock)
{
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
old = _refreshTimer;
_refreshTimer = null;
if (!_disposed)
{
if (_disposed) return;
await RefreshAsync();
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("AlarmSummary refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
_refreshTimer = new Timer(_ =>
{
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
{
if (_disposed) return;
await RefreshAsync();
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("AlarmSummary refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
}
}
old?.Dispose();
}
private void StopTimer()
{
_refreshTimer?.Dispose();
_refreshTimer = null;
Timer? old;
lock (_timerLock)
{
old = _refreshTimer;
_refreshTimer = null;
}
old?.Dispose();
}
// ── Live cache (plan #10, Task 5) ──────────────────────────────────────────
@@ -606,7 +628,10 @@
public void Dispose()
{
_disposed = true;
lock (_timerLock)
{
_disposed = true;
}
StopTimer();
DisposeLiveSubscription();
}
@@ -767,15 +767,23 @@
// and query the default site.
await LoadSiteHealthTrendsAsync();
_refreshTimer = new Timer(_ =>
// UI-4: the operator may have navigated away during the loads above. Dispose()
// has then already run and found no timer, so creating one now would leak it
// (and root this dead component) for the life of the process. Create-vs-dispose
// is atomic under _timerLock.
lock (_timerLock)
{
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
if (_disposed) return;
_refreshTimer = new Timer(_ =>
{
if (_disposed) return;
await RefreshAllAsync(forceRefresh: false);
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("Health refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
{
if (_disposed) return;
await RefreshAllAsync(forceRefresh: false);
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("Health refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
}
}
// Re-query when the operator picks a different site. Best-effort: the load
@@ -1041,10 +1049,15 @@
};
private volatile bool _disposed;
private readonly object _timerLock = new();
public void Dispose()
{
_disposed = true;
_refreshTimer?.Dispose();
lock (_timerLock)
{
_disposed = true;
_refreshTimer?.Dispose();
_refreshTimer = null;
}
}
}
@@ -358,4 +358,35 @@ public class DataConnectionsPageTests : BunitContext
Assert.Contains("PLC-A", cut.Markup);
Assert.Contains("PLC-B", cut.Markup);
}
/// <summary>
/// Code review 2026-12-02 UI-4: a navigation during the initial loads disposes the page
/// first; the continuation must not then start the 10 s health poll timer.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedDuringInitialLoad_CreatesNoHealthTimer()
{
SeedRepos();
// Hold the SECOND initial load (the health map) open: the timer is created right
// after it, so a dispose while it is in flight is the leak window.
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var gate = new TaskCompletionSource<IReadOnlyDictionary<int, ConnectionHealth>>(
TaskCreationOptions.RunContinuationsAsynchronously);
_healthQuery.GetConnectionHealthAsync(Arg.Any<CancellationToken>())
.Returns(_ => { entered.TrySetResult(); return gate.Task; });
var cut = Render<DataConnectionsPage>();
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10));
var page = cut.Instance;
await cut.InvokeAsync(page.Dispose);
gate.SetResult(new Dictionary<int, ConnectionHealth>());
await cut.InvokeAsync(() => { });
await cut.InvokeAsync(() => { });
Assert.Null(typeof(DataConnectionsPage)
.GetField("_healthTimer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(page));
}
}
@@ -105,4 +105,52 @@ public class DeploymentsPerFlightScopeTests : BunitContext
(string?)typeof(DeploymentsPage)
.GetField("_errorMessage", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(page);
private sealed class CountingNotifier : IDeploymentStatusNotifier
{
private Action<DeploymentStatusChange>? _handlers;
/// <summary>Handlers currently on the invocation list (removing an absent one is a no-op, as for a real event).</summary>
public int Subscribers => _handlers?.GetInvocationList().Length ?? 0;
public event Action<DeploymentStatusChange>? StatusChanged
{
add => _handlers += value;
remove => _handlers -= value;
}
public void NotifyStatusChanged(DeploymentStatusChange change) { }
}
/// <summary>
/// Code review 2026-12-02 UI-4: disposed while the first load is in flight, the page must
/// leave no handler on the process-singleton status notifier (it used to subscribe after
/// the load, i.e. after Dispose had already unsubscribed nothing).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedDuringFirstLoad_LeavesNoNotifierSubscription()
{
var factory = new SingleOperationRepositoryFactory();
Services.AddScoped(_ => factory.Create());
var notifier = new CountingNotifier();
Services.AddSingleton<IDeploymentStatusNotifier>(notifier);
var auth = new StubAuthStateProvider(new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie"))));
Services.AddSingleton<AuthenticationStateProvider>(auth);
Services.AddScoped(_ => new SiteScopeService(auth));
var cut = Render<DeploymentsPage>(); // first load held open
var page = cut.Instance;
await cut.InvokeAsync(page.Dispose);
factory.ReleaseFirstCall();
// The first load has finished once _loading drops; OnInitializedAsync's tail runs in
// the same dispatcher step.
cut.WaitForAssertion(() => Assert.False((bool)typeof(DeploymentsPage)
.GetField("_loading", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(page)!));
await cut.InvokeAsync(() => { });
Assert.Equal(0, notifier.Subscribers);
}
}
@@ -439,4 +439,28 @@ public class AlarmSummaryRenderTests : BunitContext
}
}
}
/// <summary>
/// Code review 2026-12-02 UI-4: picking a site runs a fan-out that can take seconds; if the
/// page is disposed meanwhile, the continuation must not start the 15 s poll timer.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedDuringSiteFanOut_CreatesNoPollTimer()
{
var gate = new TaskCompletionSource<AlarmSummaryResult>(TaskCreationOptions.RunContinuationsAsynchronously);
_summary.GetSiteAlarmsAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(gate.Task);
var cut = Render<AlarmSummaryPage>();
var page = cut.Instance;
var change = cut.Find("[data-test='alarm-summary-site']").ChangeAsync(new() { Value = "1" });
await cut.InvokeAsync(page.Dispose);
gate.SetResult(new AlarmSummaryResult(new List<AlarmSummaryRow>(), Array.Empty<string>()));
await change.WaitAsync(TimeSpan.FromSeconds(10));
Assert.Null(typeof(AlarmSummaryPage)
.GetField("_refreshTimer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(page));
}
}
@@ -106,4 +106,69 @@ public class PendingUpdatesHealthTilesTests : BunitContext
cut.WaitForAssertion(() => Assert.Equal("0", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim()));
}
/// <summary>Counts subscriptions so a test can see a leaked handler on the singleton cache.</summary>
private sealed class CountingCache : IPendingUpdatesCache
{
public TaskCompletionSource<PendingUpdatesSnapshot> Gate { get; } =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private Action? _handlers;
/// <summary>Handlers currently on the invocation list (removing an absent one is a no-op, as for a real event).</summary>
public int Subscribers => _handlers?.GetInvocationList().Length ?? 0;
public Task<PendingUpdatesSnapshot> GetAsync(bool forceRefresh = false, CancellationToken cancellationToken = default)
=> Gate.Task;
public event Action? Invalidated
{
add => _handlers += value;
remove => _handlers -= value;
}
}
/// <summary>
/// Code review 2026-12-02 UI-4: disposed while the first snapshot load is in flight, the
/// tiles must not start their poll timer, and must leave no handler on the singleton cache.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedDuringFirstLoad_CreatesNoTimer_AndLeavesNoSubscription()
{
var cache = new CountingCache();
var cut = RenderFor(cache, Role(Roles.Deployer));
var tiles = cut.Instance;
await cut.InvokeAsync(tiles.Dispose);
cache.Gate.SetResult(new PendingUpdatesSnapshot(DateTimeOffset.UtcNow, Array.Empty<SitePendingUpdates>()));
await cut.InvokeAsync(() => { });
await cut.InvokeAsync(() => { });
Assert.Null(typeof(PendingUpdatesHealthTiles)
.GetField("_timer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(tiles));
Assert.Equal(0, cache.Subscribers);
}
/// <summary>Disposed while the cascaded auth state is still pending, the tiles never subscribe.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedBeforeAuthResolves_NeverSubscribes()
{
var cache = new CountingCache();
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
Services.AddScoped<SiteScopeService>();
Services.AddSingleton<IPendingUpdatesCache>(cache);
var cut = Render<PendingUpdatesHealthTiles>(ps => ps.AddCascadingValue(auth.Task));
var tiles = cut.Instance;
await cut.InvokeAsync(tiles.Dispose);
auth.SetResult(new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new[] { Role(Roles.Deployer) }, "TestAuth"))));
await cut.InvokeAsync(() => { });
await cut.InvokeAsync(() => { });
Assert.Equal(0, cache.Subscribers);
}
}
@@ -894,4 +894,39 @@ public class HealthPageTests : BunitContext
Nodes: Array.Empty<SiteCallNodeKpiSnapshot>())));
}
}
/// <summary>
/// Code review 2026-12-02 UI-4: navigating away while the initial loads are still running
/// disposes the page first; the load's continuation must then not create the 10 s refresh
/// timer (it would never be disposed and would root the dead circuit).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedDuringInitialLoad_CreatesNoRefreshTimer()
{
SeedSites("site-a");
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var gate = new TaskCompletionSource<IReadOnlyList<KpiSeriesPoint>>(TaskCreationOptions.RunContinuationsAsynchronously);
var kpiHistory = Substitute.For<IKpiHistoryQueryService>();
kpiHistory.GetSeriesAsync(
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(),
Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<int?>(), Arg.Any<CancellationToken>())
.Returns(_ => { entered.TrySetResult(); return gate.Task; });
Services.AddSingleton(kpiHistory);
var host = RenderHealthPage();
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); // the last load phase is in flight
var page = host.Instance;
await host.InvokeAsync(page.Dispose);
gate.SetResult(SampleSeries());
host.WaitForAssertion(() => Assert.False((bool)typeof(HealthPage)
.GetField("_trendsLoading", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(page)!));
await host.InvokeAsync(() => { });
Assert.Null(typeof(HealthPage)
.GetField("_refreshTimer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(page));
}
}