Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Darling/Darling.Tests/DarlingQueryStoreRegressionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,8 @@ await LiveStoreCleanup.RunAsync(cs!, bodySucceeded, async (cleanup, cleanupCt) =
}
}

/// <summary>The truncated-baseline sentence Lite adds to its note, which this tool copies.</summary>
private const string BaselineTail = "Here the window starts at baseline_start, so the baseline holds only the part from effective_start to baseline_end.";
/// <summary>The truncated-baseline sentence both products add to the note: one constant in Common (#6649).</summary>
private const string BaselineTail = PerformanceMonitor.Common.QueryStoreRegressionRules.BaselineWindowTail;

/// <summary>
/// #4966: the store's first Query Store row comes 40 hours back, inside the 7-day baseline, so the baseline holds only part
Expand Down
18 changes: 18 additions & 0 deletions Darling/Darling.Tests/WebClampCellBehaviourTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,24 @@ public void TheAlertHistoryDetailColumn_LocalizesItsTimeLines_AndNeverTheSqlLine
Assert.Contains("{ key: \"detail_text\", label: \"Detail\", wrap: true, localizeAlertDetail: true },", fields, StringComparison.Ordinal);
}

[Fact]
public void ACellsPlainMode_PicksItsOwnPass_CountsKeepsAToolNameInARealError()
{
// #6649: the Collection Log's Error column is `plain: "counts"`; a mistyped key would fall through to the full pass, which
// turns a real error's get_ name into a tab name.
var p = Run().GetProperty("plainModes");
var raw = p.GetProperty("raw").GetString()!;
var counts = p.GetProperty("counts").GetString()!;
Assert.Equal("Connection failed (timeout=30): ring buffer truncated: 1, ring buffer events hidden: 167, newest visible event age s: 4300; ask get_collection_health for the time range", counts);
var full = p.GetProperty("full").GetString()!;
Assert.Contains("ask Collection Health for the time range", full);
Assert.DoesNotContain("get_collection_health", full);
var named = p.GetProperty("named").GetString()!;
Assert.Contains("ring_buffer_truncated=1", named);
Assert.Contains("get_collection_health for the time range", named);
Assert.Equal(raw, p.GetProperty("asStored").GetString());
}

[Fact]
public void EnterOpensTheCell_AndOtherKeysDoNot()
{
Expand Down
2 changes: 1 addition & 1 deletion Darling/Darling.Tests/WebDataStartNoteTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ public void TheHeatmapAndRegressionsPanels_DrawTheToolsOwnTruncationNote_AsSent(

var note = DarlingMcpWindowNotice.Build(
Utc(2026, 1, 3), Utc(2026, 1, 1), table,
baselineTail ? "Here the window starts at baseline_start, so the baseline holds only the part from effective_start to baseline_end." : null).TruncationNote!;
baselineTail ? PerformanceMonitor.Common.QueryStoreRegressionRules.BaselineWindowTail : null).TruncationNote!;
Assert.DoesNotMatch(@"\d{4}-\d{2}-\d{2}|\d{1,2}:\d{2}", note);
Assert.Contains("this server's raw " + table + " retains", note, StringComparison.Ordinal);
Assert.Equal(baselineTail, note.EndsWith("baseline_end.", StringComparison.Ordinal));
Expand Down
31 changes: 30 additions & 1 deletion Darling/Darling.Tests/WebPartialWindowBehaviourTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using PerformanceMonitor.Darling.Service;
using Xunit;
using static Darling.Tests.RepoFile;

Expand All @@ -22,11 +25,12 @@ namespace Darling.Tests;
/// </summary>
public sealed class WebPartialWindowBehaviourTests
{
private static JsonElement Run()
private static JsonElement Run(string? auditBody = null)
{
var psi = new ProcessStartInfo("node") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
psi.ArgumentList.Add(PathTo("Darling", "Darling.Tests", "web-partial-window-harness.mjs"));
psi.ArgumentList.Add(PathTo("Darling", "PerformanceMonitor.Darling.Service", "wwwroot", "js"));
if (auditBody is not null) psi.ArgumentList.Add(auditBody);

Process proc;
try
Expand Down Expand Up @@ -165,6 +169,31 @@ public void AnAlertBodyOnTheWeb_ShowsItsTimeLinesLocal_AndLeavesStatementsAndSer
Assert.Contains("Incident Since: 2026-10-12 23:13:00Z", G("bodyRaw"));
}

[Fact]
public void TheCollectionHistoryAuditAlert_AgreesItsSourceCount_AndKeepsEveryOtherClauseAsWritten()
{
// #6649: Alert History printed "in 1 source(s)". The body is CollectionHistoryAudit.Render's own output: ONE line of
// ". "-joined clauses (one flagged source, every other real hourly source unread), so only its first sentence may change.
var sources = CollectionHistoryAudit.Rollups;
var rendered = CollectionHistoryAudit.Render(
new DateTime(2026, 10, 20, 0, 0, 0, DateTimeKind.Utc),
new (CollectionHistoryAudit.Rollup, IReadOnlyList<CollectionHistoryAudit.FlaggedRange>)[]
{
(sources[0], new[] { new CollectionHistoryAudit.FlaggedRange(18, 21, 0, 40, 0, 0) }),
},
sources.Skip(1).ToList());
Assert.DoesNotContain('\n', rendered);
Assert.Contains("in 1 source(s), where usual", rendered);

var h2 = Run(rendered).GetProperty("h2");
var body = h2.GetProperty("auditBody").GetString()!;
Assert.Equal(rendered.Replace("in 1 source(s), where usual", "in 1 source, where usual", StringComparison.Ordinal), body);

// The match ends at its own sentence: a later clause that the full plain-text pass would rewrite prints as written.
var probe = h2.GetProperty("auditBodyWithProbe").GetString()!;
Assert.Contains("Probe: 29 database(s) were left out (see databases_left_out).", probe);
}

[Fact]
public void ACappedPanelsHeading_DropsItsWindowLabel_AndAnyOtherKeepsIt()
{
Expand Down
79 changes: 72 additions & 7 deletions Darling/Darling.Tests/WebPlainTextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
using System.Linq;
using System.Reflection;
using System.Text.Json;
using PerformanceMonitor.Common;
using PerformanceMonitor.Darling.Service.Mcp;
using Xunit;
using static Darling.Tests.RepoFile;

Expand All @@ -27,7 +29,7 @@ public sealed class WebPlainTextTests
{
private static string[] Run(string[] inputs, out string notCollectedLine) => RunDoc(inputs, out notCollectedLine).Out;

private static (string[] Out, string[] Named, string[] Tools, string[] Labels, string[] Actions) RunDoc(string[] inputs, out string notCollectedLine)
private static (string[] Out, string[] Named, string[] Tools, string[] Labels, string[] Actions, string[] Counts) RunDoc(string[] inputs, out string notCollectedLine)
{
var psi = new ProcessStartInfo("node") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
psi.ArgumentList.Add(PathTo("Darling", "Darling.Tests", "web-plain-text-harness.mjs"));
Expand All @@ -43,7 +45,7 @@ private static (string[] Out, string[] Named, string[] Tools, string[] Labels, s
{
Assert.Skip("Node is not installed, so the shipped page script cannot be run.");
notCollectedLine = "";
return ([], [], [], [], []);
return ([], [], [], [], [], []);
}

using (proc)
Expand All @@ -60,7 +62,7 @@ private static (string[] Out, string[] Named, string[] Tools, string[] Labels, s
using var doc = JsonDocument.Parse(output.Split('\n').First(l => l.StartsWith('{')));
notCollectedLine = doc.RootElement.GetProperty("line").GetString()!;
string[] Strs(string name) => doc.RootElement.GetProperty(name).EnumerateArray().Select(e => e.GetString()!).ToArray();
return (Strs("out"), Strs("named"), Strs("tools"), Strs("labels"), Strs("actions"));
return (Strs("out"), Strs("named"), Strs("tools"), Strs("labels"), Strs("actions"), Strs("counts"));
}
}

Expand Down Expand Up @@ -98,6 +100,69 @@ public void CollectorMeasurementCounts_ReadAsWords()
Assert.Equal("latest run: shred gated: 1, events read: 0, report xml empty: 0", o[0]);
}

/* #6649: the left-out databases pointer, the baseline window sentence and the memory clerk note's four arms reached the page
with the MCP answer's field names in them. The baseline sentence and the clerk notes are read from the C# that owns them
(QueryStoreRegressionRules.BaselineWindowTail, DarlingMcpQueryStoreClutterTools.ClerkNote*), so a reword there breaks this
test instead of leaving a field name on the page (#3684). The left-out pointer is a generic suffix strip, so its one
sentence is typed here. */
[Fact]
public void FieldNamesInTheServicesOwnSentences_ReadAsThePagesWords()
{
var o = Run(
[
"No Query Store rows in the 24-hour window for a database this server still has. 29 database(s) the server no longer lists were left out of this read (see databases_left_out).",
QueryStoreRegressionRules.BaselineWindowTail,
DarlingMcpQueryStoreClutterTools.ClerkNoteInNewestCapture,
DarlingMcpQueryStoreClutterTools.ClerkNoteDroppedOut,
DarlingMcpQueryStoreClutterTools.ClerkNoteNoCapture,
DarlingMcpQueryStoreClutterTools.ClerkNoteNeverAppeared,
], out _);
Comment on lines +111 to +119

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These four sentences are copied into the test rather than read from the service, so the test cannot fail the way this fix actually dies. Three of the rules added in plain-text.js are whole-sentence literal matches against strings owned by C#:

  • DarlingMcpQueryStoreRegressionTools.cs:111 (and Lite/Mcp/McpQueryTools.cs:642) — the baseline tail
  • DarlingMcpQueryStoreClutterTools.cs:408 / :409 — the two clerk notes
  • DarlingMcpQueryStoreClutterTools.cs:182, DarlingMcpFinOpsTools.IndexAnalysis.cs:215, PerformanceMonitor.Common/CollectorRunFacts.cs:80 — (see databases_left_out) (this one is a generic suffix strip, so it is the safe one)

Reword any of those C# sentences by one character and the JS replace stops matching, the field name is back on the page, and all four assertions here still pass, because they are asserting against this file's own copy of the old wording. REVIEW-TRAPS: "Two copies of one definition pinned EQUAL to each other fail only after BOTH have drifted (#3684). Alias, do not copy."

This file already knows the better way twice: TheEngineGateSentence_NamesAzureSqlDatabase_WhenThatIsTheEngine (:429) and TheTempDbFileIoAzureAnswer_IsNotCollected_AndBecomesTheAzureLine (:440) build their input by calling the producer (CollectorEngineCapability.NotCollectedMessage, DarlingEngineCapability.TempDbFileIoNotCollectedStatus) and then assert the page's words. Lifting these sentences to const on their tool classes and feeding them in the same way makes the drift fail here instead of shipping silently.

Assert.Equal("No Query Store rows in the 24-hour window for a database this server still has. 29 databases the server no longer lists were left out of this read.", o[0]);
Assert.Equal("Here the window starts before the baseline period, so the baseline holds only the part the store has.", o[1]);
Assert.Equal("The clerk is in the newest capture's top 25; Latest MB is its current footprint.", o[2]);
Assert.Contains("Latest MB is its last observed footprint", o[3]);
Assert.StartsWith("No memory clerk capture in the window: the collector wrote nothing", o[4]);
Assert.Contains("The memory clerks collector stores the top 25 clerks over 1 MB per capture", o[5]);
foreach (var line in o)
{
Assert.DoesNotContain("_left_out", line);
Assert.DoesNotContain("baseline_start", line);
Assert.DoesNotContain("effective_start", line);
Assert.DoesNotContain("_mb is", line);
Assert.DoesNotContain("memory_clerks", line);
Assert.DoesNotContain("(s)", line);
}
}

/* #6649: a count can be negative or have a fraction, and either ended the run of pairs, so the whole note stayed raw. */
[Fact]
public void ACountRunWithANegativeOrFractionalValue_StillReadsAsWords()
{
var o = Run(
[
"latest run: plans_rendered=0 plans_rendered_bytes=-12 plan_fetch_ms=0.5 deferred_hit=0",
"latest run: ring_buffer_truncated=1 ring_buffer_events_hidden=167 newest_visible_event_age_s=4300 statement_scrub_named=0",
], out _);
Assert.Equal("latest run: plans rendered: 0, plans rendered bytes: -12, plan fetch ms: 0.5, deferred hit: 0", o[0]);
Assert.DoesNotContain("=", o[0]);
Assert.DoesNotContain("=0 ", o[1] + " ");
Assert.DoesNotContain("=", o[1]);
}

/* #6649: the collection log's Error cell holds a failed run's error and a successful run's note. The note's counts are said in
words; a real error message keeps everything else, a lone key=value pair and any tool-looking word included. */
[Fact]
public void TheCollectionLogMessage_SaysItsCountsInWords_AndLeavesAnErrorAlone()
{
var (_, _, _, _, _, counts) = RunDoc(
[
"ring_buffer_truncated=1 ring_buffer_events_hidden=167 newest_visible_event_age_s=4300",
"Connection failed (timeout=30): relation \"get_orders\" is not available; widen hours_back",
], out _);
Assert.Equal("ring buffer truncated: 1, ring buffer events hidden: 167, newest visible event age s: 4300", counts[0]);
Assert.Equal("Connection failed (timeout=30): relation \"get_orders\" is not available; widen the time range", counts[1]);
}

/* #5644 W8 (live check): the CPU and Memory pages have no bucket control, the Waits and Activity notes print raw field names, and a
window count printed "24 hour(s)". */
[Fact]
Expand Down Expand Up @@ -224,7 +289,7 @@ public void TheNamedRules_TouchOnlyTheNamedTokens()
"column \"last_error\" of relation \"x\" does not exist",
"denied_since_last_success is true; move as_of or widen days_back",
];
var (_, named, _, _, _) = RunDoc(inputs, out _);
var (_, named, _, _, _, _) = RunDoc(inputs, out _);
Assert.Equal("Could not find 'dbo.get_orders' (timeout=30); widen the time range or use get_collection_health", named[0]);
/* Round-2 L1: a Last Error can quote a real relation or column, so field and table names are not rewritten here. */
Assert.Equal("latest run: events_read=4 shred_gated=1 and last_error shows it", named[1]);
Expand Down Expand Up @@ -293,15 +358,15 @@ public void CapitalsForEmphasis_AreLowerCased_AndAcronymsWaitTypesAndNamesAreNot
[Fact]
public void ThePlainNamedPath_NeverLowerCasesOrDropsAnything()
{
var (_, named, _, _, _) = RunDoc(["Last error: DID NOT connect; try analyze_server"], out _);
var (_, named, _, _, _, _) = RunDoc(["Last error: DID NOT connect; try analyze_server"], out _);
Assert.Equal("Last error: DID NOT connect; try analyze_server", named[0]);
}

[Fact]
public void TheToolNameList_IsExactlyTheRegisteredGetTools()
{
/* The get_ rule rewrites only these names, so the list must be the MCP tool registry's get_ tools, both ways. */
var (_, _, tools, _, actions) = RunDoc([], out _);
var (_, _, tools, _, actions, _) = RunDoc([], out _);
if (tools.Length == 0)
{
return;
Expand Down Expand Up @@ -330,7 +395,7 @@ public void TheToolNameList_IsExactlyTheRegisteredGetTools()
[Fact]
public void TheMeasurementLabelList_CoversEveryLabelTheCollectorsWrite()
{
var (_, _, tools, labels, _) = RunDoc([], out _);
var (_, _, tools, labels, _, _) = RunDoc([], out _);
if (tools.Length == 0)
{
return;
Expand Down
17 changes: 17 additions & 0 deletions Darling/Darling.Tests/web-clamp-cell-harness.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,21 @@ out.alertDetail = {
sqlLine: "Blocked Query: SELECT * FROM t WHERE d = '2026-01-01 00:00:00Z'",
};

/* #6649: the cell's `plain` modes through the shared renderer. "counts" (the Collection Log's Error column) says the measurement counts in
words and leaves a tool name in a real error message; true is the full pass (a tool name becomes its tab); "named" puts only the
named tokens into words; no key prints as stored. */
const modeNote = "Connection failed (timeout=30): ring_buffer_truncated=1 ring_buffer_events_hidden=167 newest_visible_event_age_s=4300; ask get_collection_health for hours_back";
const pm = VIZ.table({ rows: [{ note: modeNote }] }, {
rowsKey: "rows", title: "Plain modes", tools: false,
columns: [
{ key: "note", label: "Counts", wrap: true, plain: "counts" },
{ key: "note", label: "Full", wrap: true, plain: true },
{ key: "note", label: "Named", wrap: true, plain: "named" },
{ key: "note", label: "As stored", wrap: true },
],
});
const pmr = pm.findAll((n) => n.tag === "tr").filter((n) => n.parent && n.parent.tag === "tbody")[0];
const pmt = pmr.children.map((c) => c.textContent);
out.plainModes = { raw: modeNote, counts: pmt[0], full: pmt[1], named: pmt[2], asStored: pmt[3] };

console.log(JSON.stringify(out));
7 changes: 6 additions & 1 deletion Darling/Darling.Tests/web-partial-window-harness.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* #5644 W12: runs the web dashboard's real windowFloorStrip, cappedReadNote, partialWindowSubtitle and markPartialSubtitle (wwwroot/js/util.js)
on a small fake DOM and prints what each drew as one line of JSON. WebPartialWindowBehaviourTests starts it as
node web-partial-window-harness.mjs <path to the js folder>
node web-partial-window-harness.mjs <path to the js folder> [a collection-history audit alert body]
Only the DOM is a stand-in; util.js is the shipped module. */
import { pathToFileURL } from "node:url";

Expand Down Expand Up @@ -113,6 +113,8 @@ const alertBody = [
"",
"Newest blocked process sample: 23:12:45 UTC, 5m 20s old",
].join("\n");
/* the collection-history audit's body: the test passes CollectionHistoryAudit.Render's own output (one line of ". "-joined clauses) as argv[3] */
const auditBody = process.argv[3] ?? "";
const sample = { source: "blocked process", instant_utc: "2026-10-12T23:12:45.0000000Z", age_seconds: 320 };
out.h2 = {
spaceZ: localizeIsoText("until 2026-10-11 12:48:52Z"),
Expand All @@ -130,6 +132,9 @@ out.h2 = {
stripUtc: noticeStrip("until 2026-10-11 12:48:52Z").textContent,
here: { inc: here("2026-10-12T23:13:00Z"), fail: here("2026-10-12T07:00:00Z"), end: here("2026-10-12T08:00:00Z"), samp: here("2026-10-12T23:12:45Z") },
bodyRaw: alertBody,
auditBody: localizeAlertDetail(auditBody, null),
/* a later clause that a full plainText pass would rewrite: the audit's match must stop at the end of its own sentence */
auditBodyWithProbe: localizeAlertDetail(auditBody + " Probe: 29 database(s) were left out (see databases_left_out).", null),
};

console.log(JSON.stringify(out));
2 changes: 1 addition & 1 deletion Darling/Darling.Tests/web-plain-text-harness.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ import { pathToFileURL } from "node:url";
const jsDir = process.argv[process.argv.length - 1];
const mod = await import(pathToFileURL(path.join(jsDir, "plain-text.js")).href);
const inputs = JSON.parse(process.env.HARNESS_INPUT);
console.log(JSON.stringify({ out: inputs.map((t) => mod.plainText(t)), named: inputs.map((t) => mod.plainTextNamed(t)), line: mod.NOT_COLLECTED_LINE, tools: mod.MCP_TOOL_NAMES, labels: mod.MEASUREMENT_LABELS, actions: mod.MCP_ACTION_TOOL_NAMES }));
console.log(JSON.stringify({ out: inputs.map((t) => mod.plainText(t)), named: inputs.map((t) => mod.plainTextNamed(t)), counts: inputs.map((t) => mod.plainTextCounts(t)), line: mod.NOT_COLLECTED_LINE, tools: mod.MCP_TOOL_NAMES, labels: mod.MEASUREMENT_LABELS, actions: mod.MCP_ACTION_TOOL_NAMES }));
Loading
Loading