From 1b6cc783b1c5a39fda77a3bd90935667ddbc118a Mon Sep 17 00:00:00 2001 From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:50:28 -0500 Subject: [PATCH] Log each tab's first load and draw Performance Trends charts as their reads land (#9232) --- Lite.Tests/TabFirstLoadTests.cs | 159 +++++++++++++++++++++++++++++ Lite/Controls/ServerTab.Refresh.cs | 26 ++++- Lite/Helpers/TabFirstLoad.cs | 78 ++++++++++++++ 3 files changed, 258 insertions(+), 5 deletions(-) create mode 100644 Lite.Tests/TabFirstLoadTests.cs create mode 100644 Lite/Helpers/TabFirstLoad.cs diff --git a/Lite.Tests/TabFirstLoadTests.cs b/Lite.Tests/TabFirstLoadTests.cs new file mode 100644 index 0000000000..556d87c661 --- /dev/null +++ b/Lite.Tests/TabFirstLoadTests.cs @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2026 Erik Darling, Darling Data LLC + * + * This file is part of the SQL Server Performance Monitor Lite. + * + * Licensed under the MIT License. See LICENSE file in the project root for full license information. + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using PerformanceMonitorLite.Helpers; +using Xunit; + +namespace PerformanceMonitorLite.Tests; + +/// +/// #9232: a tab's first load writes ONE log line with its elapsed milliseconds, and a tab draws each panel as its own reads +/// land. WPF cannot run in the suite, so both decisions live in small helpers the server tab calls. +/// +public sealed class TabFirstLoadTests +{ + /// A clock the test moves by hand, one tick per millisecond. + private sealed class HandClock : TimeProvider + { + private long _ticks; + public override long TimestampFrequency => 1000; + public override long GetTimestamp() => _ticks; + public void Advance(int ms) => _ticks += ms; + } + + [Fact] + public async Task TheFirstLoadOfATab_WritesOneLine_WithTheElapsedMilliseconds() + { + var lines = new List(); + var clock = new HandClock(); + var log = new TabFirstLoad(lines.Add, clock); + + var result = await log.RunAsync("tab 2/0", "Queries > Performance Trends", () => + { + clock.Advance(1234); + return Task.FromResult(7); + }); + + Assert.Equal(7, result); + var line = Assert.Single(lines); + Assert.Equal("First load of Queries > Performance Trends: 1234 ms", line); + } + + [Fact] + public async Task ALaterLoadOfTheSameTab_WritesNothing_ButEachNewKeyWritesItsOwnLine() + { + var lines = new List(); + var clock = new HandClock(); + var log = new TabFirstLoad(lines.Add, clock); + + for (var tick = 0; tick < 5; tick++) + { + await log.RunAsync("tab 2/0", "Trends", () => { clock.Advance(10); return Task.FromResult(0); }); + } + + Assert.Single(lines); + + await log.RunAsync("tab 2/1", "Active Queries", () => { clock.Advance(20); return Task.FromResult(0); }); + await log.RunAsync("tab 2/1", "Active Queries", () => { clock.Advance(20); return Task.FromResult(0); }); + + Assert.Equal(2, lines.Count); + Assert.Equal("First load of Active Queries: 20 ms", lines[1]); + } + + [Fact] + public async Task ALoadANewerRequestAbandoned_IsNotAFirstOpen_SoItsReplayGetsTheLine() + { + var lines = new List(); + var clock = new HandClock(); + var log = new TabFirstLoad(lines.Add, clock); + + await log.RunAsync("tab 4", "CPU", () => { clock.Advance(5); return Task.FromResult(0); }, abandoned: () => true); + Assert.Empty(lines); + + await log.RunAsync("tab 4", "CPU", () => { clock.Advance(9); return Task.FromResult(0); }, abandoned: () => false); + Assert.Equal("First load of CPU: 9 ms", Assert.Single(lines)); + } + + [Fact] + public async Task ALoadThatThrows_WritesNoLine_AndTheNextLoadIsStillTheFirst() + { + var lines = new List(); + var log = new TabFirstLoad(lines.Add, new HandClock()); + + await Assert.ThrowsAsync(() => + log.RunAsync("tab 6", "File I/O", () => throw new InvalidOperationException("read failed"))); + Assert.Empty(lines); + + await log.RunAsync("tab 6", "File I/O", () => Task.FromResult(0)); + Assert.Single(lines); + } + + [Fact] + public async Task ANullKey_IsNotTracked() + { + var lines = new List(); + var log = new TabFirstLoad(lines.Add, new HandClock()); + + await log.RunAsync(null, "anything", () => Task.FromResult(0)); + + Assert.Empty(lines); + } + + [Fact] + public async Task APanel_IsDrawnWhenItsOwnReadLands_WithoutWaitingForASlowerPanel() + { + var fast = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var slow = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var drawn = new List(); + + var all = Task.WhenAll( + LandedPanels.DrawAsync(fast.Task, value => drawn.Add($"fast={value}")), + LandedPanels.DrawAsync(slow.Task, value => drawn.Add($"slow={value}"))); + + fast.SetResult(1); + await Eventually(() => drawn.Count == 1); + Assert.Equal(["fast=1"], drawn); + Assert.False(all.IsCompleted, "the slow panel's read is still running"); + + slow.SetResult(2); + await all.WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + Assert.Equal(["fast=1", "slow=2"], drawn); + } + + [Fact] + public async Task APanelThatNeedsTwoReads_WaitsForBoth_AndDrawsOnceWithBothResults() + { + var chart = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var markers = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var drawn = new List(); + + var draw = LandedPanels.DrawAsync(chart.Task, markers.Task, (value, mark) => drawn.Add($"{value}/{mark}")); + + chart.SetResult(3); + await Task.Delay(100, TestContext.Current.CancellationToken); + Assert.Empty(drawn); + + markers.SetResult("m"); + await draw.WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + Assert.Equal(["3/m"], drawn); + } + + private static async Task Eventually(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (!condition() && DateTime.UtcNow < deadline) + { + await Task.Delay(10, TestContext.Current.CancellationToken); + } + + Assert.True(condition()); + } +} diff --git a/Lite/Controls/ServerTab.Refresh.cs b/Lite/Controls/ServerTab.Refresh.cs index 46f4e36ad5..a786145c94 100644 --- a/Lite/Controls/ServerTab.Refresh.cs +++ b/Lite/Controls/ServerTab.Refresh.cs @@ -405,6 +405,9 @@ private async System.Threading.Tasks.Task RefreshEngineEditionAsync() } } + /// #9232: one INFO line per tab (per Queries sub-tab) the first time its load completes, so a slow first open can be read from the log. + private TabFirstLoad? _tabFirstLoad; + /// Reads the tab now showing. Returns the Overview lane reads that failed, named for the status line, and otherwise null. private async System.Threading.Tasks.Task RefreshVisibleTabAsync(int hoursBack, DateTime? fromDate, DateTime? toDate, bool subTabOnly = false, CancellationToken ct = default) { @@ -421,7 +424,17 @@ private async System.Threading.Tasks.Task RefreshEngineEditionAsync() if (ct.IsCancellationRequested) return null; } + /* #9232: the tab's reads are timed from here, once per tab (per Queries sub-tab), and logged when the first one completes. */ + _tabFirstLoad ??= new TabFirstLoad(line => AppLogger.Info("ServerTab", $"[{_server.DisplayName}] {line}")); + var tabIndex = MainTabControl.SelectedIndex; + var loadKey = tabIndex == QueriesTabIndex ? $"tab {tabIndex}/{QueriesSubTabControl.SelectedIndex}" : $"tab {tabIndex}"; + var loadLabel = (MainTabControl.SelectedItem as TabItem)?.Header as string ?? loadKey; + if (tabIndex == QueriesTabIndex && (QueriesSubTabControl.SelectedItem as TabItem)?.Header is string subTabLabel) + loadLabel = $"{loadLabel} > {subTabLabel}"; + string? failedReads = null; + await _tabFirstLoad.RunAsync(loadKey, loadLabel, async () => + { switch (MainTabControl.SelectedIndex) { case 0: failedReads = await RefreshOverviewAsync(hoursBack, fromDate, toDate); break; @@ -444,6 +457,8 @@ private async System.Threading.Tasks.Task RefreshEngineEditionAsync() case 17: await RefreshConfigChangesAsync(hoursBack, fromDate, toDate); break; case 18: await RefreshLongQueriesAsync(hoursBack, fromDate, toDate); break; } + return 0; + }, () => ct.IsCancellationRequested); /* #8647: a read that ended without being superseded has had its say; whatever still says "Loading..." never got an answer. */ if (!ct.IsCancellationRequested) ResolveFirstPaintLoading(); @@ -545,11 +560,12 @@ private async System.Threading.Tasks.Task RefreshQueriesAsync(int hoursBack, Dat var qsdt = Helpers.MethodProfiler.TimeAsync("QueryPerformance.QsDurationTrends", () => Task.Run(() => SafeQueryAsync(() => _dataService.GetQueryStoreDurationTrendAsync(_serverId, hoursBack, fromDate, toDate, SelectedDatabaseFilter)))); var ect = Helpers.MethodProfiler.TimeAsync("QueryPerformance.ExecutionTrends", () => Task.Run(() => SafeQueryAsync(() => _dataService.GetExecutionCountTrendAsync(_serverId, hoursBack, fromDate, toDate, SelectedDatabaseFilter)))); var disc = Helpers.MethodProfiler.TimeAsync("QueryPerformance.Discontinuities", () => Task.Run(() => SafeDiscontinuitiesAsync(hoursBack, fromDate, toDate))); - await System.Threading.Tasks.Task.WhenAll(qdt, pdt, qsdt, ect, disc); - UpdateQueryDurationTrendChart(qdt.Result, hoursBack, fromDate, toDate, disc.Result); - UpdateProcDurationTrendChart(pdt.Result, hoursBack, fromDate, toDate, disc.Result); - UpdateQueryStoreDurationTrendChart(qsdt.Result, hoursBack, fromDate, toDate, disc.Result); - UpdateExecutionCountTrendChart(ect.Result, hoursBack, fromDate, toDate, disc.Result); + /* #9232: each chart is drawn when ITS read (and the small discontinuity read) lands, not after the slowest of the five. */ + await System.Threading.Tasks.Task.WhenAll( + LandedPanels.DrawAsync(qdt, disc, (trend, markers) => UpdateQueryDurationTrendChart(trend, hoursBack, fromDate, toDate, markers)), + LandedPanels.DrawAsync(pdt, disc, (trend, markers) => UpdateProcDurationTrendChart(trend, hoursBack, fromDate, toDate, markers)), + LandedPanels.DrawAsync(qsdt, disc, (trend, markers) => UpdateQueryStoreDurationTrendChart(trend, hoursBack, fromDate, toDate, markers)), + LandedPanels.DrawAsync(ect, disc, (trend, markers) => UpdateExecutionCountTrendChart(trend, hoursBack, fromDate, toDate, markers))); break; case ActiveQueriesSubTabIndex: // Active Queries var includeMonitor = ActiveQueriesIncludeMonitor; diff --git a/Lite/Helpers/TabFirstLoad.cs b/Lite/Helpers/TabFirstLoad.cs new file mode 100644 index 0000000000..2b399ad7ce --- /dev/null +++ b/Lite/Helpers/TabFirstLoad.cs @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2026 Erik Darling, Darling Data LLC + * + * This file is part of the SQL Server Performance Monitor Lite. + * + * Licensed under the MIT License. See LICENSE file in the project root for full license information. + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace PerformanceMonitorLite.Helpers; + +/// +/// #9232: the first load of a tab or sub-tab, written to the log once with its elapsed milliseconds. Before this a slow first +/// open (30 to 45 s on Performance Trends in the field) left no line, so it could not be read from the log. Only the FIRST +/// completed load of a key is written: the timer's later ticks and a return to the tab are not first opens and stay quiet. +/// A load a newer request abandoned is not a first open, so its replay is the one that gets the line. +/// +internal sealed class TabFirstLoad +{ + private readonly HashSet _loaded = new(StringComparer.Ordinal); + private readonly Action _write; + private readonly TimeProvider _time; + + public TabFirstLoad(Action write, TimeProvider? time = null) + { + _write = write; + _time = time ?? TimeProvider.System; + } + + /// + /// Runs . The first time completes it writes + /// First load of {label}: {ms} ms, and later runs of the same key write nothing. A null key is not tracked. + /// is asked once the load ends: true means a newer request superseded it, so it is neither + /// counted nor logged. + /// + public async Task RunAsync(string? key, string label, Func> load, Func? abandoned = null) + { + if (key is null || _loaded.Contains(key)) + { + return await load(); + } + + var started = _time.GetTimestamp(); + var result = await load(); + if (abandoned?.Invoke() == true) + { + return result; + } + + if (_loaded.Add(key)) + { + var ms = (long)_time.GetElapsedTime(started).TotalMilliseconds; + _write($"First load of {label}: {ms} ms"); + } + + return result; + } +} + +/// +/// #9232: draws each panel of a tab as ITS OWN reads land. The tab used to wait for every read of the sub-tab and then draw +/// them all in a row, so the slowest read held back the chart that was ready first. +/// +internal static class LandedPanels +{ + /// Awaits , then runs with its result. Nothing else is awaited. + public static async Task DrawAsync(Task read, Action draw) => draw(await read); + + /// The same for a panel that needs two reads (a chart and the discontinuity markers it is marked with). + public static async Task DrawAsync(Task read, Task alsoRead, Action draw) + { + var first = await read; + draw(first, await alsoRead); + } +}