diff --git a/Darling/Darling.Tests/StoredServerClockRowTextTests.cs b/Darling/Darling.Tests/StoredServerClockRowTextTests.cs index 1e70719b81..a9559812a2 100644 --- a/Darling/Darling.Tests/StoredServerClockRowTextTests.cs +++ b/Darling/Darling.Tests/StoredServerClockRowTextTests.cs @@ -118,8 +118,6 @@ public void AJobStepReadFromTheStoredWallClock_PrintsNoOffset_InBothPassesOfTheR Assert.Equal("2026-11-01 01:30:00", firstPass.RunTimeLocal); Assert.Equal("2026-11-01 01:30:00", secondPass.RunTimeLocal); - Assert.Equal("2026-11-01 01:45:00", firstPass.LastSuccessfulRunLocal); - Assert.Equal("2026-11-01 01:45:00", secondPass.LastSuccessfulRunLocal); /* A real instant in the same test keeps the offset: the two passes of 01:30 are 05:30Z and 06:30Z. */ Assert.Equal("2026-11-01 01:30:00 -04:00", TrueUtcRowText(Naive(2026, 11, 1, 5, 30))); @@ -138,8 +136,6 @@ public void AJobStepOutsideTheRepeatedHour_ReadsAsTheDisplayTextItAlwaysDid() Assert.Equal("2026-11-01 00:59:00", beforeTheHour.RunTimeLocal); Assert.Equal("2026-11-01 02:00:00", afterTheHour.RunTimeLocal); Assert.Equal("2026-07-06 12:00:00", summer.RunTimeLocal); - Assert.Equal("2026-07-06 11:00:00", summer.LastSuccessfulRunLocal); - Assert.Equal("Never", beforeTheHour.LastSuccessfulRunLocal); Assert.Equal("", new ViewerJobHistoryRow().RunTimeLocal); } diff --git a/Darling/Darling.Tests/UncorroboratedRouteStoreKnobTests.cs b/Darling/Darling.Tests/UncorroboratedRouteStoreKnobTests.cs index d7f66e5857..1fc681a4c8 100644 --- a/Darling/Darling.Tests/UncorroboratedRouteStoreKnobTests.cs +++ b/Darling/Darling.Tests/UncorroboratedRouteStoreKnobTests.cs @@ -328,9 +328,13 @@ public void TheSettingsWindowCombo_PrefillsSavesAndRestores_ThroughTheThreeState Assert.Contains("darling.json value (store column cleared)\" Tag=\"\"", xaml, StringComparison.Ordinal); /* The prose: what a lone finding is, that the store wins and when, and how to hand it back. */ Assert.Contains("ONE fact in its chain and no matched co-fire check", xaml, StringComparison.Ordinal); - Assert.Contains("win over darling.json's analysis.uncorroboratedRoute", xaml, StringComparison.Ordinal); - Assert.Contains("within one collection sweep", xaml, StringComparison.Ordinal); - Assert.Contains("analysis.uncorroborated_route_source", xaml, StringComparison.Ordinal); + /* #6651 (W8): the note under the combo is ViewerLabels.UncorroboratedRouteNote, in words for a person: the page that shows which + value is in force, no MCP key name. */ + Assert.Contains("{x:Static local:ViewerLabels.UncorroboratedRouteNote}", xaml, StringComparison.Ordinal); + Assert.Contains("win over darling.json's analysis.uncorroboratedRoute", ViewerLabels.UncorroboratedRouteNote, StringComparison.Ordinal); + Assert.Contains("within one collection sweep", ViewerLabels.UncorroboratedRouteNote, StringComparison.Ordinal); + Assert.Contains("The Alert Settings page shows which one is in force.", ViewerLabels.UncorroboratedRouteNote, StringComparison.Ordinal); + Assert.DoesNotContain("analysis.uncorroborated_route_source", ViewerLabels.UncorroboratedRouteNote, StringComparison.Ordinal); Assert.Contains("Escalation is the corroboration event", xaml, StringComparison.Ordinal); Assert.Contains("SelectAnalysisUncorroboratedRoute(r.AnalysisUncorroboratedRoute);", window, StringComparison.Ordinal); diff --git a/Darling/Darling.Tests/ViewerDataStartBannerTests.cs b/Darling/Darling.Tests/ViewerDataStartBannerTests.cs index f28dc4fdd0..eb471f2267 100644 --- a/Darling/Darling.Tests/ViewerDataStartBannerTests.cs +++ b/Darling/Darling.Tests/ViewerDataStartBannerTests.cs @@ -181,7 +181,8 @@ public void CurrentWaits_AsksAboutTheToolbarWindow_AndComparesWithItsStart() toolbar's range on a load (startUtc), the slicer's selection on a drag (e.StartUtc). Both await the probe through the same catch as the two surfaces above, so a probe that throws costs the grid its banner and not the slicer and the comparison loads that follow it. The tail is what the call passes after the start: the hourly-tier suffix on Top - Queries and Top Procedures, the interval-table plan on a Query Store load, nothing on a Query Store slicer drag. */ + Queries and Top Procedures, the interval-table plan on a Query Store load, nothing on a Query Store slicer drag. Top Procedures names the databases its read left out (#6651) between the banner + and the next call. */ private const string HourlyTail = @",\s*HourlyBannerSuffix\(read\.Tier, read\.IoRoute, read\.HourlyEdgesNote\),\s*HourlyServedOf\(read\.Tier, read\.HourlyFirstBucket\)"; private const string WidePlanTail = @",\s*widePlan: widePlan"; @@ -195,7 +196,7 @@ public void QueriesTab_RangeLoad_AsksAboutTheToolbarWindow_AndComparesWithItsSta Assert.Equal(1, Matches(tab, $@"var floorTask = Timed\(timer, ""data start"", _dataService\.{probe}\(_server\.ServerId,\s*startUtc,\s*endUtc\)\);")); Assert.Equal(1, Matches(tab, - $@"UpdateTruncationBanner\({grid}TruncationBanner,\s*await DataStartOrNullAsync\(floorTask,\s*""{surface}""\),\s*startUtc{tail}\);\s*await Load{grid}SlicerAsync\(startUtc,\s*endUtc,\s*slicerTask\);\s*\}}\s*catch\s*\{{[^}}]*\}}\s*await Refresh{grid}ComparisonAsync\(startUtc,\s*endUtc,\s*timer\);")); + $@"UpdateTruncationBanner\({grid}TruncationBanner,\s*await DataStartOrNullAsync\(floorTask,\s*""{surface}""\),\s*startUtc{tail}\);(?:\s*await Update{grid}LeftOutBannerAsync\(read,\s*startUtc,\s*endUtc\);)?\s*await Load{grid}SlicerAsync\(startUtc,\s*endUtc,\s*slicerTask\);\s*\}}\s*catch\s*\{{[^}}]*\}}\s*await Refresh{grid}ComparisonAsync\(startUtc,\s*endUtc,\s*timer\);")); } [Theory] @@ -208,7 +209,7 @@ public void QueriesTab_SlicerDrag_AsksAboutTheSelection_AndComparesWithItsStart( Assert.Equal(1, Matches(tab, $@"var floorTask = _dataService\.{probe}\(_server\.ServerId,\s*e\.StartUtc,\s*e\.EndUtc\);")); Assert.Equal(1, Matches(tab, - $@"UpdateTruncationBanner\({grid}TruncationBanner,\s*await DataStartOrNullAsync\(floorTask,\s*""{surface}""\),\s*e\.StartUtc{tail}\);\s*await Refresh{grid}ComparisonAsync\(e\.StartUtc,\s*e\.EndUtc\);")); + $@"UpdateTruncationBanner\({grid}TruncationBanner,\s*await DataStartOrNullAsync\(floorTask,\s*""{surface}""\),\s*e\.StartUtc{tail}\);(?:\s*await Update{grid}LeftOutBannerAsync\(read,\s*e\.StartUtc,\s*e\.EndUtc\);)?\s*await Refresh{grid}ComparisonAsync\(e\.StartUtc,\s*e\.EndUtc\);")); } /* No read awaits its probe bare (a probe that throws would unwind the load past the slicer, or the rest of the tab), diff --git a/Darling/Darling.Tests/ViewerGridTimeColumnSortMemberTests.cs b/Darling/Darling.Tests/ViewerGridTimeColumnSortMemberTests.cs index 142680a1a7..24b807b45d 100644 --- a/Darling/Darling.Tests/ViewerGridTimeColumnSortMemberTests.cs +++ b/Darling/Darling.Tests/ViewerGridTimeColumnSortMemberTests.cs @@ -106,7 +106,6 @@ public sealed class ViewerGridTimeColumnSortMemberTests /* Columns whose row already had a UTC (or display-zone) DateTime and only lacked the SortMemberPath. */ { "AlertsHistoryTab.xaml", "AlertsDataGrid", "TimeLocal", Name(typeof(ViewerAlertRow)), "AlertTime" }, { "JobHistoryTab.xaml", "JobHistoryDataGrid", "RunTimeLocal", Name(typeof(ViewerJobHistoryRow)), "RunDateTimeUtc" }, - { "JobHistoryTab.xaml", "JobHistoryDataGrid", "LastSuccessfulRunLocal", Name(typeof(ViewerJobHistoryRow)), "LastSuccessfulRunUtc" }, { "MuteRulesWindow.xaml", "RulesGrid", "ExpiresDisplay", Name(typeof(MuteRule)), "ExpiresAtUtc" }, { "ProcedureHistoryWindow.xaml", "HistoryDataGrid", "CollectionTimeLocal", Name(typeof(ViewerProcedureStatsHistoryRow)), "CollectionTime" }, { "QueryStatsHistoryWindow.xaml", "HistoryDataGrid", "CollectionTimeLocal", Name(typeof(ViewerQueryStatsHistoryRow)), "CollectionTime" }, diff --git a/Darling/Darling.Tests/ViewerHourlyWindowEdgesTests.cs b/Darling/Darling.Tests/ViewerHourlyWindowEdgesTests.cs index 816b113b39..47babc1cdf 100644 --- a/Darling/Darling.Tests/ViewerHourlyWindowEdgesTests.cs +++ b/Darling/Darling.Tests/ViewerHourlyWindowEdgesTests.cs @@ -50,24 +50,26 @@ public void HourlyCeilingSql_IsEmptyWithoutACeiling_AndBoundsTheBucketWithOne() public void HourlySql_BindsTheCeilingOnlyWhenOneIsKnown_OnBothGrids() { const string From = "collect.query_stats_io_hourly AS f"; - foreach (var build in new Func[] + /* The procedures grid binds the dropped-database exclusion at $6 (#6651), so its ceiling is the seventh parameter. */ + foreach (var (build, slot) in new (Func, int)[] { - ceiling => ViewerDataService.BuildTopQueriesHourlySql(From, withIo: true, ceiling: ceiling), - ceiling => ViewerDataService.BuildTopQueriesHourlySql(From, withIo: false, ceiling: ceiling), - ceiling => ViewerDataService.BuildTopProceduresHourlySql(From, withIo: true, ceiling: ceiling), - ceiling => ViewerDataService.BuildTopProceduresHourlySql(From, withIo: false, ceiling: ceiling), + (ceiling => ViewerDataService.BuildTopQueriesHourlySql(From, withIo: true, ceiling: ceiling), 6), + (ceiling => ViewerDataService.BuildTopQueriesHourlySql(From, withIo: false, ceiling: ceiling), 6), + (ceiling => ViewerDataService.BuildTopProceduresHourlySql(From, withIo: true, ceiling: ceiling), 7), + (ceiling => ViewerDataService.BuildTopProceduresHourlySql(From, withIo: false, ceiling: ceiling), 7), }) { + var ceilingSlot = "bucket < $" + slot; var bounded = build(Aligned); - Assert.Contains("bucket < $6", bounded, StringComparison.Ordinal); + Assert.Contains(ceilingSlot, bounded, StringComparison.Ordinal); /* The ceiling rides beside the window end, ahead of the grouping. */ Assert.True( - bounded.IndexOf("bucket < $3", StringComparison.Ordinal) < bounded.IndexOf("bucket < $6", StringComparison.Ordinal) - && bounded.IndexOf("bucket < $6", StringComparison.Ordinal) < bounded.IndexOf("GROUP BY", StringComparison.Ordinal)); + bounded.IndexOf("bucket < $3", StringComparison.Ordinal) < bounded.IndexOf(ceilingSlot, StringComparison.Ordinal) + && bounded.IndexOf(ceilingSlot, StringComparison.Ordinal) < bounded.IndexOf("GROUP BY", StringComparison.Ordinal)); - /* A null ceiling means no bound: today's text, with no sixth parameter. */ + /* A null ceiling means no bound: today's text, with no ceiling parameter. */ var open = build(null); - Assert.DoesNotContain("$6", open, StringComparison.Ordinal); + Assert.DoesNotContain(ceilingSlot, open, StringComparison.Ordinal); Assert.Contains("bucket < $3", open, StringComparison.Ordinal); } } diff --git a/Darling/Darling.Tests/ViewerTopProceduresDroppedDatabaseTests.cs b/Darling/Darling.Tests/ViewerTopProceduresDroppedDatabaseTests.cs new file mode 100644 index 0000000000..37600a3396 --- /dev/null +++ b/Darling/Darling.Tests/ViewerTopProceduresDroppedDatabaseTests.cs @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2026 Erik Darling, Darling Data LLC + * + * This file is part of the SQL Server Performance Monitor. + * + * Licensed under the MIT License. See LICENSE file in the project root for full license information. + */ + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Npgsql; +using PerformanceMonitor.Collectors; +using PerformanceMonitor.Common; +using PerformanceMonitor.Darling.Storage; +using PerformanceMonitor.Darling.Viewer; +using Xunit; + +namespace Darling.Tests; + +/* #1776 own-store: the live tests mint their own scratch database and seed their own server, so they share no rows with another test. */ +/// +/// #6651 (#5633 item 4): the Viewer's Top Procedures by Duration read leaves out the databases the server dropped, as +/// get_top_procedures_by_cpu does, on the raw tier and on the hourly rollup. The dropped database is the HEAVIER one and the page +/// is top 1, so a read that only filtered after the LIMIT would come back empty or wrong. A database the caller names is read as asked. +/// +public sealed class ViewerTopProceduresDroppedDatabaseTests +{ + private const string Gone = "GoneDb"; + private const string Live = "LiveDb"; + + private static async Task SnapshotAsync(NpgsqlConnection connection, int serverId, string serverName, DateTime at, CancellationToken ct, params string[] databases) + { + var id = 1; + foreach (var database in databases) + { + await DarlingMcpTestData.ExecAsync(connection, ct, + "INSERT INTO database_states (collection_id, collection_time, server_id, server_name, database_name, database_id, state_desc, is_in_standby) VALUES ($1,$2,$3,$4,$5,$6,'ONLINE',FALSE)", + CollectionIdGenerator.Next(), DateTime.SpecifyKind(at, DateTimeKind.Unspecified), serverId, serverName, database, id++); + } + } + + private static async Task PlantProcedureAsync(NpgsqlConnection connection, int serverId, string serverName, string database, DateTime at, long executions, CancellationToken ct) + { + await DarlingMcpTestData.ExecAsync(connection, ct, + @"INSERT INTO collect.procedure_stats (collection_id, collection_time, server_id, server_name, database_name, schema_name, object_name, sql_handle, + delta_worker_time, delta_elapsed_time, delta_execution_count, delta_spills, sample_interval_seconds) + VALUES ($1,$2,$3,$4,$5,'dbo','usp_Work',$6,$7,$8,$9,0,3600)", + CollectionIdGenerator.Next(), DarlingMcpTestData.TruncateToSeconds(at), serverId, serverName, database, "0xH" + database, + executions * 1_000L, executions * 2_000L, executions); + } + + [Fact] + public async Task RawTier_LeavesTheDroppedDatabaseOut_RanksTheLiveOneAtTop1_AndReadsANamedDroppedDatabaseAsAsked() + { + var baseConnectionString = Environment.GetEnvironmentVariable("DARLING_TEST_PG"); + Assert.SkipWhen(string.IsNullOrEmpty(baseConnectionString), "Set DARLING_TEST_PG to a Postgres connection string to run the live Viewer dropped-database test."); + var ct = TestContext.Current.CancellationToken; + await using var scratch = await ScratchPostgres.CreateAsync(baseConnectionString!, ct); + await using var connection = new NpgsqlConnection(scratch.ConnectionString); + await connection.OpenAsync(ct); + await PgMigrations.MigrateAsync(connection, ct); + + const string serverName = "viewer-dropped-raw"; + var serverId = ServerIdHelper.GetDeterministicHashCode(serverName); + await DarlingMcpTestData.RegisterServerAsync(connection, serverId, serverName, ct); + var now = DateTime.UtcNow; + await PlantProcedureAsync(connection, serverId, serverName, Gone, now.AddHours(-2), 900, ct); + await PlantProcedureAsync(connection, serverId, serverName, Live, now.AddHours(-2), 100, ct); + + await using var viewer = new ViewerDataService(scratch.ConnectionString); + var start = now.AddHours(-24); + var end = now.AddMinutes(1); + + /* No snapshot: the set of databases is unknown, so nothing is left out and the heavier database ranks first. */ + var unknown = await viewer.GetTopProceduresByCpuRoutedAsync(serverId, start, end, 20, cancellationToken: ct); + Assert.Equal(new[] { Gone, Live }, unknown.Rows.Select(r => r.DatabaseName).ToArray()); + Assert.Null(unknown.LeftOutDatabases); + + /* An earlier snapshot named both; the newest names LiveDb only, so GoneDb was dropped in between. */ + await SnapshotAsync(connection, serverId, serverName, now.AddHours(-1), ct, Gone, Live); + await SnapshotAsync(connection, serverId, serverName, now.AddMinutes(-5), ct, Live); + + var top1 = await viewer.GetTopProceduresByCpuRoutedAsync(serverId, start, end, 1, cancellationToken: ct); + Assert.Equal("raw", top1.Tier); + Assert.Equal(new[] { Live }, top1.Rows.Select(r => r.DatabaseName).ToArray()); + Assert.Equal(new[] { Gone }, top1.LeftOutDatabases); + + /* Named, a dropped database is a question about its history and is read as asked, with nothing left out. */ + var named = await viewer.GetTopProceduresByCpuRoutedAsync(serverId, start, end, 20, new[] { Gone }, cancellationToken: ct); + Assert.Equal(new[] { Gone }, named.Rows.Select(r => r.DatabaseName).ToArray()); + Assert.Null(named.LeftOutDatabases); + } + + [Fact] + public async Task HourlyTier_LeavesTheDroppedDatabaseOut_AtTop1() + { + var baseConnectionString = Environment.GetEnvironmentVariable("DARLING_TEST_PG"); + Assert.SkipWhen(string.IsNullOrEmpty(baseConnectionString), "Set DARLING_TEST_PG to a Postgres connection string (with TimescaleDB installed) to run the live Viewer dropped-database hourly test."); + var ct = TestContext.Current.CancellationToken; + await using var scratch = await ScratchPostgres.CreateAsync(baseConnectionString!, ct); + await using var connection = new NpgsqlConnection(scratch.ConnectionString); + await connection.OpenAsync(ct); + await PgMigrations.MigrateAsync(connection, ct); + + var timescaleEnabled = await TimescaleSupport.TryEnableAsync(connection, null, ct); + Assert.SkipWhen(!timescaleEnabled, "The live Viewer dropped-database hourly test needs TimescaleDB."); + await TimescaleSupport.ConvertToHypertablesAsync(connection, null, ct); + Assert.True(await TimescaleSupport.EnsureCollectionLogHypertableAsync(connection, null, ct)); + await using (var stop = new NpgsqlCommand("SELECT _timescaledb_functions.stop_background_workers()", connection)) + { + await stop.ExecuteNonQueryAsync(ct); + } + + const string serverName = "viewer-dropped-hourly"; + var serverId = ServerIdHelper.GetDeterministicHashCode(serverName); + await DarlingMcpTestData.RegisterServerAsync(connection, serverId, serverName, ct); + await TimescaleSupport.EnsureContinuousAggregatesAsync(connection, null, ct); + + /* A fixed past window, as the other hourly live tests use; the snapshots sit just before the window's end, which the read anchors at. */ + var windowStart = new DateTime(2026, 1, 5, 0, 0, 0, DateTimeKind.Unspecified); + var hour = windowStart.AddHours(1); + var end = windowStart.AddHours(8); + var bodySucceeded = false; + try + { + await PlantProcedureAsync(connection, serverId, serverName, Gone, hour.AddMinutes(10), 900, ct); + await PlantProcedureAsync(connection, serverId, serverName, Live, hour.AddMinutes(10), 100, ct); + await SnapshotAsync(connection, serverId, serverName, end.AddHours(-4), ct, Gone, Live); + await SnapshotAsync(connection, serverId, serverName, end.AddHours(-1), ct, Live); + + foreach (var view in new[] { TimescaleSupport.ProcedureStatsHourlyView, TimescaleSupport.ProcedureStatsIntervalHourlyView, TimescaleSupport.ProcedureStatsIoHourlyView }) + { + await using var refresh = new NpgsqlCommand($"CALL refresh_continuous_aggregate('collect.{view}'::regclass, $1::timestamp, $2::timestamp)", connection); + refresh.Parameters.AddWithValue(windowStart); + refresh.Parameters.AddWithValue(end); + await refresh.ExecuteNonQueryAsync(ct); + } + + /* Purge raw so the router answers from the rollup. */ + await DarlingMcpTestData.ExecAsync(connection, ct, + "DELETE FROM collect.procedure_stats WHERE server_id = $1 AND collection_time >= $2 AND collection_time < $3", serverId, windowStart, windowStart.AddDays(1)); + + await using var viewer = new ViewerDataService(scratch.ConnectionString); + var read = await viewer.GetTopProceduresByCpuRoutedAsync(serverId, hour, end, 1, cancellationToken: ct); + Assert.Equal("hourly", read.Tier); + Assert.Equal(new[] { Live }, read.Rows.Select(r => r.DatabaseName).ToArray()); + Assert.Equal(new[] { Gone }, read.LeftOutDatabases); + + var named = await viewer.GetTopProceduresByCpuRoutedAsync(serverId, hour, end, 1, new[] { Gone }, cancellationToken: ct); + Assert.Equal(new[] { Gone }, named.Rows.Select(r => r.DatabaseName).ToArray()); + Assert.Null(named.LeftOutDatabases); + bodySucceeded = true; + } + finally + { + await LiveStoreCleanup.RunAsync(scratch.ConnectionString, bodySucceeded, (cleanup, cleanupCt) => Task.CompletedTask); + } + } + + private static readonly string[] Dropped = { "zz_a", "zz_b" }; + + [Fact] + public void LeftOutText_IsNullWhenNothingWasLeftOut() + { + Assert.Null(DatabasesLeftOut.ProcedureBanner(null, 5, null, 24)); + Assert.Null(DatabasesLeftOut.ProcedureBanner(Array.Empty(), 0, null, 24)); + } + + [Fact] + public void LeftOutText_WithRows_NamesTheDatabasesAndSaysHowToReadThem() + { + var text = DatabasesLeftOut.ProcedureBanner(Dropped, 3, null, 24)!; + Assert.Contains("Left out: zz_a, zz_b.", text, StringComparison.Ordinal); + Assert.Contains("left out of this read", text, StringComparison.Ordinal); + } + + [Fact] + public void LeftOutText_OnAnEmptyPage_SaysNoProcedureRanInADatabaseTheServerStillHas_AndHidesTheMcpKey() + { + var facts = new CollectorRunFacts(10, 4, DateTime.UtcNow, null); + var text = DatabasesLeftOut.ProcedureBanner(Dropped, 0, facts, 24)!; + Assert.Contains("No procedure ran in the last 24h in a database this server still has", text, StringComparison.Ordinal); + Assert.Contains("2 database(s) the server no longer lists were left out of this read", text, StringComparison.Ordinal); + Assert.DoesNotContain("databases_left_out", text, StringComparison.Ordinal); + Assert.Contains("Left out: zz_a, zz_b.", text, StringComparison.Ordinal); + } +} diff --git a/Darling/Darling.Tests/ViewerWebParityWordsTests.cs b/Darling/Darling.Tests/ViewerWebParityWordsTests.cs new file mode 100644 index 0000000000..ab7d13a381 --- /dev/null +++ b/Darling/Darling.Tests/ViewerWebParityWordsTests.cs @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2026 Erik Darling, Darling Data LLC + * + * This file is part of the SQL Server Performance Monitor. + * + * Licensed under the MIT License. See LICENSE file in the project root for full license information. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using PerformanceMonitor.Common; +using PerformanceMonitor.Darling.Viewer; +using Xunit; + +namespace Darling.Tests; + +/// +/// #6651: the Viewer says what the web pages and the MCP tools say after #5704 and #5705 -- the labels of a few figures, no tool or key +/// name in a sentence for a person, no per-row repeat of the job's newest success, and a break (not a line across it) in the Top Queries +/// and Top Procedures strip where the service was off. +/// +public sealed class ViewerWebParityWordsTests +{ + [Fact] + public void FinOpsCpuLabels_NameSqlServersOwnCpu_AsTheWebPageDoes() + { + Assert.Equal("Avg SQL Server CPU", ViewerLabels.AvgSqlServerCpu); + Assert.Equal("P95 SQL Server CPU", ViewerLabels.P95SqlServerCpu); + Assert.Equal("Max SQL Server CPU", ViewerLabels.MaxSqlServerCpu); + Assert.Equal("Avg SQL Server CPU %", ViewerLabels.AvgSqlServerCpuPercent); + Assert.Equal("P95 SQL Server CPU %", ViewerLabels.P95SqlServerCpuPercent); + Assert.Equal("Max SQL Server CPU %", ViewerLabels.MaxSqlServerCpuPercent); + } + + [Fact] + public void MemoryPlanCacheLabel_SaysItCountsEveryCacheStore() + => Assert.Equal("Plan cache (all cache stores)", ViewerLabels.PlanCacheAllStores); + + [Fact] + public void UncorroboratedRouteNote_IsProseForAPerson_WithNoToolNameOrKey() + { + var note = ViewerLabels.UncorroboratedRouteNote; + Assert.Contains("Alert Settings page", note, StringComparison.Ordinal); + Assert.DoesNotContain("get_", note, StringComparison.Ordinal); + Assert.DoesNotContain("_source", note, StringComparison.Ordinal); + Assert.DoesNotContain("uncorroborated_route", note, StringComparison.Ordinal); + } + + /// W21(a): the job's newest success repeated on every row (also beside runs from earlier minutes, and "Never" for a job that + /// retries) is gone from the row the grid binds; the web page removed the column. + [Fact] + public void JobHistoryRow_HasNoLastSuccessColumnValue() + => Assert.Null(typeof(ViewerJobHistoryRow).GetProperty("LastSuccessfulRunLocal")); + + private static List Hourly(DateTime start, int count) + => Enumerable.Range(0, count).Select(i => new TimeSliceBucket { BucketTime = start.AddHours(i), Value = 10 + i }).ToList(); + + private static List<(int Start, int Count)> RunsAfterLoad(List real, DateTime windowStart, DateTime windowEnd) + => StaTestThread.Run(() => + { + var slicer = new TimeRangeSlicerControl(); + slicer.LoadData(real, "Sessions", windowStart, windowEnd); + return slicer.DrawnRuns.ToList(); + }); + + /// The service was off overnight: LoadData fills every hour of the window (for the bars and the axis), and the line the strip + /// draws still breaks across the hours the real buckets did not have. Judged on the filled buckets no gap would ever show. + [Fact] + public void Strip_BreaksWhereTheServiceWasOff_InsteadOfDrawingAcrossIt() + { + var evening = Hourly(new DateTime(2026, 10, 22, 18, 0, 0, DateTimeKind.Utc), 4); // 18:00-21:00 + var morning = Hourly(new DateTime(2026, 10, 23, 7, 0, 0, DateTimeKind.Utc), 4); // 07:00-10:00 + var window = (Start: new DateTime(2026, 10, 22, 18, 0, 0, DateTimeKind.Utc), End: new DateTime(2026, 10, 23, 10, 30, 0, DateTimeKind.Utc)); + + var runs = RunsAfterLoad(evening.Concat(morning).ToList(), window.Start, window.End); + + /* 17 filled hours; indexes 4-12 (22:00-06:00) are the missing stretch and are not drawn. */ + Assert.Equal(new[] { (0, 4), (13, 4) }, runs); + } + + [Fact] + public void Strip_WithAShortHole_OrFewBuckets_StaysOneRun() + { + var start = new DateTime(2026, 10, 23, 0, 0, 0, DateTimeKind.Utc); + var holey = Hourly(start, 5).Concat(Hourly(start.AddHours(7), 5)).ToList(); // two missing hours: a 3h jump is not over 3 x the 1h median + Assert.Equal(new[] { (0, 12) }, RunsAfterLoad(holey, start, start.AddHours(11))); + + /* Fewer than two spacings have no rhythm to be silent against, so two buckets 9 hours apart never break. */ + var two = new List { Hourly(start, 1)[0], Hourly(start.AddHours(9), 1)[0] }; + Assert.Equal(new[] { (0, 10) }, RunsAfterLoad(two, start, start.AddHours(9))); + + var steady = Hourly(start, 20); + Assert.Equal(new[] { (0, 20) }, RunsAfterLoad(steady, start, start.AddHours(19))); + } +} diff --git a/Darling/PerformanceMonitor.Darling.Viewer/FinOpsTab.xaml b/Darling/PerformanceMonitor.Darling.Viewer/FinOpsTab.xaml index 1f6117f72f..5098e3425e 100644 --- a/Darling/PerformanceMonitor.Darling.Viewer/FinOpsTab.xaml +++ b/Darling/PerformanceMonitor.Darling.Viewer/FinOpsTab.xaml @@ -324,7 +324,7 @@ - + @@ -336,7 +336,7 @@ - + @@ -348,7 +348,7 @@ - + @@ -428,9 +428,9 @@ - - - + + + diff --git a/Darling/PerformanceMonitor.Darling.Viewer/JobHistoryTab.xaml b/Darling/PerformanceMonitor.Darling.Viewer/JobHistoryTab.xaml index 43b731d2ed..c0d50cb23a 100644 --- a/Darling/PerformanceMonitor.Darling.Viewer/JobHistoryTab.xaml +++ b/Darling/PerformanceMonitor.Darling.Viewer/JobHistoryTab.xaml @@ -189,14 +189,6 @@ - - - -