diff --git a/.claude/skills/build/SKILL.md b/.claude/skills/build/SKILL.md index 489cac9b60..febfcdf94b 100644 --- a/.claude/skills/build/SKILL.md +++ b/.claude/skills/build/SKILL.md @@ -1,7 +1,7 @@ --- name: build description: Build and locate the PerformanceMonitor executables -argument-hint: [lite|darling|viewer|dashboard|installer] +argument-hint: [lite|darling|viewer] disable-model-invocation: false --- @@ -18,11 +18,9 @@ Build a component of PerformanceMonitor and report the result. All paths are rel | `lite` | `Lite/PerformanceMonitorLite.csproj` | `net10.0-windows` | | `darling` or `service` | `Darling/PerformanceMonitor.Darling.Service/PerformanceMonitor.Darling.Service.csproj` | `net10.0` | | `viewer` | `Darling/PerformanceMonitor.Darling.Viewer/PerformanceMonitor.Darling.Viewer.csproj` | `net10.0-windows` | -| `dashboard` or `full` | `deprecated/Dashboard/Dashboard.csproj` | DEPRECATED since v3.3.0 | -| `installer` | `deprecated/Installer/PerformanceMonitorInstaller.csproj` | DEPRECATED since v3.3.0 | | (empty) | build whatever is in the current working directory, or ask | | -Lite, the Darling service, and the Darling Viewer are the shipping artifacts. The full Dashboard and the CLI Installer moved to `deprecated/` in v3.3.0. They still build and their tests still run in CI, but they ship no release artifacts and get bug-fix support only. +Lite, the Darling service, and the Darling Viewer are the shipping artifacts. The full Dashboard and the CLI Installer are frozen in `deprecated/dashboard-installer-source.zip`. Nothing builds, tests or releases them from this repository, so there is no `dashboard` or `installer` argument. `deprecated/README.md` says how to build them from the zip. ## Steps diff --git a/.claude/skills/release-checklist/SKILL.md b/.claude/skills/release-checklist/SKILL.md index 8a187c1d9e..4ecd0f7b9f 100644 --- a/.claude/skills/release-checklist/SKILL.md +++ b/.claude/skills/release-checklist/SKILL.md @@ -9,7 +9,7 @@ disable-model-invocation: false Run through the full release prep checklist for PerformanceMonitor. `$ARGUMENTS` is the target version (e.g., `3.3.0`). -> **Scope (since v3.3.0):** the Full Dashboard and the CLI Installer are DEPRECATED and OUT of this process — they ship no release artifacts and get no live install/upgrade testing here. The Darling service zip and the Linux tarball DO get live install and upgrade testing, in section 8a. They still build and their test suites still run in CI on the release event, and they inherit the single `` with everything else in the tree (below). The release artifacts are: Lite (zip + Velopack Setup.exe), the Darling service zip, and the Darling Viewer Setup.exe. +> **Scope (since v3.3.0):** the Full Dashboard and the CLI Installer are DEPRECATED and OUT of this process — they ship no release artifacts and get no live install/upgrade testing here. The Darling service zip and the Linux tarball DO get live install and upgrade testing, in section 8a. Their source is frozen in `deprecated/dashboard-installer-source.zip`: nothing builds or tests it in CI, and it does not take the single `` (below). The release artifacts are: Lite (zip + Velopack Setup.exe), the Darling service zip, and the Darling Viewer Setup.exe. ## Checklist @@ -68,7 +68,7 @@ Do NOT add internal/implementation changes — only user-facing features and beh ### 3. Upgrade Scripts — Schema Change Audit (conditional) -Applies ONLY when `install/` or `upgrades/` changed since the last release (the deprecated Dashboard edition remains on bug-fix support, so its schema discipline still holds when it IS touched): +Applies ONLY when `install/` or `upgrades/` changed since the last release. The frozen Dashboard in the zip reads this schema, so its schema discipline still holds when it IS touched: 1. All schema changes MUST go through the `upgrades/{from}-to-{to}/` folder — never ad hoc, never baked into base install scripts. View-only changes flow through `CREATE OR ALTER` re-runs and need no upgrade script. 2. **List all .sql files in the upgrade folder and compare against `upgrade.txt`.** A script that is not listed does not run. @@ -84,7 +84,7 @@ All projects must succeed with **0 Warning(s) / 0 Error(s)** — the repo's bar The statement-column census test fails while any entry or watched writer is pending, in every Darling test run, with or without the variable. Run `DARLING_RELEASE_CUT=1 Darling/Darling.Tests/bin/Debug/net10.0-windows/Darling.Tests.exe -method "*StatementCensus_PendingEntries_BlockARelease*"` to see the list early; the cut proceeds only when it passes. The release workflow (build.yml, the "Statement filter release gate" step) runs the same test with the variable set before it publishes or packages anything, so a release cannot ship while an entry is pending even if this step is skipped; run it here first to see the list early. -(The deprecated Installer/Dashboard test suites run in CI on the release event with the CI's own filter; they are no longer run from this checklist.) +(The frozen Installer and Dashboard test suites are not built or run anywhere. See `deprecated/README.md`.) ### 5. Cloud Platform Testing (shared collector layer — test via DARLING) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 7bf8234ff2..72af11b1d7 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -12,8 +12,6 @@ body: options: - Lite - Darling - - Full Dashboard (deprecated) - - Installer (deprecated) - SQL collection scripts validations: required: true @@ -40,7 +38,7 @@ body: id: windows-version attributes: label: Windows Version - description: The OS where the Lite, Darling, or Dashboard app is running. + description: The OS where the Lite or Darling app is running. placeholder: "e.g., Windows 11 23H2, Windows Server 2022" validations: required: true @@ -85,7 +83,7 @@ body: id: errors attributes: label: Error Messages / Log Output - description: Paste any error messages or relevant log entries. Dashboard logs are in %LOCALAPPDATA%\PerformanceMonitor\Logs\; Lite logs are in %LOCALAPPDATA%\PerformanceMonitorLite-Data\logs\ (on versions before the data-root move, %LOCALAPPDATA%\PerformanceMonitorLite\logs\); Darling logs are in %ProgramData%\PerformanceMonitorDarling\logs\. + description: Paste any error messages or relevant log entries. Lite logs are in %LOCALAPPDATA%\PerformanceMonitorLite-Data\logs\ (on versions before the data-root move, %LOCALAPPDATA%\PerformanceMonitorLite\logs\); Darling logs are in %ProgramData%\PerformanceMonitorDarling\logs\. render: text validations: required: false @@ -115,7 +113,6 @@ body: description: | Anything else that might help: - Did this work before? If so, what changed? - - Is SQL Server Agent running? (deprecated Full Dashboard edition only) - Are you monitoring Azure SQL DB, Azure MI, or AWS RDS? validations: required: false diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml index 4129a77a22..928229c0c1 100644 --- a/.github/ISSUE_TEMPLATE/question.yml +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -11,7 +11,6 @@ body: options: - Lite - Darling - - Full Dashboard (deprecated) - General / setup validations: required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 0663b11131..ce36c7283f 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -10,8 +10,6 @@ A clear description of the change and why it's being made. - [ ] Darling Tests - [ ] SQL collection scripts - [ ] Documentation -- [ ] Full Dashboard (deprecated) -- [ ] CLI Installer (deprecated) ## How was this tested? diff --git a/.github/scripts/ci-plan.py b/.github/scripts/ci-plan.py index f4c9807c52..7e7e5ef538 100644 --- a/.github/scripts/ci-plan.py +++ b/.github/scripts/ci-plan.py @@ -21,8 +21,6 @@ actionlint true when a workflow file changed check_web_js true when a dashboard JavaScript file changed pg_old_targets true when a pull request changed a file the old-PostgreSQL-target job covers (#6985, PG_OLD_TARGET_PATHS); never on a push, the nightly runs it - dashboard_tests true when the build job builds and runs deprecated/Dashboard.Tests (#6955): ci-select.py's build_dashboard_tests - installer_tests true when the build job builds and runs deprecated/Installer.Tests (#6955): ci-select.py's build_installer_tests The pattern sets are NOT copied here. The areas come from ci-select.py's Rules, which reads the docs allowlist and the area filters from the same files dorny/paths-filter reads, and the Lite-reads classes from ci-select.py's @@ -164,7 +162,7 @@ def changed_test_classes(rules, files: "list[str]", catalog: "dict | None") -> " def classify(rules, event: str, base: str, files: "list[str]", catalog: "dict | None" = None) -> dict: """The areas of one change: {areas, darling_scope, lite_scope, why}.""" - everything = {"areas": "all", "darling_scope": "full", "lite_scope": "full", "dashboard_tests": True, "installer_tests": True} + everything = {"areas": "all", "darling_scope": "full", "lite_scope": "full"} if event != "pull_request": return {**everything, "reason": f"a {event} runs every area."} if base != "dev": @@ -178,10 +176,9 @@ def classify(rules, event: str, base: str, files: "list[str]", catalog: "dict | return {**everything, "reason": f"no area knows {odd[0]}, so every area runs."} a = rules.areas(files) - area_names = ("root", "core", "installer_core", "dashboard", "lite", "installer", "darling") + area_names = ("root", "core", "lite", "darling") if a["all_count"] == a["docs_count"] and not any(a[n] for n in area_names): return {"areas": "docs-only", "darling_scope": "none", "lite_scope": "none", - "dashboard_tests": False, "installer_tests": False, "reason": "only documentation changed."} cs = _CS @@ -318,7 +315,7 @@ def plan(event: str, base: str, head_ref: str, draft: bool, labels: "list[str]", out = {"run": "true" if outcome == "run" else "false", "outcome": outcome, "why": why, "areas": "none", "darling_scope": "none", "lite_scope": "none", "build": "false", "darling_classes": "", "lite_classes": "", "test_minutes": "0", "legs": "0", "legs_json": "[]", - "actionlint": "false", "check_web_js": "false", "pg_old_targets": "false", "dashboard_tests": "false", "installer_tests": "false"} + "actionlint": "false", "check_web_js": "false", "pg_old_targets": "false"} if outcome != "run": return out @@ -331,14 +328,6 @@ def plan(event: str, base: str, head_ref: str, draft: bool, labels: "list[str]", out["actionlint"] = _bool(any(f.startswith(".github/workflows/") for f in files)) out["check_web_js"] = _bool(any(WEB_JS_MARKER in "/" + f for f in files)) out["pg_old_targets"] = _bool(event == "pull_request" and any(f.startswith(PG_OLD_TARGET_PATHS) for f in files)) - # A run that does not narrow (a push, another base, an unknown path) builds both; docs-only builds neither. Otherwise - # ci-select.py's decide() answers from the same areas the workflow's own filter reads (#6955). - if "dashboard_tests" in c: - out.update(dashboard_tests=_bool(c["dashboard_tests"]), installer_tests=_bool(c["installer_tests"])) - else: - d = _CS.decide(files, event, rules) - out.update(dashboard_tests=_bool(d["build_dashboard_tests"]), installer_tests=_bool(d["build_installer_tests"])) - if out["build"] == "true": catalog = catalog if catalog is not None else load_catalog() picks = {"darling": c.get("darling_classes", []), "lite": c.get("lite_classes", [])} diff --git a/.github/scripts/ci-select.py b/.github/scripts/ci-select.py index 10ed20bcf5..4d727ed0e3 100644 --- a/.github/scripts/ci-select.py +++ b/.github/scripts/ci-select.py @@ -271,12 +271,10 @@ def decide(files: list[str], event: str, rules: Rules) -> dict: release = event == "release" all_count, docs_count = a["all_count"], a["docs_count"] docs_only = all_count > 0 and all_count == docs_count - area_names = ("root", "core", "installer_core", "dashboard", "lite", "installer", "darling") + area_names = ("root", "core", "lite", "darling") fastpath = (not release) and docs_only and not any(a[n] for n in area_names) build_lite = release or a["lite"] or a["core"] or a["root"] - build_installer = release or a["installer"] or a["installer_core"] or a["root"] - build_dashboard = release or a["dashboard"] or a["core"] or a["installer_core"] or a["root"] build_darling = release or a["darling"] or a["core"] or a["root"] pg_run = (not release) and a["gate_darling"] @@ -290,8 +288,6 @@ def decide(files: list[str], event: str, rules: Rules) -> dict: "guard_run": (not release) and not docs_only, "docs_fastpath": fastpath, "build_lite_tests": build_lite, - "build_installer_tests": build_installer, - "build_dashboard_tests": build_dashboard, "build_darling_tests": build_darling, "darling_scope": darling_scope( event, build_darling, pg_run, release or a["darling_full"] or a["core"] or a["root"]), @@ -377,16 +373,12 @@ def _holders_of(lines: list[str]) -> set[str]: SUITE_DIRS = { "darling": os.path.join("Darling", "Darling.Tests"), "lite": "Lite.Tests", - "dashboard": os.path.join("deprecated", "Dashboard.Tests"), - "installer": os.path.join("deprecated", "Installer.Tests"), } SUITE_BY_PREFIX = { "Darling.Tests": "darling", "PerformanceMonitor.Darling.Tests": "darling", "Lite.Tests": "lite", "PerformanceMonitorLite.Tests": "lite", - "Dashboard.Tests": "dashboard", - "Installer.Tests": "installer", } @@ -557,10 +549,6 @@ def class_selected(suite: str, traits: set[str], d: dict) -> bool: if d["lite_mode"] in ("full", "release"): return True return d["lite_mode"] == "reads" and "Reads=Darling" in traits - if suite == "dashboard": - return d["build_dashboard_tests"] - if suite == "installer": - return d["build_installer_tests"] return True @@ -1568,7 +1556,7 @@ def git_drift(map_sha: str, base: str, root: str = ROOT) -> "list[str] | None": def selection_args(rules: Rules) -> dict: """The keep-full and documentation patterns, read from the same filters the workflow evaluates.""" keep = list(KEEP_FULL) - for name in ("root", "core", "installer_core"): + for name in ("root", "core"): # #5951: the shared projects are judged by map_select()'s shared_change_reason(), not as keep-full wholesale. keep.extend(p for p in rules.build.get(name, []) if not p.startswith(SHARED_PROJECT_DIRS)) return {"keep_full": tuple(dict.fromkeys(keep)), "doc_patterns": tuple(rules.build["docs"])} diff --git a/.github/scripts/tests/ci-plan-test.py b/.github/scripts/tests/ci-plan-test.py index 1a560b942f..c8cd413d40 100644 --- a/.github/scripts/tests/ci-plan-test.py +++ b/.github/scripts/tests/ci-plan-test.py @@ -37,14 +37,8 @@ def check(name, actual, expected): - 'global.json' core: - 'PerformanceMonitor.Common/**/!(*.md)' - installer_core: - - 'PerformanceMonitor.Installer/**/!(*.md)' - dashboard: - - 'deprecated/Dashboard/**/!(*.md)' lite: - 'Lite/**/!(*.md)' - installer: - - 'deprecated/Installer/**/!(*.md)' darling: - 'Darling/**/!(*.md)' - 'Lite/**/*.xaml' @@ -172,20 +166,6 @@ def run(files, event="pull_request", base="dev", head="feature/x", draft=False, r = run(["global.json"]) check("root build file: all", r["areas"], "all") -r = run(["deprecated/Installer/X.cs"]) -check("deprecated only: no area", r["areas"], "none") -check("deprecated only: builds, no legs", (r["build"], r["legs"]), ("true", "0")) -check("deprecated installer file: installer tests only", (r["installer_tests"], r["dashboard_tests"]), ("true", "false")) -r = run(["deprecated/Dashboard/X.cs"]) -check("deprecated dashboard file: dashboard tests only", (r["dashboard_tests"], r["installer_tests"]), ("true", "false")) -check("shared library: dashboard tests, not installer tests", (run(["PerformanceMonitor.Common/X.cs"])["dashboard_tests"], - run(["PerformanceMonitor.Common/X.cs"])["installer_tests"]), ("true", "false")) -check("darling file only: neither suite", (run(["Darling/X.cs"])["dashboard_tests"], run(["Darling/X.cs"])["installer_tests"]), - ("false", "false")) -check("docs only: neither suite", (run(["README.md"])["dashboard_tests"], run(["README.md"])["installer_tests"]), ("false", "false")) -check("unknown path: both suites", (run(["tools/odd.txt"])["dashboard_tests"], run(["tools/odd.txt"])["installer_tests"]), - ("true", "true")) - # --- all areas ------------------------------------------------------------------------------------------------- r = run(["tools/odd.txt"]) check("unknown path: all", (r["areas"], r["darling_scope"], r["lite_scope"]), ("all", "full", "full")) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f605fb6dd5..0b80bcbfcf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -65,9 +65,9 @@ jobs: - 'nuget.config' - 'NuGet.config' - '.github/workflows/build.yml' - # The shared PerformanceMonitor.* core libraries feed Lite, the Full Dashboard, AND - # Darling (verified via ProjectReference), so a change here fans out to all three. - # NOT the CLI Installer — it references only Installer.Core. + # The shared PerformanceMonitor.* core libraries feed Lite AND Darling (verified via + # ProjectReference), so a change here fans out to both. The deprecated Dashboard and Installer + # are frozen as a zip under deprecated/ and are no longer built or tested (#6973). # # Every area pattern says `dir/**/!(*.md)` — any non-markdown file under the # area — instead of the old `dir/**` include plus a bare `!**/*.md` exclude. @@ -89,17 +89,6 @@ jobs: - 'PerformanceMonitor.Notifications/**/!(*.md)' - 'PerformanceMonitor.PlanAnalysis/**/!(*.md)' - 'PerformanceMonitor.Ui/**/!(*.md)' - # Installer.Core is shared by the CLI Installer AND the Full Dashboard's integrated - # installer — a change rebuilds both, and nothing else. - installer_core: - - 'deprecated/Installer.Core/**/!(*.md)' - dashboard: - - 'deprecated/Dashboard/**/!(*.md)' - - 'deprecated/Dashboard.Tests/**/!(*.md)' - # ThemeParityTests compares the Dashboard's theme files with Lite's, so a change to Lite's - # themes alone must run it too. #4658 changed a Lite theme color, its CI skipped the test, - # and the next run that included it failed on dev (#4668). - - 'Lite/Themes/**/!(*.md)' lite: - 'Lite/**/!(*.md)' - 'Lite.Tests/**/!(*.md)' @@ -107,8 +96,8 @@ jobs: - '.github/scripts/run-lite-shard.ps1' - '.github/scripts/lite-shard-pack.py' # #5656: Lite.Tests pins read install/ scripts as source (CpuSchedulerStatsCollectorDefinitionTests reads install/17, - # DmvResourceDatabaseSentinelTests reads install/56). A PR that edits only an install script fires `installer` - # and `sql-validation`, neither of which runs Lite.Tests, so the nightly would be the first to catch drift. + # DmvResourceDatabaseSentinelTests reads install/56). A PR that edits only an install script fires + # `sql-validation`, which does not run Lite.Tests, so the nightly would be the first to catch drift. - 'install/**/!(*.md)' # Lite.Tests.csproj compiles tools/ui-smoke-wpf/LiteSeedGuard.cs into its own assembly and tests it, so an edit to that tree has to reach the Lite suite. - 'tools/ui-smoke-wpf/**/!(*.md)' @@ -151,11 +140,6 @@ jobs: # drift the pin exists to close. A diff that reaches only these three Darling trees runs just # the Lite.Tests classes tagged Reads=Darling, in one shard (the lite-tests job's scope step). - 'Darling/PerformanceMonitor.Darling.Service/**/!(*.md)' - installer: - - 'deprecated/Installer/**/!(*.md)' - - 'deprecated/Installer.Tests/**/!(*.md)' - - 'install/**/!(*.md)' - - 'upgrades/**/!(*.md)' darling: - 'Darling/**/!(*.md)' # nightly.yml is not a build input, but Darling.Tests PARSES it: the #1888 @@ -221,7 +205,7 @@ jobs: # not a "everything that isn't code" subtraction — a new file type defaults # to being treated as code, which is the safe direction to be wrong in. # - # NOT here, on purpose: *.sql (the installer and sql-validation compile it), + # NOT here, on purpose: *.sql (sql-validation runs it), # *.yml (workflows), *.csproj / *.props / packages.lock.json (build inputs), # and *.cs regardless of how comment-only the change looks — an XML doc # comment still recompiles, and the compiler is what proves it still builds. @@ -287,7 +271,7 @@ jobs: ALL_COUNT: ${{ steps.filter.outputs.all_count }} DOCS_COUNT: ${{ steps.filter.outputs.docs_count }} DOCS_FILES: ${{ steps.filter.outputs.docs_files }} - AREAS: 'root=${{ steps.filter.outputs.root }} core=${{ steps.filter.outputs.core }} installer_core=${{ steps.filter.outputs.installer_core }} dashboard=${{ steps.filter.outputs.dashboard }} lite=${{ steps.filter.outputs.lite }} installer=${{ steps.filter.outputs.installer }} darling=${{ steps.filter.outputs.darling }}' + AREAS: 'root=${{ steps.filter.outputs.root }} core=${{ steps.filter.outputs.core }} lite=${{ steps.filter.outputs.lite }} darling=${{ steps.filter.outputs.darling }}' run: | set -euo pipefail @@ -351,23 +335,14 @@ jobs: # check passed carrying `error NU1004` in its own log, and the only job that went red was # darling-tree-guards, whose restore is a single-command step. # - # Every project with a committed lock file bar one is reached from this list, directly or through a + # Every project with a committed lock file is reached from this list, directly or through a # ProjectReference — a locked-mode restore validates the lock file of every project in the graph it - # walks, not only the one it was handed. The exception is deprecated/Installer, and it is deliberate. - # That project is the only one publishing single-file, so the SDK adds an implicit - # Microsoft.NET.ILLink.Tasks reference at the SDK's OWN version, and its lock file is the only one - # carrying that entry; global.json rolls forward across patches, so a runner on 10.0.303 wants - # [10.0.11, ) where a file written under 10.0.302 records [10.0.10, ). No restore line makes that file - # right for both, and nothing references the project, so nothing else reaches it either: a restore - # pointed at it reports NU1004 from dev today, with no dependency change involved (#3143). Whether it - # should carry a lock file at all, and whether global.json should pin the SDK exactly, are decisions. + # walks, not only the one it was handed. # - # LockedModeRestoreCoverageTests derives both requirements — from the lock files on disk and the - # reference edges between projects — so a tenth lock file makes its restore mandatory rather than - # remembered, and re-spelling this block in a shell that swallows failures fails the suite. It derives - # the exception from the SDK coupling too, and ratchets its membership, so pinning the SDK exactly - # makes this restore mandatory and a second project taking an SDK-coupled reference fails rather than - # joining the exemption quietly. + # LockedModeRestoreCoverageTests derives that requirement from the lock files on disk and the + # reference edges between projects, so a new lock file makes its restore mandatory rather than + # remembered, and re-spelling this block in a shell that swallows failures fails the suite. It also + # ratchets the set of lock files an SDK-coupled package excuses; that set is empty (#6973). - name: Restore dependencies if: steps.fastpath.outputs.engaged != 'true' shell: bash @@ -384,8 +359,6 @@ jobs: dotnet restore Lite/PerformanceMonitorLite.csproj --locked-mode dotnet restore Lite.Tests/Lite.Tests.csproj --locked-mode - dotnet restore deprecated/Installer.Tests/Installer.Tests.csproj --locked-mode - dotnet restore deprecated/Dashboard.Tests/Dashboard.Tests.csproj --locked-mode dotnet restore Darling/Darling.Tests/Darling.Tests.csproj --locked-mode dotnet restore Darling/PerformanceMonitor.Darling.Viewer/PerformanceMonitor.Darling.Viewer.csproj --locked-mode dotnet restore tools/ui-smoke-wpf/UiSmokeWpf.csproj --locked-mode @@ -394,21 +367,6 @@ jobs: if: steps.filter.outputs.lite == 'true' || steps.filter.outputs.core == 'true' || steps.filter.outputs.root == 'true' || github.event_name == 'release' run: dotnet build Lite.Tests/Lite.Tests.csproj -c Release --no-restore - - name: Build Installer.Tests - if: steps.filter.outputs.installer == 'true' || steps.filter.outputs.installer_core == 'true' || steps.filter.outputs.root == 'true' || github.event_name == 'release' - run: dotnet build deprecated/Installer.Tests/Installer.Tests.csproj -c Release --no-restore - - # The 'dashboard' path filter was defined when the Full Dashboard moved to deprecated/ (#1612) but - # never wired to a step, so its build and tests silently stopped running — which is how a batch of - # compiler warnings and three broken ThemeParityTests accumulated unnoticed (#1643). Deprecated means - # bug-fix-only, not unverified: it still compiles warning-free and its tests still guard cross-app - # parity (the theme palettes it checks are LITE's too). - # installer_core too: the Dashboard references Installer.Core, and the filter's own comment says a - # change there rebuilds both products, which only held for the CLI Installer until now. - - name: Build Dashboard.Tests - if: steps.filter.outputs.dashboard == 'true' || steps.filter.outputs.core == 'true' || steps.filter.outputs.installer_core == 'true' || steps.filter.outputs.root == 'true' || github.event_name == 'release' - run: dotnet build deprecated/Dashboard.Tests/Dashboard.Tests.csproj -c Release --no-restore - - name: Build Darling if: steps.filter.outputs.darling == 'true' || steps.filter.outputs.core == 'true' || steps.filter.outputs.root == 'true' || github.event_name == 'release' run: | @@ -451,14 +409,6 @@ jobs: retention-days: 7 if-no-files-found: ignore - - name: Run Installer tests - if: steps.filter.outputs.installer == 'true' || steps.filter.outputs.installer_core == 'true' || steps.filter.outputs.root == 'true' || github.event_name == 'release' - run: dotnet run --project deprecated/Installer.Tests/Installer.Tests.csproj -c Release --no-build -- -class- "Installer.Tests.VersionDetectionTests" -class- "Installer.Tests.IdempotencyTests" -class- "Installer.Tests.AdversarialTests" - - - name: Run Dashboard tests - if: steps.filter.outputs.dashboard == 'true' || steps.filter.outputs.core == 'true' || steps.filter.outputs.installer_core == 'true' || steps.filter.outputs.root == 'true' || github.event_name == 'release' - run: dotnet run --project deprecated/Dashboard.Tests/Dashboard.Tests.csproj -c Release --no-build - # #5459 cut 3b: the PostgreSQL shards run EVERY Darling.Tests class, with a live store, whenever the Darling # gate matches (the same .github/darling-paths-filter.yml the darling-pg job reads). This no-store pass would # repeat their non-live classes, so while the shards run it keeps only the Stage=Guard classes. Where the gate diff --git a/.github/workflows/check-version-bump.yml b/.github/workflows/check-version-bump.yml index 85afcc9d02..5dbb0a31be 100644 --- a/.github/workflows/check-version-bump.yml +++ b/.github/workflows/check-version-bump.yml @@ -62,12 +62,7 @@ jobs: id: main shell: pwsh run: | - # main does not carry Directory.Build.props until the release that centralises the - # version (#3222) lands there, so fall back to deprecated/Dashboard/Dashboard.csproj, - # which is where main declares its version. That release PR has to be able to pass - # against a main that predates the file. Removable once main has it. $path = 'main-branch/Directory.Build.props' - if (-not (Test-Path $path)) { $path = 'main-branch/deprecated/Dashboard/Dashboard.csproj' } $version = ([xml](Get-Content $path)).Project.PropertyGroup.Version | Where-Object { $_ } # Two empty reads compare EQUAL, so an unguarded pair fails this gate for the wrong reason # while one empty side passes it for the wrong reason. diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index aedb05eec1..7a45f71bf0 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -48,9 +48,7 @@ jobs: darling_classes: ${{ steps.plan.outputs.darling_classes }} lite_classes: ${{ steps.plan.outputs.lite_classes }} build: ${{ steps.plan.outputs.build }} - dashboard_tests: ${{ steps.plan.outputs.dashboard_tests }} pg_old_targets: ${{ steps.plan.outputs.pg_old_targets }} - installer_tests: ${{ steps.plan.outputs.installer_tests }} legs: ${{ steps.plan.outputs.legs }} legs_json: ${{ steps.plan.outputs.legs_json }} steps: @@ -195,59 +193,6 @@ jobs: dotnet build Lite.Tests/Lite.Tests.csproj -c Release --no-restore - # #6955: the Dashboard and Installer test projects used to run only on a published release, so a shared-code change that - # broke one of their test copies was first caught after the tag. They run here, in the build job, because the whole - # Dashboard suite takes seconds and the Installer run (the filter build.yml uses) about as long. A red step turns this job red, - # and the verdict job turns that into a failed `CI result`. The plan's dashboard_tests and installer_tests come from - # ci-select.py's build_dashboard_tests and build_installer_tests, the rule build.yml's own filters follow. - - name: Restore the Dashboard test project - if: ${{ needs.plan.outputs.dashboard_tests == 'true' }} - shell: bash - run: | - set -euo pipefail - - dotnet restore deprecated/Dashboard.Tests/Dashboard.Tests.csproj --locked-mode - - - name: Build the Dashboard test project - if: ${{ needs.plan.outputs.dashboard_tests == 'true' }} - shell: bash - run: | - set -euo pipefail - - dotnet build deprecated/Dashboard.Tests/Dashboard.Tests.csproj -c Release --no-restore - - - name: Run Dashboard tests - if: ${{ needs.plan.outputs.dashboard_tests == 'true' }} - shell: bash - run: | - set -euo pipefail - - dotnet run --project deprecated/Dashboard.Tests/Dashboard.Tests.csproj -c Release --no-build - - - name: Restore the Installer test project - if: ${{ needs.plan.outputs.installer_tests == 'true' }} - shell: bash - run: | - set -euo pipefail - - dotnet restore deprecated/Installer.Tests/Installer.Tests.csproj --locked-mode - - - name: Build the Installer test project - if: ${{ needs.plan.outputs.installer_tests == 'true' }} - shell: bash - run: | - set -euo pipefail - - dotnet build deprecated/Installer.Tests/Installer.Tests.csproj -c Release --no-restore - - - name: Run Installer tests - if: ${{ needs.plan.outputs.installer_tests == 'true' }} - shell: bash - run: | - set -euo pipefail - - dotnet run --project deprecated/Installer.Tests/Installer.Tests.csproj -c Release --no-build -- -class- "Installer.Tests.VersionDetectionTests" -class- "Installer.Tests.IdempotencyTests" -class- "Installer.Tests.AdversarialTests" - # Where this build was made and from what, for the legs' check. No dot-prefix (upload-artifact skips hidden files). - name: Record where this build was made shell: pwsh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 51ab6e5a87..750e07baf8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,15 +18,13 @@ Thank you for your interest in contributing to the SQL Server Performance Monito This repository contains three editions of the SQL Server Performance Monitor: -**Full Edition (deprecated)** — server-installed collectors with a separate dashboard. The Full Dashboard and the CLI installer are deprecated. No release since v3.3.0 includes them, and their last builds are in the [v3.2.0 release](https://github.com/erikdarlingdata/PerformanceMonitor/releases/tag/v3.2.0). They still build from this repository and are supported for existing users. New deployments use Lite or Darling. +**Full Edition (deprecated)** — server-installed collectors with a separate dashboard. The Full Dashboard and the CLI installer are deprecated. No release since v3.3.0 includes them, and their last builds are in the [v3.2.0 release](https://github.com/erikdarlingdata/PerformanceMonitor/releases/tag/v3.2.0). Their source is frozen in [`deprecated/dashboard-installer-source.zip`](deprecated/README.md): nothing in this repository builds, tests or releases it. New deployments use Lite or Darling. | Folder | Description | |--------|-------------| | `install/` | 50+ T-SQL scripts that create the PerformanceMonitor database | | `upgrades/` | Version-specific upgrade scripts for that database | -| `deprecated/Installer/` | CLI installer for the Full Edition database and collectors | -| `deprecated/Installer.Core/` | Shared installation library (used by CLI installer and Dashboard) | -| `deprecated/Dashboard/` | WPF dashboard — connects to PerformanceMonitor database, can also install/upgrade via Add Server | +| `deprecated/` | One frozen zip holding the Full Dashboard, the CLI installer and their tests. See [`deprecated/README.md`](deprecated/README.md) | **Lite Edition** — standalone desktop app, nothing installed on the target server: @@ -71,15 +69,9 @@ PostgreSQL. git clone https://github.com/erikdarlingdata/PerformanceMonitor.git cd PerformanceMonitor -# Build Full Dashboard (deprecated) -dotnet build deprecated/Dashboard/Dashboard.csproj - # Build Lite Edition dotnet build Lite/PerformanceMonitorLite.csproj -# Build CLI Installer (deprecated, self-contained) -dotnet publish deprecated/Installer/PerformanceMonitorInstaller.csproj -c Release - # Build Darling (headless service, then the viewer) dotnet build Darling/PerformanceMonitor.Darling.Service/PerformanceMonitor.Darling.Service.csproj dotnet build Darling/PerformanceMonitor.Darling.Viewer/PerformanceMonitor.Darling.Viewer.csproj @@ -88,11 +80,6 @@ dotnet build Darling/PerformanceMonitor.Darling.Viewer/PerformanceMonitor.Darlin ### Running the Applications -**Full Dashboard (deprecated):** -1. Install the database on a SQL Server instance using the CLI installer in `deprecated/Installer/` -2. Run `deprecated/Dashboard/bin/Debug/net10.0-windows/PerformanceMonitorDashboard.exe` -3. Add your server connection and start monitoring - **Lite Edition:** 1. Run `Lite/bin/Debug/net10.0-windows/PerformanceMonitorLite.exe` 2. Add a SQL Server connection (requires VIEW SERVER STATE permission) @@ -109,7 +96,7 @@ dotnet build Darling/PerformanceMonitor.Darling.Viewer/PerformanceMonitor.Darlin ### Full Dashboard Architecture (deprecated) -The Full Edition is deprecated, so this guide does not describe its architecture in detail. It installs a `PerformanceMonitor` database on the monitored SQL Server. T-SQL collectors in that database run under SQL Agent, and the Full Dashboard in `deprecated/Dashboard/` reads the data. The scripts are in `install/`. See [`deprecated/Dashboard/README.md`](deprecated/Dashboard/README.md) for the details. +The Full Edition is deprecated, so this guide does not describe its architecture in detail. It installs a `PerformanceMonitor` database on the monitored SQL Server. T-SQL collectors in that database run under SQL Agent, and the Full Dashboard reads the data. The scripts are in `install/`. The Full Dashboard and the CLI installer are frozen in a zip, and [`deprecated/README.md`](deprecated/README.md) says what is in it and how to build it. **Key insight:** T-SQL collectors run independently from the C# Dashboard. You can modify collectors without touching C# code, and vice versa. @@ -218,17 +205,16 @@ the extension is present, so the same store works on plain PostgreSQL. |------|------------|-------| | **Full Edition T-SQL collectors (deprecated)** | Low | Clean, self-contained stored procedures | | **Full Edition reporting views (deprecated)** | Low | SQL views in `install/47_create_reporting_views.sql` | -| **Full Dashboard UI improvements (deprecated)** | Medium | WPF/C# in `deprecated/Dashboard/ServerTab.xaml*` | | **Lite UI improvements** | Medium | WPF/C# in `Lite/Controls/ServerTab.xaml*` | | **Bug fixes (any edition)** | Varies | Always welcome | | **Documentation** | Low | README, comments, troubleshooting guides | -| **MCP tool improvements** | Medium | `Lite/Mcp/`, `Darling/PerformanceMonitor.Darling.Service/Mcp/` or `deprecated/Dashboard/Mcp/` | +| **MCP tool improvements** | Medium | `Lite/Mcp/`, `Darling/PerformanceMonitor.Darling.Service/Mcp/` | | **New Lite collectors** | **High** | See warning below | | **Darling schema migrations** | **High** | Four coordinated edits — see below | ### Adding a New Full Edition Collector (deprecated) -The Full Edition is deprecated but still supported for existing users. This is its cleanest contribution path. You need to: +The Full Edition is deprecated. The CLI installer that deployed its T-SQL is frozen in the zip, so this repository's build cannot deploy a change to it. The scripts stay in `install/`. If you still edit one, you need to: 1. **Create the collection table** in `install/02_create_tables.sql` 2. **Create the collector procedure** in a new file `install/XX_collect_your_collector.sql` @@ -485,14 +471,6 @@ Use the troubleshooting scripts: - `install/99_installer_troubleshooting.sql` - Quick health check - `install/99_user_troubleshooting.sql` - Detailed diagnostics -### Testing Full Dashboard Changes (deprecated) - -1. Build and run the Full Dashboard from `deprecated/Dashboard/` -2. Connect to a test SQL Server with PerformanceMonitor installed -3. Verify your changes appear correctly -4. Test with different time ranges -5. Check that CSV export still works (right-click any grid) - ### Testing Lite Changes 1. Build and run the Lite application diff --git a/Darling/Darling.Tests/AlertDeliveryChannelTests.cs b/Darling/Darling.Tests/AlertDeliveryChannelTests.cs index c933a371f5..54952371b6 100644 --- a/Darling/Darling.Tests/AlertDeliveryChannelTests.cs +++ b/Darling/Darling.Tests/AlertDeliveryChannelTests.cs @@ -654,7 +654,7 @@ public void TheTwoSkus_DivergeOnExactlyOneStoredCombination() /// reaching for it fails here instead of quietly reintroducing #3169. /// [Fact] - public void TheLegacyHatch_HasExactlyOneProductionCaller() + public void TheLegacyHatch_HasNoProductionCaller() { var root = RepoRoot(); var callers = new List(); @@ -686,7 +686,8 @@ public void TheLegacyHatch_HasExactlyOneProductionCaller() callers.Add(relative); } - Assert.Equal(new[] { "deprecated/Dashboard/Services/EmailAlertService.cs" }, callers.OrderBy(c => c).ToArray()); + /* The one caller was the deprecated Dashboard's EmailAlertService, now frozen in a zip (#6973). */ + Assert.Empty(callers); } /* ─────────────── helpers ─────────────── */ diff --git a/Darling/Darling.Tests/LockedModeRestoreCoverageTests.cs b/Darling/Darling.Tests/LockedModeRestoreCoverageTests.cs index 15e4b57bd8..8fb5ff464c 100644 --- a/Darling/Darling.Tests/LockedModeRestoreCoverageTests.cs +++ b/Darling/Darling.Tests/LockedModeRestoreCoverageTests.cs @@ -31,21 +31,21 @@ namespace Darling.Tests; /// with error NU1004 in its own log, and the only job that went red was the one whose restore is a /// single-command step. /// -/// And one lock file was reached by nothing. deprecated/Installer carries a lock file, is +/// And one lock file was reached by nothing. The deprecated Installer carried a lock file, was /// referenced by no project, and was restored by no workflow. Measured rather than reasoned: perturbing that -/// file left all six restores CI ran green, and failed only a direct restore of that project. +/// file left all six restores CI ran green, and failed only a direct restore of that project. The project is +/// now frozen in a zip (#6973), so no lock file is exempt today and the ratchet below holds the set empty. /// /// Coverage is derived, not listed. The requirement comes from the lock files on disk and the /// ProjectReference edges between projects, so a tenth lock file arriving makes its restore mandatory /// instead of remembered. A referenced project's own lock file IS validated by a locked-mode restore of the -/// referencing project — verified against NuGet by perturbing Installer.Core's lock file and watching -/// a locked-mode restore of Installer.Tests fail NU1004 — so the closure arm encodes measured -/// behaviour rather than an assumption about it. +/// referencing project — verified against NuGet by perturbing a referenced project's lock file and watching +/// a locked-mode restore of the project that references it fail NU1004 — so the closure arm encodes +/// measured behaviour rather than an assumption about it. /// /// Where this runs. Its inputs span the whole repository — every lock file, every project /// file, global.json, Directory.Packages.props, both workflows — so no area path filter -/// reaches them, and deprecated/Installer in particular belongs to installer alone while the -/// step that runs this suite is gated on darling. Coverage therefore rests on +/// reaches them, and the step that runs this suite is gated on darling. Coverage therefore rests on /// darling-tree-guards, which runs the whole suite exactly when the darling filter did not /// fire — the backstop CrossAppGuardCiGateTests documents and whose gate it pins. Growing a filter /// to name these paths instead would be a hand-maintained copy of a whole-tree input set, and the honest @@ -74,11 +74,12 @@ public sealed class LockedModeRestoreCoverageTests /// /// The lock files that cannot be validated in locked mode while the SDK patch floats — held as a ratchet - /// on the DERIVED set below, not as the requirement itself. Without the ratchet, a project newly + /// on the DERIVED set below, not as the requirement itself. Empty since the deprecated Installer, the one + /// project that published single-file, was frozen into a zip (#6973). Without the ratchet, a project newly /// publishing single-file would take the exemption silently, which is the same shape of quiet widening /// this class exists to stop. /// - private static readonly string[] s_sdkCoupledLockFiles = { "deprecated/Installer" }; + private static readonly string[] s_sdkCoupledLockFiles = Array.Empty(); /// /// The text of a dotnet restore and what it names, deliberately broad: any line carrying the @@ -232,15 +233,8 @@ public void EveryCommittedLockFile_IsReachedByALockedModeRestoreInTheBuildWorkfl report perfect coverage. */ var lockFiles = LockFileDirectories(); Assert.Contains("Darling/Darling.Tests", lockFiles); - Assert.Contains("deprecated/Installer", lockFiles); Assert.NotEmpty(RestoredProjects(buildYaml)); - /* The closure arm carries real weight in the tree as it stands, rather than being a spare wheel that - would never turn: deprecated/Dashboard holds a lock file, is named by no restore line in the - workflow, and is covered only because Dashboard.Tests references it. */ - Assert.DoesNotContain("dotnet restore deprecated/Dashboard/Dashboard.csproj", buildYaml, StringComparison.Ordinal); - Assert.DoesNotContain("deprecated/Dashboard", UncoveredLockFiles(buildYaml, globalJson)); - var uncovered = UncoveredLockFiles(buildYaml, globalJson); Assert.True( @@ -254,11 +248,10 @@ report perfect coverage. */ /// /// The lock files exempt from that requirement are exactly the ones whose contents follow the SDK, and - /// there is one. + /// there are none. /// - /// Why an exemption exists at all. deprecated/Installer is the only project - /// publishing single-file, so the SDK adds an implicit Microsoft.NET.ILLink.Tasks reference at the - /// version bundled with whichever SDK ran the restore. global.json rolls forward across patches, + /// Why an exemption exists at all. A project publishing single-file gets an implicit + /// Microsoft.NET.ILLink.Tasks reference at the version bundled with whichever SDK ran the restore. global.json rolls forward across patches, /// so a runner on 10.0.303 wants [10.0.11, ) where a lock file written under 10.0.302 records /// [10.0.10, ). No restore line can make that file right for both, and nothing had restored the /// project, so the drift accumulated unseen until #3143 pointed a restore at it. @@ -277,13 +270,7 @@ public void TheExemptLockFiles_AreExactlyTheOnesWhoseContentsFollowTheSdk() Assert.Equal(s_sdkCoupledLockFiles, SdkCoupledLockFiles(globalJson).ToArray()); - /* The reason, read off the tree rather than restated: the exempt project publishes single-file, which - is what makes the SDK add the reference, and its lock file is the only one carrying it. */ - Assert.Contains( - "true", - ReadRepoFileLf("deprecated", "Installer", "PerformanceMonitorInstaller.csproj"), - StringComparison.Ordinal); - + /* The reason, read off the tree rather than restated: no lock file carries the SDK-coupled package. */ Assert.Equal( s_sdkCoupledLockFiles, LockFileDirectories() @@ -320,7 +307,6 @@ public void TheCoverageCheck_ReportsAnInjectedGap() StringComparer.Ordinal); var directArm = new SortedSet(StringComparer.Ordinal); - var closureArm = new SortedSet(StringComparer.Ordinal); foreach (var line in real.Split('\n').Where(IsRestoreInvocation)) { @@ -329,21 +315,17 @@ public void TheCoverageCheck_ReportsAnInjectedGap() foreach (var uncovered in UncoveredLockFiles(without, globalJson)) { - /* A directory the deleted line NAMED is the direct arm; one it only reached through a - ProjectReference is the closure arm. The two are separated by what the workflow spells, - so neither is a list. */ - _ = namedByARestore.Contains(uncovered) ? directArm.Add(uncovered) : closureArm.Add(uncovered); + /* A directory the deleted line NAMED is the direct arm. A lock file reached only through a + ProjectReference used to be the closure arm here, proved on the Dashboard; the five + remaining projects are each named by a restore, so the closure arm is proved on a fixture + in TheClosureWalk_ReachesALockFileOnlyThroughAProjectReference. */ + Assert.Contains(uncovered, namedByARestore); + directArm.Add(uncovered); } } Assert.NotEmpty(directArm); - Assert.True( - closureArm.Count > 0, - "no restore line's removal uncovers a lock file it reaches only through a ProjectReference, so " - + "the closure walk in this check is not load-bearing and could be returning the directories it " - + "was handed"); - /* The exemption arm: with the SDK pinned exactly, the SDK-coupled lock file stops being excusable and the requirement reports it — which is the state a decision to keep that lock file has to reach. */ @@ -357,6 +339,53 @@ so neither is a list. */ Assert.Equal(s_sdkCoupledLockFiles, UncoveredLockFiles(real, pinnedSdk).ToArray()); } + /// + /// The closure walk is load-bearing: a lock file that no restore names, but that a restored project + /// reaches through a ProjectReference, is covered; removing the one restore line uncovers it; and + /// a lock file nothing references is still reported. Run on a fixture because every project in the + /// repository now has a restore of its own (the Dashboard, whose Core library was reached only through + /// a reference, went into the frozen zip, #6973), so the real tree can no longer show the walk doing + /// anything a plain list of the restored directories would not. + /// + [Fact] + public void TheClosureWalk_ReachesALockFileOnlyThroughAProjectReference() + { + var fixture = Path.Combine(Path.GetTempPath(), "lockedmode-closure-" + Guid.NewGuid().ToString("N")); + + try + { + foreach (var directory in new[] { "app", "lib", "orphan" }) + { + Directory.CreateDirectory(Path.Combine(fixture, directory)); + File.WriteAllText(Path.Combine(fixture, directory, "packages.lock.json"), "{}"); + } + + File.WriteAllText( + Path.Combine(fixture, "app", "App.csproj"), + ""); + File.WriteAllText(Path.Combine(fixture, "lib", "Lib.csproj"), ""); + File.WriteAllText(Path.Combine(fixture, "orphan", "Orphan.csproj"), ""); + + const string restoreApp = " dotnet restore app/App.csproj --locked-mode\n"; + const string pinnedSdk = "{ \"sdk\": { \"rollForward\": \"disable\" } }"; + + /* lib is reached only through app's reference, and orphan by nothing: the walk covers the first + and still reports the second. */ + Assert.Equal(new[] { "orphan" }, UncoveredLockFiles(restoreApp, pinnedSdk, fixture).ToArray()); + + /* Remove the one restore line and app, which it named, and lib, which it only reached, are both + reported. A walk that returned just the directories it was handed would already have + reported lib in the first call. */ + Assert.Equal( + new[] { "app", "lib", "orphan" }, + UncoveredLockFiles(string.Empty, pinnedSdk, fixture).OrderBy(d => d, StringComparer.Ordinal).ToArray()); + } + finally + { + Directory.Delete(fixture, recursive: true); + } + } + /// /// No restore any workflow executes reaches green by leaving locked mode, and no project file switches it /// off. @@ -597,18 +626,19 @@ private static string FirstStepName(string step) /// /// Every directory holding a committed packages.lock.json, repo-relative with forward slashes. /// - private static SortedSet LockFileDirectories() + private static SortedSet LockFileDirectories(string? root = null) { + root ??= Root; var found = new SortedSet(StringComparer.Ordinal); - foreach (var lockFile in Directory.GetFiles(Root, "packages.lock.json", SearchOption.AllDirectories)) + foreach (var lockFile in Directory.GetFiles(root, "packages.lock.json", SearchOption.AllDirectories)) { - if (IsBuildOutput(lockFile)) + if (IsBuildOutput(lockFile, root)) { continue; } - found.Add(RepoRelative(Path.GetDirectoryName(lockFile)!)); + found.Add(RepoRelative(Path.GetDirectoryName(lockFile)!, root)); } Assert.NotEmpty(found); @@ -621,11 +651,11 @@ private static SortedSet LockFileDirectories() /// reason it does not today is that it names a .sln — a property of the message's wording, not of /// this code. /// - private static List RestoredProjects(string yaml) => + private static List RestoredProjects(string yaml, string? root = null) => yaml.Split('\n') .Select(RestoreTarget) .Where(target => target.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) - .Select(target => Path.GetFullPath(Path.Combine(Root, target.Replace('/', Path.DirectorySeparatorChar)))) + .Select(target => Path.GetFullPath(Path.Combine(root ?? Root, target.Replace('/', Path.DirectorySeparatorChar)))) .Distinct(StringComparer.OrdinalIgnoreCase) .ToList(); @@ -635,14 +665,14 @@ private static List RestoredProjects(string yaml) => /// SDK patch float. Empty when the SDK is pinned exactly, which is what makes the exemption a statement /// about the current configuration rather than about those projects. /// - private static List SdkCoupledLockFiles(string globalJson) + private static List SdkCoupledLockFiles(string globalJson, string? root = null) { if (globalJson.Contains("\"rollForward\": \"disable\"", StringComparison.Ordinal)) { return new List(); } - return LockFileDirectories() + return LockFileDirectories(root) .Where(directory => ReadRepoFileLf(directory, "packages.lock.json").Contains(SdkCoupledPackage, StringComparison.Ordinal)) .ToList(); } @@ -651,11 +681,11 @@ private static List SdkCoupledLockFiles(string globalJson) /// The lock-file directories no restore in one workflow reaches, excluding the ones the SDK float /// excuses. /// - private static List UncoveredLockFiles(string yaml, string globalJson) + private static List UncoveredLockFiles(string yaml, string globalJson, string? root = null) { var reached = new HashSet(StringComparer.Ordinal); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var pending = new Queue(RestoredProjects(yaml)); + var pending = new Queue(RestoredProjects(yaml, root)); while (pending.Count > 0) { @@ -671,7 +701,7 @@ private static List UncoveredLockFiles(string yaml, string globalJson) Assert.True(File.Exists(project), $"a restore names, or a ProjectReference points at, a file that is not there: {project}"); var directory = Path.GetDirectoryName(project)!; - reached.Add(RepoRelative(directory)); + reached.Add(RepoRelative(directory, root)); foreach (Match match in ProjectReference.Matches(File.ReadAllText(project))) { @@ -683,9 +713,9 @@ private static List UncoveredLockFiles(string yaml, string globalJson) } } - var excused = SdkCoupledLockFiles(globalJson); + var excused = SdkCoupledLockFiles(globalJson, root); - return LockFileDirectories() + return LockFileDirectories(root) .Where(directory => !reached.Contains(directory)) .Where(directory => !excused.Contains(directory, StringComparer.Ordinal)) .ToList(); @@ -700,8 +730,8 @@ private static List UncoveredLockFiles(string yaml, string globalJson) /// An absolute path as a repo-relative one with forward slashes, so the two sides of the coverage /// comparison and the failure message all spell a directory the same way. /// - private static string RepoRelative(string absolute) => - Path.GetRelativePath(Root, absolute).Replace(Path.DirectorySeparatorChar, '/'); + private static string RepoRelative(string absolute, string? root = null) => + Path.GetRelativePath(root ?? Root, absolute).Replace(Path.DirectorySeparatorChar, '/'); /// /// Whether a path sits under a bin or obj directory below the repository root. @@ -714,8 +744,8 @@ private static string RepoRelative(string absolute) => /// requirement produced by a local artefact, failing for whoever had built the tree and passing for /// whoever had not. The repository already excludes build output by construction for the same reason. /// - private static bool IsBuildOutput(string absolute) => - Path.GetRelativePath(Root, absolute) + private static bool IsBuildOutput(string absolute, string? root = null) => + Path.GetRelativePath(root ?? Root, absolute) .Split(Path.DirectorySeparatorChar, '/') .Any(segment => segment.Equals("bin", StringComparison.OrdinalIgnoreCase) || segment.Equals("obj", StringComparison.OrdinalIgnoreCase)); diff --git a/Darling/Darling.Tests/ProductVersionDeclarationTests.cs b/Darling/Darling.Tests/ProductVersionDeclarationTests.cs index 2f1bc01861..d496220932 100644 --- a/Darling/Darling.Tests/ProductVersionDeclarationTests.cs +++ b/Darling/Darling.Tests/ProductVersionDeclarationTests.cs @@ -65,18 +65,16 @@ public class ProductVersionDeclarationTests private const string DeclarationFile = "Directory.Build.props"; /// - /// The version-source paths a reader may name. Two entries are checkouts of main rather than - /// paths in this tree: check-version-bump.yml compares the PR's version against main's, and - /// main does not carry until the release that introduces it lands there, - /// so the gate falls back to where main does declare it. A path under main-branch/ cannot be - /// validated against this tree at all, which is why the allowance is three named literals and not a - /// prefix: a fourth arriving fails, and the fallback is meant to be deleted once main has the file. + /// The version-source paths a reader may name. One entry is a checkout of main rather than a + /// path in this tree: check-version-bump.yml compares the PR's version against main's. A path + /// under main-branch/ cannot be validated against this tree at all, which is why the allowance + /// is two named literals and not a prefix: a third arriving fails. The fallback to main's old + /// Dashboard csproj was deleted once main carried the file, and the Dashboard is now a frozen zip (#6973). /// private static readonly string[] s_permittedVersionSources = { DeclarationFile, "main-branch/" + DeclarationFile, - "main-branch/deprecated/Dashboard/Dashboard.csproj", }; /// The MSBuild properties the SDK DERIVES from the declared version. diff --git a/Darling/Darling.Tests/ViewerButtonAccessKeyTests.cs b/Darling/Darling.Tests/ViewerButtonAccessKeyTests.cs index bd11bb5e6e..0b2f40723c 100644 --- a/Darling/Darling.Tests/ViewerButtonAccessKeyTests.cs +++ b/Darling/Darling.Tests/ViewerButtonAccessKeyTests.cs @@ -28,11 +28,13 @@ namespace Darling.Tests; /// binding failure, and no resource to fail to resolve. It is a rendering fact about a template, which is /// why the assertion is over the markup. /// -/// Fifteen templates was the estimate; fifty-five is the population. #3835 named three theme +/// Fifteen templates was the estimate; the population was fifty-five, and is thirty-five now. +/// #3835 named three theme /// files by the count of TargetType="Button" templates in the Darling viewer's Themes/ /// directory. There are three PARALLEL theme families — Darling/PerformanceMonitor.Darling.Viewer/Themes/, -/// Lite/Themes/ and deprecated/Dashboard/Themes/, the last still in -/// PerformanceMonitor.sln — plus five one-off templates outside any of them, including +/// Lite/Themes/ and the Dashboard's, which moved into +/// deprecated/dashboard-installer-source.zip in #6973 and left the walk (twenty of the fifty-five +/// templates went with it) — plus five one-off templates outside any of them, including /// ViewerDarkTheme.xaml's ViewerButton, which is the implicit Button style for every /// secondary window and therefore the template the reported _Save and _Close actually hit. /// A rule scoped to the three files in the report would have left two thirds of the defect in place and @@ -194,22 +196,39 @@ the attribute would govern nothing. */ } } - /* Nine theme files across three parallel families, and the count is the point: #3835 was reported as - three. A fourth family, or a fourth theme inside one, arrives here as a governed template like any - other — but this floor is what catches a walk that stopped seeing the families it already has. */ + /* Seven theme files: the Viewer's three themes, its ViewerDarkTheme.xaml one-off (the implicit Button + style for the secondary windows) and Lite's three. The Dashboard's family went into the frozen zip + (#6973). A new theme arrives here as a governed template like any other and need not be listed, + but a listed name missing from the walk catches a walk that stopped seeing a family it already + has, which a bare count would miss (it passes on a different mix of files). */ + var expectedThemeFiles = new[] + { + "Darling/PerformanceMonitor.Darling.Viewer/Themes/CoolBreezeTheme.xaml", + "Darling/PerformanceMonitor.Darling.Viewer/Themes/DarkTheme.xaml", + "Darling/PerformanceMonitor.Darling.Viewer/Themes/LightTheme.xaml", + "Darling/PerformanceMonitor.Darling.Viewer/ViewerDarkTheme.xaml", + "Lite/Themes/CoolBreezeTheme.xaml", + "Lite/Themes/DarkTheme.xaml", + "Lite/Themes/LightTheme.xaml", + }; + var themeFilesSeen = themeFiles.Select(f => f.Replace('\\', '/')).ToHashSet(StringComparer.OrdinalIgnoreCase); + var missingThemeFiles = expectedThemeFiles.Where(f => !themeFilesSeen.Contains(f)).ToList(); Assert.True( - themeFiles.Count >= 9, - $"only {themeFiles.Count} *Theme.xaml files were read ({string.Join(", ", themeFiles.OrderBy(f => f, StringComparer.Ordinal))}); " - + "there are three parallel theme families with three themes each, so the walk is missing at least one"); + missingThemeFiles.Count == 0, + $"the walk did not read {string.Join(", ", missingThemeFiles)}; it read " + + $"{string.Join(", ", themeFilesSeen.OrderBy(f => f, StringComparer.Ordinal))}. The Viewer's three " + + "themes, ViewerDarkTheme.xaml and Lite's three themes are the theme files that remain, so the " + + "walk is missing at least one"); Assert.True( - family >= 90, + family >= 55, $"only {family} button-family ControlTemplates were seen; the element walk is not descending the " + "resource dictionaries"); Assert.True( - governed >= 50, - $"only {governed} TargetType=\"Button\" templates were found. The defect spanned 55, so either the " + governed >= 30, + $"only {governed} TargetType=\"Button\" templates were found. 35 remain (55 before the Dashboard's " + + "went into the frozen zip), so either the " + "templates were consolidated — in which case raise this floor on purpose — or this scan has " + "stopped seeing most of them and is reporting clean on the remainder"); @@ -217,7 +236,7 @@ the attribute would govern nothing. */ govern, which is the TabCloseButton shape. Flooring the presenters separately is what says the attribute assertion had subjects. */ Assert.True( - presenters >= 45, + presenters >= 25, $"only {presenters} unsourced ContentPresenters were checked inside button templates; the rule is " + "passing because it found almost nothing to judge"); diff --git a/Directory.Packages.props b/Directory.Packages.props index 5daf6e683f..66f7c7cc1f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -35,7 +35,7 @@ diff --git a/Lite.Tests/PlanViewer4632FallbackTests.cs b/Lite.Tests/PlanViewer4632FallbackTests.cs index 55753f2b0c..362445639e 100644 --- a/Lite.Tests/PlanViewer4632FallbackTests.cs +++ b/Lite.Tests/PlanViewer4632FallbackTests.cs @@ -20,8 +20,8 @@ namespace Lite.Tests; /// -/// #4632 LIVE pin: the deprecated Dashboard's three theme files deliberately do NOT declare -/// CriticalTextBrush (out of scope for #4629/#4635 — see Viewer4629Tests's class remarks in +/// #4632 LIVE pin: the deprecated Dashboard's three theme files (now frozen in a zip, #6973) deliberately +/// did NOT declare CriticalTextBrush (out of scope for #4629/#4635 — see Viewer4629Tests's class remarks in /// Darling.Tests). resolves that key in CODE, not a XAML /// StaticResource binding: (TryFindResource("CriticalTextBrush") as SolidColorBrush) ?? /// Brushes.OrangeRed in PlanViewerControl.xaml.cs. A StaticResource to a missing key @@ -29,15 +29,14 @@ namespace Lite.Tests; /// /// (both test projects) is a source scan. This is the /// first test that constructs a LIVE and proves the fallback actually -/// resolves right — under a theme that lacks the key (Dashboard's real Light theme) and one that has it -/// (Lite's real Light theme). +/// resolves right under a theme that has the key (Lite's real Light theme). The case for a theme that lacks +/// it was the Dashboard's real Light theme and went with the Dashboard source (#6973). /// /// Lives in Lite.Tests rather than twinned into Darling.Tests: this proves one /// code-behind mechanism shared by every host, not a per-app behavior, so one copy is enough — /// PerformanceMonitor.Ui grants InternalsVisibleTo to both test projects equally, so either /// could have hosted it. Lite.Tests already carries ParitySource for reading repo source -/// (including the deprecated Dashboard's) as plain text — read-only, no reference to and no build of -/// deprecated/Dashboard — plus the OnStaThread shape MainWindowAccessKeyTests, +/// as plain text, plus the OnStaThread shape MainWindowAccessKeyTests, /// ThemeColorOverrideTests and QueryWindowTruncationTests already use for constructing WPF /// objects off-screen. /// @@ -56,46 +55,12 @@ namespace Lite.Tests; [Trait("Stage", "Guard")] // #5798: walks the repo tree, so the guard stage runs it public sealed class PlanViewer4632FallbackTests { - private const string DashboardLightTheme = "deprecated/Dashboard/Themes/LightTheme.xaml"; private const string LiteLightTheme = "Lite/Themes/LightTheme.xaml"; - /// OrangeRed, #FF4500 — the pre-#4629 fixed brush PlanViewerControl falls back to when - /// CriticalTextBrush is not in scope, matching PlanViewerControl.xaml.cs's own comment - /// at the fallback line. - private static readonly Color OrangeRedHex = Color.FromRgb(0xFF, 0x45, 0x00); - /// Lite's Light theme's real CriticalTextBrush hex (#4629) — the value construction /// inside that theme's scope must resolve to instead of the fallback. private static readonly Color LiteCriticalOrangeHex = Color.FromRgb(0xA8, 0x3A, 0x0D); - [Fact] - public void DashboardScope_MissingCriticalTextBrush_ConstructsCleanly_AndFallsBackToOrangeRed() - { - StaTestThread.Run(() => - { - var dict = LoadThemeDictionary(DashboardLightTheme); - Assert.False(dict.Contains("CriticalTextBrush"), - "premise check: the Dashboard theme now declares CriticalTextBrush — this pin no longer proves the fallback path."); - - var host = new Border(); - PlanViewerControl? control = null; - SolidColorBrush? resolved = null; - - var ex = Record.Exception(() => - { - host.Resources.MergedDictionaries.Add(dict); - control = new PlanViewerControl(); - host.Child = control; - resolved = CriticalOrangeBrushOf(control); - }); - - Assert.Null(ex); - Assert.Equal(OrangeRedHex, resolved!.Color); - - control!.Cleanup(); - }); - } - [Fact] public void LiteScope_WithCriticalTextBrush_ConstructsCleanly_AndResolvesThemeHex() { diff --git a/PerformanceMonitor.Analysis/AnomalyIncidentReconciler.cs b/PerformanceMonitor.Analysis/AnomalyIncidentReconciler.cs index d0a49de762..a4de49d3cf 100644 --- a/PerformanceMonitor.Analysis/AnomalyIncidentReconciler.cs +++ b/PerformanceMonitor.Analysis/AnomalyIncidentReconciler.cs @@ -92,7 +92,7 @@ namespace PerformanceMonitor.Analysis; /// Stateless — mutates only and, for the maintenance fold /// with facts supplied, on the passed stories, so it is directly /// unit-testable without any collector or store. The one-argument Reconcile is the pre-#3704 -/// signature, kept for the frozen deprecated/Dashboard twin: it folds by the same rule and +/// signature, kept for the frozen Dashboard twin (now only in the source zip, #6973): it folds by the same rule and /// writes no sentence, because the sentence needs the fact. /// public static class AnomalyIncidentReconciler @@ -144,7 +144,7 @@ public static class AnomalyIncidentReconciler /// non-absolution stories or no regular stories to fold into. The pre-#3704 signature: folds by every /// rule the two-argument form does (including the maintenance arm, whose gate is structural) but /// cannot name the job, because the name is on the fact and this form is not given the facts. The - /// live SKUs call the two-argument form; this one remains for the frozen deprecated/Dashboard. + /// live SKUs call the two-argument form; this one remains for the frozen Dashboard source zip. /// public static void Reconcile(IReadOnlyList stories) => Reconcile(stories, facts: null); diff --git a/PerformanceMonitor.Analysis/PerformanceMonitor.Analysis.csproj b/PerformanceMonitor.Analysis/PerformanceMonitor.Analysis.csproj index 9f2f593e07..910bea64ca 100644 --- a/PerformanceMonitor.Analysis/PerformanceMonitor.Analysis.csproj +++ b/PerformanceMonitor.Analysis/PerformanceMonitor.Analysis.csproj @@ -20,9 +20,7 @@ - - diff --git a/PerformanceMonitor.Common/PerformanceMonitor.Common.csproj b/PerformanceMonitor.Common/PerformanceMonitor.Common.csproj index b2d76f111c..78286326fb 100644 --- a/PerformanceMonitor.Common/PerformanceMonitor.Common.csproj +++ b/PerformanceMonitor.Common/PerformanceMonitor.Common.csproj @@ -27,7 +27,6 @@ - @@ -40,7 +39,6 @@ - diff --git a/PerformanceMonitor.Notifications/AlertDelivery.cs b/PerformanceMonitor.Notifications/AlertDelivery.cs index df80266529..f254934ab1 100644 --- a/PerformanceMonitor.Notifications/AlertDelivery.cs +++ b/PerformanceMonitor.Notifications/AlertDelivery.cs @@ -174,7 +174,7 @@ private AlertDelivery(bool sent, string channel, string? sendError) /// is not shipped, writes to its own JSON store, and has its own display. Converting those 26 sites /// would be churn in dead code and would fix nothing an operator can see. Deliberately /// internal, so no live producer can reach it, and - /// Darling.Tests.AlertDeliveryChannelTests.TheLegacyHatch_HasExactlyOneProductionCaller pins + /// Darling.Tests.AlertDeliveryChannelTests.TheLegacyHatch_HasNoProductionCaller pins /// that it stays that way — an internal member is visible to Lite as well as to the deprecated /// SKU, so the boundary is asserted rather than assumed. /// diff --git a/PerformanceMonitor.Notifications/PerformanceMonitor.Notifications.csproj b/PerformanceMonitor.Notifications/PerformanceMonitor.Notifications.csproj index 8d38e15de9..d1f31d88d2 100644 --- a/PerformanceMonitor.Notifications/PerformanceMonitor.Notifications.csproj +++ b/PerformanceMonitor.Notifications/PerformanceMonitor.Notifications.csproj @@ -22,9 +22,7 @@ - - diff --git a/PerformanceMonitor.PlanAnalysis/PerformanceMonitor.PlanAnalysis.csproj b/PerformanceMonitor.PlanAnalysis/PerformanceMonitor.PlanAnalysis.csproj index 7a4764c9db..16439bbcb1 100644 --- a/PerformanceMonitor.PlanAnalysis/PerformanceMonitor.PlanAnalysis.csproj +++ b/PerformanceMonitor.PlanAnalysis/PerformanceMonitor.PlanAnalysis.csproj @@ -29,9 +29,7 @@ - - diff --git a/PerformanceMonitor.Ui/PerformanceMonitor.Ui.csproj b/PerformanceMonitor.Ui/PerformanceMonitor.Ui.csproj index 33e9461b3c..3e24440c51 100644 --- a/PerformanceMonitor.Ui/PerformanceMonitor.Ui.csproj +++ b/PerformanceMonitor.Ui/PerformanceMonitor.Ui.csproj @@ -30,10 +30,8 @@ - - diff --git a/PerformanceMonitor.sln b/PerformanceMonitor.sln index 4a4cc4f180..fe4307cd9a 100644 --- a/PerformanceMonitor.sln +++ b/PerformanceMonitor.sln @@ -3,20 +3,10 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.14.36930.0 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard", "deprecated\Dashboard\Dashboard.csproj", "{15117113-EE40-8DCA-BC4D-4D4D68604E97}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerformanceMonitorLite", "Lite\PerformanceMonitorLite.csproj", "{48718A1C-3679-AB80-1D5F-A9C20CC7EF9A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lite.Tests", "Lite.Tests\Lite.Tests.csproj", "{C4E76DA8-A115-7291-3AD0-12C648E24FF2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerformanceMonitorInstaller", "deprecated\Installer\PerformanceMonitorInstaller.csproj", "{0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Installer.Tests", "deprecated\Installer.Tests\Installer.Tests.csproj", "{9B2800D2-8F32-450E-A169-86B381EA5560}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Installer.Core", "deprecated\Installer.Core\Installer.Core.csproj", "{AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard.Tests", "deprecated\Dashboard.Tests\Dashboard.Tests.csproj", "{769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerformanceMonitor.Analysis", "PerformanceMonitor.Analysis\PerformanceMonitor.Analysis.csproj", "{2F8A8C93-4B0D-4B5E-A898-3B1FCD882B5B}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerformanceMonitor.PlanAnalysis", "PerformanceMonitor.PlanAnalysis\PerformanceMonitor.PlanAnalysis.csproj", "{073D8E4A-BD40-40B4-A09B-5E3770DF1814}" @@ -55,18 +45,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Debug|Any CPU.Build.0 = Debug|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Debug|x64.ActiveCfg = Debug|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Debug|x64.Build.0 = Debug|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Debug|x86.ActiveCfg = Debug|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Debug|x86.Build.0 = Debug|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Release|Any CPU.ActiveCfg = Release|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Release|Any CPU.Build.0 = Release|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Release|x64.ActiveCfg = Release|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Release|x64.Build.0 = Release|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Release|x86.ActiveCfg = Release|Any CPU - {15117113-EE40-8DCA-BC4D-4D4D68604E97}.Release|x86.Build.0 = Release|Any CPU {48718A1C-3679-AB80-1D5F-A9C20CC7EF9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {48718A1C-3679-AB80-1D5F-A9C20CC7EF9A}.Debug|Any CPU.Build.0 = Debug|Any CPU {48718A1C-3679-AB80-1D5F-A9C20CC7EF9A}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -91,54 +69,6 @@ Global {C4E76DA8-A115-7291-3AD0-12C648E24FF2}.Release|x64.Build.0 = Release|Any CPU {C4E76DA8-A115-7291-3AD0-12C648E24FF2}.Release|x86.ActiveCfg = Release|Any CPU {C4E76DA8-A115-7291-3AD0-12C648E24FF2}.Release|x86.Build.0 = Release|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Debug|x64.ActiveCfg = Debug|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Debug|x64.Build.0 = Debug|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Debug|x86.ActiveCfg = Debug|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Debug|x86.Build.0 = Debug|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Release|Any CPU.Build.0 = Release|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Release|x64.ActiveCfg = Release|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Release|x64.Build.0 = Release|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Release|x86.ActiveCfg = Release|Any CPU - {0F1EFD0D-61B6-D475-3A2E-ED7FD83BCE6E}.Release|x86.Build.0 = Release|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Debug|x64.ActiveCfg = Debug|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Debug|x64.Build.0 = Debug|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Debug|x86.ActiveCfg = Debug|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Debug|x86.Build.0 = Debug|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Release|Any CPU.Build.0 = Release|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Release|x64.ActiveCfg = Release|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Release|x64.Build.0 = Release|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Release|x86.ActiveCfg = Release|Any CPU - {9B2800D2-8F32-450E-A169-86B381EA5560}.Release|x86.Build.0 = Release|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Debug|x64.ActiveCfg = Debug|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Debug|x64.Build.0 = Debug|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Debug|x86.ActiveCfg = Debug|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Debug|x86.Build.0 = Debug|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Release|Any CPU.Build.0 = Release|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Release|x64.ActiveCfg = Release|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Release|x64.Build.0 = Release|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Release|x86.ActiveCfg = Release|Any CPU - {AFA0BA1D-42D6-4E01-9D6C-B7E327E1B7D3}.Release|x86.Build.0 = Release|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Debug|Any CPU.Build.0 = Debug|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Debug|x64.ActiveCfg = Debug|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Debug|x64.Build.0 = Debug|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Debug|x86.ActiveCfg = Debug|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Debug|x86.Build.0 = Debug|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Release|Any CPU.ActiveCfg = Release|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Release|Any CPU.Build.0 = Release|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Release|x64.ActiveCfg = Release|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Release|x64.Build.0 = Release|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Release|x86.ActiveCfg = Release|Any CPU - {769BF5E2-21F2-4D14-8C45-DC46FB9E3D86}.Release|x86.Build.0 = Release|Any CPU {2F8A8C93-4B0D-4B5E-A898-3B1FCD882B5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F8A8C93-4B0D-4B5E-A898-3B1FCD882B5B}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F8A8C93-4B0D-4B5E-A898-3B1FCD882B5B}.Debug|x64.ActiveCfg = Debug|Any CPU diff --git a/SECURITY.md b/SECURITY.md index 054d8db576..fd23bf4fd8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,7 +25,7 @@ This policy applies to: - The deprecated Full Edition, which is still supported for existing users - The SQL collection and reporting stored procedures - The SQL installation scripts in `install/` - - The Full Dashboard and the CLI installer in `deprecated/` + - The Full Dashboard and the CLI installer, whose frozen source is in `deprecated/dashboard-installer-source.zip`. They are not built or released from this repository ## Security Best Practices diff --git a/deprecated/Dashboard.Tests/AlertBadgeConditionTests.cs b/deprecated/Dashboard.Tests/AlertBadgeConditionTests.cs deleted file mode 100644 index ab25879f9e..0000000000 --- a/deprecated/Dashboard.Tests/AlertBadgeConditionTests.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using PerformanceMonitorDashboard.Interfaces; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Guards #754/#749: the server-level (Overview) tab badge must light up for an active low-disk -/// breach or a recent failed Agent job — not only for blocking/deadlock/CPU/memory — and the -/// acknowledge baseline must keep it hidden until a NEW such condition appears (false -> true). -/// The Lite badge path shares the same condition shape (UpdateAlertCounts OR-ing the two flags), -/// so this covers both apps' intent; the Lite-specific UI plumbing is verified live. -/// -public class AlertBadgeConditionTests -{ - /// Minimal IUserPreferencesService over one mutable UserPreferences instance. - private sealed class FakePreferencesService : IUserPreferencesService - { - public UserPreferences Preferences { get; } = new(); - public UserPreferences GetPreferences() => Preferences; - public void SavePreferences(UserPreferences preferences) { } - public void UpdateWaitStatsRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCpuRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateMemoryRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateFileIoRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateExpensiveQueriesRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateBlockingRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCollectionHealthRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - } - - private static ServerHealthStatus HealthyStatus() => - new(new ServerConnection { Id = "srv-1", ServerName = "SQL1", DisplayName = "SQL1" }) { IsOnline = true }; - - [Fact] - public void HasAnyAlertCondition_LowDiskOnly_IsTrue() - { - var svc = new AlertStateService(new FakePreferencesService()); - var status = HealthyStatus(); - status.HasLowDiskAlert = true; - Assert.True(svc.HasAnyAlertCondition(status)); - } - - [Fact] - public void HasAnyAlertCondition_FailedJobOnly_IsTrue() - { - var svc = new AlertStateService(new FakePreferencesService()); - var status = HealthyStatus(); - status.HasFailedJobAlert = true; - Assert.True(svc.HasAnyAlertCondition(status)); - } - - [Fact] - public void HasAnyAlertCondition_NoConditions_IsFalse() - { - var svc = new AlertStateService(new FakePreferencesService()); - Assert.False(svc.HasAnyAlertCondition(HealthyStatus())); - } - - [Fact] - public void ShouldShowBadge_LowDisk_ShowsThenSuppressedByAcknowledge_ReturnsOnNewCondition() - { - var svc = new AlertStateService(new FakePreferencesService()); - var status = HealthyStatus(); - status.HasLowDiskAlert = true; - - // The standing low-disk breach lights the Overview badge. - Assert.True(svc.ShouldShowBadge("srv-1", "Overview", status)); - - // Acknowledging snapshots the baseline; the same unchanged breach is now suppressed. - svc.AcknowledgeAlert("srv-1", "Overview", status); - Assert.False(svc.ShouldShowBadge("srv-1", "Overview", status)); - - // A newly-appearing failed-job condition is worse than the baseline -> badge returns. - status.HasFailedJobAlert = true; - Assert.True(svc.ShouldShowBadge("srv-1", "Overview", status)); - } - - [Fact] - public void ShouldShowBadge_LowDisk_AutoClearsWhenResolved() - { - var svc = new AlertStateService(new FakePreferencesService()); - var status = HealthyStatus(); - status.HasLowDiskAlert = true; - - svc.AcknowledgeAlert("srv-1", "Overview", status); - Assert.False(svc.ShouldShowBadge("srv-1", "Overview", status)); - - // Disk recovers: condition gone, baseline auto-clears, badge stays hidden. - status.HasLowDiskAlert = false; - Assert.False(svc.ShouldShowBadge("srv-1", "Overview", status)); - - // A fresh breach after the auto-clear shows the badge again (no stale ack). - status.HasLowDiskAlert = true; - Assert.True(svc.ShouldShowBadge("srv-1", "Overview", status)); - } -} diff --git a/deprecated/Dashboard.Tests/AlertContextBuildersTests.cs b/deprecated/Dashboard.Tests/AlertContextBuildersTests.cs deleted file mode 100644 index 53ce44222c..0000000000 --- a/deprecated/Dashboard.Tests/AlertContextBuildersTests.cs +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using System; -using System.Collections.Generic; -using PerformanceMonitor.Alerting; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Models; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Identity pins for the Phase-5 slice-A extraction: the six pure alert-context builders (and their -/// pure helpers) moved verbatim from this app's MainWindow.AlertEngine.cs into the shared -/// . Every expectation here is derived from the pre-extraction -/// code, so a behavioral drift in the shared copy fails a pin. The shared -/// is the DASHBOARD's version -/// (including the ("Program", ...) item this app already rendered — Lite gained it as the slice's -/// one documented reconciliation), so for this app every pin is pre-extraction behavior. -/// -public class AlertContextBuildersTests -{ - private const string Server = "SQL2022"; - - /* ---------------- poison waits ---------------- */ - - [Fact] - public void BuildPoisonWaitContext_EmptyList_ReturnsNull() - { - Assert.Null(AlertContextBuilders.BuildPoisonWaitContext(new List())); - } - - [Fact] - public void BuildPoisonWaitContext_RendersOneDetailPerWait_NoIncidents() - { - var context = AlertContextBuilders.BuildPoisonWaitContext(new List - { - new() { WaitType = "RESOURCE_SEMAPHORE", AvgMsPerWait = 2000.5, DeltaMs = 100000, DeltaTasks = 50 }, - new() { WaitType = "THREADPOOL", AvgMsPerWait = 750.0, DeltaMs = 1500, DeltaTasks = 2 } - }); - - Assert.NotNull(context); - Assert.Equal(2, context!.Details.Count); - Assert.Equal("RESOURCE_SEMAPHORE", context.Details[0].Heading); - Assert.Equal( - new List<(string, string)> - { - ("Avg ms/wait", $"{2000.5:F1}"), - ("Delta wait ms", $"{100000L:N0}"), - ("Delta tasks", $"{50L:N0}") - }, - context.Details[0].Fields); - Assert.Equal("THREADPOOL", context.Details[1].Heading); - /* The poison-wait builder never attached #1140 incidents pre-extraction. */ - Assert.Null(context.Incidents); - } - - /* ---------------- long-running queries ---------------- */ - - private static LongRunningQueryInfo Lrq( - int sessionId, long elapsedSeconds, string db = "", string program = "", string query = "", - string? waitType = null, int? blockedBy = null, string? hash = null) => new() - { - SessionId = sessionId, - ElapsedSeconds = elapsedSeconds, - DatabaseName = db, - ProgramName = program, - QueryText = query, - CpuTimeMs = 1234, - Reads = 10, - Writes = 2, - WaitType = waitType, - BlockingSessionId = blockedBy, - QueryHash = hash - }; - - [Fact] - public void BuildLongRunningQueryContext_EmptyList_ReturnsNull() - { - Assert.Null(AlertContextBuilders.BuildLongRunningQueryContext(Server, new List())); - } - - [Fact] - public void BuildLongRunningQueryContext_CapsAtThreeQueries_AppendsIncidents() - { - var queries = new List - { - Lrq(71, 314, db: "StackOverflow", query: "SELECT 1", hash: "0x9AAF0129E4E9AD07"), - Lrq(72, 200, db: "StackOverflow", query: "SELECT 2", hash: "0x1111111111111111"), - Lrq(73, 150, db: "StackOverflow", query: "SELECT 3", hash: "0x2222222222222222"), - Lrq(74, 100, db: "StackOverflow", query: "SELECT 4", hash: "0x3333333333333333") - }; - - var context = AlertContextBuilders.BuildLongRunningQueryContext(Server, queries); - - Assert.NotNull(context); - /* 3 session items (capped) + 3 appended incident items (one per hashed query). */ - Assert.Equal(6, context!.Details.Count); - Assert.Equal("Session #71 — 5m 14s", context.Details[0].Heading); - Assert.Equal("Incident 1 of 3", context.Details[3].Heading); - Assert.NotNull(context.Incidents); - Assert.Equal(3, context.Incidents!.Count); - /* Dedup key = query_hash fingerprint, scoped by server + incident type (#1140). */ - var expected = AlertFingerprint.ForKey(Server, AlertFingerprint.Query, "0x9AAF0129E4E9AD07", new[] { "StackOverflow" }); - Assert.Equal(expected!.DedupKey, context.Incidents[0].DedupKey); - } - - [Fact] - public void BuildLongRunningQueryContext_RendersProgramField() - { - /* Pre-extraction Dashboard behavior — the ("Program", ...) item Lite gained in this slice. */ - var context = AlertContextBuilders.BuildLongRunningQueryContext(Server, new List - { - Lrq(71, 314, db: "StackOverflow", program: "HammerDB", query: "SELECT 1", waitType: "CXPACKET", blockedBy: 55) - }); - - Assert.NotNull(context); - Assert.Equal( - new List<(string, string)> - { - ("Database", "StackOverflow"), - ("Program", "HammerDB"), - ("Query", "SELECT 1"), - ("CPU Time", $"{1234L:N0} ms"), - ("Reads", $"{10L:N0}"), - ("Writes", $"{2L:N0}"), - ("Wait Type", "CXPACKET"), - ("Blocked By", "Session #55") - }, - context!.Details[0].Fields); - } - - [Fact] - public void BuildLongRunningQueryContext_NullQueryHash_EmitsNoIncident() - { - var context = AlertContextBuilders.BuildLongRunningQueryContext(Server, new List - { - Lrq(71, 90, db: "StackOverflow", query: "SELECT 1", hash: null) - }); - - Assert.NotNull(context); - Assert.Single(context!.Details); - Assert.Null(context.Incidents); - } - - /* ---------------- low disk ---------------- */ - - private static VolumeFreeSpaceInfo Volume(string mount, double totalMb, double freeMb) => - new() { MountPoint = mount, TotalMb = totalMb, FreeMb = freeMb }; - - [Fact] - public void GetBreachedVolumes_FiltersOnEitherDimension_WorstFirst() - { - var volumes = new List - { - Volume("C:\\", 102400, 8192), /* 8% free, 8 GB -> breaches percent */ - Volume("D:\\", 1048576, 524288), /* 50% free, 512 GB -> healthy */ - Volume("E:\\", 10240, 3072) /* 30% free, 3 GB -> breaches GB */ - }; - - var breached = AlertContextBuilders.GetBreachedVolumes(volumes, thresholdPercent: 10, thresholdGb: 5); - - Assert.Equal(2, breached.Count); - /* Ordered by free percent ascending — the tightest volume first. */ - Assert.Equal("C:\\", breached[0].MountPoint); - Assert.Equal("E:\\", breached[1].MountPoint); - } - - [Fact] - public void GetBreachedVolumes_ZeroThresholdDisablesThatDimension() - { - var lowPercent = new List { Volume("C:\\", 102400, 8192) }; /* 8%, 8 GB */ - var lowGb = new List { Volume("E:\\", 10240, 3072) }; /* 30%, 3 GB */ - - Assert.Empty(AlertContextBuilders.GetBreachedVolumes(lowPercent, thresholdPercent: 0, thresholdGb: 5)); - Assert.Empty(AlertContextBuilders.GetBreachedVolumes(lowGb, thresholdPercent: 10, thresholdGb: 0)); - Assert.Empty(AlertContextBuilders.GetBreachedVolumes(lowPercent, thresholdPercent: 0, thresholdGb: 0)); - } - - [Theory] - [InlineData(10, 5, "10% / 5 GB")] - [InlineData(10, 0, "10%")] - [InlineData(0, 5, "5 GB")] - [InlineData(0, 0, "—")] - public void FormatLowDiskThreshold_RendersConfiguredDimensions(double pct, double gb, string expected) - { - Assert.Equal(expected, AlertContextBuilders.FormatLowDiskThreshold(pct, gb)); - } - - [Fact] - public void BuildVolumeFreeSpaceContext_RendersVolume_WithPerVolumeIncident() - { - var context = AlertContextBuilders.BuildVolumeFreeSpaceContext(Server, new List - { - Volume("C:\\", 102400, 5120) /* 5% free, 5 GB free, 100 GB total */ - }); - - Assert.NotNull(context); - /* 1 volume item + 1 appended incident item. */ - Assert.Equal(2, context!.Details.Count); - Assert.Equal("C:\\ — 5% Free", context.Details[0].Heading); - Assert.Equal( - new List<(string, string)> - { - ("Free Space", $"{5.0:F1} GB"), - ("Total Size", $"{100.0:F1} GB"), - ("Used", $"{95.0:F1} GB") - }, - context.Details[0].Fields); - - Assert.NotNull(context.Incidents); - var expected = AlertFingerprint.ForKey(Server, AlertFingerprint.Disk, "C:\\", new[] { "C:\\" }); - Assert.Equal(expected!.DedupKey, Assert.Single(context.Incidents!).DedupKey); - } - - [Fact] - public void BuildVolumeFreeSpaceContext_CapsAtFiveVolumes() - { - var volumes = new List(); - for (int i = 0; i < 6; i++) - volumes.Add(Volume($"{(char)('C' + i)}:\\", 102400, 1024 * (i + 1))); - - var context = AlertContextBuilders.BuildVolumeFreeSpaceContext(Server, volumes); - - Assert.NotNull(context); - /* 5 shown volumes + 5 incident items. */ - Assert.Equal(10, context!.Details.Count); - Assert.Equal(5, context.Incidents!.Count); - } - - /* ---------------- tempdb ---------------- */ - - [Fact] - public void BuildTempDbSpaceContext_RendersAllFields_WithTopConsumer() - { - var context = AlertContextBuilders.BuildTempDbSpaceContext(new TempDbSpaceInfo - { - TotalReservedMb = 800, - UnallocatedMb = 200, - UserObjectReservedMb = 500, - InternalObjectReservedMb = 250, - VersionStoreReservedMb = 50, - TopConsumerSessionId = 55, - TopConsumerMb = 123.4 - }); - - Assert.NotNull(context); - var item = Assert.Single(context!.Details); - Assert.Equal("tempdb — 80% Reserved", item.Heading); - Assert.Equal( - new List<(string, string)> - { - ("Total Reserved", $"{800d:F0} MB"), - ("Unallocated", $"{200d:F0} MB"), - /* #2515: no MaxSizeMb on this fixture, so the ceiling was never measured and the - percentage above is still against the allocation. */ - ("Max Size", "Unknown"), - ("User Objects", $"{500d:F0} MB"), - ("Internal Objects", $"{250d:F0} MB"), - ("Version Store", $"{50d:F0} MB"), - ("Top Consumer", $"Session #55 ({123.4:F0} MB)") - }, - item.Fields); - } - - [Fact] - public void BuildTempDbSpaceContext_NoTopConsumer_RendersNone() - { - var context = AlertContextBuilders.BuildTempDbSpaceContext(new TempDbSpaceInfo - { - TotalReservedMb = 100, - UnallocatedMb = 900, - TopConsumerSessionId = 0 - }); - - Assert.Equal(("Top Consumer", "None"), context!.Details[0].Fields[6]); - } - - /* ---------------- anomalous jobs ---------------- */ - - [Fact] - public void BuildAnomalousJobContext_RendersDurationsAndIncidents() - { - var jobs = new List - { - new() - { - JobName = "Nightly ETL", - CurrentDurationSeconds = 3661, /* -> 1h 1m */ - AvgDurationSeconds = 90, /* -> 1m 30s */ - P95DurationSeconds = 45, /* -> 45s */ - PercentOfAverage = 350, - /* #3421: the run start is the monitored server's own clock, and the offset rides with the - row so the body can state it in UTC. -240 is the measured fleet value. */ - StartTime = new DateTime(2026, 6, 19, 14, 30, 15), - UtcOffsetMinutes = -240 - } - }; - - var context = AlertContextBuilders.BuildAnomalousJobContext(Server, jobs); - - Assert.NotNull(context); - /* 1 job item + 1 appended incident item. */ - Assert.Equal(2, context!.Details.Count); - Assert.Equal("Nightly ETL", context.Details[0].Heading); - Assert.Equal( - new List<(string, string)> - { - ("Current Duration", "1h 1m"), - ("Avg Duration", "1m 30s"), - ("P95 Duration", "45s"), - ("% of Average", $"{350m:F0}%"), - ("Started", "2026-06-19 18:30:15Z") - }, - context.Details[0].Fields); - - var expected = AlertFingerprint.ForKey(Server, AlertFingerprint.Job, "Nightly ETL", new[] { "Nightly ETL" }); - Assert.Equal(expected!.DedupKey, Assert.Single(context.Incidents!).DedupKey); - } - - [Fact] - public void BuildAnomalousJobContext_NullPercentOfAverage_RendersNA_AndCapsAtThree() - { - var jobs = new List(); - for (int i = 0; i < 4; i++) - jobs.Add(new AnomalousJobInfo { JobName = $"Job {i}", PercentOfAverage = null, StartTime = DateTime.UtcNow }); - - var context = AlertContextBuilders.BuildAnomalousJobContext(Server, jobs); - - Assert.NotNull(context); - /* 3 shown jobs (capped) + 3 incident items. */ - Assert.Equal(6, context!.Details.Count); - Assert.Equal(("% of Average", "N/A"), context.Details[0].Fields[3]); - Assert.Null(AlertContextBuilders.BuildAnomalousJobContext(Server, new List())); - } - - /* ---------------- failed jobs ---------------- */ - - [Fact] - public void BuildFailedJobContext_RendersStepAndTruncatedMessage() - { - var runTime = new DateTime(2026, 6, 19, 3, 15, 0); - var context = AlertContextBuilders.BuildFailedJobContext(Server, new List - { - new() - { - JobName = "Backup Job", - RunDateTime = runTime, - UtcOffsetMinutes = -240, - StepId = 2, - StepName = "Backup databases", - Message = new string('x', 350) - } - }); - - Assert.NotNull(context); - Assert.Equal(2, context!.Details.Count); /* 1 job item + 1 incident item */ - Assert.Equal("Backup Job", context.Details[0].Heading); - Assert.Equal( - new List<(string, string)> - { - ("Job", "Backup Job"), - ("Failed At", "2026-06-19 07:15:00Z"), - ("Step", "2 — Backup databases"), - ("Message", new string('x', 300) + "...") - }, - context.Details[0].Fields); - - var expected = AlertFingerprint.ForKey(Server, AlertFingerprint.Job, "Backup Job", new[] { "Backup Job" }); - Assert.Equal(expected!.DedupKey, Assert.Single(context.Incidents!).DedupKey); - } - - [Fact] - public void BuildFailedJobContext_OutcomeRowWithoutStep_OmitsStepField_AndCapsAtFive() - { - var jobs = new List(); - for (int i = 0; i < 6; i++) - jobs.Add(new FailedJobInfo { JobName = $"Job {i}", RunDateTime = DateTime.UtcNow, StepId = 0 }); - - var context = AlertContextBuilders.BuildFailedJobContext(Server, jobs); - - Assert.NotNull(context); - /* 5 shown jobs (capped) + 5 incident items. */ - Assert.Equal(10, context!.Details.Count); - Assert.DoesNotContain(context.Details[0].Fields, f => f.Label == "Step"); - Assert.Null(AlertContextBuilders.BuildFailedJobContext(Server, new List())); - } - - /* ---------------- helpers ---------------- */ - - [Fact] - public void ContextToDetailText_NullOrEmptyContext_ReturnsNull() - { - Assert.Null(AlertContextBuilders.ContextToDetailText(null)); - Assert.Null(AlertContextBuilders.ContextToDetailText(new AlertContext())); - } - - [Fact] - public void ContextToDetailText_RendersHeadingsAndIndentedFields() - { - var context = new AlertContext(); - context.Details.Add(new AlertDetailItem { Heading = "H1", Fields = new() { ("A", "1") } }); - context.Details.Add(new AlertDetailItem { Heading = "H2", Fields = new() { ("B", "2") } }); - - var expected = string.Join(Environment.NewLine, "H1", " A: 1", "", "H2", " B: 2"); - Assert.Equal(expected, AlertContextBuilders.ContextToDetailText(context)); - } - - [Fact] - public void TruncateText_CollapsesNewlines_TruncatesWithEllipsis() - { - Assert.Equal("", AlertContextBuilders.TruncateText("")); - /* '\r' and '\n' each become a space (historical behavior — not collapsed to one). */ - Assert.Equal("a b", AlertContextBuilders.TruncateText("a\r\nb")); - Assert.Equal("abc", AlertContextBuilders.TruncateText(" abc ")); - Assert.Equal(new string('x', 300) + "...", AlertContextBuilders.TruncateText(new string('x', 350))); - Assert.Equal("ab...", AlertContextBuilders.TruncateText("abcdef", 2)); - } - - /* ---------------- A0: the shared row types are the app's row types ---------------- */ - - [Fact] - public void RowTypes_ResolveToAlertingNamespace_ThroughAppApiSurface() - { - /* The global using aliases in the Dashboard's GlobalUsings.cs point the old bare type names - at PerformanceMonitor.Alerting — so AlertHealthResult (the alert engine's input carrier) - must now surface the SHARED types on all six alert row members. */ - Assert.Equal("PerformanceMonitor.Alerting", typeof(FailedJobInfo).Namespace); - - Assert.Equal(typeof(List), - typeof(AlertHealthResult).GetProperty("PoisonWaits")!.PropertyType); - Assert.Equal(typeof(List), - typeof(AlertHealthResult).GetProperty("LongRunningQueries")!.PropertyType); - Assert.Equal(typeof(TempDbSpaceInfo), - typeof(AlertHealthResult).GetProperty("TempDbSpace")!.PropertyType); - Assert.Equal(typeof(List), - typeof(AlertHealthResult).GetProperty("Volumes")!.PropertyType); - Assert.Equal(typeof(List), - typeof(AlertHealthResult).GetProperty("AnomalousJobs")!.PropertyType); - Assert.Equal(typeof(List), - typeof(AlertHealthResult).GetProperty("RecentlyFailedJobs")!.PropertyType); - } -} diff --git a/deprecated/Dashboard.Tests/AlertDeliveryModeOverrideTests.cs b/deprecated/Dashboard.Tests/AlertDeliveryModeOverrideTests.cs deleted file mode 100644 index 98aea0248d..0000000000 --- a/deprecated/Dashboard.Tests/AlertDeliveryModeOverrideTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using System.Text.Json; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Models; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #1236 per-server alert delivery override persists on (servers.json, -/// same WriteIndented options ServerManager uses). A pre-#1236 file with no field inherits the global. -/// The shared precedence rule () is covered in Lite.Tests. -/// -public class AlertDeliveryModeOverrideTests -{ - private static readonly JsonSerializerOptions s_jsonOptions = new() { WriteIndented = true }; - - [Fact] - public void Override_RoundTripsThroughJson() - { - var server = new ServerConnection { ServerName = "S1", AlertDeliveryModeOverride = AlertNotificationMode.PerEvent }; - var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(server, s_jsonOptions), s_jsonOptions); - Assert.Equal(AlertNotificationMode.PerEvent, back!.AlertDeliveryModeOverride); - } - - [Fact] - public void NullOverride_RoundTripsAsNull() - { - var server = new ServerConnection { ServerName = "S1", AlertDeliveryModeOverride = null }; - var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(server, s_jsonOptions), s_jsonOptions); - Assert.Null(back!.AlertDeliveryModeOverride); - } - - [Fact] - public void LegacyServersJson_WithoutField_InheritsGlobal() - { - // A servers.json written before #1236 has no AlertDeliveryModeOverride property -> null -> inherit. - var back = JsonSerializer.Deserialize("{\"ServerName\":\"S1\",\"DisplayName\":\"S1\"}", s_jsonOptions); - Assert.Null(back!.AlertDeliveryModeOverride); - } -} diff --git a/deprecated/Dashboard.Tests/AnalysisEnabledPreferenceTests.cs b/deprecated/Dashboard.Tests/AnalysisEnabledPreferenceTests.cs deleted file mode 100644 index 00adeef3ac..0000000000 --- a/deprecated/Dashboard.Tests/AnalysisEnabledPreferenceTests.cs +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using System.Text.Json; -using PerformanceMonitorDashboard.Models; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Recommendations rebuild PR-1 (D0): the new -/// setting gates analysis *production* and is independent of the notification *delivery* -/// gate (). These tests pin the -/// defaults and the JSON persistence contract that UserPreferencesService relies on -/// (it serializes/deserializes the whole UserPreferences object with the same options). -/// -public class AnalysisEnabledPreferenceTests -{ - /// Serializer options matching UserPreferencesService (WriteIndented = true). - private static readonly JsonSerializerOptions s_jsonOptions = new() { WriteIndented = true }; - - [Fact] - public void AnalysisEnabled_DefaultsToTrue() - { - var prefs = new UserPreferences(); - Assert.True(prefs.AnalysisEnabled); - } - - [Fact] - public void AnalysisNotificationsEnabled_StillDefaultsToFalse() - { - // D0 keeps delivery opt-in: production is on by default, notifications are not. - var prefs = new UserPreferences(); - Assert.False(prefs.AnalysisNotificationsEnabled); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void AnalysisEnabled_RoundTripsThroughJson(bool value) - { - // This is exactly what UserPreferencesService.SavePreferences/LoadPreferences do: - // JsonSerializer.Serialize(prefs) -> file -> JsonSerializer.Deserialize. - var prefs = new UserPreferences { AnalysisEnabled = value }; - - var json = JsonSerializer.Serialize(prefs, s_jsonOptions); - var loaded = JsonSerializer.Deserialize(json); - - Assert.NotNull(loaded); - Assert.Equal(value, loaded!.AnalysisEnabled); - } - - [Fact] - public void AnalysisEnabled_AbsentFromExistingJson_DeserializesToTrueDefault() - { - // An existing preferences.json written before this PR has no "AnalysisEnabled" key. - // The default initializer (= true) must apply so upgraded installs get analysis on. - const string legacyJson = """ - { - "AnalysisNotificationsEnabled": false, - "AnalysisIntervalMinutes": 30 - } - """; - - var loaded = JsonSerializer.Deserialize(legacyJson); - - Assert.NotNull(loaded); - Assert.True(loaded!.AnalysisEnabled); - Assert.False(loaded.AnalysisNotificationsEnabled); - } - - [Fact] - public void AnalysisEnabled_AndNotifications_AreIndependentInJson() - { - // Production on, delivery off — the canonical D0 default-on/notify-off state. - var prefs = new UserPreferences - { - AnalysisEnabled = true, - AnalysisNotificationsEnabled = false - }; - - var json = JsonSerializer.Serialize(prefs, s_jsonOptions); - var loaded = JsonSerializer.Deserialize(json); - - Assert.NotNull(loaded); - Assert.True(loaded!.AnalysisEnabled); - Assert.False(loaded.AnalysisNotificationsEnabled); - } -} diff --git a/deprecated/Dashboard.Tests/AnalysisNotificationTests.cs b/deprecated/Dashboard.Tests/AnalysisNotificationTests.cs deleted file mode 100644 index ef641453d0..0000000000 --- a/deprecated/Dashboard.Tests/AnalysisNotificationTests.cs +++ /dev/null @@ -1,695 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using PerformanceMonitor.Analysis; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Dashboard's first notification-formatter tests. Mirrors the Lite suite's -/// FindingMessageFormatter.BuildContext ordering/omission cases plus the -/// AlertContext serialization round-trip (triage v1 PR (b)). Dashboard threads -/// the notify threshold as a method parameter, so BuildContext takes (finding, threshold). -/// -public class AnalysisNotificationTests -{ - private static AnalysisFinding MakeFinding( - string hash, - double severity = 1.8, - string category = "cpu_pressure", - int serverId = 1, - double? rootValue = 92.5, - Dictionary? metadata = null, - Dictionary? drillDown = null, - string rootFactKey = "CPU_SPIKE") - { - return new AnalysisFinding - { - ServerId = serverId, - ServerName = "TestServer", - Category = category, - StoryPath = "CPU_SPIKE → PLAN_REGRESSION", - StoryPathHash = hash, - Severity = severity, - Confidence = 0.67, - FactCount = 2, - RootFactKey = rootFactKey, - RootFactValue = rootValue, - TimeRangeStart = DateTime.UtcNow.AddHours(-4), - TimeRangeEnd = DateTime.UtcNow, - RootFactMetadata = metadata, - DrillDown = drillDown - }; - } - - private static Dictionary RegressedQueriesDrillDown() => new() - { - ["regressed_queries"] = new List - { - new - { - database = "AdventureWorks", - query_id = 4242L, - best_plan_id = 17L, - latest_plan_hash = "0xDEAD", - best_plan_hash = "0xBEEF", - latest_cpu_per_exec_us = 9000.0, - best_cpu_per_exec_us = 1200.0, - regression_factor = 7.5 - } - } - }; - - [Fact] - public void BuildContext_RenderingOrder_DiagnosisAdviceTsqlDrillDown() - { - var finding = MakeFinding("planreg000000001", rootFactKey: "PLAN_REGRESSION", - drillDown: RegressedQueriesDrillDown()); - - var context = FindingMessageFormatter.BuildContext(finding, notifyThreshold: 1.5); - - // [0] Diagnosis, [1] Advice prose, [2] Remediation T-SQL, [3] regressed_queries drill-down. - Assert.Equal(4, context.Details.Count); - Assert.Equal("Diagnosis", context.Details[0].Heading); - - Assert.NotNull(context.Details[1].Body); - Assert.False(context.Details[1].IsCodeBlock); - Assert.Contains("Investigation:", context.Details[1].Body); - Assert.Contains("Remediation:", context.Details[1].Body); - - Assert.Equal("Remediation T-SQL", context.Details[2].Heading); - Assert.True(context.Details[2].IsCodeBlock); - Assert.NotNull(context.Details[2].Body); - Assert.Contains("sp_query_store_force_plan", context.Details[2].Body); - - Assert.Equal("Regressed Queries", context.Details[3].Heading); - } - - [Fact] - public void BuildContext_UnknownFactKey_OmitsAdviceAndTsql() - { - var finding = MakeFinding("unknown000000001", rootFactKey: "ZZZ_TEST"); - - var context = FindingMessageFormatter.BuildContext(finding, notifyThreshold: 1.5); - - // Diagnosis only — no advice block for an unknown fact key, and no T-SQL. - var only = Assert.Single(context.Details); - Assert.Equal("Diagnosis", only.Heading); - Assert.DoesNotContain(context.Details, d => d.Heading == "Remediation T-SQL"); - } - - [Fact] - public void BuildContext_NonPlanRegression_OmitsTsqlOnly() - { - // CPU_SPIKE has advice but is not PLAN_REGRESSION, so advice renders but no T-SQL. - var context = FindingMessageFormatter.BuildContext(MakeFinding("cpuonly000000001"), notifyThreshold: 1.5); - - Assert.Contains(context.Details, d => d.Body is not null && !d.IsCodeBlock); - Assert.DoesNotContain(context.Details, d => d.IsCodeBlock); - Assert.DoesNotContain(context.Details, d => d.Heading == "Remediation T-SQL"); - } - - [Fact] - public void AlertContext_SerializesAndDeserializes_PreservingFieldsBodyAndCodeBlock() - { - // MINOR-3: round-trip the real BuildContext output for a PLAN_REGRESSION finding (generated - // T-SQL with newlines/brackets/semicolons/-- comments + drill-down Fields), not a hand-built - // context, through the production AlertContextSerializer / DTO. - var finding = MakeFinding("roundtrip0000001", rootFactKey: "PLAN_REGRESSION", - drillDown: RegressedQueriesDrillDown()); - var context = FindingMessageFormatter.BuildContext(finding, notifyThreshold: 1.5); - - var json = AlertContextSerializer.Serialize(context); - Assert.True(AlertContextSerializer.TryDeserialize(json, out var restored)); - - Assert.Equal(context.Details.Count, restored.Details.Count); - for (int i = 0; i < context.Details.Count; i++) - { - var expected = context.Details[i]; - var actual = restored.Details[i]; - - Assert.Equal(expected.Heading, actual.Heading); - Assert.Equal(expected.Body, actual.Body); - Assert.Equal(expected.IsCodeBlock, actual.IsCodeBlock); - Assert.Equal(expected.Fields.Count, actual.Fields.Count); - for (int j = 0; j < expected.Fields.Count; j++) - { - Assert.Equal(expected.Fields[j].Label, actual.Fields[j].Label); - Assert.Equal(expected.Fields[j].Value, actual.Fields[j].Value); - } - } - - // The T-SQL code block in particular must survive intact. - var tsql = restored.Details.Single(d => d.IsCodeBlock); - Assert.Contains("sp_query_store_force_plan", tsql.Body); - } - - [Fact] - public void BuildContext_PlanRegression_AttachesStructuredRemediationToCodeBlock() - { - var finding = MakeFinding("remstruct0000001", rootFactKey: "PLAN_REGRESSION", - drillDown: RegressedQueriesDrillDown()); - - var context = FindingMessageFormatter.BuildContext(finding, notifyThreshold: 1.5); - - var tsql = context.Details.Single(d => d.IsCodeBlock); - Assert.NotNull(tsql.Remediation); - Assert.Equal("PLAN_REGRESSION", tsql.Remediation!.FactKey); - Assert.Equal("force", tsql.Remediation.Action); - var target = Assert.Single(tsql.Remediation.Targets); - Assert.Equal("AdventureWorks", target.Database); - Assert.Equal(4242, target.QueryId); - Assert.Equal(17, target.PlanId); - } - - [Fact] - public void AlertContext_RemediationAction_SurvivesRoundTrip() - { - var finding = MakeFinding("remround00000001", rootFactKey: "PLAN_REGRESSION", - drillDown: RegressedQueriesDrillDown()); - var context = FindingMessageFormatter.BuildContext(finding, notifyThreshold: 1.5); - - var json = AlertContextSerializer.Serialize(context); - Assert.True(AlertContextSerializer.TryDeserialize(json, out var restored)); - - var rem = restored.Details.Single(d => d.IsCodeBlock).Remediation; - Assert.NotNull(rem); - Assert.Equal("PLAN_REGRESSION", rem!.FactKey); - Assert.Equal("force", rem.Action); - var t = Assert.Single(rem.Targets); - Assert.Equal("AdventureWorks", t.Database); - Assert.Equal(4242, t.QueryId); - Assert.Equal(17, t.PlanId); - Assert.Equal("0xBEEF", t.BestPlanHash); - Assert.Equal(7.5, t.RegressionFactor); - } - - [Fact] - public void AlertContext_DbConfigAction_DbConfigTargetsSurviveRoundTrip() - { - // m-A: a DB_CONFIG action must come back with its DbConfigTargets intact after - // a full serialize -> deserialize. A 3-arg FromDto ctor call would silently - // drop them (action survives but un-applyable); this pins they survive. - var action = new RemediationAction("DB_CONFIG", "set", - Array.Empty(), - new List - { - new("Foo", DbConfigSetting.AutoShrinkOff, "ON"), - new("Foo", DbConfigSetting.PageVerifyChecksum, "TORN_PAGE_DETECTION") - }); - - var context = new AlertContext(); - context.Details.Add(new AlertDetailItem - { - Heading = "Remediation T-SQL", - IsCodeBlock = true, - Body = "ALTER DATABASE [Foo] SET AUTO_SHRINK OFF;", - Remediation = action - }); - - var json = AlertContextSerializer.Serialize(context); - Assert.True(AlertContextSerializer.TryDeserialize(json, out var restored)); - - var rem = restored.Details.Single(d => d.IsCodeBlock).Remediation; - Assert.NotNull(rem); - Assert.Equal("DB_CONFIG", rem!.FactKey); - Assert.Equal("set", rem.Action); - Assert.Empty(rem.Targets); // force-plan list empty - Assert.NotNull(rem.DbConfigTargets); - Assert.Equal(2, rem.DbConfigTargets!.Count); - Assert.Equal("Foo", rem.DbConfigTargets[0].Database); - Assert.Equal(DbConfigSetting.AutoShrinkOff, rem.DbConfigTargets[0].Setting); - Assert.Equal("ON", rem.DbConfigTargets[0].CurrentValue); - Assert.Equal(DbConfigSetting.PageVerifyChecksum, rem.DbConfigTargets[1].Setting); - Assert.Equal("TORN_PAGE_DETECTION", rem.DbConfigTargets[1].CurrentValue); - } - - [Fact] - public void AlertContext_ForcePlanAction_DbConfigTargetsNull_AfterRoundTrip() - { - // A force-plan action has no DbConfigTargets; it must round-trip to null - // (not an empty list that would imply a DB_CONFIG action). - var finding = MakeFinding("remround00000002", rootFactKey: "PLAN_REGRESSION", - drillDown: RegressedQueriesDrillDown()); - var context = FindingMessageFormatter.BuildContext(finding, notifyThreshold: 1.5); - - var json = AlertContextSerializer.Serialize(context); - Assert.True(AlertContextSerializer.TryDeserialize(json, out var restored)); - - var rem = restored.Details.Single(d => d.IsCodeBlock).Remediation; - Assert.NotNull(rem); - Assert.Null(rem!.DbConfigTargets); - } - - // ── B3 Phase 3 (PR-B): second "Enable RCSI (advanced)" detail item + cross-surface ── - - private static AnalysisFinding DbConfigRcsiFinding( - bool rcsiOff = true, bool enrichment = true, bool alsoAutoShrink = false, - int blocking = 12, int deadlocks = 3, int? rwPct = 80, string hash = "dbconfig00000099") - { - var row = new Dictionary - { - ["database"] = "Foo", - ["recovery_model"] = "FULL", - ["rcsi"] = !rcsiOff, // rcsi == true means RCSI is ON - ["query_store"] = true, - ["issues"] = rcsiOff ? new[] { "RCSI OFF" } : System.Array.Empty(), - ["auto_shrink"] = alsoAutoShrink, - ["auto_close"] = false, - ["page_verify"] = "CHECKSUM", - }; - if (enrichment) - { - row["rcsi_blocking_events"] = blocking; - row["rcsi_deadlocks"] = deadlocks; - row["rcsi_reader_writer_pct"] = rwPct; - } - return MakeFinding(hash, rootFactKey: "DB_CONFIG", category: "config_issues", - drillDown: new Dictionary { ["config_issues"] = new List { row } }); - } - - [Fact] - public void BuildContext_RcsiOffWithEnrichment_EmitsSecondEnableRcsiItem() - { - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(), notifyThreshold: 1.5); - - var rcsiItem = Assert.Single(context.Details, d => d.Heading == "Enable RCSI (advanced)"); - Assert.True(rcsiItem.IsCodeBlock); - Assert.NotNull(rcsiItem.Remediation); - Assert.Equal("RCSI", rcsiItem.Remediation!.FactKey); - Assert.Contains("SET READ_COMMITTED_SNAPSHOT ON", rcsiItem.Body); - // The figures rode the action (captured while the finding was in hand). - Assert.NotNull(rcsiItem.Remediation.RcsiFigures); - Assert.Equal(12, rcsiItem.Remediation.RcsiFigures!.BlockingEvents); - - // The cross-surface disclosure item is also present (read-only, both email bodies + webhook). - var disclosure = Assert.Single(context.Details, d => d.Heading == "RCSI — risks of changing / not changing"); - Assert.False(disclosure.IsCodeBlock); - Assert.Contains("Risks of CHANGING", disclosure.Body); - Assert.Contains("Risks of NOT changing", disclosure.Body); - Assert.Contains("RCSI eliminates", disclosure.Body); // 80% reader/writer - } - - [Fact] - public void BuildContext_RcsiOn_EmitsNoEnableRcsiItem() - { - // RCSI already ON -> the affordance must NOT appear (M2-1 polarity). - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(rcsiOff: false), notifyThreshold: 1.5); - Assert.DoesNotContain(context.Details, d => d.Heading == "Enable RCSI (advanced)"); - Assert.DoesNotContain(context.Details, d => d.Heading == "RCSI — risks of changing / not changing"); - } - - [Fact] - public void BuildContext_RcsiOffNoEnrichment_EmitsNoEnableRcsiItem() - { - // Legacy alert: RCSI off but no §3.3 enrichment -> no affordance. - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(enrichment: false), notifyThreshold: 1.5); - Assert.DoesNotContain(context.Details, d => d.Heading == "Enable RCSI (advanced)"); - } - - [Fact] - public void BuildContext_RcsiItem_NotGatedBehindAlwaysSafeRemediationTsql() - { - // The residual round-2 note: emit the RCSI item on ANY config_issues-bearing - // finding, NOT only when the always-safe block emitted a Remediation T-SQL item. - // Here ONLY RCSI is wrong (no auto_shrink/auto_close/page_verify issue), so the - // always-safe BuildAction yields null and NO "Remediation T-SQL" item is emitted — - // yet the RCSI item must still appear. - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(alsoAutoShrink: false), notifyThreshold: 1.5); - - Assert.DoesNotContain(context.Details, d => d.Heading == "Remediation T-SQL"); - Assert.Contains(context.Details, d => d.Heading == "Enable RCSI (advanced)"); - } - - [Fact] - public void BuildContext_BothItems_WhenAlsoAlwaysSafeIssue() - { - // RCSI off + an always-safe issue (auto_shrink ON): BOTH the always-safe - // "Remediation T-SQL" item AND the separate "Enable RCSI (advanced)" item appear, - // each with its own singular Remediation. The always-safe one never carries RCSI. - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(alsoAutoShrink: true), notifyThreshold: 1.5); - - var safe = Assert.Single(context.Details, d => d.Heading == "Remediation T-SQL"); - Assert.Equal("DB_CONFIG", safe.Remediation!.FactKey); - Assert.All(safe.Remediation.DbConfigTargets!, t => Assert.NotEqual(DbConfigSetting.ReadCommittedSnapshotOn, t.Setting)); - - var rcsi = Assert.Single(context.Details, d => d.Heading == "Enable RCSI (advanced)"); - Assert.Equal("RCSI", rcsi.Remediation!.FactKey); - } - - [Fact] - public void BuildContext_RcsiItem_RemediationActionAndFigures_SurviveRoundTrip() - { - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(), notifyThreshold: 1.5); - var json = AlertContextSerializer.Serialize(context); - Assert.True(AlertContextSerializer.TryDeserialize(json, out var restored)); - - var rcsi = Assert.Single(restored.Details, d => d.Heading == "Enable RCSI (advanced)"); - Assert.NotNull(rcsi.Remediation); - Assert.Equal("RCSI", rcsi.Remediation!.FactKey); - var t = Assert.Single(rcsi.Remediation.DbConfigTargets!); - Assert.Equal(DbConfigSetting.ReadCommittedSnapshotOn, t.Setting); - // The real figures survive the persistence round-trip. - Assert.NotNull(rcsi.Remediation.RcsiFigures); - Assert.Equal(12, rcsi.Remediation.RcsiFigures!.BlockingEvents); - Assert.Equal(3, rcsi.Remediation.RcsiFigures.Deadlocks); - Assert.Equal(80, rcsi.Remediation.RcsiFigures.ReaderWriterPct); - } - - [Fact] - public void CrossSurface_RiskDisclosure_RendersInBothEmailBodiesAndWebhook() - { - var context = FindingMessageFormatter.BuildContext(DbConfigRcsiFinding(), notifyThreshold: 1.5); - var branding = EmailAlertService.Branding; - - // Both email bodies flow from context.Details — the disclosure must render in EACH - // (feedback_emailtemplatebuilder_two_bodies: HTML + plain-text are separate bodies). - var (html, plain) = EmailTemplateBuilder.BuildAlertEmail( - "High CPU", "TestServer", "n/a", "n/a", 15, branding, context); - - foreach (var body in new[] { html, plain }) - { - Assert.Contains("RCSI — risks of changing / not changing", body); - Assert.Contains("Risks of CHANGING", body); - Assert.Contains("Risks of NOT changing", body); - Assert.Contains("RCSI eliminates", body); - } - - // Webhook payloads (Teams + Slack) also flow from context.Details. - var teams = WebhookAlertService.BuildTeamsPayload( - "High CPU", "TestServer", "n/a", "n/a", branding, context: context); - var slack = WebhookAlertService.BuildSlackPayload( - "High CPU", "TestServer", "n/a", "n/a", branding, context: context); - - foreach (var payload in new[] { teams, slack }) - { - Assert.Contains("Risks of NOT changing", payload); - Assert.Contains("RCSI eliminates", payload); - } - } - - // ── Clear-cached-plan (PR-B): "Clear cached plan (advanced)" item + cross-surface ── - - private static AnalysisFinding CpuFindingWithAbnormalPlans( - bool withRow = true, string rootFactKey = "CPU_SQL_PERCENT", - int cpuPercent = 62, bool planRegressionCoFired = false, bool parameterSensitivityCoFired = false) - { - var rows = new List(); - if (withRow) - { - rows.Add(new - { - query_hash = "0xABCDEF0123456789", - database = "AdventureWorks", - current_cpu_per_exec_ms = 45.0, - baseline_cpu_per_exec_ms = 9.0, - anomaly_ratio = 5.0, - execution_count = 1200L, - total_cpu_ms = 54000.0, - latest_plan_handle = "0x06000100ABCD", - query_text = "SELECT * FROM dbo.BigTable WHERE x = @p", - cpu_percent = cpuPercent, - plan_regression_cofired = planRegressionCoFired, - parameter_sensitivity_cofired = parameterSensitivityCoFired - }); - } - return MakeFinding("cpuplan000000001", rootFactKey: rootFactKey, category: "cpu", - drillDown: new Dictionary { ["abnormal_cpu_plans"] = rows }); - } - - [Fact] - public void BuildContext_CpuWithAbnormalPlans_EmitsClearCachedPlanItem() - { - var context = FindingMessageFormatter.BuildContext(CpuFindingWithAbnormalPlans(), notifyThreshold: 1.5); - - var item = Assert.Single(context.Details, d => d.Heading == "Clear cached plan (advanced)"); - Assert.True(item.IsCodeBlock); - Assert.NotNull(item.Remediation); - Assert.Equal("CLEAR_PLAN", item.Remediation!.FactKey); - var t = Assert.Single(item.Remediation.ClearPlanTargets!); - Assert.Equal("0xABCDEF0123456789", t.QueryHash); - // The figures rode the action (captured while the finding was in hand) incl. the REAL cpu%. - Assert.NotNull(item.Remediation.ClearPlanFigures); - Assert.Equal(62, item.Remediation.ClearPlanFigures!.CpuPercent); - - // The cross-surface disclosure item is also present (read-only, both email bodies + webhook). - var disclosure = Assert.Single(context.Details, d => d.Heading == "Clear cached plan — risks of changing / not changing"); - Assert.False(disclosure.IsCodeBlock); - Assert.Contains("Risks of CHANGING", disclosure.Body); - Assert.Contains("Risks of NOT changing", disclosure.Body); - Assert.Contains("62%", disclosure.Body); // the REAL cpu% (LOW-1 fix), not 0% - Assert.Contains("forces a recompile", disclosure.Body); - } - - [Fact] - public void BuildContext_CpuSpikeRootKey_AlsoEmitsClearCachedPlanItem() - { - var context = FindingMessageFormatter.BuildContext( - CpuFindingWithAbnormalPlans(rootFactKey: "CPU_SPIKE"), notifyThreshold: 1.5); - Assert.Contains(context.Details, d => d.Heading == "Clear cached plan (advanced)"); - } - - [Fact] - public void BuildContext_CpuNoQualifyingRow_EmitsNoClearCachedPlanItem() - { - // No qualifying abnormal_cpu_plans row -> no affordance, no disclosure. - var context = FindingMessageFormatter.BuildContext( - CpuFindingWithAbnormalPlans(withRow: false), notifyThreshold: 1.5); - Assert.DoesNotContain(context.Details, d => d.Heading == "Clear cached plan (advanced)"); - Assert.DoesNotContain(context.Details, d => d.Heading == "Clear cached plan — risks of changing / not changing"); - } - - [Fact] - public void BuildContext_ClearPlanItem_ActionAndFigures_SurviveRoundTrip() - { - var context = FindingMessageFormatter.BuildContext(CpuFindingWithAbnormalPlans(), notifyThreshold: 1.5); - var json = AlertContextSerializer.Serialize(context); - Assert.True(AlertContextSerializer.TryDeserialize(json, out var restored)); - - var item = Assert.Single(restored.Details, d => d.Heading == "Clear cached plan (advanced)"); - Assert.NotNull(item.Remediation); - Assert.Equal("CLEAR_PLAN", item.Remediation!.FactKey); - var t = Assert.Single(item.Remediation.ClearPlanTargets!); - Assert.Equal("0xABCDEF0123456789", t.QueryHash); - // The real figures (incl. the cpu% fix) survive the persistence round-trip. - Assert.NotNull(item.Remediation.ClearPlanFigures); - Assert.Equal(62, item.Remediation.ClearPlanFigures!.CpuPercent); - Assert.Equal(5.0, item.Remediation.ClearPlanFigures.AnomalyRatio); - } - - [Fact] - public void CrossSurface_ClearPlan_RiskDisclosure_RendersInBothEmailBodiesAndWebhook() - { - var context = FindingMessageFormatter.BuildContext(CpuFindingWithAbnormalPlans(), notifyThreshold: 1.5); - var branding = EmailAlertService.Branding; - - // Both email bodies flow from context.Details — the disclosure must render in EACH - // (feedback_emailtemplatebuilder_two_bodies: HTML + plain-text are separate bodies). - var (html, plain) = EmailTemplateBuilder.BuildAlertEmail( - "High CPU", "TestServer", "n/a", "n/a", 15, branding, context); - - foreach (var body in new[] { html, plain }) - { - Assert.Contains("Clear cached plan — risks of changing / not changing", body); - Assert.Contains("Risks of CHANGING", body); - Assert.Contains("Risks of NOT changing", body); - Assert.Contains("62%", body); // the REAL cpu% in both bodies - } - - // Webhook payloads (Teams + Slack) also flow from context.Details. - var teams = WebhookAlertService.BuildTeamsPayload( - "High CPU", "TestServer", "n/a", "n/a", branding, context: context); - var slack = WebhookAlertService.BuildSlackPayload( - "High CPU", "TestServer", "n/a", "n/a", branding, context: context); - - foreach (var payload in new[] { teams, slack }) - { - Assert.Contains("Risks of NOT changing", payload); - Assert.Contains("forces a recompile", payload); - } - } - - [Fact] - public void CrossSurface_ClearPlan_McpDisclosure_FromGetForFinding() - { - // The MCP analyze_server output reads advice.Risks from FactAdvice.GetForFinding — - // the SAME seam email/webhook use. A CPU finding with abnormal_cpu_plans must carry - // the two-sided CLEAR_PLAN disclosure there too. - var advice = FactAdvice.GetForFinding(CpuFindingWithAbnormalPlans()); - Assert.NotNull(advice); - Assert.NotNull(advice!.Risks); - Assert.NotEmpty(advice.Risks!.RisksOfChanging); - Assert.NotEmpty(advice.Risks.RisksOfNotChanging); - Assert.Contains(advice.Risks.RisksOfChanging, r => r.Text.Contains("forces a recompile")); - Assert.Contains(advice.Risks.RisksOfNotChanging, r => r.Text.Contains("62%")); - } - - [Fact] - public void AlertContext_LegacyJsonWithoutRemediation_DeserializesToNull() - { - // A persisted context written before the Remediation field existed: a code - // block with no "Remediation" property. It must deserialize cleanly with - // Remediation == null (no Apply button, no crash) — backward compatibility. - const string legacyJson = - "{\"Details\":[{\"Heading\":\"Remediation T-SQL\",\"Fields\":[]," + - "\"Body\":\"EXEC sys.sp_query_store_force_plan @query_id = 1, @plan_id = 2;\",\"IsCodeBlock\":true}]}"; - - Assert.True(AlertContextSerializer.TryDeserialize(legacyJson, out var restored)); - var item = Assert.Single(restored.Details); - Assert.True(item.IsCodeBlock); - Assert.Null(item.Remediation); - Assert.Contains("sp_query_store_force_plan", item.Body); - } - - // ── Recommendations rebuild D2: persist the BUILT RemediationAction on a finding ── - // SerializeAction/DeserializeAction wrap the SAME private ToDto/FromDto the alert - // path uses, so a finding's persisted action round-trips byte-identically. These - // mirror the RCSI/clear-plan ContextJson round-trips above, but exercise the new - // single-action seam the Recommendations reader uses. - - [Fact] - public void SerializeAction_RcsiAction_RoundTripsFiguresAndTargets() - { - // Build a real RCSI action from a finding whose config_issues row is rcsi:false - // with the inaction enrichment, then round-trip ONLY the action (the finding seam). - var action = FactRemediation.BuildRcsiAction(DbConfigRcsiFinding()); - Assert.NotNull(action); - Assert.Equal("RCSI", action!.FactKey); - - var json = AlertContextSerializer.SerializeAction(action); - Assert.NotNull(json); - var restored = AlertContextSerializer.DeserializeAction(json); - - Assert.NotNull(restored); - Assert.Equal("RCSI", restored!.FactKey); - var t = Assert.Single(restored.DbConfigTargets!); - Assert.Equal(DbConfigSetting.ReadCommittedSnapshotOn, t.Setting); - // The RcsiInactionFigures survive the persist round-trip. - Assert.NotNull(restored.RcsiFigures); - Assert.Equal(12, restored.RcsiFigures!.BlockingEvents); - Assert.Equal(3, restored.RcsiFigures.Deadlocks); - Assert.Equal(80, restored.RcsiFigures.ReaderWriterPct); - } - - [Fact] - public void SerializeAction_ClearPlanAction_RoundTripsFiguresAndTargets() - { - var action = FactRemediation.BuildClearPlanAction(CpuFindingWithAbnormalPlans()); - Assert.NotNull(action); - Assert.Equal("CLEAR_PLAN", action!.FactKey); - - var json = AlertContextSerializer.SerializeAction(action); - Assert.NotNull(json); - var restored = AlertContextSerializer.DeserializeAction(json); - - Assert.NotNull(restored); - Assert.Equal("CLEAR_PLAN", restored!.FactKey); - var t = Assert.Single(restored.ClearPlanTargets!); - Assert.Equal("0xABCDEF0123456789", t.QueryHash); - // The ClearPlanFigures survive the persist round-trip. - Assert.NotNull(restored.ClearPlanFigures); - Assert.Equal(62, restored.ClearPlanFigures!.CpuPercent); - Assert.Equal(5.0, restored.ClearPlanFigures.AnomalyRatio); - } - - [Fact] - public void SerializeAction_NullAction_SerializesAndDeserializesToNull() - { - // A finding with no execution shape persists a NULL column → no Apply affordance. - Assert.Null(AlertContextSerializer.SerializeAction(null)); - Assert.Null(AlertContextSerializer.DeserializeAction(null)); - Assert.Null(AlertContextSerializer.DeserializeAction("")); - // Garbage JSON degrades to null (try-catch), never throws. - Assert.Null(AlertContextSerializer.DeserializeAction("{ not json")); - } - - [Fact] - public void PersistedRcsiAction_RendersTwoSidedConsentGate_WithFindingNull() - { - // THE C1 GATING TEST. The Recommendations Apply surface reconstructs the action from - // the persisted remediation_action_json and has NO finding in hand, then asks - // FactRiskDisclosure.GetForAction(action, finding: null) for the consent gate. This - // proves the gate renders the REAL inaction figures from the PERSISTED ACTION ALONE. - var built = FactRemediation.BuildRcsiAction(DbConfigRcsiFinding(blocking: 12, deadlocks: 3, rwPct: 80)); - Assert.NotNull(built); - - // Round-trip through the exact persistence seam the store row uses. - var json = AlertContextSerializer.SerializeAction(built); - var action = AlertContextSerializer.DeserializeAction(json); - Assert.NotNull(action); - - // finding: null — exactly how the real Apply call site invokes it. - var disclosure = FactRiskDisclosure.GetForAction(action!, finding: null); - - Assert.NotNull(disclosure); - Assert.NotEmpty(disclosure!.RisksOfChanging); // two-sided: risk OF changing - Assert.NotEmpty(disclosure.RisksOfNotChanging); // two-sided: risk of NOT changing - - // The original inaction figures (carried on the action) are present in the rendered - // inaction side — proving they survived persistence and drive the gate with no finding. - var inaction = string.Join(" ", disclosure.RisksOfNotChanging.Select(r => r.Text)); - Assert.Contains("12 blocked-process events", inaction); - Assert.Contains("3 deadlocks", inaction); - Assert.Contains("80%", inaction); // 80% reader/writer - Assert.Contains("RCSI eliminates", inaction); // the >=50% reader/writer arm - } - - // ── WS3: percent-autogrowth action persists + round-trips ────────── - - // The FILE_AUTOGROWTH_PERCENT action is built from the drill-down and carries its per-file - // targets through the SAME SerializeAction/DeserializeAction round-trip the store uses for - // remediation_action_json — so the Recommendations reader can rebuild the copy-paste on read - // AND the FileAutogrowthHandler can re-derive the MODIFY FILE targets at apply (the drill-down - // itself is ephemeral). The action is Apply-able (handler registered) and copy-paste. - [Fact] - public void FileAutogrowthAction_BuildsFromDrillDown_AndRoundTrips() - { - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - Category = "config", - StoryPath = "FILE_AUTOGROWTH_PERCENT", - StoryPathHash = "fa9001", - RootFactKey = "FILE_AUTOGROWTH_PERCENT", - DrillDown = new Dictionary - { - ["autogrowth_percent_files"] = new List - { - new { database = "AppDb", logical_file_name = "AppDb_log", file_type = "LOG", - total_size_mb = 250000.0, growth_pct = 10, - issue = "10% autogrowth on 244.1 GB LOG file", - alter_statement = "ignored-on-read" } - } - } - }; - - var action = FactRemediation.BuildFileAutogrowthAction(finding); - Assert.NotNull(action); - Assert.Equal("FILE_AUTOGROWTH_PERCENT", action!.FactKey); - Assert.NotNull(action.FileGrowthTargets); - Assert.Single(action.FileGrowthTargets!); - // LOG file -> 64 MB flat (data files -> 1024 MB). - Assert.Equal(64, action.FileGrowthTargets![0].RecommendedGrowthMb); - - var json = AlertContextSerializer.SerializeAction(action); - Assert.NotNull(json); - var restored = AlertContextSerializer.DeserializeAction(json); - - Assert.NotNull(restored); - Assert.Equal("FILE_AUTOGROWTH_PERCENT", restored!.FactKey); - Assert.NotNull(restored.FileGrowthTargets); - var t = Assert.Single(restored.FileGrowthTargets!); - Assert.Equal("AppDb", t.Database); - Assert.Equal("AppDb_log", t.LogicalFileName); - Assert.Equal(10, t.CurrentGrowthPercent); - Assert.Equal(64, t.RecommendedGrowthMb); - // The shared renderer rebuilds the exact copy-paste from the restored target. - Assert.Equal( - "ALTER DATABASE [AppDb] MODIFY FILE (NAME = [AppDb_log], FILEGROWTH = 64MB);", - FactRemediation.BuildModifyFileStatement(t.Database, t.LogicalFileName, t.RecommendedGrowthMb)); - } -} diff --git a/deprecated/Dashboard.Tests/AnomalyIncidentReconcilerTests.cs b/deprecated/Dashboard.Tests/AnomalyIncidentReconcilerTests.cs deleted file mode 100644 index 90743c2a9f..0000000000 --- a/deprecated/Dashboard.Tests/AnomalyIncidentReconcilerTests.cs +++ /dev/null @@ -1,257 +0,0 @@ -using System.Collections.Generic; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the shared (Stage B, change 3): after clustering -/// stamps each story's incident id, an ANOMALY_* story folds into the REGULAR finding that describes -/// the same symptom in the same run and same database, by rewriting its incident id onto the parent's. -/// Fold-don't-suppress, database-aware, and only when a real parent exists. Lives in both Lite.Tests -/// and Dashboard.Tests because the reconciler is shared and each app references the assembly. -/// -public class AnomalyIncidentReconcilerTests -{ - private static AnalysisStory Story( - string rootKey, string incidentId, string? db = null, - Dictionary? metadata = null, double severity = 1.0, - IEnumerable? path = null) => - new() - { - RootFactKey = rootKey, - IncidentId = incidentId, - DatabaseName = db, - Severity = severity, - RootFactMetadata = metadata, - // Real stories carry their full traversal path (root + members). Default to the single-key - // path the earlier tests used; pass `path` to place a family fact as a NON-ROOT member. - Path = path is null ? [rootKey] : new List(path), - }; - - [Fact] - public void CxDominantWaitProfile_FoldsIntoCxpacketIncident() - { - // Dominant contrib_ is a CX* type -> family CXPACKET (mirrors GroupParallelismWaits). - var regular = Story("CXPACKET", "cx-incident", severity: 1.4); - var anomaly = Story("ANOMALY_WAIT_PROFILE", "anomaly-solo", - metadata: new() { ["contrib_CXPACKET"] = 5000, ["contrib_SOS_SCHEDULER_YIELD"] = 900 }); - - AnomalyIncidentReconciler.Reconcile(new List { regular, anomaly }); - - Assert.Equal("cx-incident", anomaly.IncidentId); // folded into the CXPACKET incident - Assert.Equal("cx-incident", regular.IncidentId); // parent id untouched - } - - [Fact] - public void GeneralLockDominantWaitProfile_FoldsIntoLckIncident() - { - // LCK_M_X is a general lock mode -> family LCK (mirrors IsGeneralLockWait grouping). - var regular = Story("LCK", "lck-incident"); - var anomaly = Story("ANOMALY_WAIT_PROFILE", "anomaly-solo", - metadata: new() { ["contrib_LCK_M_X"] = 8000, ["contrib_CXPACKET"] = 100 }); - - AnomalyIncidentReconciler.Reconcile(new List { regular, anomaly }); - - Assert.Equal("lck-incident", anomaly.IncidentId); - } - - [Fact] - public void ReaderLockDominantWaitProfile_FoldsIntoOwnKey_NotLck() - { - // LCK_M_S is kept separate from the LCK family (RCSI signal) -> family LCK_M_S, so it must - // fold into the LCK_M_S finding, NOT the general LCK one. - var lck = Story("LCK", "lck-incident"); - var readerLock = Story("LCK_M_S", "readerlock-incident"); - var anomaly = Story("ANOMALY_WAIT_PROFILE", "anomaly-solo", - metadata: new() { ["contrib_LCK_M_S"] = 8000, ["contrib_LCK_M_X"] = 10 }); - - AnomalyIncidentReconciler.Reconcile(new List { lck, readerLock, anomaly }); - - Assert.Equal("readerlock-incident", anomaly.IncidentId); - } - - [Fact] - public void CpuSpike_FoldsIntoCpuIncident() - { - var regular = Story("CPU_SQL_PERCENT", "cpu-incident"); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { regular, anomaly }); - - Assert.Equal("cpu-incident", anomaly.IncidentId); - } - - [Fact] - public void NoRegularParent_AnomalyStaysSolo() - { - // ANOMALY_CPU_SPIKE with no CPU_SQL_PERCENT parent (only an unrelated regular story) stays solo. - var unrelated = Story("CXPACKET", "cx-incident"); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { unrelated, anomaly }); - - Assert.Equal("anomaly-solo", anomaly.IncidentId); - } - - [Fact] - public void DifferentDatabase_DoesNotFold() - { - // The anomaly is in db1, the only regular parent is in db2 -> DB-aware, no fold. - var regular = Story("CPU_SQL_PERCENT", "cpu-db2", db: "db2"); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-db1", db: "db1"); - - AnomalyIncidentReconciler.Reconcile(new List { regular, anomaly }); - - Assert.Equal("anomaly-db1", anomaly.IncidentId); - } - - [Fact] - public void SameDatabase_Folds() - { - var regular = Story("CPU_SQL_PERCENT", "cpu-db1", db: "db1"); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-db1", db: "db1"); - - AnomalyIncidentReconciler.Reconcile(new List { regular, anomaly }); - - Assert.Equal("cpu-db1", anomaly.IncidentId); - } - - [Fact] - public void AnomalyObject_NeverCrossDbFolds() - { - // ANOMALY_OBJECT_* is unmapped AND db-scoped: it never folds, and certainly not into a - // regular finding in a different database. - var regularDb2 = Story("BLOCKING_EVENTS", "blk-db2", db: "db2"); - var objectAnomaly = Story("ANOMALY_OBJECT_CONTENTION", "object-db1", db: "db1"); - - AnomalyIncidentReconciler.Reconcile(new List { regularDb2, objectAnomaly }); - - Assert.Equal("object-db1", objectAnomaly.IncidentId); - } - - [Fact] - public void UnmappedAnomaly_StaysSolo() - { - // Batch/session/query-duration anomalies have no single regular counterpart. - var regular = Story("CPU_SQL_PERCENT", "cpu-incident"); - var anomaly = Story("ANOMALY_BATCH_REQUESTS", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { regular, anomaly }); - - Assert.Equal("anomaly-solo", anomaly.IncidentId); - } - - [Fact] - public void AbsolutionParent_IsIgnored() - { - // An absolution story is never a fold target. - var absolution = new AnalysisStory { RootFactKey = "server_health", IsAbsolution = true, IncidentId = "" }; - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { absolution, anomaly }); - - Assert.Equal("anomaly-solo", anomaly.IncidentId); - } - - [Fact] - public void FewerThanTwoStories_NoOp() - { - AnomalyIncidentReconciler.Reconcile(null!); // no throw - var solo = new List { Story("ANOMALY_CPU_SPIKE", "anomaly-solo") }; - AnomalyIncidentReconciler.Reconcile(solo); - Assert.Equal("anomaly-solo", solo[0].IncidentId); - } - - /* ── Path-based fold-target indexing (review finding 2): a mapped family fact is frequently a - NON-ROOT member of a larger story, so fold targets are indexed by every key in a regular story's - PATH, not just its root — the case the earlier tests (family fact always AS the root) never hit. ── */ - - [Fact] - public void CpuSpike_FoldsIntoStory_WhereCpuSqlPercentIsNonRootMember() - { - // Canonical correlated run: a higher-severity SOS_SCHEDULER_YIELD roots the story and consumes - // CPU_SQL_PERCENT as a member (SOS -> CPU_SQL_PERCENT). No story is ROOTED on CPU_SQL_PERCENT, so - // root-only indexing missed this exact case; path indexing folds the anomaly in. - var cpuStory = Story("SOS_SCHEDULER_YIELD", "cpu-incident", severity: 1.7, - path: new[] { "SOS_SCHEDULER_YIELD", "CPU_SQL_PERCENT" }); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { cpuStory, anomaly }); - - Assert.Equal("cpu-incident", anomaly.IncidentId); - } - - [Fact] - public void BlockingSpike_FoldsIntoStory_WhereBlockingIsNonRootMember() - { - // Generality beyond CPU: BLOCKING_EVENTS consumed as a member of a THREADPOOL-rooted story - // (THREADPOOL/LCK -> BLOCKING_EVENTS). The root key is the THREADPOOL relabel (not a fold - // target itself), but its BLOCKING_EVENTS member is indexed and captures the anomaly. - var threadpool = Story("THREADPOOL_BLOCKING", "blk-incident", severity: 1.8, - path: new[] { "THREADPOOL_BLOCKING", "BLOCKING_EVENTS" }); - var anomaly = Story("ANOMALY_BLOCKING_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { threadpool, anomaly }); - - Assert.Equal("blk-incident", anomaly.IncidentId); - } - - [Fact] - public void CpuSpike_FoldsIntoCpuSpikeRootedStory() - { - // Sub-note: a run whose CPU story is keyed on the BURST detector (CPU_SPIKE) rather than the - // sustained CPU_SQL_PERCENT is still a valid parent for ANOMALY_CPU_SPIKE. - var burst = Story("CPU_SPIKE", "burst-incident"); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { burst, anomaly }); - - Assert.Equal("burst-incident", anomaly.IncidentId); - } - - [Fact] - public void CpuSpike_FoldsIntoStory_WhereCpuSpikeIsNonRootMember() - { - // Sub-note, non-root form: CPU_SPIKE consumed as a member of a plan-regression story - // (PLAN_REGRESSION -> CPU_SPIKE) is still a valid CPU parent for the anomaly. - var planStory = Story("PLAN_REGRESSION", "plan-incident", severity: 1.5, - path: new[] { "PLAN_REGRESSION", "CPU_SPIKE" }); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { planStory, anomaly }); - - Assert.Equal("plan-incident", anomaly.IncidentId); - } - - [Fact] - public void PathIndexing_DoesNotFoldIntoUnrelatedMultiKeyStory() - { - // No over-fold: a multi-key story that does NOT contain a CPU family key must not capture - // ANOMALY_CPU_SPIKE, even though path indexing now considers every member. - var unrelated = Story("ASYNC_NETWORK_IO", "net-incident", severity: 1.3, - path: new[] { "ASYNC_NETWORK_IO", "PAGELATCH_EX" }); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { unrelated, anomaly }); - - Assert.Equal("anomaly-solo", anomaly.IncidentId); - } - - [Fact] - public void MultiKeyIndexing_FoldsIntoOwningStory_LeavesOthersUntouched() - { - // With two unrelated regular stories, the anomaly folds into the ONE whose path owns the CPU - // family (as a non-root member) and leaves the other incident id untouched — no over-fold. - var ioStory = Story("IO_READ_LATENCY_MS", "io-incident", severity: 1.2); - var cpuStory = Story("SOS_SCHEDULER_YIELD", "cpu-incident", severity: 1.7, - path: new[] { "SOS_SCHEDULER_YIELD", "CPU_SQL_PERCENT" }); - var anomaly = Story("ANOMALY_CPU_SPIKE", "anomaly-solo"); - - AnomalyIncidentReconciler.Reconcile(new List { ioStory, cpuStory, anomaly }); - - Assert.Equal("cpu-incident", anomaly.IncidentId); - Assert.Equal("io-incident", ioStory.IncidentId); // unrelated story untouched - Assert.Equal("cpu-incident", cpuStory.IncidentId); // parent id untouched - } -} diff --git a/deprecated/Dashboard.Tests/AzureAuthConnectionStringTests.cs b/deprecated/Dashboard.Tests/AzureAuthConnectionStringTests.cs deleted file mode 100644 index e31d004fe2..0000000000 --- a/deprecated/Dashboard.Tests/AzureAuthConnectionStringTests.cs +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using System.Collections.Generic; -using Microsoft.Data.SqlClient; -using PerformanceMonitor.Common; -using PerformanceMonitorDashboard.Interfaces; -using PerformanceMonitorDashboard.Models; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Connection-string SHAPE tests for the non-interactive Azure auth modes: service principal and -/// managed identity. Mirrors Lite.Tests/AzureAuthConnectionStringTests so the two apps' SP/MI keyword -/// mapping can never silently drift apart. The testable surface is the keywords emitted by -/// ServerConnection.ApplyAuthentication (shared by the production GetConnectionString builder and the -/// Add/Edit dialog's Test-Connection builder). Real Azure auth (token acquisition) is a maintainer -/// E2E step and is NOT exercised here. -/// -public class AzureAuthConnectionStringTests -{ - /// In-memory ICredentialService so the credential-fetch paths can be exercised without - /// touching the real Windows Credential Manager. - private sealed class FakeCredentialService : ICredentialService - { - private readonly Dictionary _store = new(); - - public bool SaveCredential(string serverId, string username, string password) - { - _store[serverId] = (username, password); - return true; - } - - public (string Username, string Password)? GetCredential(string serverId) - => _store.TryGetValue(serverId, out var c) ? c : null; - - public bool DeleteCredential(string serverId) - { - _store.Remove(serverId); - return true; - } - - public bool CredentialExists(string serverId) => _store.ContainsKey(serverId); - - public bool UpdateCredential(string serverId, string username, string password) - { - _store[serverId] = (username, password); - return true; - } - } - - // ---- ApplyAuthentication keyword mapping ---------------------------------------------- - // Tests the shared helper directly (internal, visible via InternalsVisibleTo=Dashboard.Tests). - - private static (SqlAuthenticationMethod Auth, string? User, string? Pwd, bool Integrated) AuthShape( - string authType, string? user, string? pwd, string? azureClientId, string? miClientId) - { - var b = new SqlConnectionStringBuilder(); - ServerConnection.ApplyAuthentication(b, authType, user, pwd, azureClientId, miClientId); - return (b.Authentication, b.UserID, b.Password, b.IntegratedSecurity); - } - - [Fact] - public void ServicePrincipal_SetsActiveDirectoryServicePrincipal_WithClientIdAndSecret() - { - var shape = AuthShape(AuthenticationTypes.ServicePrincipal, "client-id-123", "the-secret", - azureClientId: null, miClientId: null); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryServicePrincipal, shape.Auth); - Assert.Equal("client-id-123", shape.User); - Assert.Equal("the-secret", shape.Pwd); - Assert.False(shape.Integrated); - } - - [Fact] - public void ServicePrincipal_FallsBackToAzureClientId_WhenUsernameNull() - { - var shape = AuthShape(AuthenticationTypes.ServicePrincipal, null, "secret", - azureClientId: "model-client-id", miClientId: null); - - Assert.Equal("model-client-id", shape.User); - Assert.Equal("secret", shape.Pwd); - } - - [Fact] - public void ManagedIdentity_SystemAssigned_NoUserIdNoPassword() - { - var shape = AuthShape(AuthenticationTypes.ManagedIdentity, null, null, - azureClientId: null, miClientId: null); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, shape.Auth); - Assert.True(string.IsNullOrEmpty(shape.User)); - Assert.True(string.IsNullOrEmpty(shape.Pwd)); - Assert.False(shape.Integrated); - } - - [Fact] - public void ManagedIdentity_UserAssigned_SetsUserIdToClientId() - { - var shape = AuthShape(AuthenticationTypes.ManagedIdentity, null, null, - azureClientId: null, miClientId: "uami-client-id"); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, shape.Auth); - Assert.Equal("uami-client-id", shape.User); - Assert.True(string.IsNullOrEmpty(shape.Pwd)); - } - - // ---- Regression: existing modes unchanged --------------------------------------------- - - [Fact] - public void Windows_UsesIntegratedSecurity_NoAuthenticationKeyword() - { - var shape = AuthShape(AuthenticationTypes.Windows, null, null, null, null); - - Assert.True(shape.Integrated); - Assert.Equal(SqlAuthenticationMethod.NotSpecified, shape.Auth); - } - - [Fact] - public void SqlServer_SetsUserIdAndPassword_NoAuthenticationKeyword() - { - var shape = AuthShape(AuthenticationTypes.SqlServer, "sa", "pw", null, null); - - Assert.False(shape.Integrated); - Assert.Equal("sa", shape.User); - Assert.Equal("pw", shape.Pwd); - Assert.Equal(SqlAuthenticationMethod.NotSpecified, shape.Auth); - } - - [Fact] - public void EntraMfa_SetsActiveDirectoryInteractive() - { - var shape = AuthShape(AuthenticationTypes.EntraMFA, "user@tenant.com", null, null, null); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryInteractive, shape.Auth); - Assert.Equal("user@tenant.com", shape.User); - } - - // ---- AuthenticationDisplay switch (label parity with Lite) ---------------------------- - - [Theory] - [InlineData(AuthenticationTypes.ServicePrincipal, "Azure — Service Principal")] - [InlineData(AuthenticationTypes.ManagedIdentity, "Azure — Managed Identity")] - [InlineData(AuthenticationTypes.EntraMFA, "Microsoft Entra MFA")] - [InlineData(AuthenticationTypes.SqlServer, "SQL Server")] - [InlineData(AuthenticationTypes.Windows, "Windows")] - public void AuthenticationDisplay_MapsEachMode(string authType, string expected) - { - var server = new ServerConnection { AuthenticationType = authType }; - Assert.Equal(expected, server.AuthenticationDisplay); - } - - // ---- Full GetConnectionString path (unified builder + credential resolution) ---------- - - private static SqlConnectionStringBuilder Build(ServerConnection server, ICredentialService cs) - => new(server.GetConnectionString(cs)); - - [Fact] - public void GetConnectionString_ServicePrincipal_FetchesStoredSecret() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { ServerName = "s", AuthenticationType = AuthenticationTypes.ServicePrincipal }; - cs.SaveCredential(server.Id, "stored-client-id", "stored-secret"); - - var conn = Build(server, cs); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryServicePrincipal, conn.Authentication); - Assert.Equal("stored-client-id", conn.UserID); - Assert.Equal("stored-secret", conn.Password); - // Dashboard always targets the PerformanceMonitor database. - Assert.Equal("PerformanceMonitor", conn.InitialCatalog); - } - - [Fact] - public void GetConnectionString_ServicePrincipal_FallsBackToAzureClientId_WhenNoStoredUsername() - { - // No stored credential — the model's AzureClientId supplies the UserID. - var cs = new FakeCredentialService(); - var server = new ServerConnection - { - ServerName = "s", - AuthenticationType = AuthenticationTypes.ServicePrincipal, - AzureClientId = "model-client-id" - }; - - var conn = Build(server, cs); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryServicePrincipal, conn.Authentication); - Assert.Equal("model-client-id", conn.UserID); - } - - [Fact] - public void GetConnectionString_ManagedIdentity_FetchesNoSecret() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { ServerName = "s", AuthenticationType = AuthenticationTypes.ManagedIdentity }; - // Even if a stale credential somehow existed, MI must not pull it into the string. - cs.SaveCredential(server.Id, "leftover", "leftover-secret"); - - var conn = Build(server, cs); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, conn.Authentication); - Assert.True(string.IsNullOrEmpty(conn.Password)); - Assert.NotEqual("leftover", conn.UserID); - } - - [Fact] - public void GetConnectionString_ManagedIdentity_UserAssigned_SetsUserId() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection - { - ServerName = "s", - AuthenticationType = AuthenticationTypes.ManagedIdentity, - ManagedIdentityClientId = "uami-client-id" - }; - - var conn = Build(server, cs); - - Assert.Equal("uami-client-id", conn.UserID); - Assert.True(string.IsNullOrEmpty(conn.Password)); - } - - [Fact] - public void GetConnectionString_Windows_UsesIntegratedSecurity() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { ServerName = "s", AuthenticationType = AuthenticationTypes.Windows }; - - var conn = Build(server, cs); - - Assert.True(conn.IntegratedSecurity); - Assert.Equal(SqlAuthenticationMethod.NotSpecified, conn.Authentication); - } - - [Fact] - public void GetConnectionString_SqlServer_FetchesStoredUsernameAndPassword() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { ServerName = "s", AuthenticationType = AuthenticationTypes.SqlServer }; - cs.SaveCredential(server.Id, "sa", "pw"); - - var conn = Build(server, cs); - - Assert.False(conn.IntegratedSecurity); - Assert.Equal("sa", conn.UserID); - Assert.Equal("pw", conn.Password); - Assert.Equal(SqlAuthenticationMethod.NotSpecified, conn.Authentication); - } - - [Fact] - public void GetConnectionString_EntraMfa_SetsInteractive_AndUsernameHint() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { ServerName = "s", AuthenticationType = AuthenticationTypes.EntraMFA }; - cs.SaveCredential(server.Id, "user@tenant.com", string.Empty); - - var conn = Build(server, cs); - - Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryInteractive, conn.Authentication); - Assert.Equal("user@tenant.com", conn.UserID); - } - - // ---- HasStoredCredentials -------------------------------------------------------------- - - [Fact] - public void HasStoredCredentials_ManagedIdentity_IsTrue_WithoutCredential() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { AuthenticationType = AuthenticationTypes.ManagedIdentity }; - - Assert.True(server.HasStoredCredentials(cs)); - } - - [Fact] - public void HasStoredCredentials_ServicePrincipal_ReflectsCredentialStore() - { - var cs = new FakeCredentialService(); - var server = new ServerConnection { AuthenticationType = AuthenticationTypes.ServicePrincipal }; - - Assert.False(server.HasStoredCredentials(cs)); - - cs.SaveCredential(server.Id, "client", "secret"); - Assert.True(server.HasStoredCredentials(cs)); - } - - // ---- Two-build-site PARITY ------------------------------------------------------------ - // The dialog's Test-Connection builder and ServerConnection's production builder both route - // their auth keywords through the shared ServerConnection.ApplyAuthentication helper, so they - // emit identical Authentication / UserID / Password / IntegratedSecurity for each mode. - - [Theory] - [InlineData(AuthenticationTypes.Windows)] - [InlineData(AuthenticationTypes.SqlServer)] - [InlineData(AuthenticationTypes.EntraMFA)] - [InlineData(AuthenticationTypes.ServicePrincipal)] - [InlineData(AuthenticationTypes.ManagedIdentity)] - public void BuildSites_ProduceIdenticalAuthShape_PerMode(string authType) - { - string? user = authType switch - { - AuthenticationTypes.SqlServer => "sa", - AuthenticationTypes.EntraMFA => "user@tenant.com", - AuthenticationTypes.ServicePrincipal => "client-id", - _ => null - }; - string? pwd = authType is AuthenticationTypes.SqlServer or AuthenticationTypes.ServicePrincipal ? "secret" : null; - string? mi = authType == AuthenticationTypes.ManagedIdentity ? "uami-id" : null; - - // Production builder passes the model's AzureClientId; the dialog builder passes null (it - // surfaces the SP client id as the username). Both must reduce to the same auth shape. - var production = AuthShape(authType, user, pwd, azureClientId: "client-id", miClientId: mi); - var dialog = AuthShape(authType, user, pwd, azureClientId: null, miClientId: mi); - - Assert.Equal(production, dialog); - } -} diff --git a/deprecated/Dashboard.Tests/BaselineBucketTests.cs b/deprecated/Dashboard.Tests/BaselineBucketTests.cs deleted file mode 100644 index 94ed27c4d5..0000000000 --- a/deprecated/Dashboard.Tests/BaselineBucketTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -using PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests for BaselineBucket.EffectiveStdDev: proportional floor and division-by-zero handling. -/// -public class BaselineBucketTests -{ - // ── Division by zero: proportional floor ── - - [Fact] - public void EffectiveStdDev_ZeroStdDev_UsesProportionalFloor() - { - // All identical values → stddev = 0, mean = 50 - var bucket = new BaselineBucket - { - HourOfDay = 14, DayOfWeek = 3, - Mean = 50.0, StdDev = 0.0, SampleCount = 20, - Tier = BaselineTier.Full - }; - - // Should be max(0, 50 * 0.01) = 0.5 - Assert.Equal(0.5, bucket.EffectiveStdDev); - } - - [Fact] - public void EffectiveStdDev_ZeroMeanAndZeroStdDev_ReturnsZero() - { - // Zero activity → skip scoring - var bucket = new BaselineBucket - { - HourOfDay = 14, DayOfWeek = 3, - Mean = 0.0, StdDev = 0.0, SampleCount = 20, - Tier = BaselineTier.Full - }; - - Assert.Equal(0.0, bucket.EffectiveStdDev); - } - - [Fact] - public void EffectiveStdDev_NormalStdDev_ReturnsActual() - { - var bucket = new BaselineBucket - { - HourOfDay = 14, DayOfWeek = 3, - Mean = 50.0, StdDev = 5.0, SampleCount = 20, - Tier = BaselineTier.Full - }; - - // StdDev (5.0) > Mean * 0.01 (0.5), so return actual - Assert.Equal(5.0, bucket.EffectiveStdDev); - } -} diff --git a/deprecated/Dashboard.Tests/BlockingChainReconstructorTests.cs b/deprecated/Dashboard.Tests/BlockingChainReconstructorTests.cs deleted file mode 100644 index 7333c67873..0000000000 --- a/deprecated/Dashboard.Tests/BlockingChainReconstructorTests.cs +++ /dev/null @@ -1,308 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Pure unit tests for BlockingChainReconstructor — apex/depth/victim reconstruction, the (monitor_loop, -/// spid, ecid) session identity (mirroring sp_HumanEventsBlockViewer), cumulative-vs-per-scan scoping, cycle -/// handling, and the traversal caps. No database. -/// -public class BlockingChainReconstructorTests -{ - private const int MaxDepth = 50; - private const int MaxPairs = 5000; - private const int StepBudget = 100_000; - - private static DateTime TranFor(int spid) => new DateTime(2026, 5, 22, 9, 0, 0).AddSeconds(spid); - - private static BlockingPairRow Pair( - int blockedSpid, int blockingSpid, - int? monitorLoop = null, int blockedEcid = 0, int blockingEcid = 0, - long waitMs = 1000, string blockingStatus = "running") - { - return new BlockingPairRow - { - EventTime = new DateTime(2026, 5, 22, 10, 0, 0), - DatabaseName = "TestDb", - BlockedSpid = blockedSpid, - BlockedTranStarted = TranFor(blockedSpid), - BlockingSpid = blockingSpid, - BlockingTranStarted = TranFor(blockingSpid), - MonitorLoop = monitorLoop, - BlockedEcid = blockedEcid, - BlockingEcid = blockingEcid, - WaitTimeMs = waitMs, - LockMode = "X", - BlockingStatus = blockingStatus, - BlockedSqlText = "blocked sql", - BlockingSqlText = "blocking sql" - }; - } - - // Default scope is cumulative (the collector path); the viewer-style tests pass scopeByMonitorLoop: true. - private static BlockingReconstruction Run(IEnumerable rows, bool scopeByMonitorLoop = false) => - BlockingChainReconstructor.Reconstruct(rows, MaxDepth, MaxPairs, StepBudget, scopeByMonitorLoop); - - [Fact] - public void Empty_ProducesNoChains() - { - var result = Run(Array.Empty()); - Assert.Empty(result.Chains); - } - - [Fact] - public void DepthFourLine_ReportsApexDepthAndVictims() - { - // 200 → 201 → 202 → 203 → 204 - var result = Run(new[] - { - Pair(201, 200), Pair(202, 201), Pair(203, 202), Pair(204, 203) - }); - - var chain = Assert.Single(result.Chains); - Assert.Equal(200, chain.ApexSpid); - Assert.Equal(4, chain.Depth); - Assert.Equal(4, chain.VictimCount); - Assert.False(result.CycleDetected); - } - - [Fact] - public void FanOut_IsDepthOneWithAllVictims() - { - // 300 blocks 301..305 directly - var result = Run(Enumerable.Range(301, 5).Select(v => Pair(v, 300))); - - var chain = Assert.Single(result.Chains); - Assert.Equal(300, chain.ApexSpid); - Assert.Equal(1, chain.Depth); - Assert.Equal(5, chain.VictimCount); - } - - [Fact] - public void DeepChain_WithNullBlockerTran_StillFormsOneChain() - { - // The bug this whole change fixes: blocking_last_tran_started is always NULL, so the old (spid, tran) - // key split a mid-chain node. Keying by spid:ecid within monitor_loop, 116 → 111 → 80 is ONE depth-2 - // chain — 111 unifies as (loop, 111, 0) whether it is the blocker or the blocked party. - var result = Run(new[] - { - Pair(111, 116, monitorLoop: 620365), - Pair(80, 111, monitorLoop: 620365), - }, scopeByMonitorLoop: true); - - var chain = Assert.Single(result.Chains); - Assert.Equal(116, chain.ApexSpid); - Assert.Equal(2, chain.Depth); - Assert.Equal(2, chain.VictimCount); - } - - [Fact] - public void SeparateEpisodes_SameSpid_DoNotLeak() - { - // The same blocker→blocked pair in two different monitor_loops (episodes) must stay two chains, not - // merge — the cross-episode leakage the monitor_loop scope prevents for the viewer. - var result = Run(new[] - { - Pair(201, 200, monitorLoop: 1), - Pair(201, 200, monitorLoop: 2), - }, scopeByMonitorLoop: true); - - Assert.Equal(2, result.Chains.Count); - Assert.All(result.Chains, c => Assert.Equal(200, c.ApexSpid)); - Assert.Contains(result.Chains, c => c.MonitorLoop == 1); - Assert.Contains(result.Chains, c => c.MonitorLoop == 2); - } - - [Fact] - public void ParallelBlocker_DistinctEcid_AreDistinctNodes() - { - // Same SPID, different ecid (parallel workers) are distinct sessions: spid 200 ecid 0 and ecid 1 each - // head their own chain. - var result = Run(new[] - { - Pair(201, 200, monitorLoop: 1, blockingEcid: 0), - Pair(202, 200, monitorLoop: 1, blockingEcid: 1), - }, scopeByMonitorLoop: true); - - Assert.Equal(2, result.Chains.Count); - Assert.Contains(result.Chains, c => c.ApexEcid == 0); - Assert.Contains(result.Chains, c => c.ApexEcid == 1); - } - - [Fact] - public void Cumulative_MergesAcrossScans() - { - // The collector (scopeByMonitorLoop:false) ignores monitor_loop, so an episode's per-scan re-fires - // merge into ONE chain — preserving window-level depth/victims for the severity fact (per-scan scoping - // would under-count). 200 → 201 (scan 1) and 201 → 202 (scan 2) form one depth-2 chain. - var result = Run(new[] - { - Pair(201, 200, monitorLoop: 1), - Pair(202, 201, monitorLoop: 2), - }, scopeByMonitorLoop: false); - - var chain = Assert.Single(result.Chains); - Assert.Equal(200, chain.ApexSpid); - Assert.Equal(2, chain.Depth); - Assert.Null(chain.MonitorLoop); // cumulative chains carry no episode - } - - [Fact] - public void SpidReuse_DifferentMonitorLoop_DoesNotSplice() - { - // SPID 201 reused across two episodes is two distinct sessions, not one spliced chain. - var result = Run(new[] - { - Pair(201, 200, monitorLoop: 1), - Pair(202, 201, monitorLoop: 1), // 200 → 201 → 202 in episode 1 - Pair(203, 201, monitorLoop: 2), // reused 201 heads its own chain in episode 2 - }, scopeByMonitorLoop: true); - - Assert.Equal(2, result.Chains.Count); - Assert.Contains(result.Chains, c => c.ApexSpid == 200 && c.Depth == 2); - Assert.Contains(result.Chains, c => c.ApexSpid == 201 && c.Depth == 1); - } - - [Fact] - public void PureCycle_IsDetectedAndGetsFallbackRoot() - { - // A blocks B, B blocks A — every node is blocked, so there is no apex. - var result = Run(new[] - { - Pair(blockedSpid: 401, blockingSpid: 400), - Pair(blockedSpid: 400, blockingSpid: 401) - }); - - Assert.True(result.CycleDetected); - Assert.NotEmpty(result.Chains); // fallback root — the cycle is not silently dropped - } - - [Fact] - public void DepthCap_IsFlaggedAndBounded() - { - // A 12-edge line, reconstructed with a maxDepth of 4. - var rows = Enumerable.Range(0, 12).Select(i => Pair(501 + i, 500 + i)).ToList(); - var result = BlockingChainReconstructor.Reconstruct(rows, maxDepth: 4, MaxPairs, StepBudget, scopeByMonitorLoop: false); - - Assert.True(result.DepthCapped); - var chain = Assert.Single(result.Chains); - Assert.True(chain.Depth <= 4, $"depth {chain.Depth} should be capped at 4"); - } - - [Fact] - public void EdgeDedup_KeepsTheLargestWaitTime() - { - // Same blocked/blocker pair re-fires with a growing wait time. - var result = Run(new[] - { - Pair(601, 600, waitMs: 1_000), - Pair(601, 600, waitMs: 9_000), - Pair(601, 600, waitMs: 4_000) - }); - - var chain = Assert.Single(result.Chains); - Assert.Equal(9_000, chain.MaxWaitMs); - } - - [Fact] - public void SleepingApex_IsReported() - { - var result = Run(new[] - { - Pair(701, 700, blockingStatus: "sleeping"), - Pair(702, 701) - }); - - var chain = Assert.Single(result.Chains); - Assert.Equal(700, chain.ApexSpid); - Assert.True(chain.ApexSleeping); - } - - [Fact] - public void Ranking_PutsTheHigherMagnitudeChainFirst() - { - // Chain A: depth 1, 8 victims (wide). Chain B: depth 2, 2 victims (shallow). - var rows = new List(); - rows.AddRange(Enumerable.Range(801, 8).Select(v => Pair(v, 800))); // wide - rows.Add(Pair(901, 900)); // narrow - rows.Add(Pair(902, 901)); - - var result = Run(rows); - - Assert.Equal(2, result.Chains.Count); - // The 8-victim fan-out out-scores the depth-2 / 2-victim chain. - Assert.Equal(800, result.Chains[0].ApexSpid); - } - - [Fact] - public void ReconstructedOutput_CarriesTranStartedAndDatabaseName() - { - // Transaction start is display-only now, sourced from the rows (apex from its first outgoing edge). - var result = Run(new[] { Pair(201, 200), Pair(202, 201) }); - - var chain = Assert.Single(result.Chains); - Assert.Equal(200, chain.ApexSpid); - Assert.Equal(TranFor(200), chain.ApexTranStarted); - - Assert.NotEmpty(chain.Levels); - Assert.All(chain.Levels, l => Assert.Equal("TestDb", l.DatabaseName)); - - var top = chain.Levels.Single(l => l.BlockingSpid == 200 && l.BlockedSpid == 201); - Assert.Equal(TranFor(200), top.BlockingTranStarted); - Assert.Equal(TranFor(201), top.BlockedTranStarted); - } - - [Fact] - public void FindChainForSession_AnyMember_ReturnsChainRootedAtApex() - { - // Two separate chains — A: 200 → 201 → 202 ; B: 300 → 301. The viewer scopes to the ONE chain a - // clicked session belongs to, rooted at its apex regardless of where in the chain it sits. - var result = Run(new[] { Pair(201, 200), Pair(202, 201), Pair(301, 300) }); - - // Mid-level 201 -> chain A, rooted at apex 200 (not at the clicked node). monitor_loop null -> matches - // by spid:ecid. - var chainA = BlockingChainReconstructor.FindChainForSession(result, null, 201, 0); - Assert.NotNull(chainA); - Assert.Equal(200, chainA!.ApexSpid); - - Assert.Equal(200, BlockingChainReconstructor.FindChainForSession(result, null, 200, 0)!.ApexSpid); - Assert.Equal(200, BlockingChainReconstructor.FindChainForSession(result, null, 202, 0)!.ApexSpid); - Assert.Equal(300, BlockingChainReconstructor.FindChainForSession(result, null, 301, 0)!.ApexSpid); - Assert.Null(BlockingChainReconstructor.FindChainForSession(result, null, 999, 0)); - } - - [Fact] - public void FindChainForSession_DisambiguatesByMonitorLoop() - { - // Victim 500 was blocked by apex 100 in episode 1 and apex 200 in episode 2 — two scoped chains, both - // containing 500. The clicked row's monitor_loop selects the right one. - var result = Run(new[] - { - Pair(blockedSpid: 500, blockingSpid: 100, monitorLoop: 1), - Pair(blockedSpid: 500, blockingSpid: 200, monitorLoop: 2) - }, scopeByMonitorLoop: true); - - Assert.Equal(100, BlockingChainReconstructor.FindChainForSession(result, 1, 500, 0)!.ApexSpid); - Assert.Equal(200, BlockingChainReconstructor.FindChainForSession(result, 2, 500, 0)!.ApexSpid); - } - - [Fact] - public void FindChainForSession_NullMonitorLoop_FallsBackToSpidEcid() - { - // A lead-blocker grid row may not supply its monitor_loop; the click must still resolve via spid:ecid - // rather than reporting "no reconstructable chain" (supersedes the #1222 SPID-only fallback). - var result = Run(new[] - { - Pair(201, 200, monitorLoop: 7), - Pair(202, 201, monitorLoop: 7), - }, scopeByMonitorLoop: true); - - var chain = BlockingChainReconstructor.FindChainForSession(result, null, 200, 0); - Assert.NotNull(chain); - Assert.Equal(200, chain!.ApexSpid); - } -} diff --git a/deprecated/Dashboard.Tests/BlockingPairRowMergeTests.cs b/deprecated/Dashboard.Tests/BlockingPairRowMergeTests.cs deleted file mode 100644 index 3818079b53..0000000000 --- a/deprecated/Dashboard.Tests/BlockingPairRowMergeTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Unit tests for BlockingPairRowMerge — merging always-on DMV-snapshot pair-rows into blocked-process-report -/// rows: BPR preferred, DMV-only filled in (the AWS RDS / threshold-unset case), overlapping edges kept from both sources. -/// No database. -/// -public class BlockingPairRowMergeTests -{ - private static readonly DateTime BaseTime = new(2026, 5, 22, 10, 0, 0); - - private static BlockingPairRow Pair(int blockedSpid, int blockingSpid, string source, - DateTime? eventTime = null, int blockedEcid = 0, int blockingEcid = 0) => - new() - { - EventTime = eventTime ?? BaseTime, - DatabaseName = "TestDb", - BlockedSpid = blockedSpid, - BlockingSpid = blockingSpid, - BlockedEcid = blockedEcid, - BlockingEcid = blockingEcid, - LockMode = "X", - BlockingStatus = "running", - BlockedSqlText = source, // tag the origin so assertions can tell which row survived - BlockingSqlText = source - }; - - [Fact] - public void EmptySnapshots_LeavesPrimaryUnchanged() - { - var primary = new List { Pair(201, 200, "BPR") }; - BlockingPairRowMerge.MergeInto(primary, Array.Empty()); - Assert.Equal("BPR", Assert.Single(primary).BlockedSqlText); - } - - [Fact] - public void EmptyPrimary_AddsAllSnapshots() - { - // The RDS / threshold-unset case: no blocked-process reports, the DMV snapshot is the only source. - var primary = new List(); - BlockingPairRowMerge.MergeInto(primary, new[] { Pair(201, 200, "DMV"), Pair(203, 202, "DMV") }); - Assert.Equal(2, primary.Count); - Assert.All(primary, r => Assert.Equal("DMV", r.BlockedSqlText)); - } - - [Fact] - public void OverlappingEdge_KeepsBothSources() - { - // Same edge (blocked/blocker spid:ecid, same minute) from both sources: both stay. Reconstruction is per scan - // and a BPR row and a DMV row never share a scan, so neither is a double count (#6931). - var primary = new List { Pair(201, 200, "BPR") }; - BlockingPairRowMerge.MergeInto(primary, new[] { Pair(201, 200, "DMV") }); - Assert.Equal(new[] { "BPR", "DMV" }, primary.Select(r => r.BlockedSqlText)); - } - - [Fact] - public void DistinctEdge_AddsDmvRow() - { - var primary = new List { Pair(201, 200, "BPR") }; - BlockingPairRowMerge.MergeInto(primary, new[] { Pair(301, 300, "DMV") }); - Assert.Equal(2, primary.Count); - } - - [Fact] - public void SameSpidsDifferentMinute_AreNotDeduped() - { - var primary = new List { Pair(201, 200, "BPR", BaseTime) }; - BlockingPairRowMerge.MergeInto(primary, new[] { Pair(201, 200, "DMV", BaseTime.AddMinutes(5)) }); - Assert.Equal(2, primary.Count); - } - - [Fact] - public void SameSpidDifferentEcid_AreNotDeduped() - { - // Parallel workers (distinct ecid) are distinct edges, not duplicates. - var primary = new List { Pair(201, 200, "BPR", blockingEcid: 0) }; - BlockingPairRowMerge.MergeInto(primary, new[] { Pair(201, 200, "DMV", blockingEcid: 1) }); - Assert.Equal(2, primary.Count); - } -} diff --git a/deprecated/Dashboard.Tests/ChartClickIsolateTests.cs b/deprecated/Dashboard.Tests/ChartClickIsolateTests.cs deleted file mode 100644 index 1ffbdc14f1..0000000000 --- a/deprecated/Dashboard.Tests/ChartClickIsolateTests.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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 PerformanceMonitor.Ui; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the pure, app-agnostic logic behind the shared chart click-to-isolate mechanic -/// (): toggle transitions, the dim-vs-full visual decision, and faithful -/// per-series restore for fill vs line-only charts. Isolate dims the other series and leaves the Y axis -/// untouched (no auto-fit). Mirror of Lite.Tests for parity. -/// -public class ChartClickIsolateTests -{ - // ── NextIsolate: toggle transitions ────────────────────────────────────────────────────── - - [Fact] - public void NextIsolate_FromNothing_IsolatesClicked() - { - Assert.Equal("CXPACKET", ChartHoverHelper.NextIsolate(null, "CXPACKET")); - } - - [Fact] - public void NextIsolate_ClickingIsolatedSeries_TogglesOff() - { - Assert.Null(ChartHoverHelper.NextIsolate("CXPACKET", "CXPACKET")); - } - - [Fact] - public void NextIsolate_ClickingDifferentSeries_SwitchesTarget() - { - Assert.Equal("WRITELOG", ChartHoverHelper.NextIsolate("CXPACKET", "WRITELOG")); - } - - [Fact] - public void NextIsolate_IsCaseSensitive_DifferentCaseIsADifferentSeries() - { - // Labels are exact series identifiers; a case difference is a different series, not a toggle-off. - Assert.Equal("cxpacket", ChartHoverHelper.NextIsolate("CXPACKET", "cxpacket")); - } - - // ── ResolveSeriesVisual: dim vs full decision ──────────────────────────────────────────── - - [Fact] - public void ResolveSeriesVisual_NothingIsolated_EverySeriesIsFull() - { - var v = ChartHoverHelper.ResolveSeriesVisual(null, "AnySeries"); - Assert.False(v.Dim); - Assert.True(v.FillRibbon); - } - - [Fact] - public void ResolveSeriesVisual_TargetSeries_IsFull() - { - var v = ChartHoverHelper.ResolveSeriesVisual("WRITELOG", "WRITELOG"); - Assert.False(v.Dim); - Assert.True(v.FillRibbon); - } - - [Fact] - public void ResolveSeriesVisual_NonTargetSeries_IsDimmedWithNoFill() - { - var v = ChartHoverHelper.ResolveSeriesVisual("WRITELOG", "CXPACKET"); - Assert.True(v.Dim); - Assert.False(v.FillRibbon); // the gradient ribbon is dropped while dimmed - Assert.Equal(ChartHoverHelper.DimAlpha, v.LineAlpha); - } - - [Fact] - public void DimAlpha_IsFaintButVisible() - { - Assert.Equal((byte)40, ChartHoverHelper.DimAlpha); - Assert.Equal((byte)40, ChartHoverHelper.IsolateVisual.Dimmed.LineAlpha); - Assert.True(ChartHoverHelper.IsolateVisual.Full.FillRibbon); - Assert.False(ChartHoverHelper.IsolateVisual.Full.Dim); - } - - // ── RestoreSeriesVisual: faithful restore for line-only AND fill charts (regression) ───────── - - [Fact] - public void RestoreSeriesVisual_LineOnlyChart_StaysLineOnly_NoPhantomMarkersOrFill() - { - // CollectorDuration / trend charts build line-only (MarkerSize 0, no fill) and never call - // StyleScatter. Restore must NOT re-run StyleScatter — that would add density markers + a fill. - var plot = new ScottPlot.Plot(); - var sc = plot.Add.Scatter(new double[] { 1, 2, 3 }, new double[] { 1, 2, 3 }); - var identity = ScottPlot.Color.FromHex("#4E79A7"); - sc.Color = identity; - sc.LineWidth = 1.5f; - sc.MarkerSize = 0; - sc.FillY = false; - var entry = new ChartHoverHelper.SeriesEntry(sc, "Collector", identity, - sc.LineColor, sc.LineWidth, sc.MarkerSize, sc.FillY); - - sc.Color = identity.WithAlpha(ChartHoverHelper.DimAlpha); // simulate a dim - ChartHoverHelper.RestoreSeriesVisual(entry); - - Assert.Equal(0f, sc.MarkerSize); // no phantom density markers - Assert.False(sc.FillY); // no phantom fill ribbon - Assert.Equal(1.5f, sc.LineWidth); // original width preserved - } - - [Fact] - public void RestoreSeriesVisual_FillChart_RebuildsTheStyleScatterLook() - { - // A StyleScatter'd fill chart restores via StyleScatter, which rebuilds the gradient from the - // unchanged data — reproducing the original look (isolate never spans a re-render). - var plot = new ScottPlot.Plot(); - var sc = plot.Add.Scatter(new double[] { 1, 2, 3 }, new double[] { 0, 5, 10 }); - var identity = ScottPlot.Color.FromHex("#4E79A7"); - sc.Color = identity; - ChartStyle.StyleScatter(sc); - var entry = new ChartHoverHelper.SeriesEntry(sc, "Wait", identity, - sc.LineColor, sc.LineWidth, sc.MarkerSize, sc.FillY); - Assert.True(entry.OrigFillY); // StyleScatter set FillY=true (data has a range) - - sc.Color = identity.WithAlpha(ChartHoverHelper.DimAlpha); - sc.FillY = false; // simulate a dim - ChartHoverHelper.RestoreSeriesVisual(entry); - - Assert.True(sc.FillY); // fill ribbon rebuilt - Assert.Equal(2f, sc.LineWidth); // StyleScatter's signature line width - } -} diff --git a/deprecated/Dashboard.Tests/ChartStyleYLimitsTests.cs b/deprecated/Dashboard.Tests/ChartStyleYLimitsTests.cs deleted file mode 100644 index 3613ca56e4..0000000000 --- a/deprecated/Dashboard.Tests/ChartStyleYLimitsTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 PerformanceMonitor.Ui; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Regression tests for — the pure Y-limit math -/// shared by every trend chart in all three apps (Lite, Dashboard, and the Darling viewer). Pins the fix -/// for the magnitude-scaled negative floor bug: a non-negative series (dataYMin >= 0) must floor the -/// axis at 0, NOT at -5% of the data max. The old middle branch put a big dead-band under high-value -/// charts (e.g. Wait Stats peaking ~6000 ms/sec dropped to a -300 floor). Only genuinely-negative data -/// keeps a below-zero margin. Mirror of Lite.Tests for parity. -/// -public class ChartStyleYLimitsTests -{ - [Fact] - public void ZeroDataMin_FloorsAtZero_NoNegativeDeadBand() - { - // The exact bug: callers pass an explicit dataYMin == 0, which used to hit the middle branch - // and produce yMin = -(range * 0.05) = -300 for a 0..6000 chart. It must now floor at 0. - var (yMin, _) = ChartStyle.ComputeYLimitsWithLegendPadding(0, 6000); - Assert.Equal(0.0, yMin); - } - - [Fact] - public void PositiveDataMin_FloorsAtZero() - { - var (yMin, _) = ChartStyle.ComputeYLimitsWithLegendPadding(50, 6000); - Assert.Equal(0.0, yMin); - } - - [Fact] - public void NegativeDataMin_KeepsTenPercentBelowZeroMargin() - { - // range = 100; genuinely-negative data keeps its 10%-of-range breathing room below the min. - var (yMin, _) = ChartStyle.ComputeYLimitsWithLegendPadding(-10, 90); - Assert.Equal(-20.0, yMin, 6); // -10 - (100 * 0.10) - } - - [Fact] - public void TopPadding_IsFifteenPercentOfRange() - { - var (_, yMax) = ChartStyle.ComputeYLimitsWithLegendPadding(0, 6000); - Assert.Equal(6900.0, yMax, 6); // 6000 + (6000 * 0.15) - } - - [Fact] - public void FlatData_ExpandsRangeAndStillFloorsAtZero() - { - // dataYMax <= dataYMin forces range to 1 so a flat non-negative series still gets a visible band. - var (yMin, yMax) = ChartStyle.ComputeYLimitsWithLegendPadding(5, 5); - Assert.Equal(0.0, yMin); - Assert.Equal(6.15, yMax, 6); // dataYMax -> 6, + (1 * 0.15) - } -} diff --git a/deprecated/Dashboard.Tests/CoFiredSummaryTests.cs b/deprecated/Dashboard.Tests/CoFiredSummaryTests.cs deleted file mode 100644 index 7f49e37136..0000000000 --- a/deprecated/Dashboard.Tests/CoFiredSummaryTests.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Collections.Generic; -using PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Services.Recommendations; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the shared "what else fired in this window" cross-reference (correlate-and-focus slice 1, -/// review §1d): the pure helper and the Dashboard reader's per-card -/// append. The Lite reader's append is covered in LiteRecommendationsReaderTests. -/// -public class CoFiredSummaryTests -{ - [Fact] - public void OtherTitles_ExcludesSelf_OrdersBySeverityDesc_Dedups() - { - var window = new List<(string, double)> { ("A", 0.5), ("B", 1.9), ("C", 0.8), ("B", 1.0) }; - var others = CoFiredSummary.OtherTitles("A", window); - Assert.Equal(new[] { "B", "C" }, others); // self A excluded; B(1.9) before C(0.8); duplicate B collapsed - } - - [Fact] - public void Line_CapsAndCountsTheRest() - { - var others = new List { "A", "B", "C", "D", "E" }; - Assert.Equal( - "Also surfaced in this analysis window: A; B; C (+2 more).", - CoFiredSummary.Line(others, cap: 3)); - } - - [Fact] - public void Line_NoExtra_OmitsTheCount() - { - Assert.Equal( - "Also surfaced in this analysis window: A; B.", - CoFiredSummary.Line(new List { "A", "B" }, cap: 3)); - } - - [Fact] - public void Line_NullForEmpty() - { - Assert.Null(CoFiredSummary.Line(new List())); - } - - [Fact] - public void DashboardReader_AppendCoFired_AppendsTheOthersToEachCard() - { - var items = new List - { - new() { Title = "High problem", RawSeverity = 1.9, AdviceText = "fix high." }, - new() { Title = "Low problem", RawSeverity = 0.5, AdviceText = "fix low." }, - }; - - RecommendationsReader.AppendCoFired(items); - - Assert.Contains("fix high.", items[0].AdviceText); - Assert.Contains("Also surfaced in this analysis window: Low problem.", items[0].AdviceText); - Assert.Contains("Also surfaced in this analysis window: High problem.", items[1].AdviceText); - } - - [Fact] - public void DashboardReader_AppendCoFired_SingleCard_NoOp() - { - var items = new List - { - new() { Title = "Only problem", RawSeverity = 1.0, AdviceText = "fix it." }, - }; - - RecommendationsReader.AppendCoFired(items); - - Assert.Equal("fix it.", items[0].AdviceText); // nothing else fired -> unchanged - } -} diff --git a/deprecated/Dashboard.Tests/CollectionStoppedDetectionTests.cs b/deprecated/Dashboard.Tests/CollectionStoppedDetectionTests.cs deleted file mode 100644 index 22ee94bea2..0000000000 --- a/deprecated/Dashboard.Tests/CollectionStoppedDetectionTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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 PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Verifies the "collection stopped" decision logic (): -/// disabled collector jobs are the immediate, specific signal; a collection-freshness gap is the catch-all -/// for the Agent service being stopped or collectors silently erroring. This is the one health signal the -/// app must compute itself, since the collector that fills every other table is exactly what may be off. -/// -public class CollectionStoppedDetectionTests -{ - private const int Threshold = 30; - - [Fact] - public void AllJobsDisabled_IsStopped_WithAllReason() - { - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 6, totalJobs: 6, minutesSince: 2, thresholdMinutes: Threshold); - - Assert.True(r.Stopped); - Assert.Contains("All 6", r.Reason); - Assert.Equal(6, r.DisabledJobs); - } - - [Fact] - public void SomeJobsDisabled_IsStopped_WithPartialReason() - { - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 2, totalJobs: 6, minutesSince: 1, thresholdMinutes: Threshold); - - Assert.True(r.Stopped); - Assert.Contains("2 of 6", r.Reason); - } - - [Fact] - public void DisabledJobs_WinOverFreshness_EvenWhenDataIsFresh() - { - // Jobs just disabled — collection_log is still fresh, but we must flag it immediately, not wait 30m. - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 1, totalJobs: 6, minutesSince: 0, thresholdMinutes: Threshold); - - Assert.True(r.Stopped); - Assert.Contains("disabled", r.Reason); - } - - [Fact] - public void NoDisabledJobs_FreshData_IsNotStopped() - { - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 0, totalJobs: 6, minutesSince: 3, thresholdMinutes: Threshold); - - Assert.False(r.Stopped); - Assert.Null(r.Reason); - } - - [Fact] - public void NoDisabledJobs_StaleData_IsStopped_WithFreshnessReason() - { - // Jobs enabled but nothing has run for > threshold — Agent stopped or collectors erroring. - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 0, totalJobs: 6, minutesSince: 45, thresholdMinutes: Threshold); - - Assert.True(r.Stopped); - Assert.Contains("45 minutes", r.Reason); - } - - [Fact] - public void FreshnessAtThreshold_IsStopped() - { - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 0, totalJobs: 6, minutesSince: Threshold, thresholdMinutes: Threshold); - - Assert.True(r.Stopped); - } - - [Fact] - public void JobStateUnreadable_FreshData_IsNotStopped() - { - // msdb unreadable (Azure / RDS / no SQLAgentReaderRole): totalJobs = 0 must NOT read as "all disabled". - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 0, totalJobs: 0, minutesSince: 4, thresholdMinutes: Threshold); - - Assert.False(r.Stopped); - } - - [Fact] - public void JobStateUnreadable_StaleData_StillCaughtByFreshness() - { - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 0, totalJobs: 0, minutesSince: 60, thresholdMinutes: Threshold); - - Assert.True(r.Stopped); - Assert.Contains("60 minutes", r.Reason); - } - - [Fact] - public void NeverCollected_NoDisabledJobs_IsNotStopped() - { - // minutesSince null = collection_log empty (fresh install / never ran), not "stopped". - var r = DatabaseService.DecideCollectionStopped(disabledJobs: 0, totalJobs: 6, minutesSince: null, thresholdMinutes: Threshold); - - Assert.False(r.Stopped); - } -} diff --git a/deprecated/Dashboard.Tests/Dashboard.Tests.csproj b/deprecated/Dashboard.Tests/Dashboard.Tests.csproj deleted file mode 100644 index de6a137f09..0000000000 --- a/deprecated/Dashboard.Tests/Dashboard.Tests.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - net10.0-windows - enable - true - false - true - - Exe - CA1849;CA2007;CA1508;CA1822;CA1805;CA1510;CA1816;CA1861;CA1845;CA2201;CS4014;NU1701;CA1001;CA1848;CA1852;CA1305;CA1860;CA1707;CA1507;CA1806 - - - - - - - - - - diff --git a/deprecated/Dashboard.Tests/DashboardAlertHistoryValueTests.cs b/deprecated/Dashboard.Tests/DashboardAlertHistoryValueTests.cs deleted file mode 100644 index 4b37fcc30c..0000000000 --- a/deprecated/Dashboard.Tests/DashboardAlertHistoryValueTests.cs +++ /dev/null @@ -1,211 +0,0 @@ -using System; -using System.Threading.Tasks; -using PerformanceMonitor.Common; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Interfaces; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Pins what the Dashboard's Alert History grid shows in its Value column (#1913), and — just as -/// importantly — pins WHY the Dashboard does not participate in the em-dash rendering Lite and the -/// Darling Viewer got from #1846/#1881. -/// -/// The Dashboard's alert history is STRING-typed end to end. The fire site passes display -/// text, JsonAlertHistoryStore copies it into AlertLogEntry.CurrentValue (a string) and -/// discards AlertHistoryRecord's numeric slots, and the grid binds that string directly. There is -/// no double on this path, so there is no "0.00" to render and nothing for -/// — which takes a double — to be called with. -/// -/// That is not a gap to close. The em dash exists because Lite's and Darling's value columns are -/// NOT NULL doubles, so a metric whose value is a STATE has nowhere to put it; the Dashboard keeps the -/// state and shows it. Making the Dashboard numeric in order to render a dash would REPLACE -/// "Blocking and Deadlock" with "—", which is strictly less information. The tests below fix that -/// reasoning in place so the next person to notice the divergence finds the answer instead of -/// re-deriving it — this suite exists because the divergence was filed as a bug once already. -/// -public class DashboardAlertHistoryValueTests -{ - private sealed class FakePreferencesService : IUserPreferencesService - { - public UserPreferences Preferences { get; } = new(); - public UserPreferences GetPreferences() => Preferences; - public void SavePreferences(UserPreferences preferences) { } - public void UpdateWaitStatsRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCpuRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateMemoryRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateFileIoRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateExpensiveQueriesRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateBlockingRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCollectionHealthRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - } - - private const int Threshold = 30; - - /* ---------------- #1913: the Value column carries the incident's actual figures ---------------- */ - - [Fact] - public void CollectionStopped_DisabledJobsBranch_ShortValueKeepsTheTotal() - { - /* The fire site used to build this string itself and reported only the disabled count. "2 job(s) - disabled" reads the same on a 6-job server (partially stopped, some data still landing) and on - a 2-job server (completely stopped) — and the reason beside it draws exactly that distinction. */ - var r = DatabaseService.DecideCollectionStopped( - disabledJobs: 2, totalJobs: 6, minutesSince: 1, thresholdMinutes: Threshold); - - Assert.Equal("2 of 6 job(s) disabled", r.ShortValue); - Assert.Contains("2 of 6", r.Reason); - } - - [Fact] - public void CollectionStopped_AllJobsDisabled_ShortValueSaysSoWithoutAmbiguity() - { - var r = DatabaseService.DecideCollectionStopped( - disabledJobs: 6, totalJobs: 6, minutesSince: 2, thresholdMinutes: Threshold); - - Assert.Equal("6 of 6 job(s) disabled", r.ShortValue); - } - - [Fact] - public void CollectionStopped_StalenessBranch_ShortValueCarriesTheMinutes() - { - /* THE defect this issue is really about. The staleness branch used to report the constant - "no recent collection" — which restates the metric name and discards the one figure the alert - was raised to report. The reason and the email both carried the minutes; only the grid did not. */ - var r = DatabaseService.DecideCollectionStopped( - disabledJobs: 0, totalJobs: 6, minutesSince: 47, thresholdMinutes: Threshold); - - Assert.Equal("no collection in 47m", r.ShortValue); - Assert.Contains("47 minutes", r.Reason); - Assert.DoesNotContain("no recent collection", r.ShortValue!, StringComparison.Ordinal); - } - - [Fact] - public void CollectionStopped_Healthy_HasNoShortValue() - { - var r = DatabaseService.DecideCollectionStopped( - disabledJobs: 0, totalJobs: 6, minutesSince: 1, thresholdMinutes: Threshold); - - Assert.False(r.Stopped); - Assert.Null(r.Reason); - Assert.Null(r.ShortValue); - } - - [Theory] - /* disabled-jobs wins over staleness, so both branches are exercised with the other input live. */ - [InlineData(2, 6, 99, "disabled")] - [InlineData(0, 6, 99, "no collection")] - [InlineData(6, 6, 0, "disabled")] - public void ShortValueAndReason_AlwaysDescribeTheSameBranch( - int disabledJobs, int totalJobs, int? minutesSince, string expectedShape) - { - /* The drift guard, and the reason ShortValue is computed in DecideCollectionStopped rather than at - the fire site. Two renderings of one cause, derived twice, is two chances to disagree about which - branch fired — and disagree is exactly what they did: the grid said "no recent collection" while - the email explained a disabled-job count, for one incident. */ - var r = DatabaseService.DecideCollectionStopped(disabledJobs, totalJobs, minutesSince, Threshold); - - Assert.True(r.Stopped); - Assert.Contains(expectedShape, r.ShortValue!, StringComparison.Ordinal); - - var reasonIsDisabledBranch = r.Reason!.Contains("disabled", StringComparison.Ordinal); - var valueIsDisabledBranch = r.ShortValue!.Contains("disabled", StringComparison.Ordinal); - Assert.Equal(reasonIsDisabledBranch, valueIsDisabledBranch); - } - - [Fact] - public void ShortValue_StaysShortEnoughForTheGridColumn() - { - /* The Value column is 200px and its siblings are compact ("87% (Total CPU)", "Session #12 running - 45m"). The fix was NOT to dump the full reason sentence in there — that is what DetailText, the - Alert Detail window and the email already carry. Both branches stay in the siblings' range. */ - foreach (var r in new[] - { - DatabaseService.DecideCollectionStopped(2, 6, 1, Threshold), - DatabaseService.DecideCollectionStopped(0, 6, 1440, Threshold), - }) - { - Assert.NotNull(r.ShortValue); - Assert.True( - r.ShortValue!.Length <= 40, - $"Value-column text should stay compact; got {r.ShortValue.Length} chars: '{r.ShortValue}'"); - Assert.True(r.Reason!.Length > r.ShortValue.Length, "the reason is the long form, by construction"); - } - } - - /* ---------------- the Dashboard's store is string-typed, and that is deliberate ---------------- */ - - [Fact] - public async Task StateOnlyMetric_KeepsItsDisplayTextVerbatim_AndIsNotDashed() - { - /* "Capture Down" IS state-only by the shared classifier, and on Lite and Darling its row renders an - em dash because their NOT NULL double columns could only store a 0 for it. The Dashboard stores - the words. This asserts the words survive — the property #1913 assumed was broken. */ - var store = new JsonAlertHistoryStore(new FakePreferencesService()); - var serverId = "test-" + Guid.NewGuid().ToString("N"); - - await store.RecordAlertAsync(new AlertHistoryRecord( - serverId, "Srv", "Capture Down", - CurrentValueText: "Blocking and Deadlock", ThresholdValueText: "session running", - NumericCurrentValue: null, NumericThresholdValue: null, - Delivery: LegacyTrayDelivery(), - Muted: false, DetailText: null, ContextJson: null)); - - var row = Assert.Single(store.GetAlertHistory(200), e => e.ServerId == serverId); - - Assert.True(AlertMetricClassifier.IsStateOnly("Capture Down"), "premise: the metric IS state-only"); - Assert.Equal("Blocking and Deadlock", row.CurrentValue); - Assert.Equal("session running", row.ThresholdValue); - Assert.NotEqual(AlertMetricClassifier.StateOnlyDisplay, row.CurrentValue); - Assert.DoesNotContain("0.00", row.CurrentValue, StringComparison.Ordinal); - } - - [Fact] - public async Task TheStoreDiscardsTheNumericSlots_SoNothingCanCoerceAValueToZero() - { - /* The structural reason the Dashboard never had #1846/#1881's defect, asserted rather than assumed. - AlertHistoryRecord carries optional doubles for the stores that need them; this one ignores them - and keeps the text. If a future change starts persisting the numerics, this test fails and - whoever makes that change has to decide — deliberately — what the grid should then render. */ - var store = new JsonAlertHistoryStore(new FakePreferencesService()); - var serverId = "test-" + Guid.NewGuid().ToString("N"); - - await store.RecordAlertAsync(new AlertHistoryRecord( - serverId, "Srv", "Collection Stopped", - CurrentValueText: "no collection in 47m", ThresholdValueText: "collecting", - /* Numerics deliberately supplied AND deliberately expected to be ignored. */ - NumericCurrentValue: 47, NumericThresholdValue: 30, - Delivery: LegacyTrayDelivery(), - Muted: false, DetailText: null, ContextJson: null)); - - var row = Assert.Single(store.GetAlertHistory(200), e => e.ServerId == serverId); - - Assert.Equal("no collection in 47m", row.CurrentValue); - Assert.Equal("collecting", row.ThresholdValue); - } - - [Fact] - public void TheSharedFormatterIsNotReachableFromAStringStore_ByType() - { - /* States the boundary as a compile-checked fact rather than a comment: FormatHistoryValue consumes - a double. The Dashboard's row exposes strings, so "just route the Dashboard through it" is not a - small change — it requires inventing the numeric the Dashboard deliberately does not keep. The - formatter still works, and is still right, for the two stores that DO hold doubles. */ - Assert.Equal(AlertMetricClassifier.StateOnlyDisplay, - AlertMetricClassifier.FormatHistoryValue("Capture Down", 0)); - Assert.Equal("87.0%", AlertMetricClassifier.FormatHistoryValue("High CPU", 87)); - - var dashboardRow = new AlertLogEntry { MetricName = "Capture Down", CurrentValue = "Blocking and Deadlock" }; - Assert.IsType(dashboardRow.CurrentValue); - } - - /* The deprecated SKU records a hand-decided disposition; its 26 production callers do the same, so its - tests state one too rather than deriving it. */ -#pragma warning disable CS0618 - private static AlertDelivery LegacyTrayDelivery() => - AlertDelivery.FromLegacyStoredColumns(true, "tray", null); -#pragma warning restore CS0618 -} diff --git a/deprecated/Dashboard.Tests/DashboardAlertSettingsTests.cs b/deprecated/Dashboard.Tests/DashboardAlertSettingsTests.cs deleted file mode 100644 index dd2c355642..0000000000 --- a/deprecated/Dashboard.Tests/DashboardAlertSettingsTests.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Interfaces; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Plan E Stage E1 — verifies the Dashboard adapter mirrors -/// Plan D's invariance discipline: it reads live from -/// (no caching), it clamps the analysis-notify bounds at the settings boundary (the inline -/// clamp was removed from AnalysisNotificationService), and the credential-backed getters -/// route to the service statics without throwing when no credential is present. -/// -public class DashboardAlertSettingsTests -{ - /// Minimal IUserPreferencesService over one mutable UserPreferences instance. - private sealed class FakePreferencesService : IUserPreferencesService - { - public UserPreferences Preferences { get; } = new(); - - public UserPreferences GetPreferences() => Preferences; - public void SavePreferences(UserPreferences preferences) { } - public void UpdateWaitStatsRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCpuRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateMemoryRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateFileIoRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateExpensiveQueriesRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateBlockingRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCollectionHealthRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - } - - [Fact] - public void ReadsLiveFromPreferences_NoCaching() - { - var fake = new FakePreferencesService(); - var settings = new DashboardAlertSettings(fake); - - // Plain string/bool/int pass-throughs reflect the current value on every access. - fake.Preferences.SmtpServer = "smtp.example.com"; - Assert.Equal("smtp.example.com", settings.SmtpServer); - - fake.Preferences.SmtpServer = "smtp.changed.com"; - Assert.Equal("smtp.changed.com", settings.SmtpServer); - - fake.Preferences.SmtpEnabled = true; - Assert.True(settings.SmtpEnabled); - - fake.Preferences.EmailCooldownMinutes = 42; - Assert.Equal(42, settings.EmailCooldownMinutes); - - fake.Preferences.TeamsWebhookEnabled = true; - Assert.True(settings.TeamsWebhookEnabled); - - fake.Preferences.TeamsProxyAddress = "http://proxy:8080"; - Assert.Equal("http://proxy:8080", settings.TeamsProxyAddress); - } - - [Fact] - public void AnalysisNotifySeverity_ClampsToZeroTwoRange() - { - var fake = new FakePreferencesService(); - var settings = new DashboardAlertSettings(fake); - - fake.Preferences.AnalysisNotifySeverity = -3.0; - Assert.Equal(0.0, settings.AnalysisNotifySeverity); - - fake.Preferences.AnalysisNotifySeverity = 9.9; - Assert.Equal(2.0, settings.AnalysisNotifySeverity); - - fake.Preferences.AnalysisNotifySeverity = 1.25; - Assert.Equal(1.25, settings.AnalysisNotifySeverity); - } - - [Fact] - public void AnalysisNotifyCooldownMinutes_ClampsTo30To10080Range() - { - var fake = new FakePreferencesService(); - var settings = new DashboardAlertSettings(fake); - - fake.Preferences.AnalysisNotifyCooldownMinutes = 5; - Assert.Equal(30, settings.AnalysisNotifyCooldownMinutes); - - fake.Preferences.AnalysisNotifyCooldownMinutes = 99999; - Assert.Equal(10080, settings.AnalysisNotifyCooldownMinutes); - - fake.Preferences.AnalysisNotifyCooldownMinutes = 360; - Assert.Equal(360, settings.AnalysisNotifyCooldownMinutes); - } - - [Fact] - public void CredentialBackedGetters_RouteToStatics_WithoutThrowing() - { - var fake = new FakePreferencesService(); - var settings = new DashboardAlertSettings(fake); - - // Structural/smoke check: these route to EmailAlertService.GetSmtpPassword() and - // WebhookAlertService.Get{Teams,Slack}WebhookUrl(). They must not throw; with no - // credential present the password getter returns null and the URL getters "". - var ex = Record.Exception(() => - { - _ = settings.GetSmtpPassword(); - _ = settings.TeamsWebhookUrl; - _ = settings.SlackWebhookUrl; - }); - Assert.Null(ex); - Assert.NotNull(settings.TeamsWebhookUrl); - Assert.NotNull(settings.SlackWebhookUrl); - } - - [Fact] - public void TransientAdapter_ReadsFromGivenPreferences_NotLiveService() - { - // The test-send adapter (MOD-1) reads the UserPreferences it was handed — the form - // values the user just typed — never the saved IUserPreferencesService. - var formValues = new UserPreferences - { - SmtpEnabled = true, - SmtpServer = "typed.example.com", - SmtpPort = 2525, - SmtpFromAddress = "from@example.com", - SmtpRecipients = "to@example.com", - EmailCooldownMinutes = 7 - }; - var settings = new UserPreferencesAlertSettings(formValues); - - Assert.Equal("typed.example.com", settings.SmtpServer); - Assert.Equal(2525, settings.SmtpPort); - Assert.Equal("from@example.com", settings.SmtpFromAddress); - Assert.Equal("to@example.com", settings.SmtpRecipients); - Assert.Equal(7, settings.EmailCooldownMinutes); - Assert.True(settings.SmtpEnabled); - } -} diff --git a/deprecated/Dashboard.Tests/DashboardMirrorPinTests.cs b/deprecated/Dashboard.Tests/DashboardMirrorPinTests.cs deleted file mode 100644 index 7384b64d6d..0000000000 --- a/deprecated/Dashboard.Tests/DashboardMirrorPinTests.cs +++ /dev/null @@ -1,265 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using PerformanceMonitor.Alerting; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Analysis; -using PerformanceMonitorDashboard.Mcp; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #3653: the frozen Dashboard's mirrors of five of the 2026-09 brains-review honesty fixes, pinned in the -/// only idiom the Dashboard's test project has for its SQL-Server-side readers — the source text, because -/// there is no test database — plus the pure-logic pieces called directly. Each section names the merged -/// PR whose class it mirrors; the Dashboard says the same thing in its own voice, and these pins hold the -/// voice to the meaning: a page count is not a total, one slow wait does not page, a mute that matched -/// nothing says so, an unbanded collector dot is Unknown (its own file: ServerHealthStatusCollectorVerdictTests), -/// and the per-second counter does not truncate. -/// -public class DashboardMirrorPinTests -{ - /* ---------------- #3594's class: page counts stop posing as totals ---------------- */ - - [Theory] - [InlineData(0, 30, false)] // reader saw nothing: nothing beyond the page - [InlineData(5, 30, false)] // reader under its own cap, all rows fit: the whole window is here - [InlineData(30, 30, false)] // exactly the page, reader under its cap: still the whole window - [InlineData(31, 30, true)] // a row in hand beyond the page was dropped here - [InlineData(100, 30, true)] // reader at its cap AND beyond the page: dropped here regardless - [InlineData(100, 100, null)] // reader filled to its cap, page took it all: rows beyond are unknowable - [InlineData(100, 500, null)] // a limit above the reader's cap cannot widen the page; same unknown - [InlineData(99, 100, false)] // one under the cap: the reader saw the whole window - public void PageTruncated_ReportsWhatIsKnown_AndNullWhereTheReaderCapHidesIt(int readerRows, int limit, bool? expected) - { - Assert.Equal(100, DatabaseService.EventGridCap); - Assert.Equal(expected, McpBlockingTools.PageTruncated(readerRows, limit)); - } - - [Fact] - public void BlockingReaders_EveryRowCapLiteral_IsTheNamedGridCap() - { - /* The readers keep their fixed TOP (the grids' cap) rather than a parameterised one; the const the MCP - tools publish as limit_applied_by_reader must BE that literal. Every numeric TOP in the file is either - a single-row fetch (the on-demand XML reads) or the cap. */ - var src = Read("deprecated", "Dashboard", "Services", "DatabaseService.QueryPerformance.Blocking.cs"); - var tops = Regex.Matches(src, @"SELECT TOP \((\d+)\)").Select(m => int.Parse(m.Groups[1].Value)).ToList(); - Assert.NotEmpty(tops); - Assert.All(tops, t => Assert.True(t == 1 || t == DatabaseService.EventGridCap, $"TOP ({t}) is neither a single-row fetch nor EventGridCap")); - Assert.Equal(4, tops.Count(t => t == DatabaseService.EventGridCap)); // BPR + deadlock readers, both window arms - Assert.Contains("const int gridCap = EventGridCap;", src); // the DMV merge's re-cap - } - - [Fact] - public void PagedTools_PublishReturnedCounts_NotTotals() - { - var blocking = Read("deprecated", "Dashboard", "Mcp", "McpBlockingTools.cs"); - Assert.DoesNotContain("total_events", blocking); - Assert.DoesNotContain("total_deadlocks", blocking); - Assert.Contains("events_returned = result.Count", blocking); - Assert.Contains("deadlocks_returned = result.Count", blocking); - Assert.Equal(2, Regex.Matches(blocking, @"truncated = PageTruncated\(rows\.Count, limit\)").Count); - Assert.Equal(2, Regex.Matches(blocking, @"limit_applied_by_reader = DatabaseService\.EventGridCap").Count); - - /* The alert-history store takes a limit, so that tool uses the shared dialect: fetch one past the limit - and OBSERVE the extra row, never infer from count >= limit. */ - var alerts = Read("deprecated", "Dashboard", "Mcp", "McpAlertTools.cs"); - Assert.DoesNotContain("total_alerts", alerts); - Assert.Contains("GetAlertHistory(hours_back, limit + 1)", alerts); - Assert.Contains("var truncated = fetched.Count > limit;", alerts); - Assert.Contains("alerts_returned = alerts.Count", alerts); - Assert.DoesNotContain(">= limit", alerts); - } - - /* ---------------- #3593's class: one slow wait stops paging ---------------- */ - - [Fact] - public void PoisonWaitRead_IsAWindowAccumulation_NotTheNewestDeltas() - { - var src = Read("deprecated", "Dashboard", "Services", "DatabaseService.NocHealth.cs"); - var sql = Between(src, "private async Task> GetPoisonWaitDeltasAsync", "var results = new List();"); - - /* Presences: the sums, the grouping, the window bound from the evaluator, worst-first. */ - Assert.Contains("wait_time_ms_delta = SUM(wait_time_ms_delta)", sql); - Assert.Contains("waiting_tasks_count_delta = SUM(waiting_tasks_count_delta)", sql); - Assert.Contains("GROUP BY wait_type", sql); - Assert.Contains("ORDER BY SUM(wait_time_ms_delta) DESC", sql); - Assert.Contains("DATEADD(MINUTE, -@window_minutes, SYSDATETIME())", sql); - Assert.Contains("Value = PoisonWaitEvaluator.WindowMinutes", Between(src, "GetPoisonWaitDeltasAsync", "Failed to get poison wait deltas")); - - /* Absences: the retired shape's three tells. A TOP on a sum is an undercount; the task filter dropped a - task still waiting across the interval boundary; a literal window can drift from the evaluator's. */ - Assert.DoesNotContain("TOP (3)", sql); - Assert.DoesNotContain("AND waiting_tasks_count_delta > 0", sql); - Assert.DoesNotContain("DATEADD(MINUTE, -10", sql); - - /* The wait-type list is the evaluator's, in the store's spelling. */ - foreach (var waitType in PoisonWaitEvaluator.SqlServerWaitTypes) - { - Assert.Contains($"N'{waitType}'", sql); - } - } - - [Fact] - public void PoisonWaitLoop_GradesOnTheSharedBars_HoldsOnAnEmptyRead_AndNoLongerReadsTheKnob() - { - var src = Read("deprecated", "Dashboard", "MainWindow.AlertEngine.cs"); - var block = Between(src, "/* Poison wait alerts.", "/* Long-running query alerts */"); - - Assert.Contains("PoisonWaitEvaluator.Grade(w.DeltaMs) is not null", block); - Assert.DoesNotContain("AvgMsPerWait >= prefs.PoisonWaitThresholdMs", block); - Assert.DoesNotContain("prefs.PoisonWaitThresholdMs", block); - - /* The clear arm requires an observation: an empty read is collector silence, not a quiet server. */ - Assert.Contains("else if (health.PoisonWaits.Count > 0 && _activePoisonWaitAlert.TryRemove(serverId, out var wasPoisonWait) && wasPoisonWait)", block); - - /* The threshold text every record/email carries is the shared bar, derived not typed. */ - Assert.Contains("PoisonWaitEvaluator.WarningAvgWaiters * poisonWindowSeconds:N0}s accumulated over {PoisonWaitEvaluator.WindowMinutes}m", block); - Assert.Equal(3, Regex.Matches(block, @"\bpoisonThresholdText\b(?!\s*=)").Count); // fire record, email, clear record - } - - [Fact] - public void PoisonWaitBars_AreTheSharedEvaluators_AndTheDashboardGradesLikeTheEngine() - { - /* The Dashboard references PoisonWaitEvaluator directly (its csproj references PerformanceMonitor.Alerting), - so there is no copied constant to pin equal — these pin the figures the loop's comments and the Settings - tooltip state, so a shared-side move shows up here as a falsified label rather than a silent drift. */ - Assert.Equal(10, PoisonWaitEvaluator.WindowMinutes); - Assert.Equal(1.0, PoisonWaitEvaluator.WarningAvgWaiters); - Assert.Equal(10.0, PoisonWaitEvaluator.CriticalAvgWaiters); - - /* The exact shapes the brief names: one 600 ms wait is silent; 600 s accumulated fires; one ms under does not. */ - Assert.Null(PoisonWaitEvaluator.Grade(600)); - Assert.Null(PoisonWaitEvaluator.Grade(599_999)); - Assert.Equal(AlertSeverityLevel.Warning, PoisonWaitEvaluator.Grade(600_000)); - Assert.Equal(AlertSeverityLevel.Critical, PoisonWaitEvaluator.Grade(6_000_000)); - - /* The storm the average could not see: 10,000 waits of 50 ms a minute, sustained across the window — - 5,000 s of starvation on a 50 ms average, which the retired 500 ms-avg bar never noticed. */ - Assert.Equal(AlertSeverityLevel.Warning, PoisonWaitEvaluator.Grade(10 * 10_000 * 50)); - - /* The Settings preview and tooltip speak in these figures. */ - var xaml = Read("deprecated", "Dashboard", "SettingsWindow.xaml"); - Assert.Contains("IsEnabled=\"False\"", Between(xaml, "x:Name=\"PoisonWaitThresholdTextBox\"", "/>")); - Assert.Contains("600 s of wait inside 10 minutes (WARNING) or 6,000 s (CRITICAL)", xaml); - var settings = Read("deprecated", "Dashboard", "SettingsWindow.xaml.cs"); - Assert.DoesNotContain("ms avg\"", settings); - Assert.Contains("PoisonWaitEvaluator.WarningAvgWaiters", settings); - } - - /* ---------------- #3615's class: a mute that matched nothing says so ---------------- */ - - [Fact] - public void MuteAnalysisFinding_ReportsWhatTheWriteDid() - { - var src = Read("deprecated", "Dashboard", "Mcp", "McpAnalysisTools.cs"); - var body = Between(src, "[McpServerTool(Name = \"mute_analysis_finding\")", "McpHelpers.FormatError(\"mute_analysis_finding\""); - - Assert.Contains("var registered = await analysisService.MuteFindingAsync(finding, reason);", body); - Assert.Contains("var matchedNow = await analysisService.CountStoredFindingsAsync(serverId, story_path_hash);", body); - Assert.Contains("status = matchedNow > 0 ? \"muted\" : \"muted_unmatched\"", body); - Assert.Contains("status = \"error\"", body); - Assert.Contains("status = \"invalid\"", body); - Assert.Contains("matched_now = matchedNow", body); - Assert.DoesNotContain("new { status = \"muted\", story_path_hash, reason }", body); - - /* The description says what the payload says. */ - var description = Between(body, "Description(\"", "\")]"); - Assert.Contains("registered", description); - Assert.Contains("matched_now", description); - Assert.Contains("muted_unmatched", description); - - /* The store says whether the row landed, and the count is a real read of the findings table. */ - Assert.Equal(typeof(Task), typeof(SqlServerFindingStore).GetMethod(nameof(SqlServerFindingStore.MuteStoryAsync))!.ReturnType); - Assert.Equal(typeof(Task), typeof(AnalysisService).GetMethod(nameof(AnalysisService.MuteFindingAsync))!.ReturnType); - Assert.Equal(typeof(Task), typeof(SqlServerFindingStore).GetMethod(nameof(SqlServerFindingStore.CountStoredFindingsAsync))!.ReturnType); - var storeSrc = Read("deprecated", "Dashboard", "Analysis", "SqlServerFindingStore.cs"); - var countSql = Between(storeSrc, "public async Task CountStoredFindingsAsync", "var result = await cmd.ExecuteScalarAsync();"); - Assert.Contains("COUNT_BIG(*)", countSql); - Assert.Contains("FROM config.analysis_findings", countSql); - Assert.Contains("WHERE server_id = @serverId", countSql); - Assert.Contains("AND story_path_hash = @storyPathHash", countSql); - } - - /* ---------------- #3540 A11: the per-second counter stops truncating ---------------- */ - - [Fact] - public void PerfmonReads_RecomputeThePerSecondRate_AsAFraction() - { - /* The table's computed column is bigint / integer — T-SQL integer division — so 59 events over a 60-second - interval read as 0/sec. Both perfmon readers now compute the rate on the read as a fraction; the raw - computed column is no longer selected by either. */ - var src = Read("deprecated", "Dashboard", "Services", "DatabaseService.ResourceMetrics.Perfmon.cs"); - var lf = src.Replace("\r\n", "\n"); - Assert.Equal(2, Regex.Matches(lf, @"cntr_value_per_second =\n\s+ps\.cntr_value_delta \* 1\.0 /\n\s+NULLIF\(ps\.sample_interval_seconds, 0\)").Count); - Assert.DoesNotContain("ps.cntr_value_per_second", src); - - /* The model carries the fraction; the reader materialises it as a double (the numeric the * 1.0 produces). */ - Assert.Equal(typeof(double?), typeof(PerfmonStatsItem).GetProperty(nameof(PerfmonStatsItem.CntrValuePerSecond))!.PropertyType); - Assert.Equal(2, Regex.Matches(src, @"CntrValuePerSecond = reader\.IsDBNull\(10\) \? null : Convert\.ToDouble\(reader\.GetValue\(10\), CultureInfo\.InvariantCulture\)").Count); - Assert.DoesNotContain("reader.GetInt64(10)", src); - } - - /* ---------------- #3616's class: the lab-box markers ---------------- */ - - [Fact] - public void AnomalyDetector_NoLongerNamesTheLabBox_AndSaysWhatWasMeasured() - { - var src = Read("deprecated", "Dashboard", "Analysis", "SqlServerAnomalyDetector.cs"); - Assert.DoesNotContain("HAMMERDB", src, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("SQL2025", src); - Assert.Contains("unmeasured\n /// on the Dashboard tier", src.Replace("\r\n", "\n")); - /* Comment-only: the numbers did not move. */ - Assert.Contains("private const double DefaultRatioThreshold = 4.0;", src); - Assert.Contains("private const double WaitProfileFallbackMsPerSec = 250.0;", src); - } - - /* ---------------- helpers ---------------- */ - - private static string Read(params string[] pathParts) - { - var root = FindRepoRoot(); - Assert.True(root is not null, $"Could not locate the repo root (a directory containing deprecated/Dashboard/Dashboard.csproj) by walking up from {AppContext.BaseDirectory}."); - var path = Path.Combine(new[] { root! }.Concat(pathParts).ToArray()); - Assert.True(File.Exists(path), $"Source file not found: {path}"); - return File.ReadAllText(path); - } - - /// The slice of from the first to the next , both asserted present. - private static string Between(string src, string start, string end) - { - var s = src.IndexOf(start, StringComparison.Ordinal); - Assert.True(s >= 0, $"anchor not found: {start}"); - var e = src.IndexOf(end, s + start.Length, StringComparison.Ordinal); - Assert.True(e >= 0, $"anchor not found after start: {end}"); - return src.Substring(s, e - s); - } - - /// Walks up from the test output directory to the repo root — the directory holding the Dashboard project. Mirrors ThemeParityTests. - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (File.Exists(Path.Combine(dir.FullName, "deprecated", "Dashboard", "Dashboard.csproj"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/DataGridExportTests.cs b/deprecated/Dashboard.Tests/DataGridExportTests.cs deleted file mode 100644 index 828454a21a..0000000000 --- a/deprecated/Dashboard.Tests/DataGridExportTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Windows.Controls; -using System.Windows.Data; -using PerformanceMonitor.Ui; -using Xunit; - -namespace Dashboard.Tests; - -/// -/// Tests for the shared DataGridExport (PerformanceMonitor.Ui) used by every copy/export -/// context menu in both apps. Because all ~29 sites delegate here, these cover their behavior. -/// The pure formatter/escaper tests run anywhere; the grid tests run on an STA thread because -/// WPF objects require it. -/// -public class DataGridExportTests -{ - private sealed class Row - { - public string Name { get; set; } = ""; - public int Value { get; set; } - public string Note { get; set; } = ""; - } - - private static T RunSta(Func body) - { - T result = default!; - Exception? error = null; - var thread = new Thread(() => - { - try { result = body(); } - catch (Exception ex) { error = ex; } - }); - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - thread.Join(); - if (error != null) throw error; - return result; - } - - private static DataGrid BuildGrid() - { - var grid = new DataGrid(); - grid.Columns.Add(new DataGridTextColumn { Header = "Name", Binding = new Binding(nameof(Row.Name)) }); - grid.Columns.Add(new DataGridTextColumn { Header = "Value", Binding = new Binding(nameof(Row.Value)) }); - - // A template column with a TextBlock bound to Note -- the case the old Dashboard - // handlers mishandled (header filtered out, value kept). - var template = new System.Windows.DataTemplate(); - var tb = new System.Windows.FrameworkElementFactory(typeof(TextBlock)); - tb.SetBinding(TextBlock.TextProperty, new Binding(nameof(Row.Note))); - template.VisualTree = tb; - template.Seal(); - grid.Columns.Add(new DataGridTemplateColumn { Header = "Note", CellTemplate = template }); - - grid.ItemsSource = new[] - { - new Row { Name = "a,b", Value = 42, Note = "hi" }, - new Row { Name = "plain", Value = 7, Note = "there" } - }; - return grid; - } - - [Theory] - [InlineData(null, "")] - [InlineData("text", "text")] - public void FormatForExport_HandlesStringsAndNull(string? input, string expected) - { - Assert.Equal(expected, DataGridExport.FormatForExport(input)); - } - - [Fact] - public void FormatForExport_UsesInvariantCultureForNumbers() - { - var prior = CultureInfo.CurrentCulture; - try - { - // A culture whose decimal separator is a comma -- proves we don't emit "1,5". - CultureInfo.CurrentCulture = new CultureInfo("de-DE"); - Assert.Equal("1.5", DataGridExport.FormatForExport(1.5)); - Assert.Equal("42", DataGridExport.FormatForExport(42)); - } - finally - { - CultureInfo.CurrentCulture = prior; - } - } - - [Theory] - [InlineData("plain", "plain")] - [InlineData("", "")] - [InlineData("a,b", "\"a,b\"")] - [InlineData("a\"b", "\"a\"\"b\"")] - [InlineData("a\nb", "\"a\nb\"")] - public void CsvEscape_QuotesWhenNeeded(string input, string expected) - { - Assert.Equal(expected, DataGridExport.CsvEscape(input, ",")); - } - - [Fact] - public void CsvEscape_QuotesWhenValueContainsSeparator() - { - // A comma, semicolon or tab is quoted whatever the separator, so a spreadsheet whose list separator - // differs cannot split the value into a new cell. - Assert.Equal("\"a,b\"", DataGridExport.CsvEscape("a,b", ";")); - Assert.Equal("\"a;b\"", DataGridExport.CsvEscape("a;b", ";")); - } - - [Fact] - public void GetRowValues_ReturnsOneValuePerColumn_IncludingTemplate() - { - var values = RunSta(() => - { - var grid = BuildGrid(); - var item = grid.Items.Cast().First(); - return DataGridExport.GetRowValues(grid, item); - }); - - // Bound, bound, template -> three values, in column order. - Assert.Equal(new[] { "a,b", "42", "hi" }, values); - } - - [Fact] - public void BuildClipboardText_KeepsHeadersAndRowsAligned() - { - var (headerFields, rowFieldCounts, columnCount) = RunSta(() => - { - var grid = BuildGrid(); - var text = DataGridExport.BuildClipboardText(grid); - var lines = text.Replace("\r\n", "\n").TrimEnd('\n').Split('\n'); - var headers = lines[0].Split('\t'); - var counts = lines.Skip(1).Select(l => l.Split('\t').Length).ToArray(); - return (headers, counts, grid.Columns.Count); - }); - - Assert.Equal(new[] { "Name", "Value", "Note" }, headerFields); - Assert.Equal(3, columnCount); - // The regression guard: every row has exactly as many fields as there are columns/headers. - Assert.All(rowFieldCounts, count => Assert.Equal(columnCount, count)); - } - - [Fact] - public void BuildCsv_EscapesAndIncludesAllColumns() - { - var csv = RunSta(() => - { - var grid = BuildGrid(); - return DataGridExport.BuildCsv(grid, ",").Replace("\r\n", "\n"); - }); - - var lines = csv.TrimEnd('\n').Split('\n'); - Assert.Equal("Name,Value,Note", lines[0]); - Assert.Equal("\"a,b\",42,hi", lines[1]); // comma value quoted, number invariant, template value present - Assert.Equal("plain,7,there", lines[2]); - } -} diff --git a/deprecated/Dashboard.Tests/DeadlockAlertClearPolicyTests.cs b/deprecated/Dashboard.Tests/DeadlockAlertClearPolicyTests.cs deleted file mode 100644 index 7d3d01cdd5..0000000000 --- a/deprecated/Dashboard.Tests/DeadlockAlertClearPolicyTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests -{ - /// - /// Truth-table coverage for (#1091). Deadlock - /// detection is edge-triggered, so the check right after a deadlock has a zero delta and would - /// flap straight to "Deadlocks Cleared". The policy holds the alert active until a deadlock-quiet - /// window has elapsed since the last new deadlock, matching Lite's rolling-window semantics. - /// - public class DeadlockAlertClearPolicyTests - { - private static readonly TimeSpan QuietWindow = TimeSpan.FromHours(1); - private static readonly DateTime Now = new DateTime(2026, 6, 11, 12, 0, 0, DateTimeKind.Utc); - - [Fact] - public void NotActive_NeverClears() - { - Assert.False(DeadlockAlertClearPolicy.ShouldClear( - wasActive: false, lastDeadlockActivity: Now - TimeSpan.FromHours(2), Now, QuietWindow)); - } - - [Fact] - public void Active_WithinQuietWindow_DoesNotFlap() - { - // A deadlock one minute ago: the next check must NOT clear (the #1091 flap). - Assert.False(DeadlockAlertClearPolicy.ShouldClear( - wasActive: true, lastDeadlockActivity: Now - TimeSpan.FromMinutes(1), Now, QuietWindow)); - } - - [Fact] - public void Active_JustBeforeWindow_StillHeld() - { - Assert.False(DeadlockAlertClearPolicy.ShouldClear( - wasActive: true, lastDeadlockActivity: Now - TimeSpan.FromMinutes(59), Now, QuietWindow)); - } - - [Fact] - public void Active_AtQuietWindow_Clears() - { - Assert.True(DeadlockAlertClearPolicy.ShouldClear( - wasActive: true, lastDeadlockActivity: Now - QuietWindow, Now, QuietWindow)); - } - - [Fact] - public void Active_PastQuietWindow_Clears() - { - Assert.True(DeadlockAlertClearPolicy.ShouldClear( - wasActive: true, lastDeadlockActivity: Now - TimeSpan.FromHours(2), Now, QuietWindow)); - } - - [Fact] - public void Active_WithoutRecordedActivity_Clears() - { - // Active but no timestamp tracked: nothing holds it open, so clearing is safe. - Assert.True(DeadlockAlertClearPolicy.ShouldClear( - wasActive: true, lastDeadlockActivity: null, Now, QuietWindow)); - } - } -} diff --git a/deprecated/Dashboard.Tests/EmailTemplateBrandingTests.cs b/deprecated/Dashboard.Tests/EmailTemplateBrandingTests.cs deleted file mode 100644 index 2b5707f643..0000000000 --- a/deprecated/Dashboard.Tests/EmailTemplateBrandingTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Render invariant for Plan E Stage E3a: the shared EmailTemplateBuilder, fed -/// Dashboard's wired AlertBranding (via EmailAlertService.Branding), must reproduce -/// Dashboard's pre-E3a alert email exactly — edition string "Performance Monitor -/// Dashboard" and NO snooze hint (Dashboard's branding carries a null hint, so the -/// snooze section is omitted from both the HTML and plain-text bodies). -/// -public class EmailTemplateBrandingTests -{ - [Fact] - public void BuildAlertEmail_DashboardBranding_IncludesEditionAndOmitsSnoozeFromBothBodies() - { - var branding = EmailAlertService.Branding; - Assert.Equal("Performance Monitor Dashboard", branding.EditionName); - Assert.Null(branding.SnoozeHint); - - var (html, plain) = EmailTemplateBuilder.BuildAlertEmail( - "High CPU", "TestServer", "95%", "90%", 15, branding); - - // Edition string present, Lite's absent. - Assert.Contains("Performance Monitor Dashboard", html); - Assert.DoesNotContain("Performance Monitor Lite", html); - - // No snooze hint in either body. - Assert.DoesNotContain("To silence this alert", html); - Assert.DoesNotContain("To silence this alert", plain); - } -} diff --git a/deprecated/Dashboard.Tests/FactAdviceComposeTests.cs b/deprecated/Dashboard.Tests/FactAdviceComposeTests.cs deleted file mode 100644 index c6e597480b..0000000000 --- a/deprecated/Dashboard.Tests/FactAdviceComposeTests.cs +++ /dev/null @@ -1,367 +0,0 @@ -using System.Collections.Generic; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the value-stated advice substrate (FactAdvice.Compose / PopulateStoryText / -/// GetComposedForFinding / Serialize-round-trip). The composer reads the server's ACTUAL settings -/// from the full fact set and states them — current MAXDOP, CTFP, cores — instead of generic -/// folklore, and the result is frozen into StoryText so read-back cards show the same numbers. -/// -public class FactAdviceComposeTests -{ - private static Dictionary Facts(params Fact[] facts) - { - var d = new Dictionary(); - foreach (var f in facts) - d[f.Key] = f; - return d; - } - - private static Fact F(string key, double value) => - new() { Key = key, Source = "config", Value = value, Severity = 0.0 }; - - private static Fact Hardware(int coresPerSocket) => - new() - { - Key = "SERVER_HARDWARE", - Source = "config", - Value = 1, - Severity = 0, - Metadata = new Dictionary { ["cores_per_socket"] = coresPerSocket } - }; - - private static Fact FM(string key, double value, Dictionary meta, string? obj = null) => - new() { Key = key, Source = "x", Value = value, Severity = 1, Metadata = meta, ObjectName = obj }; - - // The audience invariant: composed advice must never contain MCP tool names or internal field names. - private static readonly string[] ToolNameMarkers = - { "get_", "audit_config", "parallel_only", "schema_table", "reconstructed_blocking_chains", "top_cpu_queries", "lock_mode_breakdown", "queries_at_spike", "best_plan_id" }; - - private static void AssertComposedAndClean(AdviceBlock? a) - { - Assert.NotNull(a); - var text = a!.Headline + " " + a.Investigation + " " + a.Remediation; - foreach (var m in ToolNameMarkers) - Assert.DoesNotContain(m, text); - } - - // Regression guard for the routing bug: range-lock findings surface under the real LCK_M_R* keys - // (kept individual by the collector), not "LCK_RANGE" — they must reach the composer (state wait - // totals, no tool names), not fall through to the tool-named static block. - [Fact] - public void RangeLock_RealKey_IsComposed_StatesWaitTotals_NoToolNames() - { - var wait = new Dictionary - { - ["wait_time_ms"] = 75000, ["waiting_tasks_count"] = 300, ["avg_ms_per_wait"] = 250, - ["signal_wait_time_ms"] = 0, ["resource_wait_time_ms"] = 75000, ["period_duration_ms"] = 3600000, - }; - var a = FactAdvice.Compose("LCK_M_RS_S", Facts(FM("LCK_M_RS_S", 0.05, wait))); - AssertComposedAndClean(a); - Assert.Contains("Key-range lock waits", a!.Investigation); // wait-totals prefix = composed, not static - Assert.Contains("SERIALIZABLE", a.Investigation); - } - - [Fact] - public void BlockingChain_StatesDepthAndVictims_NoToolNames() - { - var meta = new Dictionary - { - ["worst_chain_depth"] = 7, ["worst_chain_victim_count"] = 12, ["worst_apex_sleeping"] = 1, - ["worst_chain_max_wait_ms"] = 48000, ["total_reconstructed_chains"] = 23, - }; - var a = FactAdvice.Compose("BLOCKING_CHAIN", Facts(FM("BLOCKING_CHAIN", 7, meta))); - AssertComposedAndClean(a); - Assert.Contains("7", a!.Investigation); - Assert.Contains("12", a.Investigation); - } - - [Fact] - public void AnomalyObjectGrowth_NamesTheObject_NoToolNames() - { - var meta = new Dictionary { ["growth_mb"] = 6200, ["growth_pct"] = 44, ["current_mb"] = 20200 }; - var a = FactAdvice.Compose("ANOMALY_OBJECT_GROWTH", Facts(FM("ANOMALY_OBJECT_GROWTH", 6200, meta, obj: "dbo.Orders"))); - AssertComposedAndClean(a); - Assert.Contains("dbo.Orders", a!.Headline); - } - - [Fact] - public void Sos_StatesSignalWaitShare_NoToolNames() - { - var wait = new Dictionary - { - ["wait_time_ms"] = 600000, ["waiting_tasks_count"] = 5000, ["avg_ms_per_wait"] = 120, - ["signal_wait_time_ms"] = 180000, ["resource_wait_time_ms"] = 420000, ["period_duration_ms"] = 3600000, - }; - var a = FactAdvice.Compose("SOS_SCHEDULER_YIELD", Facts(FM("SOS_SCHEDULER_YIELD", 0.2, wait))); - AssertComposedAndClean(a); - Assert.Contains("signal wait", a!.Investigation); - } - - [Fact] - public void Cxpacket_Composed_NoToolNames() - { - var a = FactAdvice.Compose("CXPACKET", Facts(F("CONFIG_MAXDOP", 16), F("CONFIG_CTFP", 5), Hardware(8))); - AssertComposedAndClean(a); - } - - // ── THREADPOOL_PARALLEL: states the actual MAXDOP/CTFP, recommends the topology cap ── - - [Fact] - public void ThreadpoolParallel_StatesCurrentMaxdopAndCtfp_AndRecommendsTopologyCap() - { - var advice = FactAdvice.Compose( - "THREADPOOL_PARALLEL", Facts(F("CONFIG_MAXDOP", 16), F("CONFIG_CTFP", 5), Hardware(8))); - - Assert.NotNull(advice); - var r = advice!.Remediation; - Assert.Contains("MAXDOP is 16", r); - Assert.Contains("cost threshold for parallelism is 5", r); - Assert.Contains("raise cost threshold for parallelism to 50", r); - Assert.Contains("lower MAXDOP from 16 to 8", r); - // The whole point: no hedging about settings the engine collected. - Assert.DoesNotContain("if those are already set", r); - } - - [Fact] - public void ThreadpoolParallel_AlreadyWithinGuidance_GuardsHarder() - { - // MAXDOP 8 / CTFP 50 are within topology guidance yet the pool still exhausted, so the - // driver is concurrency volume — the workload-aware override guards harder. - var advice = FactAdvice.Compose( - "THREADPOOL_PARALLEL", Facts(F("CONFIG_MAXDOP", 8), F("CONFIG_CTFP", 50), Hardware(8))); - - var r = advice!.Remediation; - Assert.Contains("MAXDOP is 8", r); - Assert.Contains("already within topology guidance", r); - Assert.Contains("MAXDOP from 8 to 4", r); // harder = rec/2 - } - - [Fact] - public void ThreadpoolParallel_NoConfigFacts_FallsBackToStaticBlock() - { - var advice = FactAdvice.Compose("THREADPOOL_PARALLEL", Facts()); - Assert.Equal(FactAdvice.GetForFactKey("THREADPOOL_PARALLEL"), advice); - } - - // ── CONFIG_MAXDOP: headline states the real value (the static block hard-coded "0") ── - - [Theory] - [InlineData(0, "MAXDOP is 0")] - [InlineData(1, "MAXDOP is 1")] - [InlineData(16, "MAXDOP is 16")] - public void ConfigMaxdop_HeadlineStatesActualValue(int maxdop, string expected) - { - var advice = FactAdvice.Compose("CONFIG_MAXDOP", Facts(F("CONFIG_MAXDOP", maxdop), Hardware(8))); - Assert.Contains(expected, advice!.Headline); - } - - [Fact] - public void ConfigMaxdop_AboveGuidance_RecommendsLoweringToCores() - { - var advice = FactAdvice.Compose("CONFIG_MAXDOP", Facts(F("CONFIG_MAXDOP", 32), Hardware(8))); - Assert.Contains("Lower MAXDOP from 32 to 8", advice!.Remediation); - } - - // ── CONFIG_CTFP: states the real value ── - - [Fact] - public void ConfigCtfp_StatesActualValue() - { - var advice = FactAdvice.Compose("CONFIG_CTFP", Facts(F("CONFIG_CTFP", 5))); - Assert.Contains("Cost Threshold for Parallelism is 5", advice!.Headline); - Assert.Contains("Raise it to 50", advice.Remediation); - } - - // ── non-value keys pass through to the static block ── - - [Fact] - public void Compose_NonValueKey_ReturnsStaticBlock() - { - Assert.Equal(FactAdvice.GetForFactKey("DEADLOCKS"), FactAdvice.Compose("DEADLOCKS", Facts())); - } - - // ── serialize / read-back round-trip ── - - [Fact] - public void SerializeForStoryText_RoundTrips() - { - var composed = FactAdvice.Compose( - "THREADPOOL_PARALLEL", Facts(F("CONFIG_MAXDOP", 16), F("CONFIG_CTFP", 5), Hardware(8))); - var json = FactAdvice.SerializeForStoryText(composed); - - Assert.StartsWith("{", json); - var back = FactAdvice.TryReadStoryText(json); - Assert.NotNull(back); - Assert.Equal(composed!.Headline, back!.Headline); - Assert.Equal(composed.Investigation, back.Investigation); - Assert.Equal(composed.Remediation, back.Remediation); - } - - [Fact] - public void TryReadStoryText_LegacyOrEmpty_ReturnsNull() - { - Assert.Null(FactAdvice.TryReadStoryText("")); - Assert.Null(FactAdvice.TryReadStoryText(null)); - Assert.Null(FactAdvice.TryReadStoryText("plain legacy text")); - } - - // ── render entry point: prefer frozen StoryText, fall back to static ── - - [Fact] - public void GetComposedForFinding_PrefersFrozenStoryText() - { - var custom = new AdviceBlock("Frozen headline", "Frozen investigation", "Frozen remediation"); - var finding = new AnalysisFinding - { - RootFactKey = "THREADPOOL_PARALLEL", - StoryText = FactAdvice.SerializeForStoryText(custom) - }; - - var advice = FactAdvice.GetComposedForFinding(finding); - Assert.Equal("Frozen headline", advice!.Headline); - Assert.Equal("Frozen remediation", advice.Remediation); - } - - [Fact] - public void GetComposedForFinding_EmptyStoryText_FallsBackToStatic() - { - var finding = new AnalysisFinding { RootFactKey = "CONFIG_CTFP", StoryText = "" }; - Assert.Equal(FactAdvice.GetForFactKey("CONFIG_CTFP"), FactAdvice.GetComposedForFinding(finding)); - } - - // ── PopulateStoryText: freezes value-stated advice, skips absolution ── - - [Fact] - public void PopulateStoryText_FreezesValueStatedAdvice_OnValueBearingStory() - { - var story = new AnalysisStory { RootFactKey = "THREADPOOL_PARALLEL", IsAbsolution = false }; - var facts = new List { F("CONFIG_MAXDOP", 16), F("CONFIG_CTFP", 5), Hardware(8) }; - - FactAdvice.PopulateStoryText(new[] { story }, facts); - - Assert.StartsWith("{", story.StoryText); - var back = FactAdvice.TryReadStoryText(story.StoryText); - Assert.Contains("MAXDOP is 16", back!.Remediation); - } - - [Fact] - public void PopulateStoryText_SkipsAbsolution() - { - var story = new AnalysisStory { RootFactKey = "server_health", IsAbsolution = true, StoryText = "" }; - FactAdvice.PopulateStoryText(new[] { story }, new List()); - Assert.Equal("", story.StoryText); - } - - // ── B1: parallelism value-gap blocks state the server's actual MAXDOP/CTFP ── - - [Theory] - [InlineData("CXPACKET")] - [InlineData("QUERY_HIGH_DOP")] - [InlineData("THREADPOOL")] - public void ParallelismBlocks_StateCurrentMaxdopCtfp(string key) - { - var facts = Facts(F("CONFIG_MAXDOP", 16), F("CONFIG_CTFP", 5), Hardware(8)); - var advice = FactAdvice.Compose(key, facts); - Assert.Contains("MAXDOP is 16", advice!.Remediation); - Assert.Contains("cost threshold for parallelism is 5", advice.Remediation); - Assert.Contains("lower MAXDOP from 16 to 8", advice.Remediation); - } - - [Fact] - public void ParallelismBlocks_NoConfigFacts_FallBackToStatic() - { - Assert.Equal(FactAdvice.GetForFactKey("CXPACKET"), FactAdvice.Compose("CXPACKET", Facts())); - } - - [Fact] - public void Cxpacket_Investigation_DropsAuditConfigDeferral() - { - Assert.DoesNotContain("call `audit_config` to check CTFP and MAXDOP", - FactAdvice.GetForFactKey("CXPACKET")!.Investigation); - } - - // ── B2: memory value blocks state the actual cap / physical RAM instead of deferring ── - - [Fact] - public void ConfigMaxMemory_StatesConcreteSuggestedCap() - { - var facts = Facts(F("CONFIG_MAX_MEMORY_MB", 2147483647), F("MEMORY_TOTAL_PHYSICAL_MB", 65536)); - var advice = FactAdvice.Compose("CONFIG_MAX_MEMORY_MB", facts); - Assert.Contains("65,536 MB", advice!.Investigation); // total physical RAM stated - Assert.Contains("58,983 MB", advice.Remediation); // suggested cap = total - max(4096, 10%) - Assert.DoesNotContain("audit_config", advice.Investigation); - } - - [Fact] - public void ConfigMinMaxNarrow_StatesConfiguredMinAndMax() - { - var f = new Fact - { - Key = "CONFIG_MIN_MAX_MEMORY_NARROW", Source = "config", Value = 24000, Severity = 0.4, - Metadata = new Dictionary { ["min_memory_mb"] = 24000, ["max_memory_mb"] = 28672 } - }; - var advice = FactAdvice.Compose("CONFIG_MIN_MAX_MEMORY_NARROW", Facts(f)); - Assert.Contains("24,000 MB", advice!.Investigation); - Assert.Contains("28,672 MB", advice.Investigation); - Assert.DoesNotContain("audit_config", advice.Investigation); - } - - [Theory] - [InlineData("PAGEIOLATCH_SH")] - [InlineData("QUERY_SPILLS")] - [InlineData("ANOMALY_MEMORY_PRESSURE")] - public void MemoryWaitBlocks_StateCurrentCap_NoAuditConfigDeferral(string key) - { - var facts = Facts(F("CONFIG_MAX_MEMORY_MB", 28672), F("MEMORY_TOTAL_PHYSICAL_MB", 65536)); - var advice = FactAdvice.Compose(key, facts); - Assert.Contains("max server memory is set to 28,672 MB", advice!.Remediation); - Assert.DoesNotContain("audit_config", advice.Remediation); - } - - [Fact] - public void MemoryWaitBlocks_NoCapFact_FallBackToStatic() - { - Assert.Equal(FactAdvice.GetForFactKey("QUERY_SPILLS"), FactAdvice.Compose("QUERY_SPILLS", Facts())); - } - - // ── B3: RCSI-deferral blocks state the RCSI-off count instead of deferring to audit_config ── - - private static Fact DbConfig(int rcsiOff) => new() - { - Key = "DB_CONFIG", Source = "config", Value = 1, Severity = 0.3, - Metadata = new Dictionary { ["rcsi_off_count"] = rcsiOff } - }; - - [Theory] - [InlineData("BLOCKING_EVENTS")] - [InlineData("DEADLOCKS")] - public void RcsiBlocks_StateRcsiOffCount_WhenDbConfigCoFired(string key) - { - var advice = FactAdvice.Compose(key, Facts(DbConfig(9))); - Assert.Contains("9 databases on this server currently have RCSI off", advice!.Remediation); - } - - [Fact] - public void RcsiBlocks_SingularPhrasing_ForOneDatabase() - { - var advice = FactAdvice.Compose("BLOCKING_EVENTS", Facts(DbConfig(1))); - Assert.Contains("One database on this server currently has RCSI off", advice!.Remediation); - } - - [Fact] - public void RcsiBlocks_NoDbConfig_FallBackToStatic() - { - Assert.Equal(FactAdvice.GetForFactKey("DEADLOCKS"), FactAdvice.Compose("DEADLOCKS", Facts())); - } - - [Fact] - public void BlockingAndDeadlock_DropAuditConfigRcsiDeferral() - { - Assert.DoesNotContain("audit_config", FactAdvice.GetForFactKey("BLOCKING_EVENTS")!.Remediation); - Assert.DoesNotContain("audit_config", FactAdvice.GetForFactKey("DEADLOCKS")!.Investigation); - } -} diff --git a/deprecated/Dashboard.Tests/FactAdviceCorrectnessTests.cs b/deprecated/Dashboard.Tests/FactAdviceCorrectnessTests.cs deleted file mode 100644 index df89fedad6..0000000000 --- a/deprecated/Dashboard.Tests/FactAdviceCorrectnessTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Regression guards for the sourced-wrong claims and the retrospective "kill it" survivors the -/// post-merge broad review flagged in FactAdvice's static blocks. Each was either contradicted by -/// MS Learn (range locks are SERIALIZABLE-only; an UPDATE maintains only changed-column indexes; -/// last-page contention is fixed by OPTIMIZE_FOR_SEQUENTIAL_KEY, not by adding a clustered index; -/// tempdb autogrowth should be ENABLED) or gave live-firefighting advice for a tool that reports on -/// windows that have already passed. -/// -public class FactAdviceCorrectnessTests -{ - private static string Text(string key) - { - var a = FactAdvice.GetForFactKey(key); - Assert.NotNull(a); - return $"{a!.Headline}\n{a.Investigation}\n{a.Remediation}"; - } - - [Fact] - public void Sos_DoesNotClaimDemandExceedsSupply_NorCircularDeferral() - { - var t = Text("SOS_SCHEDULER_YIELD"); - Assert.DoesNotContain("demand than capacity", t); - Assert.DoesNotContain("demand exceeds supply", t); - Assert.DoesNotContain("recommendation engine will tell you", t); - Assert.Contains("quantum", t); // states the real cooperative-scheduling mechanism - } - - [Fact] - public void IoWriteLatency_DoesNotClaimEveryUpdateTouchesEveryIndex() - { - Assert.DoesNotContain("every UPDATE touches every nonclustered index", Text("IO_WRITE_LATENCY_MS")); - } - - [Fact] - public void MissingIndex_UpdateMaintenanceClaimIsPrecise() - { - Assert.DoesNotContain("every INSERT/UPDATE/DELETE pays", Text("MISSING_INDEX")); - } - - // #4149: last-page-insert / OPTIMIZE_FOR_SEQUENTIAL_KEY moved to PAGELATCH_EX — LATCH_EX excludes - // buffer latches (sys.dm_os_wait_stats), so it is no longer where this advice belongs. - [Fact] - public void PagelatchEx_LastPageFix_IsOptimizeForSequentialKey_NotAddClusteredIndex() - { - var t = Text("PAGELATCH_EX"); - Assert.DoesNotContain("add a clustered index", t); - Assert.Contains("OPTIMIZE_FOR_SEQUENTIAL_KEY", t); - } - - [Fact] - public void LatchEx_DoesNotDescribePageLatches() - { - var t = Text("LATCH_EX"); - Assert.DoesNotContain("OPTIMIZE_FOR_SEQUENTIAL_KEY", t); - Assert.Contains("non-buffer", t); - } - - [Fact] - public void Tempdb_AutogrowthIsEnabled_NotDisabled_AndNoKill() - { - var t = Text("TEMPDB_USAGE"); - Assert.DoesNotContain("autogrowth disabled", t); - Assert.DoesNotContain("kill it", t); - } - - [Fact] - public void RangeLocks_AreSerializableOnly_NotRepeatableRead() - { - Assert.DoesNotContain("SERIALIZABLE or REPEATABLE READ", Text("LCK_RANGE")); - } - - [Fact] - public void AnomalyBlockingSpike_NoKillIt() - { - Assert.DoesNotContain("kill it", Text("ANOMALY_BLOCKING_SPIKE")); - } - - [Theory] - [InlineData("ANOMALY_READ_LATENCY")] - [InlineData("ANOMALY_WRITE_LATENCY")] - public void LatencyAnomalies_HeadlineNotRightNow(string key) - { - Assert.DoesNotContain("right now", FactAdvice.GetForFactKey(key)!.Headline); - } - - // #3531: the two reader/writer lock twins hand out the same RCSI ALTER, so both must name its - // counter-objectives — the brief exclusive lock the ALTER takes, the test-on-a-copy warning for - // NOLOCK-dependent code, and the tempdb version-store cost FactRiskDisclosure discloses at apply - // time. LCK_M_IS shipped the bare ALTER calling RCSI "strictly better" with none of them. - [Theory] - [InlineData("LCK_M_S")] - [InlineData("LCK_M_IS")] - public void RcsiLockTwins_NameTheCaveatsAlongsideTheAlter(string key) - { - var remediation = FactAdvice.GetForFactKey(key)!.Remediation; - Assert.Contains("brief exclusive lock", remediation); - Assert.Contains("test on a copy", remediation); - Assert.Contains("version store", remediation); - } - - // Review note (§2): SOS rewrite over-swung to "never CPU pressure". The amount + a deep runnable - // queue IS demand-exceeds-capacity; the advice must point at the runnable-queue discriminator. - [Fact] - public void Sos_UsesRunnableQueueDiscriminator_NotAbsoluteNoPressure() - { - var t = Text("SOS_SCHEDULER_YIELD"); - Assert.Contains("runnable queue", t); - Assert.DoesNotContain("not as SOS_SCHEDULER_YIELD", t); // the over-correction is gone - Assert.DoesNotContain("get_cpu_scheduler_pressure", t); // MCP tool names removed from human prose - } - - // Review note (§1): MAXDOP can be set per database; the advice must acknowledge the DB-scoped - // override and point at get_database_scoped_config (the engine itself scores only the server default). - [Fact] - public void ConfigMaxdop_NotesPerDatabaseScopedOverride() - { - var advice = FactAdvice.GetForFactKey("CONFIG_MAXDOP"); - Assert.Contains("DATABASE SCOPED CONFIGURATION", advice!.Investigation); - Assert.DoesNotContain("get_database_scoped_config", advice.Investigation); // MCP tool name removed - } -} diff --git a/deprecated/Dashboard.Tests/FactScorerTests.cs b/deprecated/Dashboard.Tests/FactScorerTests.cs deleted file mode 100644 index cc39dd4acd..0000000000 --- a/deprecated/Dashboard.Tests/FactScorerTests.cs +++ /dev/null @@ -1,1161 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests FactScorer Layer 1 (base severity) and Layer 2 (amplifiers). -/// Validates threshold formulas, amplifier firing, and severity capping. -/// -public class FactScorerTests -{ - /* ── Threshold formula unit tests ── */ - - [Theory] - [InlineData(0.0, 0.25, null, 0.0)] // Zero → 0.0 - [InlineData(0.125, 0.25, null, 0.5)] // Half of concerning → 0.5 - [InlineData(0.25, 0.25, null, 1.0)] // At concerning (no critical) → 1.0 - [InlineData(0.50, 0.25, null, 1.0)] // Above concerning (no critical) → capped at 1.0 - [InlineData(0.0, 0.25, 0.75, 0.0)] // Zero → 0.0 - [InlineData(0.125, 0.25, 0.75, 0.25)] // Half of concerning → 0.25 - [InlineData(0.25, 0.25, 0.75, 0.5)] // At concerning → 0.5 - [InlineData(0.50, 0.25, 0.75, 0.75)] // Midway → 0.75 - [InlineData(0.75, 0.25, 0.75, 1.0)] // At critical → 1.0 - [InlineData(1.00, 0.25, 0.75, 1.0)] // Above critical → 1.0 - public void ApplyThresholdFormula_ReturnsExpected( - double value, double concerning, double? critical, double expected) - { - var result = FactScorer.ApplyThresholdFormula(value, concerning, critical); - Assert.Equal(expected, result, precision: 4); - } - - /* ── Unknown wait types ── */ - - [Fact] - public void Score_UnknownWaitType_GetsSeverityZero() - { - var facts = new List - { - new() { Source = "waits", Key = "UNKNOWN_WAIT_XYZ", Value = 0.50 } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(0.0, facts[0].BaseSeverity); - } - - /* ── Wait-profile anomaly scoring (change 1) ── */ - - // The shared ANOMALY_WAIT_PROFILE arm scores on the HONEST per-second ratio: below 4x → 0, 4x → - // 0.5, saturating to 1.0 at 12x. Same shared FactScorer as Lite — pinned here for parity. - [Theory] - [InlineData(3.0, 0.0)] - [InlineData(4.0, 0.5)] - [InlineData(12.0, 1.0)] - [InlineData(100.0, 1.0)] - public void Score_WaitProfile_RampsFromHonestRatio(double ratio, double expected) - { - var fact = new Fact - { - Source = "anomaly", - Key = "ANOMALY_WAIT_PROFILE", - Metadata = new() { ["ratio"] = ratio } - }; - new FactScorer().ScoreAll(new List { fact }); - Assert.Equal(expected, fact.BaseSeverity, precision: 4); - } - - [Fact] - public void WaitProfile_HasAdviceBlock() - { - var advice = FactAdvice.GetForFactKey("ANOMALY_WAIT_PROFILE"); - Assert.NotNull(advice); - Assert.False(string.IsNullOrWhiteSpace(advice!.Headline)); - Assert.False(string.IsNullOrWhiteSpace(advice.Investigation)); - Assert.False(string.IsNullOrWhiteSpace(advice.Remediation)); - } - - /* ── Bounded-metric low-quality (thin-baseline) fallback scoring (finding 1) ── */ - - // When the quality gate fires on a thin/untrustworthy baseline (baseline_low_quality=1) the stored - // deviation_sigma is the real (small) z — the 2σ gate would zero it and InferenceEngine would drop the - // finding. The scorer grades off the absolute exceedance (peak ÷ the fallback bar) instead: floor 0.5 - // AT the bar, ramping to 1.0 at 2× the bar. Same shared FactScorer as Lite — pinned here for parity. - [Theory] - [InlineData("ANOMALY_CPU_SPIKE", 1.0, 0.5)] // exactly at the bar → the 0.5 floor - [InlineData("ANOMALY_MEMORY_PRESSURE", 1.25, 0.625)] - [InlineData("ANOMALY_READ_LATENCY", 1.5, 0.75)] // 1.5× the bar → midway - [InlineData("ANOMALY_WRITE_LATENCY", 2.0, 1.0)] // 2× the bar → saturated - [InlineData("ANOMALY_BATCH_REQUESTS", 5.0, 1.0)] // far past → clamped to 1.0 - public void Score_LowQualityFallback_GradesOffExceedance_NotSigma( - string key, double exceedance, double expected) - { - var fact = new Fact - { - Source = "anomaly", - Key = key, - Metadata = new() - { - ["deviation_sigma"] = 0.7, // a real, sub-2σ z the gate must ignore - ["baseline_low_quality"] = 1.0, - ["fallback_exceedance"] = exceedance, - ["confidence"] = 1.0 - } - }; - new FactScorer().ScoreAll(new List { fact }); - Assert.Equal(expected, fact.BaseSeverity, precision: 4); - } - - // The finding's exact regression: memory 96% on a thin baseline (95% fallback bar) used to score 0 - // (small z → 2σ gate → 0 → InferenceEngine drops it → NO finding). It must now clear the 0.5 entry. - [Fact] - public void Score_Memory96PercentOnThinBaseline_ClearsInferenceEntryPoint() - { - var fact = new Fact - { - Source = "anomaly", - Key = "ANOMALY_MEMORY_PRESSURE", - Metadata = new() - { - ["deviation_sigma"] = 0.4, - ["baseline_low_quality"] = 1.0, - ["fallback_exceedance"] = 96.0 / 95.0, - ["confidence"] = 1.0 - } - }; - new FactScorer().ScoreAll(new List { fact }); - Assert.True(fact.BaseSeverity >= 0.5, "a thin-baseline memory-96% fallback must surface, not vanish"); - } - - // The trustworthy z-path is unchanged: with baseline_low_quality=0 a sub-2σ deviation still scores 0. - [Fact] - public void Score_TrustworthyBaseline_SubTwoSigma_StillScoresZero() - { - var fact = new Fact - { - Source = "anomaly", - Key = "ANOMALY_MEMORY_PRESSURE", - Metadata = new() - { - ["deviation_sigma"] = 1.5, - ["baseline_low_quality"] = 0.0, - ["fallback_exceedance"] = 0.0, - ["confidence"] = 1.0 - } - }; - new FactScorer().ScoreAll(new List { fact }); - Assert.Equal(0.0, fact.BaseSeverity, precision: 4); - } - - /* ── Layer 2: Amplifier tests ── */ - - [Fact] - public void Amplifier_SeverityCappedAt2() - { - // Synthetic: create a fact set where amplifiers would push past 2.0 - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base = 1.0 - new() { Source = "waits", Key = "SOS_SCHEDULER_YIELD", Value = 0.50 }, // > 25% threshold - new() { Source = "waits", Key = "THREADPOOL", Value = 0.05, // real thread exhaustion - Metadata = new() { ["wait_time_ms"] = 7_200_000, ["avg_ms_per_wait"] = 3_600 } }, // 2h total, 3.6s avg - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // bad CTFP - new() { Source = "config", Key = "CONFIG_MAXDOP", Value = 0 }, // bad MAXDOP - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - - // base 1.0 * (1.0 + 0.3 SOS + 0.4 THREADPOOL + 0.3 CTFP + 0.2 MAXDOP) = 2.2 → capped at 2.0. - // (SOS + THREADPOOL are impact peers, so the Layer-3 tuning cap is released here.) - Assert.True(cx.Severity <= 2.0, "Severity should never exceed 2.0"); - Assert.Equal(2.0, cx.Severity); - } - - /* ── Layer 3: tuning-class severity cap + impact escalation (change 4) ── */ - - // Parallelism is a tuning opportunity, not an outage. CXPACKET saturates its base to 1.0 and - // non-impact amplifiers (CTFP + MAXDOP + high-DOP queries) push the Layer-2 product to 1.7, which - // WOULD land in the CRITICAL band (>= 1.5). With no impact peer co-firing, Layer 3 caps it at the - // 1.49 WARNING ceiling. Same shared FactScorer as Lite — pinned here for parity. - [Fact] - public void Score_CxPacketAlone_CappedAtWarningCeiling() - { - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base 1.0 - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // +0.3 (not an impact peer) - new() { Source = "config", Key = "CONFIG_MAXDOP", Value = 0 }, // +0.2 (not an impact peer) - new() { Source = "queries", Key = "QUERY_HIGH_DOP", Value = 10 }, // +0.2 (not an impact peer) - }; - - new FactScorer().ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - // Layer-2 product = 1.0 * (1 + 0.3 + 0.2 + 0.2) = 1.7; Layer 3 caps it to 1.49. - Assert.Equal(1.49, cx.Severity, precision: 4); - Assert.True(cx.Severity < 1.5, "parallelism alone must stay in the WARNING band, never CRITICAL"); - } - - // Escape hatch: when an impact-bearing peer co-fires (THREADPOOL = real thread exhaustion) the cap - // is released and CXPACKET keeps its full amplified severity into the CRITICAL band. - [Fact] - public void Score_CxPacketWithThreadpool_CapReleased() - { - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base 1.0 - new() { Source = "waits", Key = "THREADPOOL", Value = 0.05, // real thread exhaustion (+0.4 on CXPACKET) - Metadata = new() { ["wait_time_ms"] = 7_200_000, ["avg_ms_per_wait"] = 3_600 } }, - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // +0.3 - }; - - new FactScorer().ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - // 1.0 * (1 + 0.4 THREADPOOL + 0.3 CTFP) = 1.7, uncapped because an impact peer co-fired. - Assert.Equal(1.7, cx.Severity, precision: 4); - Assert.True(cx.Severity >= 1.5, "an impact peer co-firing releases the cap into CRITICAL"); - } - - // REGRESSION (escape-hatch significance gate): the cap-release peers SOS_SCHEDULER_YIELD and - // RESOURCE_SEMAPHORE must be SIGNIFICANT to release the cap, not merely present. Neither has a - // minimum guard in ScoreWaitFact, so BaseSeverity > 0 fires on any trace of the wait — and SOS - // physically co-occurs with high CXPACKET (parallel workers yield -> SOS). A trivial SOS used to - // release the cap on exactly the busy servers the cap targets, re-admitting CXPACKET=CRITICAL - // noise. These pin the significance bars (SOS 0.25, RS 0.10) the escape hatch now uses. Same shared - // FactScorer as Lite — pinned here for parity. - - // A TRIVIAL SOS (0.1% of period, far below the 0.25 bar) must NOT release the cap: CXPACKET stays - // capped at the WARNING ceiling even though a sub-threshold SOS wait is present. - [Fact] - public void Score_CxPacketWithTrivialSos_CapHolds() - { - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base 1.0 - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // +0.3 - new() { Source = "config", Key = "CONFIG_MAXDOP", Value = 0 }, // +0.2 - new() { Source = "queries", Key = "QUERY_HIGH_DOP", Value = 10 }, // +0.2 - new() { Source = "waits", Key = "SOS_SCHEDULER_YIELD", Value = 0.001 }, // TRIVIAL — 0.1%, < 0.25 bar - }; - - new FactScorer().ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - // Trivial SOS neither amplifies CXPACKET (amp bar is 0.25) nor releases the cap: 1.7 -> 1.49. - Assert.Equal(1.49, cx.Severity, precision: 4); - Assert.True(cx.Severity <= 1.49, "a trivial SOS must NOT release the tuning cap"); - } - - // A SIGNIFICANT SOS (30% of period, >= the 0.25 bar) DOES release the cap: CXPACKET reaches CRITICAL. - [Fact] - public void Score_CxPacketWithSignificantSos_CapReleased() - { - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base 1.0 - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // +0.3 - new() { Source = "config", Key = "CONFIG_MAXDOP", Value = 0 }, // +0.2 - new() { Source = "queries", Key = "QUERY_HIGH_DOP", Value = 10 }, // +0.2 - new() { Source = "waits", Key = "SOS_SCHEDULER_YIELD", Value = 0.30 }, // SIGNIFICANT — >= 0.25 bar - }; - - new FactScorer().ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - // Significant SOS also fires the CXPACKET SOS amplifier (+0.3): 1.0*(1+0.3+0.3+0.2+0.2)=2.0, uncapped. - Assert.Equal(2.0, cx.Severity, precision: 4); - Assert.True(cx.Severity >= 1.5, "a significant SOS releases the cap into CRITICAL"); - } - - // A TRIVIAL RESOURCE_SEMAPHORE (0.1% of period, below the 0.10 bar) must NOT release the cap. RS - // never amplifies CXPACKET, so pre-cap CXPACKET is 1.7 either way — this isolates the escape hatch. - [Fact] - public void Score_CxPacketWithTrivialResourceSemaphore_CapHolds() - { - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base 1.0 - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // +0.3 - new() { Source = "config", Key = "CONFIG_MAXDOP", Value = 0 }, // +0.2 - new() { Source = "queries", Key = "QUERY_HIGH_DOP", Value = 10 }, // +0.2 - new() { Source = "waits", Key = "RESOURCE_SEMAPHORE", Value = 0.001 }, // TRIVIAL — 0.1%, < 0.10 bar - }; - - new FactScorer().ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - Assert.Equal(1.49, cx.Severity, precision: 4); - Assert.True(cx.Severity <= 1.49, "a trivial RESOURCE_SEMAPHORE must NOT release the tuning cap"); - } - - // A SIGNIFICANT RESOURCE_SEMAPHORE (15% of period, >= the 0.10 bar) DOES release the cap. RS does - // not amplify CXPACKET, so the pre-cap 1.7 passes through uncapped — the escape hatch in isolation. - [Fact] - public void Score_CxPacketWithSignificantResourceSemaphore_CapReleased() - { - var facts = new List - { - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, // base 1.0 - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // +0.3 - new() { Source = "config", Key = "CONFIG_MAXDOP", Value = 0 }, // +0.2 - new() { Source = "queries", Key = "QUERY_HIGH_DOP", Value = 10 }, // +0.2 - new() { Source = "waits", Key = "RESOURCE_SEMAPHORE", Value = 0.15 }, // SIGNIFICANT — >= 0.10 bar - }; - - new FactScorer().ScoreAll(facts); - - var cx = facts.First(f => f.Key == "CXPACKET"); - // RS does not amplify CXPACKET; the pre-cap 1.7 is released unchanged. - Assert.Equal(1.7, cx.Severity, precision: 4); - Assert.True(cx.Severity >= 1.5, "a significant RESOURCE_SEMAPHORE releases the cap into CRITICAL"); - } - - // THREADPOOL is the impact-bearing escalation path and is NEVER capped. The raised CXPACKET - // amplifier (+0.5) and the new runnable-queue amplifier (+0.5, off the RUNNABLE_TASKS context fact) - // drive a genuine parallelism -> thread-exhaustion meltdown to CRITICAL through THREADPOOL. - [Fact] - public void Score_Threadpool_ReachesCritical_ViaCxPacketAndRunnableQueue() - { - var facts = new List - { - new() { Source = "waits", Key = "THREADPOOL", Value = 0.05, // base 1.0 - Metadata = new() { ["wait_time_ms"] = 7_200_000, ["avg_ms_per_wait"] = 3_600 } }, - new() { Source = "waits", Key = "CXPACKET", Value = 0.40 }, // >= 0.10 -> raised amp +0.5 - new() { Source = "cpu", Key = "RUNNABLE_TASKS", Value = 48, // runnable_tasks_warning set -> amp +0.5 - Metadata = new() { ["total_runnable_tasks"] = 48, ["runnable_tasks_warning"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - var tp = facts.First(f => f.Key == "THREADPOOL"); - // 1.0 * (1 + 0.5 CXPACKET + 0.5 runnable-queue) = 2.0, uncapped (THREADPOOL is an impact key). - Assert.Equal(2.0, tp.Severity, precision: 4); - Assert.True(tp.Severity >= 1.5, "THREADPOOL must reach CRITICAL on a real meltdown"); - - var cxAmp = tp.AmplifierResults.First(a => a.Description.Contains("CXPACKET")); - Assert.True(cxAmp.Matched); - Assert.Equal(0.5, cxAmp.Boost); - - var rqAmp = tp.AmplifierResults.First(a => a.Description.Contains("Runnable-task queue")); - Assert.True(rqAmp.Matched); - Assert.Equal(0.5, rqAmp.Boost); - } - - // The runnable-queue amplifier only fires on genuine scheduler pressure: a shallow runnable queue - // (below the trip level) does not boost THREADPOOL. - [Fact] - public void Score_Threadpool_RunnableQueueAmplifier_DoesNotFireBelowThreshold() - { - var facts = new List - { - new() { Source = "waits", Key = "THREADPOOL", Value = 0.05, - Metadata = new() { ["wait_time_ms"] = 7_200_000, ["avg_ms_per_wait"] = 3_600 } }, - new() { Source = "cpu", Key = "RUNNABLE_TASKS", Value = 4, // warning clear -> no boost - Metadata = new() { ["total_runnable_tasks"] = 4, ["runnable_tasks_warning"] = 0 } }, - }; - - new FactScorer().ScoreAll(facts); - - var tp = facts.First(f => f.Key == "THREADPOOL"); - var rqAmp = tp.AmplifierResults.First(a => a.Description.Contains("Runnable-task queue")); - Assert.False(rqAmp.Matched); - } - - // ── Tier-2 parity arms (batch 1): runnable-queue / security-cache / QS-off ────────────────── - // All three are additions to the SHARED FactScorer, so they fire identically for Lite, Dashboard, - // and Darling findings. Sourced thresholds are cited per arm against the deprecated Dashboard SQL. - - // ARM 3 — runnable-task-queue depth roots a STANDALONE finding off the collected cpu_scheduler_stats - // snapshot, tiered to the Dashboard's report.cpu_scheduler_pressure CASE (install/47:1839-1841): - // > 50 CRITICAL-tier (base 1.0), > 20 HIGH (0.75), > 10 MEDIUM (0.5 — the 0.5 root entry point). - // Base maxes at 1.0 (top of WARNING) like every base fact; CRITICAL band is reached only via the - // #1494 runnable-queue -> THREADPOOL amplifier, which still fires independently. - [Theory] - [InlineData(60, 1.0)] // > 50 -> CRITICAL tier (install/47:1839) - [InlineData(30, 0.75)] // > 20 -> HIGH tier (install/47:1840) - [InlineData(15, 0.5)] // > 10 -> MEDIUM tier (install/47:1841) - public void Score_RunnableTasks_TiersMatchDashboard(double total, double expected) - { - var facts = new List - { - new() { Source = "cpu", Key = "RUNNABLE_TASKS", Value = total, - Metadata = new() { ["total_runnable_tasks"] = total, ["runnable_tasks_warning"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - var rt = facts.First(f => f.Key == "RUNNABLE_TASKS"); - // No amplifiers on RUNNABLE_TASKS and it is not tuning-class, so Severity == base. - Assert.Equal(expected, rt.Severity, precision: 4); - Assert.True(rt.Severity >= 0.5, "a non-NORMAL runnable queue must clear the 0.5 root threshold"); - } - - // A shallow queue below the > 10 bar with the warning flag CLEAR does not score (context-only). - [Fact] - public void Score_RunnableTasks_BelowThreshold_DoesNotScore() - { - var facts = new List - { - new() { Source = "cpu", Key = "RUNNABLE_TASKS", Value = 5, - Metadata = new() { ["total_runnable_tasks"] = 5, ["runnable_tasks_warning"] = 0 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "RUNNABLE_TASKS").Severity, precision: 4); - } - - // Small-box fallback: below the absolute > 10 bar, the collector's runnable_tasks_warning flag - // (SUM(runnable_tasks_count) >= cpu_count) still scores HIGH (install/47:1844). - [Fact] - public void Score_RunnableTasks_WarningFlagOnSmallBox_ScoresHigh() - { - var facts = new List - { - new() { Source = "cpu", Key = "RUNNABLE_TASKS", Value = 6, - Metadata = new() { ["total_runnable_tasks"] = 6, ["runnable_tasks_warning"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.75, facts.First(f => f.Key == "RUNNABLE_TASKS").Severity, precision: 4); - } - - // ARM 2 — TokenAndPermUserStore (security cache) growth scores a flat WARNING at >= 1 GB off the - // otherwise context-only MEMORY_CLERKS fact (install/50:562 severity=WARNING, :583 threshold 1 GB). - // The clerk size rides in metadata keyed by clerk_type (= sys.dm_os_memory_clerks.type). - [Fact] - public void Score_MemoryClerks_SecurityCacheOver1Gb_ScoresWarning() - { - var facts = new List - { - new() { Source = "memory", Key = "MEMORY_CLERKS", Value = 52_048, - Metadata = new() - { - ["MEMORYCLERK_SQLBUFFERPOOL"] = 50_000, - ["USERSTORE_TOKENPERM"] = 2_048, // 2 GB - ["total_top_clerks_mb"] = 52_048, - ["clerk_count"] = 2 - } }, - }; - - new FactScorer().ScoreAll(facts); - - var mc = facts.First(f => f.Key == "MEMORY_CLERKS"); - Assert.True(mc.Severity >= 0.75 && mc.Severity < 1.5, "security-cache growth bands WARNING"); - } - - // Under 1 GB does not score; MEMORY_CLERKS stays context-only. - [Fact] - public void Score_MemoryClerks_SecurityCacheUnder1Gb_DoesNotScore() - { - var facts = new List - { - new() { Source = "memory", Key = "MEMORY_CLERKS", Value = 50_512, - Metadata = new() - { - ["MEMORYCLERK_SQLBUFFERPOOL"] = 50_000, - ["USERSTORE_TOKENPERM"] = 512, // 0.5 GB — below the 1 GB bar - } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "MEMORY_CLERKS").Severity, precision: 4); - } - - // A normal clerk set with no TokenAndPermUserStore entry scores 0 (context-only preserved). - [Fact] - public void Score_MemoryClerks_NoSecurityCacheClerk_DoesNotScore() - { - var facts = new List - { - new() { Source = "memory", Key = "MEMORY_CLERKS", Value = 50_000, - Metadata = new() { ["MEMORYCLERK_SQLBUFFERPOOL"] = 50_000, ["clerk_count"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "MEMORY_CLERKS").Severity, precision: 4); - } - - // ── Tier-2 ARM: plan-cache single-use bloat scores off PLAN_CACHE_BLOAT (Value = single_use_percent), - // tiered > 50/30/20% (install/47:1485-1487) behind a single_use_size_mb >= 100 noise guard. ── - [Fact] - public void Score_PlanCacheBloat_Over50Percent_BandsWarningCeiling() - { - var facts = new List - { - new() { Source = "memory", Key = "PLAN_CACHE_BLOAT", Value = 62, - Metadata = new() - { - ["single_use_plans"] = 6_200, - ["total_plans"] = 10_000, - ["single_use_size_mb"] = 800, // >= 100 MB — real bloat - ["total_size_mb"] = 1_300, - ["single_use_percent"] = 62 - } }, - }; - - new FactScorer().ScoreAll(facts); - - // > 50% is the Dashboard's CRITICAL tier, but base caps at the WARNING ceiling (1.0); CRITICAL is - // earned only via corroboration. - Assert.Equal(1.0, facts.First(f => f.Key == "PLAN_CACHE_BLOAT").Severity, precision: 4); - } - - [Fact] - public void Score_PlanCacheBloat_Between30And50_ScoresHigh() - { - var facts = new List - { - new() { Source = "memory", Key = "PLAN_CACHE_BLOAT", Value = 38, - Metadata = new() { ["single_use_size_mb"] = 400, ["single_use_percent"] = 38 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.75, facts.First(f => f.Key == "PLAN_CACHE_BLOAT").Severity, precision: 4); - } - - [Fact] - public void Score_PlanCacheBloat_Between20And30_ScoresMedium() - { - var facts = new List - { - new() { Source = "memory", Key = "PLAN_CACHE_BLOAT", Value = 24, - Metadata = new() { ["single_use_size_mb"] = 250, ["single_use_percent"] = 24 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.5, facts.First(f => f.Key == "PLAN_CACHE_BLOAT").Severity, precision: 4); - } - - // Under 20% single-use is healthy plan-cache composition — dormant. - [Fact] - public void Score_PlanCacheBloat_Under20Percent_DoesNotScore() - { - var facts = new List - { - new() { Source = "memory", Key = "PLAN_CACHE_BLOAT", Value = 12, - Metadata = new() { ["single_use_size_mb"] = 400, ["single_use_percent"] = 12 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "PLAN_CACHE_BLOAT").Severity, precision: 4); - } - - // A high single-use % on a tiny footprint (< 100 MB) is noise — the size guard keeps it dormant even - // above the 20% bar. - [Fact] - public void Score_PlanCacheBloat_HighPercentButTinyFootprint_DoesNotScore() - { - var facts = new List - { - new() { Source = "memory", Key = "PLAN_CACHE_BLOAT", Value = 70, - Metadata = new() { ["single_use_size_mb"] = 40, ["single_use_percent"] = 70 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "PLAN_CACHE_BLOAT").Severity, precision: 4); - } - - // ── Tier-2 ARM: ring-buffer physical-memory-pressure scores off MEMORY_PRESSURE_EVENTS (Value = the - // max indicator), banded >= 3 HIGH (0.9) / >= 2 MEDIUM (0.5) per report.memory_pressure_events - // (install/47:229-236). ── - [Fact] - public void Score_MemoryPressureEvents_Indicator3_BandsWarning() - { - var facts = new List - { - new() { Source = "memory", Key = "MEMORY_PRESSURE_EVENTS", Value = 3, - Metadata = new() { ["event_count"] = 12, ["max_process_indicator"] = 3, ["max_system_indicator"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - var mp = facts.First(f => f.Key == "MEMORY_PRESSURE_EVENTS"); - Assert.Equal(0.9, mp.Severity, precision: 4); - Assert.True(mp.Severity >= 0.75 && mp.Severity < 1.5, "HIGH pressure bands WARNING"); - } - - [Fact] - public void Score_MemoryPressureEvents_Indicator2_ScoresMedium() - { - var facts = new List - { - new() { Source = "memory", Key = "MEMORY_PRESSURE_EVENTS", Value = 2, - Metadata = new() { ["event_count"] = 4, ["max_process_indicator"] = 2, ["max_system_indicator"] = 0 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.5, facts.First(f => f.Key == "MEMORY_PRESSURE_EVENTS").Severity, precision: 4); - } - - // Indicator 1 (steady / LOW) does not score — a defensive floor (the collector already gates < 2 out). - [Fact] - public void Score_MemoryPressureEvents_Indicator1_DoesNotScore() - { - var facts = new List - { - new() { Source = "memory", Key = "MEMORY_PRESSURE_EVENTS", Value = 1, - Metadata = new() { ["event_count"] = 0, ["max_process_indicator"] = 1, ["max_system_indicator"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "MEMORY_PRESSURE_EVENTS").Severity, precision: 4); - } - - // batch-2b — priority boost enabled is a Dashboard WARNING (install/50:368). CONFIG_PRIORITY_BOOST - // bands WARNING (0.9) when value_in_use == 1, and scores 0 when disabled. - [Fact] - public void Score_ConfigPriorityBoost_Enabled_BandsWarning() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_PRIORITY_BOOST", Value = 1, Metadata = new() { ["value_in_use"] = 1 } }, - }; - new FactScorer().ScoreAll(facts); - var f = facts.First(f => f.Key == "CONFIG_PRIORITY_BOOST"); - Assert.True(f.Severity >= 0.75 && f.Severity < 1.5, "priority boost bands WARNING when enabled"); - } - - [Fact] - public void Score_ConfigPriorityBoost_Disabled_DoesNotScore() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_PRIORITY_BOOST", Value = 0, Metadata = new() { ["value_in_use"] = 0 } }, - }; - new FactScorer().ScoreAll(facts); - Assert.Equal(0.0, facts.First(f => f.Key == "CONFIG_PRIORITY_BOOST").Severity, precision: 4); - } - - // Lightweight pooling enabled is a Dashboard WARNING (install/50:401) — same shape. - [Fact] - public void Score_ConfigLightweightPooling_Enabled_BandsWarning() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_LIGHTWEIGHT_POOLING", Value = 1, Metadata = new() { ["value_in_use"] = 1 } }, - }; - new FactScorer().ScoreAll(facts); - var f = facts.First(f => f.Key == "CONFIG_LIGHTWEIGHT_POOLING"); - Assert.True(f.Severity >= 0.75 && f.Severity < 1.5, "lightweight pooling bands WARNING when enabled"); - } - - [Fact] - public void Score_ConfigLightweightPooling_Disabled_DoesNotScore() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_LIGHTWEIGHT_POOLING", Value = 0, Metadata = new() { ["value_in_use"] = 0 } }, - }; - new FactScorer().ScoreAll(facts); - Assert.Equal(0.0, facts.First(f => f.Key == "CONFIG_LIGHTWEIGHT_POOLING").Severity, precision: 4); - } - - // ARM 1 — Query Store off on a user database is an INFO advisory carried by the DB_CONFIG fact, - // detected as query_store_on_count < database_count (install/50:83 severity=INFO). Low 0.3 base = - // INFO band, and DB_CONFIG roots at any positive severity (a ConfigAdvisoryRootKey). - [Fact] - public void Score_DbConfig_QueryStoreOff_ScoresInfoAdvisory() - { - var facts = new List - { - new() { Source = "database_config", Key = "DB_CONFIG", Value = 3, - Metadata = new() { ["database_count"] = 3, ["query_store_on_count"] = 1 } }, - }; - - new FactScorer().ScoreAll(facts); - - var db = facts.First(f => f.Key == "DB_CONFIG"); - Assert.Equal(0.3, db.Severity, precision: 4); - Assert.True(db.Severity > 0 && db.Severity < 0.75, "QS-off is an INFO-band advisory"); - } - - // Every user DB has Query Store on and nothing else drifted -> DB_CONFIG does not score. - [Fact] - public void Score_DbConfig_QueryStoreAllOn_NoContribution() - { - var facts = new List - { - new() { Source = "database_config", Key = "DB_CONFIG", Value = 3, - Metadata = new() { ["database_count"] = 3, ["query_store_on_count"] = 3 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "DB_CONFIG").Severity, precision: 4); - } - - // QS-off never lowers a worse co-present DB_CONFIG issue (existing arms unchanged): AUTO_SHRINK on - // 3 DBs stays 0.9 even with Query Store also off on all of them. - [Fact] - public void Score_DbConfig_QueryStoreOff_DoesNotLowerWorseIssue() - { - var facts = new List - { - new() { Source = "database_config", Key = "DB_CONFIG", Value = 3, - Metadata = new() - { - ["database_count"] = 3, - ["query_store_on_count"] = 0, // all off - ["auto_shrink_on_count"] = 3 // worse issue -> 3 * 0.3 = 0.9 - } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.9, facts.First(f => f.Key == "DB_CONFIG").Severity, precision: 4); - } - - // ── Tier-2 parity arms (batch 2): tempdb-deep — version-store size + PAGELATCH_UP allocation ───── - // Both are additions to the SHARED FactScorer, so they fire identically for Lite, Dashboard, and - // Darling findings. Every trip point is cited to the deprecated Dashboard's install SQL. - - // ARM 1 — tempdb VERSION-STORE pressure by ABSOLUTE size (max_version_store_mb in the TEMPDB_USAGE - // fact metadata), scored as the WORSE of space-fraction and version-store size. Tiers mirror - // report.tempdb_pressure's pressure_level CASE (install/47:1431-1433): > 5000 MB CRITICAL-tier - // (base 1.0), > 2000 MB HIGH (0.75), > 1000 MB MEDIUM (0.5 — the 0.5 root entry point). Space is only - // 20% full, whose sub-0.5 fraction score is dominated by the version-store arm via Math.Max, so the - // asserted severity IS the version-store tier — proving the arm scores independently of fill. - [Theory] - [InlineData(6000, 1.0)] // > 5000 -> CRITICAL tier (install/47:1431) - [InlineData(3000, 0.75)] // > 2000 -> HIGH tier (install/47:1432) - [InlineData(1500, 0.5)] // > 1000 -> MEDIUM tier (install/47:1433) - public void Score_TempDbVersionStore_TiersMatchDashboard(double versionMb, double expected) - { - var facts = new List - { - new() { Source = "tempdb", Key = "TEMPDB_USAGE", Value = 0.20, // space only 20% full - Metadata = new() { ["max_version_store_mb"] = versionMb } }, - }; - - new FactScorer().ScoreAll(facts); - - var t = facts.First(f => f.Key == "TEMPDB_USAGE"); - Assert.Equal(expected, t.Severity, precision: 4); - Assert.True(t.Severity >= 0.5, "a version store over 1 GB must clear the 0.5 root threshold"); - } - - // A version store below the > 1000 MB bar does not score. Space fraction 0 isolates the version-store - // arm (the space-fraction arm yields a small sub-0.5 base for any positive fill), proving a 900 MB - // store trips nothing on its own. - [Fact] - public void Score_TempDbVersionStore_BelowThreshold_DoesNotScore() - { - var facts = new List - { - new() { Source = "tempdb", Key = "TEMPDB_USAGE", Value = 0.0, - Metadata = new() { ["max_version_store_mb"] = 900 } }, // 900 MB — below the 1 GB bar - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "TEMPDB_USAGE").Severity, precision: 4); - } - - // WORSE-of: the version-store arm never LOWERS a higher space-fraction score. Space 95% full (the - // fraction arm hits its 0.90 critical -> 1.0) with a small version store stays 1.0. - [Fact] - public void Score_TempDbVersionStore_DoesNotLowerWorseSpaceFraction() - { - var facts = new List - { - new() { Source = "tempdb", Key = "TEMPDB_USAGE", Value = 0.95, - Metadata = new() { ["max_version_store_mb"] = 200 } }, // small VS, but space is critical - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(1.0, facts.First(f => f.Key == "TEMPDB_USAGE").Severity, precision: 4); - } - - // ARM 2 — tempdb allocation / PFS-GAM-SGAM contention scored off the PAGELATCH_UP wait fact by - // wait_time_ms PER OBSERVED HOUR (server-wide wait_stats, the SAME data the source view reads), - // tripping at > 10000 ms/hr -> MEDIUM (install/47:2411 sums the last hour; :2515: pagelatch_up_ms > - // 10000 -> "MEDIUM - PAGELATCH_UP contention"). Flat 0.5 — the view has no higher PAGELATCH_UP band. - // Value (fraction-of-period) only has to be > 0 to clear the wait guard; the hourly wait_time_ms is - // what scores. These fixtures carry no period_duration_ms, which the shared scorer reads as a one-hour - // window (#3538 A7), so 15,000 ms is 15 s/hr and 8,000 ms is 8 s/hr and the pins hold unchanged. - [Fact] - public void Score_PageLatchUp_Over10Sec_ScoresMedium() - { - var facts = new List - { - new() { Source = "waits", Key = "PAGELATCH_UP", Value = 0.01, - Metadata = new() { ["wait_time_ms"] = 15_000, ["waiting_tasks_count"] = 800 } }, - }; - - new FactScorer().ScoreAll(facts); - - var p = facts.First(f => f.Key == "PAGELATCH_UP"); - Assert.Equal(0.5, p.Severity, precision: 4); - Assert.True(p.Severity >= 0.5, "PAGELATCH_UP over the 10s bar must clear the 0.5 root threshold"); - } - - // At/under the 10000 ms bar PAGELATCH_UP stays context-only (a little allocation latching is normal). - [Fact] - public void Score_PageLatchUp_Under10Sec_DoesNotScore() - { - var facts = new List - { - new() { Source = "waits", Key = "PAGELATCH_UP", Value = 0.01, - Metadata = new() { ["wait_time_ms"] = 8_000, ["waiting_tasks_count"] = 300 } }, - }; - - new FactScorer().ScoreAll(facts); - - Assert.Equal(0.0, facts.First(f => f.Key == "PAGELATCH_UP").Severity, precision: 4); - } - - // Confidence-hardening: the low-quality fallback floors at 0.5 AFTER the confidence multiply, so a - // fired thin-baseline anomaly stays >= InferenceEngine's 0.5 root entry-point even if confidence - // ever drops below 1.0 (it is a hardcoded 1.0 today; this guards the future). Same shared scorer. - [Theory] - [InlineData(1.0, 0.8, 0.5)] // at the bar, conf 0.8: 0.5*0.8 = 0.4 -> floored to 0.5 - [InlineData(1.5, 0.6, 0.5)] // 0.75*0.6 = 0.45 -> floored to 0.5 - [InlineData(2.0, 0.6, 0.6)] // 1.0*0.6 = 0.6 -> above the floor, kept - [InlineData(2.0, 1.0, 1.0)] // conf 1.0 unchanged - public void Score_LowQualityFallback_FloorsAtHalf_EvenWithSubUnitConfidence( - double exceedance, double confidence, double expected) - { - var fact = new Fact - { - Source = "anomaly", - Key = "ANOMALY_CPU_SPIKE", - Metadata = new() - { - ["deviation_sigma"] = 0.5, - ["baseline_low_quality"] = 1.0, - ["fallback_exceedance"] = exceedance, - ["confidence"] = confidence - } - }; - new FactScorer().ScoreAll(new List { fact }); - Assert.Equal(expected, fact.BaseSeverity, precision: 4); - } - - /* ── Regression: duplicate fact keys must not crash scoring ── */ - - // A duplicated fact key (e.g. a config collector returning two rows for the same setting) - // once aborted the ENTIRE analysis for a server: ScoreAll built its amplifier lookup with a - // raw ToDictionary(f => f.Key), which throws on a duplicate. The exception was swallowed - // upstream, silently blanking every finding. ScoreAll must now dedupe and survive. - [Fact] - public void ScoreAll_WithDuplicateFactKeys_DoesNotThrow() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, // duplicate key - new() { Source = "waits", Key = "CXPACKET", Value = 0.80 }, - }; - - var scorer = new FactScorer(); - var ex = Record.Exception(() => scorer.ScoreAll(facts)); - - Assert.Null(ex); - } - - // The backstop helper keeps the first fact per key and never throws on duplicates. - [Fact] - public void ToFactLookup_DedupesByKey_KeepsFirst() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_CTFP", Value = 5 }, - new() { Source = "config", Key = "CONFIG_CTFP", Value = 99 }, - }; - - var lookup = facts.ToFactLookup(); - - Assert.Single(lookup); - Assert.Equal(5, lookup["CONFIG_CTFP"].Value); // first wins - } - - /* ── WS3: percent-autogrowth-on-large-files config fact ── */ - - // A FILE_AUTOGROWTH_PERCENT fact scores the 0.3 advisory base when at least one large - // percent-growth file was found (file_count > 0) — mirroring DB_CONFIG's single-misconfig - // base. It is deliberately below the 0.5 incident threshold; it surfaces only because it - // is a config-advisory root key (see the InferenceEngine rooting test). - [Fact] - public void FileAutogrowthPercent_ScoresAdvisoryBase_WhenFilesPresent() - { - var facts = new List - { - new() { Source = "config", Key = "FILE_AUTOGROWTH_PERCENT", Value = 2, - Metadata = new() { ["file_count"] = 2, ["database_count"] = 1 } } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(0.3, facts[0].BaseSeverity, precision: 4); - } - - // No offending files (file_count == 0) → no severity. Defends the collector contract that - // the fact is emitted only when file_count > 0, and the scorer's own guard. - [Fact] - public void FileAutogrowthPercent_ScoresZero_WhenNoFiles() - { - var facts = new List - { - new() { Source = "config", Key = "FILE_AUTOGROWTH_PERCENT", Value = 0, - Metadata = new() { ["file_count"] = 0, ["database_count"] = 0 } } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(0.0, facts[0].BaseSeverity, precision: 4); - } - - // Advice exists for the fact key (a missing AdviceBlock is the P1 dead-fact bug class — - // a fact that roots but renders no advice). Headline must be the authored copy. - [Fact] - public void FileAutogrowthPercent_HasAdviceBlock() - { - var advice = FactAdvice.GetForFactKey("FILE_AUTOGROWTH_PERCENT"); - - Assert.NotNull(advice); - Assert.Equal("Large file(s) growing in percentage steps", advice!.Headline); - Assert.False(string.IsNullOrWhiteSpace(advice.Investigation)); - Assert.False(string.IsNullOrWhiteSpace(advice.Remediation)); - } - - /* ── WS3: server-level config facts (MAXDOP / CTFP / max & min memory) ── */ - - // Each per-setting CONFIG_* fact scores the 0.4 advisory base ONLY when the value is bad, and - // 0 otherwise — so audit_config still sees every CONFIG_* fact (it reads the raw value) but - // only a BAD one roots a recommendation card. - [Theory] - // MAXDOP: 0 is bad (unlimited); any other value is operator-chosen. - [InlineData("CONFIG_MAXDOP", 0, 0.4)] - [InlineData("CONFIG_MAXDOP", 4, 0.0)] - [InlineData("CONFIG_MAXDOP", 8, 0.0)] - // CTFP: <= 5 is bad (default-and-below); above is fine. - [InlineData("CONFIG_CTFP", 5, 0.4)] - [InlineData("CONFIG_CTFP", 1, 0.4)] - [InlineData("CONFIG_CTFP", 50, 0.0)] - [InlineData("CONFIG_CTFP", 6, 0.0)] - // max server memory: the 2 PB default (2147483647) is bad; a real cap is fine. - [InlineData("CONFIG_MAX_MEMORY_MB", 2147483647, 0.4)] - [InlineData("CONFIG_MAX_MEMORY_MB", 28672, 0.0)] - public void ServerConfigFact_ScoresBadValueOnly(string key, long value, double expected) - { - var facts = new List - { - new() { Source = "config", Key = key, Value = value, - Metadata = new() { ["value_in_use"] = value } } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(expected, facts[0].BaseSeverity, precision: 4); - } - - // CONFIG_MIN_MAX_MEMORY_NARROW is emitted by the collector ONLY when bad, so any presence of - // the fact scores 0.4 (the fact's existence is the flag). - [Fact] - public void NarrowMemoryFact_AlwaysScoresAdvisoryBase() - { - var facts = new List - { - new() { Source = "config", Key = "CONFIG_MIN_MAX_MEMORY_NARROW", Value = 24000, - Metadata = new() { ["min_memory_mb"] = 24000, ["max_memory_mb"] = 28672 } } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(0.4, facts[0].BaseSeverity, precision: 4); - } - - // CONFIG_MIN_MEMORY_MB and CONFIG_MAX_WORKER_THREADS are leaf/context facts — never scored - // (they feed audit_config / the narrow-memory derivation, not a card of their own). - [Theory] - [InlineData("CONFIG_MIN_MEMORY_MB")] - [InlineData("CONFIG_MAX_WORKER_THREADS")] - public void ServerConfigLeafFacts_ScoreZero(string key) - { - var facts = new List - { - new() { Source = "config", Key = key, Value = 1024, Metadata = new() { ["value_in_use"] = 1024 } } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(0.0, facts[0].BaseSeverity, precision: 4); - } - - // Advice exists for each of the four server-config root keys (dead-fact guard). - [Theory] - [InlineData("CONFIG_MAXDOP")] - [InlineData("CONFIG_CTFP")] - [InlineData("CONFIG_MAX_MEMORY_MB")] - [InlineData("CONFIG_MIN_MAX_MEMORY_NARROW")] - public void ServerConfigKeys_HaveAdviceBlocks(string key) - { - var advice = FactAdvice.GetForFactKey(key); - - Assert.NotNull(advice); - Assert.False(string.IsNullOrWhiteSpace(advice!.Headline)); - Assert.False(string.IsNullOrWhiteSpace(advice.Investigation)); - Assert.False(string.IsNullOrWhiteSpace(advice.Remediation)); - } - - // The shared narrow-memory builder: emitted only when max is CONFIGURED and min >= 80% of max. - [Theory] - [InlineData(28672, 24000, true)] // min 83.7% of max -> narrow - [InlineData(28672, 22938, true)] // just over 80% (threshold 22937.6) -> narrow - [InlineData(28672, 22000, false)] // ~76.7% -> just under 80%, not narrow - [InlineData(28672, 14000, false)] // min ~49% -> not narrow - [InlineData(2147483647, 2000000000, false)] // max unconfigured -> never narrow - [InlineData(0, 0, false)] // max 0 -> guard - public void BuildNarrowMemoryFact_FollowsThreshold(long maxMb, long minMb, bool emitted) - { - var fact = FactRemediation.BuildNarrowMemoryFact(1, maxMb, minMb); - - if (!emitted) - { - Assert.Null(fact); - return; - } - - Assert.NotNull(fact); - Assert.Equal("CONFIG_MIN_MAX_MEMORY_NARROW", fact!.Key); - Assert.Equal(minMb, fact.Value); - Assert.Equal(minMb, fact.Metadata["min_memory_mb"]); - Assert.Equal(maxMb, fact.Metadata["max_memory_mb"]); - } - - [Fact] - public void BuildNarrowMemoryFact_NullInputs_ReturnsNull() - { - Assert.Null(FactRemediation.BuildNarrowMemoryFact(1, null, 24000)); - Assert.Null(FactRemediation.BuildNarrowMemoryFact(1, 28672, null)); - } - - /* ── WS5: server-health advisory facts (LPIM / IFI / memory dumps) ── */ - - // Each WS5 server-health fact scores its 0.4 advisory base ONLY when the value is bad, and 0 - // otherwise — mirroring the WS3 server-config keys. The collectors gate emission (Express / - // small-RAM / dumps>0) so a fact that would score 0 is normally never emitted, but the scorer - // is still independently bad-only so it can be unit-tested in isolation. - [Theory] - // IFI: disabled (Value 0) is bad; enabled (Value 1) is fine. - [InlineData("CONFIG_IFI_DISABLED", 0, 0.4)] - [InlineData("CONFIG_IFI_DISABLED", 1, 0.0)] - // LPIM: disabled (Value 0) is bad; enabled (Value 1) is fine. - [InlineData("CONFIG_LPIM_DISABLED", 0, 0.4)] - [InlineData("CONFIG_LPIM_DISABLED", 1, 0.0)] - // Memory dumps: any count > 0 is bad; 0 is fine. - [InlineData("SERVER_MEMORY_DUMPS", 1, 0.4)] - [InlineData("SERVER_MEMORY_DUMPS", 7, 0.4)] - [InlineData("SERVER_MEMORY_DUMPS", 0, 0.0)] - public void ServerHealthFact_ScoresBadValueOnly(string key, long value, double expected) - { - var facts = new List - { - new() { Source = "config", Key = key, Value = value } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(expected, facts[0].BaseSeverity, precision: 4); - } - - // Advice exists for each WS5 server-health root key (dead-fact guard — a fact that roots but - // renders no advice is the P1 dead-fact bug class). - [Theory] - [InlineData("CONFIG_IFI_DISABLED")] - [InlineData("CONFIG_LPIM_DISABLED")] - [InlineData("SERVER_MEMORY_DUMPS")] - public void ServerHealthKeys_HaveAdviceBlocks(string key) - { - var advice = FactAdvice.GetForFactKey(key); - - Assert.NotNull(advice); - Assert.False(string.IsNullOrWhiteSpace(advice!.Headline)); - Assert.False(string.IsNullOrWhiteSpace(advice.Investigation)); - Assert.False(string.IsNullOrWhiteSpace(advice.Remediation)); - // Advise-only: no generated Apply T-SQL is attached to the bare advice block. - Assert.Null(advice.RemediationTsql); - } - - // WS4: plan-XML advisories. MISSING_INDEX / PLAN_WARNING (Source "queries", Value = count) - // score only when the count is > 0, and 0 otherwise. Advise-only. PLAN_WARNING keeps the 0.4 - // advisory base; MISSING_INDEX is demoted to the Information rung (#3805, - // FactScorer.MissingIndexCorroborationSeverity = 0.25) — a request is corroboration and never - // outranks a standing misconfiguration — and the pin reads the constant so the ORDERING, not the - // digit, is what a future change has to argue with. - [Theory] - [InlineData("MISSING_INDEX", 1, FactScorer.MissingIndexCorroborationSeverity)] - [InlineData("MISSING_INDEX", 5, FactScorer.MissingIndexCorroborationSeverity)] - [InlineData("MISSING_INDEX", 0, 0.0)] - [InlineData("PLAN_WARNING", 1, 0.4)] - [InlineData("PLAN_WARNING", 0, 0.0)] - public void PlanAdvisoryFact_ScoresWhenPresentOnly(string key, long value, double expected) - { - var facts = new List - { - new() { Source = "queries", Key = key, Value = value } - }; - - var scorer = new FactScorer(); - scorer.ScoreAll(facts); - - Assert.Equal(expected, facts[0].BaseSeverity, precision: 4); - } - - // Advice exists for each WS4 plan-advisory root key (dead-fact guard); advise-only (no Apply T-SQL). - [Theory] - [InlineData("MISSING_INDEX")] - [InlineData("PLAN_WARNING")] - public void PlanAdvisoryKeys_HaveAdviceBlocks(string key) - { - var advice = FactAdvice.GetForFactKey(key); - - Assert.NotNull(advice); - Assert.False(string.IsNullOrWhiteSpace(advice!.Headline)); - Assert.False(string.IsNullOrWhiteSpace(advice.Investigation)); - Assert.False(string.IsNullOrWhiteSpace(advice.Remediation)); - Assert.Null(advice.RemediationTsql); - } - - // C (workload-aware MAXDOP/CTFP): every THREADPOOL attribution variant InferenceEngine can root - // on (parallel/blocking/mixed) plus the generic fallback has an advice block — a relabeled root - // with no advice would render an empty card (the dead-fact bug class). - [Theory] - [InlineData("THREADPOOL")] - [InlineData("THREADPOOL_PARALLEL")] - [InlineData("THREADPOOL_BLOCKING")] - [InlineData("THREADPOOL_MIXED")] - public void ThreadpoolVariants_HaveAdviceBlocks(string key) - { - var advice = FactAdvice.GetForFactKey(key); - - Assert.NotNull(advice); - Assert.False(string.IsNullOrWhiteSpace(advice!.Headline)); - Assert.False(string.IsNullOrWhiteSpace(advice.Investigation)); - Assert.False(string.IsNullOrWhiteSpace(advice.Remediation)); - } -} diff --git a/deprecated/Dashboard.Tests/FailedJobWatermarkPreferenceTests.cs b/deprecated/Dashboard.Tests/FailedJobWatermarkPreferenceTests.cs deleted file mode 100644 index c354fe09e1..0000000000 --- a/deprecated/Dashboard.Tests/FailedJobWatermarkPreferenceTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using System; -using System.Collections.Generic; -using System.Text.Json; -using PerformanceMonitorDashboard.Models; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Failed-job tray watermark persistence (the Dashboard half of the #1145 parity fix): a reopen -/// must not re-fire tray toasts for failures still inside the lookback window that the user already -/// saw and dismissed. The watermark is the newest already-alerted failure's server-local run time, -/// stored as in . -/// These pin the JSON persistence contract UserPreferencesService relies on (it serializes/ -/// deserializes the whole UserPreferences object with the same options). -/// -public class FailedJobWatermarkPreferenceTests -{ - /// Serializer options matching UserPreferencesService (WriteIndented = true). - private static readonly JsonSerializerOptions s_jsonOptions = new() { WriteIndented = true }; - - [Fact] - public void FailedJobAlertWatermarkTicks_DefaultsToEmpty() - { - var prefs = new UserPreferences(); - Assert.NotNull(prefs.FailedJobAlertWatermarkTicks); - Assert.Empty(prefs.FailedJobAlertWatermarkTicks); - } - - [Fact] - public void FailedJobAlertWatermarkTicks_RoundTripsExactValue_ThroughJson() - { - /* Ticks keep the server-local run time basis-exact across the JSON round-trip — the value is - compared directly against FailedJobInfo.RunDateTime, so DateTimeKind drift would corrupt it. */ - var serverLocal = new DateTime(2026, 6, 19, 14, 30, 15); - var prefs = new UserPreferences - { - FailedJobAlertWatermarkTicks = new Dictionary - { - ["server-a"] = serverLocal.Ticks, - ["server-b"] = new DateTime(2026, 6, 19, 9, 5, 0).Ticks - } - }; - - var json = JsonSerializer.Serialize(prefs, s_jsonOptions); - var loaded = JsonSerializer.Deserialize(json); - - Assert.NotNull(loaded); - Assert.Equal(2, loaded!.FailedJobAlertWatermarkTicks.Count); - Assert.Equal(serverLocal, new DateTime(loaded.FailedJobAlertWatermarkTicks["server-a"])); - Assert.Equal(new DateTime(2026, 6, 19, 9, 5, 0), new DateTime(loaded.FailedJobAlertWatermarkTicks["server-b"])); - } - - [Fact] - public void FailedJobAlertWatermarkTicks_AbsentFromExistingJson_DeserializesToEmpty() - { - // A preferences.json written before this PR has no "FailedJobAlertWatermarkTicks" key; - // the default initializer (= empty dict) must apply so upgraded installs don't NRE on seed. - const string legacyJson = """ - { - "AnalysisIntervalMinutes": 30 - } - """; - - var loaded = JsonSerializer.Deserialize(legacyJson); - - Assert.NotNull(loaded); - Assert.NotNull(loaded!.FailedJobAlertWatermarkTicks); - Assert.Empty(loaded.FailedJobAlertWatermarkTicks); - } -} diff --git a/deprecated/Dashboard.Tests/FailedJobsQueryTests.cs b/deprecated/Dashboard.Tests/FailedJobsQueryTests.cs deleted file mode 100644 index 57827e0896..0000000000 --- a/deprecated/Dashboard.Tests/FailedJobsQueryTests.cs +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using System; -using System.Collections; -using System.Data.Common; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using PerformanceMonitor.Alerting; -using PerformanceMonitor.Notifications; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Identity pins for the Phase-5 slice-E extraction: the live msdb failed-jobs alert query moved -/// verbatim from this app's DatabaseService.NocHealth.cs (whitespace-normalized identical -/// to Lite's RemoteCollectorService.RunningJobs.cs twin) into the shared -/// . The clause pins are derived from the pre-extraction SQL, so a -/// drift in the shared copy fails a pin; the ReadAsync pins reproduce the pre-extraction row -/// mapping including its null handling (for this app that includes the explicit -/// InvariantCulture step_id conversion the shared copy adopted). -/// -public class FailedJobsQueryTests -{ - /* ---------------- the SQL contract ---------------- */ - - [Fact] - public void Sql_ContainsLoadBearingClauses() - { - var sql = FailedJobsQuery.Sql; - - /* Dirty read — never block a monitored server's Agent from an alert check. */ - Assert.Contains("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;", sql); - - /* The sources: job history joined to job names. */ - Assert.Contains("FROM msdb.dbo.sysjobhistory AS jh", sql); - Assert.Contains("JOIN msdb.dbo.sysjobs AS j", sql); - - /* Bounded row count, newest failures first. */ - Assert.Contains("SELECT TOP (50)", sql); - Assert.Contains("run_datetime DESC", sql); - Assert.Contains("OPTION(RECOMPILE);", sql); - - /* The outcome-row filter: step_id = 0 is the per-run outcome row, run_status = 0 = FAILED. */ - Assert.Contains("WHERE jh.step_id = 0", sql); - Assert.Contains("AND jh.run_status = 0", sql); - - /* The failing-step resolution: OUTER APPLY correlates the actual failed step (step_id > 0, - run_status = 0) from THIS run via instance_id, bounded after the previous outcome row. */ - Assert.Contains("OUTER APPLY", sql); - Assert.Contains("AND s.step_id > 0", sql); - Assert.Contains("AND s.run_status = 0", sql); - Assert.Contains("AND s.instance_id < jh.instance_id", sql); - Assert.Contains("AND p.step_id = 0", sql); - - /* The outcome-row fallback when a job-level failure has no failed step row. */ - Assert.Contains("step_id = ISNULL(fs.step_id, jh.step_id)", sql); - Assert.Contains("step_name = ISNULL(fs.step_name, jh.step_name)", sql); - Assert.Contains("message = ISNULL(fs.message, jh.message)", sql); - - /* #3421: the server's own UTC offset, measured in the same statement that read the - server-local run_datetime, so FailedJobInfo can state the failure instant in the frame the - alert body and alert_time share. */ - Assert.Contains("utc_offset_minutes = DATEDIFF(MINUTE, GETUTCDATE(), GETDATE())", sql); - } - - [Fact] - public void Sql_LookbackParameter_AppearsAtBothFilterSites() - { - Assert.Equal("@lookback_minutes", FailedJobsQuery.LookbackMinutesParameter); - - /* The lookback binds twice: the coarse run_date integer filter and the exact - server-local run_datetime filter. Both must survive — dropping the coarse one - makes the query scan all of sysjobhistory. */ - Assert.Equal(2, Regex.Matches(FailedJobsQuery.Sql, Regex.Escape(FailedJobsQuery.LookbackMinutesParameter)).Count); - Assert.Contains("jh.run_date >= CONVERT(integer, CONVERT(varchar(8), DATEADD(MINUTE, -@lookback_minutes, GETDATE()), 112))", FailedJobsQuery.Sql); - Assert.Contains(") >= DATEADD(MINUTE, -@lookback_minutes, GETDATE())", FailedJobsQuery.Sql); - } - - /* ---------------- the row mapping ---------------- */ - - [Fact] - public async Task ReadAsync_MapsRepresentativeRow() - { - var runTime = new DateTime(2026, 6, 30, 23, 45, 12); - var reader = new FakeFailedJobsDataReader(new object[] - { - "Nightly ETL", - "3f2504e0-4f89-11d3-9a0c-0305e82c3301", - runTime, - 3, - "Load fact table", - "Executed as user: NT SERVICE\\SQLSERVERAGENT. The step failed.", - -240 - }); - - var items = await FailedJobsQuery.ReadAsync(reader, CancellationToken.None); - - var job = Assert.Single(items); - Assert.Equal("Nightly ETL", job.JobName); - Assert.Equal("3f2504e0-4f89-11d3-9a0c-0305e82c3301", job.JobId); - Assert.Equal(runTime, job.RunDateTime); - /* #3421: the offset is ordinal 6, and the row states the run instant in UTC from it. */ - Assert.Equal(-240, job.UtcOffsetMinutes); - Assert.Equal(runTime.AddMinutes(240), job.RunDateTimeUtc); - Assert.Equal("2026-07-01 03:45:12Z", job.RunDateTimeFormatted); - Assert.Equal(3, job.StepId); - Assert.Equal("Load fact table", job.StepName); - Assert.Equal("Executed as user: NT SERVICE\\SQLSERVERAGENT. The step failed.", job.Message); - } - - [Fact] - public async Task ReadAsync_NullColumns_MapToEmptyStringAndZero() - { - /* job_name is never null (sysjobs.name); every other column degrades like the - pre-extraction mapping: "" for strings, 0 for step_id. */ - var reader = new FakeFailedJobsDataReader(new object[] - { - "Nightly ETL", - DBNull.Value, - new DateTime(2026, 6, 30, 23, 45, 12), - DBNull.Value, - DBNull.Value, - DBNull.Value, - DBNull.Value - }); - - var items = await FailedJobsQuery.ReadAsync(reader, CancellationToken.None); - - var job = Assert.Single(items); - Assert.Equal("", job.JobId); - Assert.Equal(0, job.StepId); - Assert.Equal("", job.StepName); - Assert.Equal("", job.Message); - - /* #3421: a provider that could not evaluate the offset expression leaves the instant - unconvertible, and the rendering SAYS so rather than claiming UTC it has not earned. */ - Assert.Null(job.UtcOffsetMinutes); - Assert.Null(job.RunDateTimeUtc); - Assert.EndsWith(AlertTimestamp.UnknownOffsetMarker, job.RunDateTimeFormatted, StringComparison.Ordinal); - } - - [Fact] - public async Task ReadAsync_EmptyReader_ReturnsEmptyList() - { - var items = await FailedJobsQuery.ReadAsync(new FakeFailedJobsDataReader(), CancellationToken.None); - Assert.Empty(items); - } - - /// - /// Minimal in-memory DbDataReader for the ReadAsync pins (single result set) — the Dashboard - /// twin of Lite.Tests' CollectorDefinitionTestFakes.FakeCollectorDataReader. - /// - private sealed class FakeFailedJobsDataReader : DbDataReader - { - private readonly object[][] _rows; - private int _rowIndex = -1; - - public FakeFailedJobsDataReader(params object[][] rows) => _rows = rows; - - public override bool Read() => ++_rowIndex < _rows.Length; - - public override bool NextResult() => false; - - public override string GetString(int ordinal) => (string)_rows[_rowIndex][ordinal]; - - public override DateTime GetDateTime(int ordinal) => (DateTime)_rows[_rowIndex][ordinal]; - - public override bool IsDBNull(int ordinal) => _rows[_rowIndex][ordinal] is DBNull; - - public override object GetValue(int ordinal) => _rows[_rowIndex][ordinal]; - - public override int FieldCount => _rows.Length == 0 ? 0 : _rows[0].Length; - - public override bool HasRows => _rows.Length > 0; - - public override bool IsClosed => false; - - public override int Depth => 0; - - public override int RecordsAffected => -1; - - public override object this[int ordinal] => _rows[_rowIndex][ordinal]; - - public override object this[string name] => throw new NotSupportedException(); - - public override bool GetBoolean(int ordinal) => (bool)_rows[_rowIndex][ordinal]; - public override byte GetByte(int ordinal) => (byte)_rows[_rowIndex][ordinal]; - public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length) => throw new NotSupportedException(); - public override char GetChar(int ordinal) => (char)_rows[_rowIndex][ordinal]; - public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length) => throw new NotSupportedException(); - public override string GetDataTypeName(int ordinal) => throw new NotSupportedException(); - public override decimal GetDecimal(int ordinal) => (decimal)_rows[_rowIndex][ordinal]; - public override double GetDouble(int ordinal) => (double)_rows[_rowIndex][ordinal]; - public override IEnumerator GetEnumerator() => _rows.GetEnumerator(); - public override Type GetFieldType(int ordinal) => _rows[_rowIndex][ordinal].GetType(); - public override float GetFloat(int ordinal) => (float)_rows[_rowIndex][ordinal]; - public override Guid GetGuid(int ordinal) => (Guid)_rows[_rowIndex][ordinal]; - public override short GetInt16(int ordinal) => (short)_rows[_rowIndex][ordinal]; - public override int GetInt32(int ordinal) => (int)_rows[_rowIndex][ordinal]; - public override long GetInt64(int ordinal) => (long)_rows[_rowIndex][ordinal]; - public override string GetName(int ordinal) => throw new NotSupportedException(); - public override int GetOrdinal(string name) => throw new NotSupportedException(); - public override int GetValues(object[] values) => throw new NotSupportedException(); - } -} diff --git a/deprecated/Dashboard.Tests/FileAutogrowthHandlerTests.cs b/deprecated/Dashboard.Tests/FileAutogrowthHandlerTests.cs deleted file mode 100644 index bd71c3f6fc..0000000000 --- a/deprecated/Dashboard.Tests/FileAutogrowthHandlerTests.cs +++ /dev/null @@ -1,333 +0,0 @@ -/* - * 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 System.Threading; -using System.Threading.Tasks; -using PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Services.Remediation; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Coverage for the always-safe percent-autogrowth handler (FILE_AUTOGROWTH_PERCENT): -/// the self-gating against a faked executor — -/// audit-table hard block (no mutation), the happy path passing each target's -/// already-computed through to -/// SetFileGrowthAsync + writing one audit row per attempt, per-target -/// independence, the preflight dispositions, and the apply-only un-apply restriction. -/// Mirrors the DB-config handler tests exactly; the single-connection (R2-MOD-1) -/// guarantee is an executor/real-server concern (SPID equality) not provable here. -/// Reuses the shared FakeExecutor from via a -/// thin local fake of the same shape (the nested one is private to that class). -/// -public class FileAutogrowthHandlerTests -{ - private static readonly RemediationIdentity Identity = - new("TESTDOMAIN\\tester", "Analysis: file_autogrowth [abcd1234]"); - - private static RemediationAction FileAction(params FileGrowthTarget[] targets) => - new("FILE_AUTOGROWTH_PERCENT", "set", Array.Empty(), - FileGrowthTargets: targets.ToList()); - - private static FileGrowthTarget DataTarget(string db = "BigDb", string logical = "BigDb_data") => - new(db, logical, CurrentSizeMb: 51200, CurrentGrowthPercent: 10, RecommendedGrowthMb: 1024); - - private static FileGrowthTarget LogTarget(string db = "BigDb", string logical = "BigDb_log") => - new(db, logical, CurrentSizeMb: 250000, CurrentGrowthPercent: 25, RecommendedGrowthMb: 64); - - // ── Handler contract ──────────────────────────────────────────────────────── - - [Fact] - public void FactKey_IsFileAutogrowthPercent() - { - Assert.Equal("FILE_AUTOGROWTH_PERCENT", new FileAutogrowthHandler().FactKey); - } - - [Fact] - public void NotDestructive_AndApplyOnly() - { - var handler = new FileAutogrowthHandler(); - Assert.False(handler.IsDestructive); // metadata-only, online — same class as AUTO_SHRINK OFF - Assert.False(handler.SupportsUnapply); // no sensible reverse for FILEGROWTH - } - - [Fact] - public async Task UnapplyAsync_Throws() - { - await Assert.ThrowsAsync(() => - new FileAutogrowthHandler().UnapplyAsync( - FileAction(DataTarget()), new FakeFileExecutor(), Identity, CancellationToken.None)); - } - - [Fact] - public void Registry_ResolvesFileAutogrowthHandler() - { - var registry = new RemediationHandlerRegistry( - new IRemediationHandler[] { new ForcePlanHandler(), new DbConfigHandler(), new FileAutogrowthHandler() }); - Assert.IsType(registry.TryGet("FILE_AUTOGROWTH_PERCENT")); - } - - // ── Apply: audit-absent hard block, happy path, per-target independence ─────── - - [Fact] - public async Task AuditTableAbsent_HardBlocks_NoMutation_NoAudit() - { - var exec = new FakeFileExecutor { AuditTableExists = false }; - - var result = await new FileAutogrowthHandler().ApplyAsync( - FileAction(DataTarget("BigDb", "BigDb_data"), LogTarget("BigDb", "BigDb_log")), - exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.False(o.AuditWritten); - Assert.Contains("3.0.0", o.Message); - }); - Assert.Equal(0, exec.SetFileCalls); // NOT mutated - Assert.Empty(exec.AuditRecords); // nowhere to write - } - - [Fact] - public async Task HappyPath_AppliesEachTarget_WithRecommendedGrowth_AndAudits() - { - var exec = new FakeFileExecutor(); // default success outcome - - var result = await new FileAutogrowthHandler().ApplyAsync( - FileAction(DataTarget("BigDb", "BigDb_data"), LogTarget("BigDb", "BigDb_log")), - exec, Identity, CancellationToken.None); - - // One SetFileGrowthAsync call per target, EACH with the target's own already-computed - // RecommendedGrowthMb (1024 data / 64 log) — the handler never recomputes it. - Assert.Equal(2, exec.SetFileCalls); - Assert.Contains(("BigDb", "BigDb_data", 1024), exec.SetFileArgs); - Assert.Contains(("BigDb", "BigDb_log", 64), exec.SetFileArgs); - - // Two success outcomes, both audited. - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.True(o.AuditWritten); - Assert.False(o.AppliedButUnlogged); - }); - - // Audit rows: one per attempt, the precise taxonomy + per-target database, non-consent. - Assert.Equal(2, exec.AuditRecords.Count); - Assert.All(exec.AuditRecords, r => - { - Assert.Equal("FILE_AUTOGROWTH_PERCENT", r.FactKey); - Assert.Equal("set_file_growth", r.Action); - Assert.Equal("success", r.Result); - Assert.Equal("BigDb", r.TargetDatabase); - Assert.Null(r.QueryId); // no query_id/plan_id for file rows - Assert.Null(r.PlanId); - Assert.False(r.ConsentAcknowledged); // not destructive — explicit false - Assert.Contains("MODIFY FILE", r.GeneratedSql); - }); - } - - [Fact] - public async Task AppliesButAuditFails_FlagsAppliedButUnlogged() - { - var exec = new FakeFileExecutor { AuditWriteResult = false }; - - var result = await new FileAutogrowthHandler().ApplyAsync( - FileAction(DataTarget()), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.False(o.AuditWritten); - Assert.True(o.AppliedButUnlogged); - } - - [Fact] - public async Task PermissionDenied_FailsClosed_AuditSkipped() - { - var exec = new FakeFileExecutor - { - SetFileFunc = (db, logical, mb) => new FileGrowthOutcome - { - Database = db, LogicalFileName = logical, Status = RemediationStatus.PermissionDenied, - Applied = false, Message = "lacks ALTER", PriorValue = "percent" - } - }; - - var result = await new FileAutogrowthHandler().ApplyAsync( - FileAction(DataTarget()), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.PermissionDenied, o.Status); - Assert.False(o.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - Assert.Equal(1, exec.SetFileCalls); - } - - [Fact] - public async Task AlreadyDesired_Skips_AuditSkipped() - { - var exec = new FakeFileExecutor - { - SetFileFunc = (db, logical, mb) => new FileGrowthOutcome - { - Database = db, LogicalFileName = logical, Status = RemediationStatus.Skipped, - Applied = false, Message = "already at desired growth", PriorValue = "1024 MB" - } - }; - - var result = await new FileAutogrowthHandler().ApplyAsync( - FileAction(DataTarget()), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Skipped, o.Status); - Assert.False(o.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - } - - [Fact] - public async Task OneTargetThrows_OthersStillRun() - { - var exec = new FakeFileExecutor - { - SetFileFunc = (db, logical, mb) => - { - if (logical == "A") throw new InvalidOperationException("boom"); - return new FileGrowthOutcome { Database = db, LogicalFileName = logical, Status = RemediationStatus.Success, Applied = true, PriorValue = "percent" }; - } - }; - - var result = await new FileAutogrowthHandler().ApplyAsync( - FileAction( - new FileGrowthTarget("BigDb", "A", 51200, 10, 1024), - new FileGrowthTarget("BigDb", "B", 51200, 10, 1024)), - exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.Equal(RemediationStatus.Error, result.Outcomes[0].Status); - Assert.Equal(RemediationStatus.Success, result.Outcomes[1].Status); - // Error target is still audited (aborted/error result), per-target independence. - Assert.Equal(2, exec.AuditRecords.Count); - } - - // ── Preflight dispositions ──────────────────────────────────────────────────── - - [Theory] - [InlineData(false, true, true, false, RemediationDisposition.BlockDatabaseNotFound)] // db missing - [InlineData(true, false, true, false, RemediationDisposition.BlockDatabaseNotFound)] // file missing - [InlineData(true, true, false, false, RemediationDisposition.BlockNoAlter)] // no ALTER - [InlineData(true, true, true, true, RemediationDisposition.AlreadyInDesiredState)] // already fixed-MB - [InlineData(true, true, true, false, RemediationDisposition.Ok)] // ready - public async Task Preflight_ClassifiesDisposition(bool dbExists, bool fileExists, bool hasAlter, bool alreadyDesired, RemediationDisposition expected) - { - var exec = new FakeFileExecutor - { - FilePreflightFunc = (db, logical, mb) => new FileGrowthPreflight - { - Database = db, LogicalFileName = logical, RecommendedGrowthMb = mb, - DatabaseExists = dbExists, FileExists = fileExists, HasAlter = hasAlter, - AlreadyInDesiredState = alreadyDesired, CurrentValue = "percent" - } - }; - - var pre = await new FileAutogrowthHandler().PreflightAsync( - FileAction(DataTarget()), exec, CancellationToken.None); - Assert.Equal(expected, pre.Targets.Single().Disposition); - } - - [Fact] - public async Task Preflight_AuditTableAbsent_OverridesDisposition() - { - var exec = new FakeFileExecutor { AuditTableExists = false }; - - var pre = await new FileAutogrowthHandler().PreflightAsync( - FileAction(DataTarget()), exec, CancellationToken.None); - - Assert.False(pre.AuditTableExists); - Assert.Equal(RemediationDisposition.BlockAuditTableAbsent, pre.Targets.Single().Disposition); - } - - /// - /// A standalone fake of shaped like the one nested in - /// (which is private to that class). Only the audit + the - /// file-growth seam are exercised here; the force-plan / DB-config / clear-plan members - /// return harmless defaults. - /// - private sealed class FakeFileExecutor : IRemediationExecutor - { - public bool AuditTableExists = true; - public bool AuditWriteResult = true; - - public Func? FilePreflightFunc; - public Func? SetFileFunc; - public int SetFileCalls; - public readonly List<(string Database, string Logical, int GrowthMb)> SetFileArgs = new(); - public readonly List AuditRecords = new(); - - public Task AuditTableExistsAsync(CancellationToken ct) => Task.FromResult(AuditTableExists); - - public Task PreflightFileGrowthAsync(string database, string logicalFileName, int growthMb, CancellationToken ct) - => Task.FromResult(FilePreflightFunc?.Invoke(database, logicalFileName, growthMb) ?? new FileGrowthPreflight - { - Database = database, LogicalFileName = logicalFileName, RecommendedGrowthMb = growthMb, - DatabaseExists = true, FileExists = true, HasAlter = true, AlreadyInDesiredState = false, - ExecutingLogin = "sa", CurrentValue = "percent" - }); - - public Task SetFileGrowthAsync(string database, string logicalFileName, int growthMb, RemediationIdentity identity, CancellationToken ct) - { - SetFileCalls++; - SetFileArgs.Add((database, logicalFileName, growthMb)); - return Task.FromResult(SetFileFunc?.Invoke(database, logicalFileName, growthMb) ?? new FileGrowthOutcome - { - Database = database, LogicalFileName = logicalFileName, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "sa", PriorValue = "percent", - GeneratedSql = $"ALTER DATABASE [{database}] MODIFY FILE (NAME = [{logicalFileName}], FILEGROWTH = {growthMb}MB);", - GateSpid = 55, ExecSpid = 55 - }); - } - - public Task WriteAuditAsync(RemediationAuditRecord record, CancellationToken ct) - { - AuditRecords.Add(record); - return Task.FromResult(AuditWriteResult); - } - - // ── Unused seams (return harmless defaults) ────────────────────────────── - public Task PreflightForcePlanAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(new TargetPreflight { Database = database, QueryId = queryId, PlanId = planId }); - - public Task HasPriorForceAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(false); - - public Task ForcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ForcePlanOutcome { Database = database, QueryId = queryId, PlanId = planId, Status = RemediationStatus.Success }); - - public Task UnforcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ForcePlanOutcome { Database = database, QueryId = queryId, PlanId = planId, Status = RemediationStatus.Success }); - - public Task PreflightDbConfigAsync(string database, DbConfigSetting setting, CancellationToken ct) - => Task.FromResult(new DbConfigPreflight { Database = database, Setting = setting }); - - public Task SetDatabaseOptionAsync(string database, DbConfigSetting setting, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new DbConfigOutcome { Database = database, Setting = setting, Status = RemediationStatus.Success }); - - public Task ClearProcCacheAsync(string queryHash, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ClearPlanOutcome { QueryHash = queryHash, Status = RemediationStatus.Success }); - - public Task PreflightServerConfigAsync(ServerConfigSetting setting, long recommendedValue, CancellationToken ct) - => Task.FromResult(new ServerConfigPreflight { Setting = setting, RecommendedValue = recommendedValue, HasPermission = true }); - - public Task SetServerConfigAsync(ServerConfigSetting setting, long value, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ServerConfigOutcome { Setting = setting, Status = RemediationStatus.Success }); - } -} diff --git a/deprecated/Dashboard.Tests/FinOpsHeatmapBuilderTests.cs b/deprecated/Dashboard.Tests/FinOpsHeatmapBuilderTests.cs deleted file mode 100644 index 380c8ca109..0000000000 --- a/deprecated/Dashboard.Tests/FinOpsHeatmapBuilderTests.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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 PerformanceMonitor.Common; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the shared, app-agnostic FinOps heatmap shaping (#1138): the top-N-by-growth ranking and the -/// long→matrix pivot that both Dashboard and Lite depend on. (Phase-2 color-scale math is exercised by the -/// ColumnLogIntensities tests below.) Pure functions, no database. -/// -public class FinOpsHeatmapBuilderTests -{ - private static readonly DateTime D1 = new(2026, 6, 1); - private static readonly DateTime D2 = new(2026, 6, 2); - private static readonly DateTime D3 = new(2026, 6, 3); - - // ── RankTopGrowers ── - - [Fact] - public void RankTopGrowers_OrdersByGrowthDescending_TakesTopN() - { - var ranked = FinOpsHeatmapBuilder.RankTopGrowers( - new[] { ("a", 10.0), ("b", 50.0), ("c", 30.0), ("d", 5.0) }, topN: 2); - - Assert.Equal(new[] { "b", "c" }, ranked); - } - - [Fact] - public void RankTopGrowers_TieBreaksOnKeyOrdinal_ForDeterminism() - { - var ranked = FinOpsHeatmapBuilder.RankTopGrowers( - new[] { ("z", 10.0), ("a", 10.0), ("m", 10.0) }, topN: 2); - - Assert.Equal(new[] { "a", "m" }, ranked); - } - - [Fact] - public void RankTopGrowers_TopNExceedsCount_ReturnsAll() - { - var ranked = FinOpsHeatmapBuilder.RankTopGrowers( - new[] { ("a", 1.0), ("b", 2.0) }, topN: 10); - - Assert.Equal(new[] { "b", "a" }, ranked); - } - - // ── BuildMatrix (long → dense pivot) ── - - [Fact] - public void BuildMatrix_PivotsToRowsByDays_WithMissingCellsZero() - { - var samples = new[] - { - new FinOpsObjectDaySample("big", D1, 100), - new FinOpsObjectDaySample("big", D2, 200), - new FinOpsObjectDaySample("small", D1, 10), - // "small" has no D2 sample — that cell must stay 0. - }; - - // Rows bottom-to-top: index 0 = "small" (bottom), index 1 = "big" (top). - var matrix = FinOpsHeatmapBuilder.BuildMatrix(new[] { "small", "big" }, samples); - - Assert.Equal(new[] { "small", "big" }, matrix.RowLabels); - Assert.Equal(new[] { D1, D2 }, matrix.Days); // ascending - Assert.Equal(10, matrix.Intensities[0, 0]); // small / D1 - Assert.Equal(0, matrix.Intensities[0, 1]); // small / D2 (missing) - Assert.Equal(100, matrix.Intensities[1, 0]); // big / D1 - Assert.Equal(200, matrix.Intensities[1, 1]); // big / D2 - } - - [Fact] - public void BuildMatrix_IgnoresSamplesNotInRowKeys() - { - var samples = new[] - { - new FinOpsObjectDaySample("a", D1, 5), - new FinOpsObjectDaySample("ghost", D1, 999), - }; - - var matrix = FinOpsHeatmapBuilder.BuildMatrix(new[] { "a" }, samples); - - Assert.Single(matrix.RowLabels); - Assert.Equal(5, matrix.Intensities[0, 0]); - // "ghost" introduced no extra row; only its day survives as a column. - Assert.Equal(1, matrix.Intensities.GetLength(0)); - } - - [Fact] - public void BuildMatrix_SumsDuplicateKeyDayPairs() - { - var samples = new[] - { - new FinOpsObjectDaySample("a", D1, 5), - new FinOpsObjectDaySample("a", D1, 7), - }; - - var matrix = FinOpsHeatmapBuilder.BuildMatrix(new[] { "a" }, samples); - - Assert.Equal(12, matrix.Intensities[0, 0]); - } - - [Fact] - public void BuildMatrix_OrdersDaysAscendingRegardlessOfInputOrder() - { - var samples = new[] - { - new FinOpsObjectDaySample("a", D3, 3), - new FinOpsObjectDaySample("a", D1, 1), - new FinOpsObjectDaySample("a", D2, 2), - }; - - var matrix = FinOpsHeatmapBuilder.BuildMatrix(new[] { "a" }, samples); - - Assert.Equal(new[] { D1, D2, D3 }, matrix.Days); - Assert.Equal(1, matrix.Intensities[0, 0]); - Assert.Equal(2, matrix.Intensities[0, 1]); - Assert.Equal(3, matrix.Intensities[0, 2]); - } - - [Fact] - public void BuildMatrix_NoSamples_IsEmpty() - { - var matrix = FinOpsHeatmapBuilder.BuildMatrix(new[] { "a" }, Array.Empty()); - Assert.True(matrix.IsEmpty); - } - - // ── ColumnLogIntensities (Phase 2 color-scale binding) ── - - [Fact] - public void ColumnLogIntensities_MaxIsOne_ZeroIsZero_OthersBetween() - { - var intensities = FinOpsHeatmapBuilder.ColumnLogIntensities(new long[] { 0, 10, 100 }); - - Assert.Equal(0.0, intensities[0]); // zero -> no shade - Assert.Equal(1.0, intensities[2], 6); // column max -> full shade - Assert.InRange(intensities[1], 0.0001, 0.9999); // mid -> partial - Assert.True(intensities[1] < intensities[2]); - } - - [Fact] - public void ColumnLogIntensities_AllZero_ReturnsAllZero() - { - var intensities = FinOpsHeatmapBuilder.ColumnLogIntensities(new long[] { 0, 0, 0 }); - Assert.All(intensities, v => Assert.Equal(0.0, v)); // max=0 divide-by-zero guard (§3B) - } - - [Fact] - public void ColumnLogIntensities_NegativeClampsToZero() - { - var intensities = FinOpsHeatmapBuilder.ColumnLogIntensities(new long[] { -5, 100 }); - Assert.Equal(0.0, intensities[0]); - Assert.Equal(1.0, intensities[1], 6); - } - - [Fact] - public void ColumnLogIntensities_LogScale_CompressesLargeRange() - { - // A single hot value among many quiet ones: the quiet values still get a visible (non-tiny) - // shade because of the log scale, not a linear one. - var intensities = FinOpsHeatmapBuilder.ColumnLogIntensities(new long[] { 10, 10000 }); - Assert.True(intensities[0] > 0.2, $"log scale should keep the small value visible, got {intensities[0]}"); - Assert.Equal(1.0, intensities[1], 6); - } -} diff --git a/deprecated/Dashboard.Tests/FinOpsInventoryQueryTests.cs b/deprecated/Dashboard.Tests/FinOpsInventoryQueryTests.cs deleted file mode 100644 index 98f7a5d7e8..0000000000 --- a/deprecated/Dashboard.Tests/FinOpsInventoryQueryTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #1535 regression guard (Dashboard mirror of Lite's FinOpsInventoryQueryTests): the FinOps live -/// server-inventory query must read edition/version/storage from permission-free scalars and dynamic -/// SQL only — never sys.dm_os_sys_info (VIEW DATABASE STATE on Azure SQL DB), and never a -/// hard-coded sys.master_files (absent on Azure SQL DB) without an engine-edition branch. The -/// hardware read that genuinely needs the DMV stays isolated in its own best-effort query so a -/// permission gap loses only CPU/memory/socket facts, not the whole inventory row. -/// -public class FinOpsInventoryQueryTests -{ - [Fact] - public void InventoryQuery_DoesNotDependOnDmOsSysInfo() - { - Assert.DoesNotContain("dm_os_sys_info", DatabaseService.InventoryQueryText, StringComparison.Ordinal); - } - - [Fact] - public void HardwareQuery_IsolatesTheDmvRead() - { - Assert.Contains("sys.dm_os_sys_info", DatabaseService.HardwareQueryText, StringComparison.Ordinal); - // The hardware-only columns must ride the isolated read, not the inventory query. - Assert.Contains("cpu_count", DatabaseService.HardwareQueryText, StringComparison.Ordinal); - Assert.Contains("sqlserver_start_time", DatabaseService.HardwareQueryText, StringComparison.Ordinal); - } - - [Fact] - public void InventoryQuery_StillDetectsEditionAndStaysAzureSafeForStorage() - { - // Edition/version classification survives on permission-free scalars. - Assert.Contains("SERVERPROPERTY('EngineEdition')", DatabaseService.InventoryQueryText, StringComparison.Ordinal); - // Storage no longer hard-codes sys.master_files (absent on Azure SQL DB); the engine-edition - // branch reads sys.database_files there. - Assert.Contains("sys.database_files", DatabaseService.InventoryQueryText, StringComparison.Ordinal); - } -} diff --git a/deprecated/Dashboard.Tests/IncidentIdTests.cs b/deprecated/Dashboard.Tests/IncidentIdTests.cs deleted file mode 100644 index 9ee003599b..0000000000 --- a/deprecated/Dashboard.Tests/IncidentIdTests.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Generic; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the incident id (correlate-and-focus slice 2): one analysis run = one incident, so every -/// non-absolution story shares the id; the id fingerprints the primary (highest-severity) finding + -/// database so the same recurring incident is trackable across runs. -/// -public class IncidentIdTests -{ - private static AnalysisStory Story(string key, double sev, string? db = null, bool absolution = false) => - new() { RootFactKey = key, Severity = sev, DatabaseName = db, IsAbsolution = absolution }; - - [Fact] - public void StampStories_StampsAllNonAbsolution_WithTheSameId() - { - var stories = new List { Story("CPU_SQL_PERCENT", 1.6), Story("BLOCKING_EVENTS", 1.0) }; - IncidentId.StampStories("SQL1", stories); - - Assert.NotEmpty(stories[0].IncidentId); - Assert.Equal(stories[0].IncidentId, stories[1].IncidentId); // one incident per run - } - - [Fact] - public void StampStories_SamePrimaryProblem_SameIdAcrossRuns() - { - // Different co-fired members, SAME primary (CPU on Sales) -> trackable as one recurring incident. - var run1 = new List { Story("CPU_SQL_PERCENT", 1.6, "Sales"), Story("CXPACKET", 0.9) }; - var run2 = new List { Story("CPU_SQL_PERCENT", 1.7, "Sales"), Story("WRITELOG", 0.8) }; - IncidentId.StampStories("SQL1", run1); - IncidentId.StampStories("SQL1", run2); - - Assert.Equal(run1[0].IncidentId, run2[0].IncidentId); - } - - [Fact] - public void StampStories_DifferentPrimaryServerOrDb_DifferentId() - { - var a = new List { Story("CPU_SQL_PERCENT", 1.6, "Sales") }; - var b = new List { Story("CPU_SQL_PERCENT", 1.6, "Orders") }; // different database - var c = new List { Story("BLOCKING_EVENTS", 1.6, "Sales") }; // different primary key - IncidentId.StampStories("SQL1", a); - IncidentId.StampStories("SQL1", b); - IncidentId.StampStories("SQL2", c); - - Assert.NotEqual(a[0].IncidentId, b[0].IncidentId); - Assert.NotEqual(a[0].IncidentId, c[0].IncidentId); - } - - [Fact] - public void StampStories_AbsolutionOnly_LeavesIdsEmpty() - { - var stories = new List { Story("server_health", 0, absolution: true) }; - IncidentId.StampStories("SQL1", stories); - Assert.Equal(string.Empty, stories[0].IncidentId); - } - - [Fact] - public void Compute_IsDeterministic_OnSeverityTies() - { - var s1 = new List { Story("AAA", 1.0), Story("BBB", 1.0) }; - var s2 = new List { Story("BBB", 1.0), Story("AAA", 1.0) }; // same set, reversed order - Assert.Equal(IncidentId.Compute("SQL1", s1), IncidentId.Compute("SQL1", s2)); // tiebroken by root key - } - - // ── StampClusters: per-component ids (the clustering refinement) ── - - [Fact] - public void StampClusters_GivesEachComponentItsOwnId() - { - var component1 = new List { Story("CPU_SQL_PERCENT", 1.6), Story("CXPACKET", 0.9) }; - var component2 = new List { Story("DISK_SPACE", 1.5) }; - - IncidentId.StampClusters("SQL1", new[] { component1, component2 }); - - Assert.NotEmpty(component1[0].IncidentId); - Assert.Equal(component1[0].IncidentId, component1[1].IncidentId); // same incident -> same id - Assert.NotEqual(component1[0].IncidentId, component2[0].IncidentId); // different incidents -> different ids - } -} diff --git a/deprecated/Dashboard.Tests/InferenceEngineTests.cs b/deprecated/Dashboard.Tests/InferenceEngineTests.cs deleted file mode 100644 index 794ff887f3..0000000000 --- a/deprecated/Dashboard.Tests/InferenceEngineTests.cs +++ /dev/null @@ -1,410 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using PerformanceMonitor.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Tests the InferenceEngine and RelationshipGraph against seeded scenarios. -/// Validates that stories are built with correct paths and severity ordering. -/// -public class InferenceEngineTests -{ - /* ── Unit tests: graph edge evaluation ── */ - - [Fact] - public void Graph_NoEdgesForUnknownFact() - { - var graph = new RelationshipGraph(); - var facts = new Dictionary(); - - var edges = graph.GetActiveEdges("UNKNOWN_THING", facts); - Assert.Empty(edges); - } - - [Fact] - public void Graph_CxPacketEdgeFires_WhenSosIsHigh() - { - var graph = new RelationshipGraph(); - var facts = new Dictionary - { - ["SOS_SCHEDULER_YIELD"] = new() { Key = "SOS_SCHEDULER_YIELD", Value = 0.50, Severity = 0.67 } - }; - - var edges = graph.GetActiveEdges("CXPACKET", facts); - Assert.Contains(edges, e => e.Destination == "SOS_SCHEDULER_YIELD"); - } - - [Fact] - public void Graph_CxPacketEdgeDoesNotFire_WhenSosIsLow() - { - var graph = new RelationshipGraph(); - var facts = new Dictionary - { - ["SOS_SCHEDULER_YIELD"] = new() { Key = "SOS_SCHEDULER_YIELD", Value = 0.10, Severity = 0.13 } - }; - - var edges = graph.GetActiveEdges("CXPACKET", facts); - Assert.DoesNotContain(edges, e => e.Destination == "SOS_SCHEDULER_YIELD"); - } - - // WS3: a config-advisory fact (DB_CONFIG/SERVER_CONFIG) roots a standalone recommendation - // at its base severity (e.g. RCSI-off = 0.3), below the 0.5 incident threshold — so a - // standing misconfig surfaces on a quiet, healthy server. An incident fact at the same - // severity does NOT root. - [Fact] - public void ConfigFact_RootsStandalone_BelowMinimumSeverity() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "DB_CONFIG", Source = "config", Value = 1, Severity = 0.3, - Metadata = new Dictionary { ["rcsi_off_count"] = 9 } } - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == "DB_CONFIG"); - } - - [Fact] - public void IncidentFact_BelowMinimumSeverity_DoesNotRoot() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "CPU_SQL_PERCENT", Source = "cpu", Value = 60, Severity = 0.3 } - }; - - var stories = engine.BuildStories(facts); - - Assert.DoesNotContain(stories, s => s.RootFactKey == "CPU_SQL_PERCENT"); - } - - // WS3: a FILE_AUTOGROWTH_PERCENT fact at its 0.3 advisory base roots a standalone - // recommendation, below the 0.5 incident threshold — because it is a config-advisory root - // key. Mirrors ConfigFact_RootsStandalone_BelowMinimumSeverity for the new key. - [Fact] - public void FileAutogrowthPercentFact_RootsStandalone_BelowMinimumSeverity() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "FILE_AUTOGROWTH_PERCENT", Source = "config", Value = 2, Severity = 0.3, - Metadata = new Dictionary { ["file_count"] = 2 } } - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == "FILE_AUTOGROWTH_PERCENT"); - } - - // WS3: each bad server-level config fact at its 0.4 advisory base roots a standalone - // recommendation, below the 0.5 incident threshold — because each is a config-advisory root - // key. One finding per CONFIG_* fact (they are leaves with no edges between them). - [Theory] - [InlineData("CONFIG_MAXDOP")] - [InlineData("CONFIG_CTFP")] - [InlineData("CONFIG_MAX_MEMORY_MB")] - [InlineData("CONFIG_MIN_MAX_MEMORY_NARROW")] - public void ServerConfigFact_RootsStandalone_BelowMinimumSeverity(string key) - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = key, Source = "config", Value = 0, Severity = 0.4 } - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == key); - } - - // WS4: each plan-XML advisory (MISSING_INDEX / PLAN_WARNING) roots a standalone recommendation - // below the 0.5 incident threshold — they are config-advisory root keys, like the server facts. - [Theory] - [InlineData("MISSING_INDEX")] - [InlineData("PLAN_WARNING")] - public void PlanAdvisoryFact_RootsStandalone_BelowMinimumSeverity(string key) - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = key, Source = "queries", Value = 3, Severity = 0.4 } - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == key); - } - - // All four bad server-config facts together root four distinct standalone findings (no edges - // between them, so none consumes another). - [Fact] - public void ServerConfigFacts_AllFour_RootFourDistinctFindings() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "CONFIG_MAXDOP", Source = "config", Value = 0, Severity = 0.4 }, - new() { Key = "CONFIG_CTFP", Source = "config", Value = 5, Severity = 0.4 }, - new() { Key = "CONFIG_MAX_MEMORY_MB", Source = "config", Value = 2147483647, Severity = 0.4 }, - new() { Key = "CONFIG_MIN_MAX_MEMORY_NARROW", Source = "config", Value = 24000, Severity = 0.4 }, - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == "CONFIG_MAXDOP"); - Assert.Contains(stories, s => s.RootFactKey == "CONFIG_CTFP"); - Assert.Contains(stories, s => s.RootFactKey == "CONFIG_MAX_MEMORY_MB"); - Assert.Contains(stories, s => s.RootFactKey == "CONFIG_MIN_MAX_MEMORY_NARROW"); - } - - // WS5: each server-health advisory fact at its 0.4 advisory base roots a standalone - // recommendation, below the 0.5 incident threshold — because each is a config-advisory root - // key. One finding per fact (they are leaves with no edges between them). Mirrors the WS3 - // ServerConfigFact_RootsStandalone_BelowMinimumSeverity test. - [Theory] - [InlineData("CONFIG_IFI_DISABLED")] - [InlineData("CONFIG_LPIM_DISABLED")] - [InlineData("SERVER_MEMORY_DUMPS")] - public void ServerHealthFact_RootsStandalone_BelowMinimumSeverity(string key) - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = key, Source = "config", Value = 0, Severity = 0.4 } - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == key); - } - - // All three server-health facts together root three distinct standalone findings (no edges - // between them, so none consumes another). - [Fact] - public void ServerHealthFacts_AllThree_RootThreeDistinctFindings() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "CONFIG_IFI_DISABLED", Source = "config", Value = 0, Severity = 0.4 }, - new() { Key = "CONFIG_LPIM_DISABLED", Source = "config", Value = 0, Severity = 0.4 }, - new() { Key = "SERVER_MEMORY_DUMPS", Source = "config", Value = 3, Severity = 0.4 }, - }; - - var stories = engine.BuildStories(facts); - - Assert.Contains(stories, s => s.RootFactKey == "CONFIG_IFI_DISABLED"); - Assert.Contains(stories, s => s.RootFactKey == "CONFIG_LPIM_DISABLED"); - Assert.Contains(stories, s => s.RootFactKey == "SERVER_MEMORY_DUMPS"); - } - - // Regression: a duplicated fact key (e.g. a collector returning two rows for the same - // setting) once aborted the entire analysis — BuildStories built its lookup with a raw - // ToDictionary(f => f.Key), which throws on a duplicate. It must now dedupe and survive. - [Fact] - public void BuildStories_WithDuplicateFactKeys_DoesNotThrow() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "CONFIG_CTFP", Source = "config", Value = 5, Severity = 0.4 }, - new() { Key = "CONFIG_CTFP", Source = "config", Value = 5, Severity = 0.4 }, // duplicate key - }; - - var ex = Record.Exception(() => engine.BuildStories(facts)); - - Assert.Null(ex); - } - - // C (workload-aware MAXDOP/CTFP): a THREADPOOL root is relabeled by its co-elevated cause so the - // persisted root key carries parallel-vs-blocking — only the parallel flavor is a MAXDOP/CTFP - // problem. CXPACKET/high-DOP co-fired -> _PARALLEL; blocking co-fired -> _BLOCKING; both -> - // _MIXED; neither -> generic THREADPOOL. Co-causes are seeded below 0.5 so only THREADPOOL roots. - [Fact] - public void Threadpool_RootIsAttributedByCoElevatedCause() - { - var engine = new InferenceEngine(new RelationshipGraph()); - - string ThreadpoolRoot(params Fact[] facts) => - engine.BuildStories(facts.ToList()) - .First(s => s.RootFactKey.StartsWith("THREADPOOL")) - .RootFactKey; - - Fact Tp() => new() { Key = "THREADPOOL", Source = "waits", Value = 0.5, Severity = 0.9 }; - Fact Cx() => new() { Key = "CXPACKET", Source = "waits", Value = 0.3, Severity = 0.3 }; - Fact Dop() => new() { Key = "QUERY_HIGH_DOP", Source = "queries", Value = 6, Severity = 0.3 }; - Fact Blk() => new() { Key = "BLOCKING_EVENTS", Source = "blocking", Value = 20, Severity = 0.3 }; - - Assert.Equal("THREADPOOL_PARALLEL", ThreadpoolRoot(Tp(), Cx())); - Assert.Equal("THREADPOOL_PARALLEL", ThreadpoolRoot(Tp(), Dop())); - Assert.Equal("THREADPOOL_BLOCKING", ThreadpoolRoot(Tp(), Blk())); - Assert.Equal("THREADPOOL_MIXED", ThreadpoolRoot(Tp(), Cx(), Blk())); - Assert.Equal("THREADPOOL", ThreadpoolRoot(Tp())); - } - - // Regression: RootFactValue/LeafFactValue must carry the fact's RAW collected VALUE, not its - // severity. They were both set to .Severity, so a CONFIG_CTFP finding (value 5, severity 0.4) - // reported RootFactValue 0.4 — which the MCP root_fact.value contract and the notification - // headline surface as "the value", contradicting the value-stated advice ("CTFP is 5"). - [Fact] - public void BuildStory_RootFactValue_IsFactValue_NotSeverity() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var facts = new List - { - new() { Key = "CONFIG_CTFP", Source = "config", Value = 5, Severity = 0.4 } - }; - - var story = engine.BuildStories(facts).First(s => s.RootFactKey == "CONFIG_CTFP"); - - Assert.Equal(5, story.RootFactValue); // the collected value, NOT 0.4 - Assert.Equal(0.4, story.Severity); // severity still on its own field - } - - [Fact] - public void BuildStory_LeafFactValue_IsFactValue_NotSeverity() - { - var engine = new InferenceEngine(new RelationshipGraph()); - // CXPACKET roots (severity >= 0.5) and traverses to SOS_SCHEDULER_YIELD (edge fires when SOS - // severity is high), so the story has a leaf whose value must be SOS's value, not its severity. - var facts = new List - { - new() { Key = "CXPACKET", Source = "waits", Value = 0.6, Severity = 0.9 }, - new() { Key = "SOS_SCHEDULER_YIELD", Source = "waits", Value = 0.5, Severity = 0.67 } - }; - - var story = engine.BuildStories(facts).First(s => s.RootFactKey == "CXPACKET"); - - Assert.Equal(0.6, story.RootFactValue); // CXPACKET value, not 0.9 - Assert.Equal("SOS_SCHEDULER_YIELD", story.LeafFactKey); - Assert.Equal(0.5, story.LeafFactValue); // SOS value, not 0.67 - } - - // ── correlate-and-focus: graph-connectivity incident clustering ── - - [Fact] - public void ClusterIntoIncidents_MergesGraphConnectedStories() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var stories = new List - { - new() { RootFactKey = "CPU_SQL_PERCENT", Severity = 1.6, Path = ["CPU_SQL_PERCENT"] }, - new() { RootFactKey = "PLAN_REGRESSION", Severity = 0.6, Path = ["PLAN_REGRESSION"] }, - }; - var facts = new List - { - new() { Key = "CPU_SQL_PERCENT", Source = "cpu", Value = 90, Severity = 1.6 }, - new() { Key = "PLAN_REGRESSION", Source = "queries", Value = 1, Severity = 0.6, BaseSeverity = 0.6 }, - }; - - // CPU_SQL_PERCENT -> PLAN_REGRESSION is an active edge (PLAN_REGRESSION.BaseSeverity > 0), - // so the two stories are one incident even though the greedy traversal left them separate. - Assert.Single(engine.ClusterIntoIncidents(stories, facts)); - } - - [Fact] - public void ClusterIntoIncidents_KeepsIndependentStoriesSeparate() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var stories = new List - { - new() { RootFactKey = "CPU_SQL_PERCENT", Severity = 1.6, Path = ["CPU_SQL_PERCENT"] }, - new() { RootFactKey = "DISK_SPACE", Severity = 1.6, Path = ["DISK_SPACE"] }, - }; - var facts = new List - { - new() { Key = "CPU_SQL_PERCENT", Source = "cpu", Value = 90, Severity = 1.6 }, - new() { Key = "DISK_SPACE", Source = "disk", Value = 5, Severity = 1.6 }, - }; - - // No graph edge between CPU and disk space -> two separate incidents. - Assert.Equal(2, engine.ClusterIntoIncidents(stories, facts).Count); - } - - [Fact] - public void ClusterIntoIncidents_NormalizesThreadpoolRelabel_AndBridgesToBlocking() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var stories = new List - { - new() { RootFactKey = "THREADPOOL_BLOCKING", Severity = 0.9, Path = ["THREADPOOL_BLOCKING"] }, - new() { RootFactKey = "LCK", Severity = 0.9, Path = ["LCK"] }, - }; - var facts = new List - { - new() { Key = "THREADPOOL", Source = "waits", Value = 0.5, Severity = 0.9 }, - new() { Key = "LCK", Source = "waits", Value = 0.5, Severity = 0.9 }, - }; - - // The relabeled THREADPOOL_BLOCKING path key normalizes to THREADPOOL, whose active - // THREADPOOL->LCK bridge (LCK severity >= 0.5) merges it with the blocking story. - Assert.Single(engine.ClusterIntoIncidents(stories, facts)); - } - - // ── correlate-and-focus: DB-aware incident clustering (Stage B change 3, option i) ── - - // A CPU_SQL_PERCENT->PLAN_REGRESSION edge fires, but the two stories name DIFFERENT databases — - // the DB-aware union refuses to merge them, so a db1 problem and a db2 problem stay two incidents - // (was one cross-database incident before the fix). - [Fact] - public void ClusterIntoIncidents_DifferentDatabases_DoNotMerge() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var stories = new List - { - new() { RootFactKey = "CPU_SQL_PERCENT", Severity = 1.6, Path = ["CPU_SQL_PERCENT"], DatabaseName = "db1" }, - new() { RootFactKey = "PLAN_REGRESSION", Severity = 0.6, Path = ["PLAN_REGRESSION"], DatabaseName = "db2" }, - }; - var facts = new List - { - new() { Key = "CPU_SQL_PERCENT", Source = "cpu", Value = 90, Severity = 1.6 }, - new() { Key = "PLAN_REGRESSION", Source = "queries", Value = 1, Severity = 0.6, BaseSeverity = 0.6 }, - }; - - Assert.Equal(2, engine.ClusterIntoIncidents(stories, facts).Count); - } - - // The same active edge, but the two stories name the SAME database -> still one incident. Guards - // against over-fragmentation: DB-awareness must not split a genuine same-database incident. - [Fact] - public void ClusterIntoIncidents_SameDatabase_StillMerge() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var stories = new List - { - new() { RootFactKey = "CPU_SQL_PERCENT", Severity = 1.6, Path = ["CPU_SQL_PERCENT"], DatabaseName = "db1" }, - new() { RootFactKey = "PLAN_REGRESSION", Severity = 0.6, Path = ["PLAN_REGRESSION"], DatabaseName = "db1" }, - }; - var facts = new List - { - new() { Key = "CPU_SQL_PERCENT", Source = "cpu", Value = 90, Severity = 1.6 }, - new() { Key = "PLAN_REGRESSION", Source = "queries", Value = 1, Severity = 0.6, BaseSeverity = 0.6 }, - }; - - Assert.Single(engine.ClusterIntoIncidents(stories, facts)); - } - - // A server-scoped story (no DatabaseName) still bridges freely to a db-scoped one, so a server-wide - // symptom (CPU) correlates with a db-scoped cause (a regressed plan on db1) -> one incident. - [Fact] - public void ClusterIntoIncidents_ServerScopedStory_BridgesToDbScoped() - { - var engine = new InferenceEngine(new RelationshipGraph()); - var stories = new List - { - new() { RootFactKey = "CPU_SQL_PERCENT", Severity = 1.6, Path = ["CPU_SQL_PERCENT"], DatabaseName = null }, - new() { RootFactKey = "PLAN_REGRESSION", Severity = 0.6, Path = ["PLAN_REGRESSION"], DatabaseName = "db1" }, - }; - var facts = new List - { - new() { Key = "CPU_SQL_PERCENT", Source = "cpu", Value = 90, Severity = 1.6 }, - new() { Key = "PLAN_REGRESSION", Source = "queries", Value = 1, Severity = 0.6, BaseSeverity = 0.6 }, - }; - - Assert.Single(engine.ClusterIntoIncidents(stories, facts)); - } -} diff --git a/deprecated/Dashboard.Tests/JsonAlertHistoryStoreDedupKeyTests.cs b/deprecated/Dashboard.Tests/JsonAlertHistoryStoreDedupKeyTests.cs deleted file mode 100644 index b3ba098bca..0000000000 --- a/deprecated/Dashboard.Tests/JsonAlertHistoryStoreDedupKeyTests.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Interfaces; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #1154: the Dashboard JSON store's per-fingerprint cooldown seed. Proves the in-memory scan -/// restricts to rows whose ContextJson carries the #1140 dedup key, isolates per-fingerprint, and -/// — critically — does NOT NRE on the many null-ContextJson rows (tray/muted) the scan also visits -/// (the round-1 MAJOR). A unique serverId keeps the test isolated from any on-disk alert_history.json -/// the store loads in its constructor. -/// -public class JsonAlertHistoryStoreDedupKeyTests -{ - /// Minimal IUserPreferencesService over one UserPreferences instance (mirrors the other Dashboard tests). - private sealed class FakePreferencesService : IUserPreferencesService - { - public UserPreferences Preferences { get; } = new(); - public UserPreferences GetPreferences() => Preferences; - public void SavePreferences(UserPreferences preferences) { } - public void UpdateWaitStatsRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCpuRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateMemoryRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateFileIoRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateExpensiveQueriesRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateBlockingRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCollectionHealthRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - } - - private static string JsonWith(string dedupKey) - { - var ctx = new AlertContext - { - Incidents = new List { new(dedupKey, new[] { "db.dbo.T" }) } - }; - return AlertContextSerializer.Serialize(ctx); - } - - private static Task RecordAsync(JsonAlertHistoryStore store, string serverId, string metric, string type, string? contextJson) - => store.RecordAlertAsync(new AlertHistoryRecord( - serverId, "Srv", metric, "4", "1", null, null, -#pragma warning disable CS0618 - Delivery: AlertDelivery.FromLegacyStoredColumns(true, type, null), -#pragma warning restore CS0618 - Muted: false, DetailText: null, ContextJson: contextJson)); - - [Fact] - public async Task GetLastSentUtc_WithDedupKey_FiltersToFingerprint_AndIgnoresNullContextRows() - { - var store = new JsonAlertHistoryStore(new FakePreferencesService()); - var srv = "test-" + Guid.NewGuid().ToString("N"); // unique -> isolated from on-disk history - - // Email rows: AAA earlier, BBB later, then a null-context "email" row (must not NRE, must be - // excluded by a dedupKey filter, but still counts for the metric-level seed). - await RecordAsync(store, srv, "Deadlocks Detected", "email", JsonWith("aaaa1111")); - await Task.Delay(10, TestContext.Current.CancellationToken); - await RecordAsync(store, srv, "Deadlocks Detected", "email", JsonWith("bbbb2222")); - await Task.Delay(10, TestContext.Current.CancellationToken); - await RecordAsync(store, srv, "Deadlocks Detected", "email", null); - - var lastAaa = await store.GetLastEmailSentUtcAsync(srv, "Deadlocks Detected", "aaaa1111"); - var lastBbb = await store.GetLastEmailSentUtcAsync(srv, "Deadlocks Detected", "bbbb2222"); - var lastCcc = await store.GetLastEmailSentUtcAsync(srv, "Deadlocks Detected", "cccc3333"); - var lastMetric = await store.GetLastEmailSentUtcAsync(srv, "Deadlocks Detected"); // metric-level (null key) - - Assert.NotNull(lastAaa); - Assert.NotNull(lastBbb); - Assert.Null(lastCcc); // no such fingerprint - Assert.True(lastAaa!.Value < lastBbb!.Value); // the filter isolates per-fingerprint - Assert.NotNull(lastMetric); - Assert.True(lastMetric!.Value >= lastBbb.Value); // metric-level still sees the later null-context row - - // Webhook channel parity. - await RecordAsync(store, srv, "Blocking Detected", "webhook", JsonWith("dddd4444")); - Assert.NotNull(await store.GetLastWebhookSentUtcAsync(srv, "Blocking Detected", "dddd4444")); - Assert.Null(await store.GetLastWebhookSentUtcAsync(srv, "Blocking Detected", "eeee5555")); - } -} diff --git a/deprecated/Dashboard.Tests/JsonAlertHistoryStoreMutedFilterTests.cs b/deprecated/Dashboard.Tests/JsonAlertHistoryStoreMutedFilterTests.cs deleted file mode 100644 index eca278362a..0000000000 --- a/deprecated/Dashboard.Tests/JsonAlertHistoryStoreMutedFilterTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using PerformanceMonitor.Common; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Interfaces; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #1225: muted alerts and resolution notices ("... Cleared/Resolved/Restored") are written to -/// history for audit but must not count toward the sidebar Alert badge. Proves GetAlertHistory's -/// includeMuted/includeResolved filters drop those rows, that the defaults still return them for -/// the history grid / MCP tool, and — the regression that bit the reporter — that both filters run -/// BEFORE the row limit, so noise can't evict a real alert from the counted window. A unique -/// serverId keeps the test isolated from any on-disk alert_history.json the store loads in its -/// constructor. -/// -public class JsonAlertHistoryStoreMutedFilterTests -{ - /// Minimal IUserPreferencesService over one UserPreferences instance (mirrors the other Dashboard tests). - private sealed class FakePreferencesService : IUserPreferencesService - { - public UserPreferences Preferences { get; } = new(); - public UserPreferences GetPreferences() => Preferences; - public void SavePreferences(UserPreferences preferences) { } - public void UpdateWaitStatsRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCpuRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateMemoryRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateFileIoRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateExpensiveQueriesRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateBlockingRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - public void UpdateCollectionHealthRange(int hoursBack, DateTime? fromDate = null, DateTime? toDate = null) { } - } - - private static Task RecordAsync(JsonAlertHistoryStore store, string serverId, string metric, bool muted) - => store.RecordAlertAsync(new AlertHistoryRecord( - serverId, "Srv", metric, "4", "1", null, null, -#pragma warning disable CS0618 - Delivery: AlertDelivery.FromLegacyStoredColumns(!muted, muted ? "muted" : "tray", null), -#pragma warning restore CS0618 - Muted: muted, DetailText: null, ContextJson: null)); - - [Fact] - public async Task GetAlertHistory_ExcludeMuted_DropsMutedRows_ButDefaultKeepsThem() - { - var store = new JsonAlertHistoryStore(new FakePreferencesService()); - var srv = "test-" + Guid.NewGuid().ToString("N"); // unique -> isolated from on-disk history - - await RecordAsync(store, srv, "Long Running Query", muted: false); - await RecordAsync(store, srv, "Long Running Query", muted: true); - await RecordAsync(store, srv, "Deadlocks Detected", muted: false); - await RecordAsync(store, srv, "Long Running Query", muted: true); - - var all = store.GetAlertHistory(hoursBack: 24, limit: 100); // history grid / MCP - var actionable = store.GetAlertHistory(hoursBack: 24, limit: 100, includeMuted: false); // sidebar badge - - Assert.Equal(4, all.Count(a => a.ServerId == srv)); // default: muted rows still shown for audit - var mine = actionable.Where(a => a.ServerId == srv).ToList(); - Assert.Equal(2, mine.Count); // only the two unmuted alerts count - Assert.All(mine, a => Assert.False(a.Muted)); - } - - [Fact] - public async Task GetAlertHistory_ExcludeMuted_FiltersBeforeLimit_SoMutedNoiseCannotEvictRealAlert() - { - var store = new JsonAlertHistoryStore(new FakePreferencesService()); - var srv = "test-" + Guid.NewGuid().ToString("N"); - - // One real alert first (oldest), then a flood of newer muted noise (the reporter's scenario: - // a muted trace-reader session re-firing every cooldown). - await RecordAsync(store, srv, "Deadlocks Detected", muted: false); - await Task.Delay(10, TestContext.Current.CancellationToken); - for (int i = 0; i < 5; i++) - await RecordAsync(store, srv, "Long Running Query", muted: true); - - // Newest-first ordering + a small limit: the muted flood crowds the real alert out of the - // window when muted rows are included (this is what made the old badge under/over-count). - var withMuted = store.GetAlertHistory(hoursBack: 24, limit: 3); - Assert.DoesNotContain(withMuted, a => a.ServerId == srv && !a.Muted); - - // Excluding muted BEFORE the limit keeps the real alert inside the counted window (#1225). - var actionable = store.GetAlertHistory(hoursBack: 24, limit: 3, includeMuted: false); - var mine = actionable.Where(a => a.ServerId == srv).ToList(); - Assert.Single(mine); - Assert.False(mine[0].Muted); - } - - [Fact] - public async Task GetAlertHistory_ExcludeResolved_DropsResolutionRows_FiltersBeforeLimit() - { - var store = new JsonAlertHistoryStore(new FakePreferencesService()); - var srv = "test-" + Guid.NewGuid().ToString("N"); - - // One real alert first (oldest), then a flood of newer resolution notices. "Capture Restored" - // and "Server Restored" are included deliberately: the pre-#1225 classifier matched only - // Cleared/Resolved, so those "Restored" rows would have slipped into the badge count. - await RecordAsync(store, srv, "Deadlocks Detected", muted: false); - await Task.Delay(10, TestContext.Current.CancellationToken); - foreach (var resolved in new[] { "Blocking Cleared", "CPU Resolved", "Capture Restored", "tempdb Space Resolved", "Server Restored" }) - await RecordAsync(store, srv, resolved, muted: false); - - // Default includes resolution rows for audit (history grid / MCP); a small limit fills with them. - var all = store.GetAlertHistory(hoursBack: 24, limit: 3); - Assert.DoesNotContain(all, a => a.ServerId == srv && !AlertMetricClassifier.IsResolution(a.MetricName)); - - // Excluding resolution rows before the limit keeps the one real alert in the counted window. - var actionable = store.GetAlertHistory(hoursBack: 24, limit: 3, includeResolved: false); - var mine = actionable.Where(a => a.ServerId == srv).ToList(); - Assert.Single(mine); - Assert.Equal("Deadlocks Detected", mine[0].MetricName); - } -} diff --git a/deprecated/Dashboard.Tests/LatestValueLookbackSqlTests.cs b/deprecated/Dashboard.Tests/LatestValueLookbackSqlTests.cs deleted file mode 100644 index 8667e5d1d5..0000000000 --- a/deprecated/Dashboard.Tests/LatestValueLookbackSqlTests.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using PerformanceMonitorDashboard.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #3896, the frozen Dashboard's mirror: its "latest value" reads — database size, percent autogrowth, disk -/// space, memory_stats, memory clerks and the autogrowth drill-down — take each series' newest sample within -/// its collector's lookback of the window's end (a day, or twice the collector's interval in -/// config.collection_schedule if that is longer), the Darling/Lite twins' bound. Unbounded, a dropped -/// database's files stayed in DATABASE_TOTAL_SIZE_MB (and its ALTER DATABASE in the autogrowth -/// drill-down) for the whole collection retention. The reads are pinned on the source text, the only idiom -/// this project has for its SQL-Server-side reads — there is no test database — and the bounds' arithmetic -/// directly. -/// -public class LatestValueLookbackSqlTests -{ - [Theory] - [InlineData("SqlServerFactCollector.Storage.cs", "CollectDatabaseSizeFactAsync", "FileIoStats")] - [InlineData("SqlServerFactCollector.Storage.cs", "CollectFileAutogrowthFactsAsync", "DatabaseSizeStats")] - [InlineData("SqlServerFactCollector.Storage.cs", "CollectDiskSpaceFactsAsync", "DatabaseSizeStats")] - [InlineData("SqlServerFactCollector.Resources.cs", "CollectMemoryFactsAsync", "MemoryStats")] - [InlineData("SqlServerFactCollector.Resources.cs", "CollectMemoryClerkFactsAsync", "MemoryClerks")] - [InlineData("SqlServerDrillDownCollector.Storage.cs", "CollectAutogrowthPercentFiles", "DatabaseSizeStats")] - public void EachLatestValueRead_IsBoundedBelowByItsCollectorsLookback_AndAboveByTheWindowEnd(string file, string method, string collector) - { - var body = MethodBody(Read("deprecated", "Dashboard", "Analysis", file), method); - - Assert.Contains("collection_time >= @lookbackStart", body); - Assert.Contains("collection_time <= @endTime", body); - Assert.Contains($"new SqlParameter(\"@lookbackStart\", context.LatestValueStartFor(SqlServerLatestValueBounds.{collector}))", body); - Assert.Contains("new SqlParameter(\"@endTime\", context.TimeRangeEnd)", body); - } - - /// The bounds are stamped before the first read, and the drill-down stamps a context it is handed - /// bare — the pass's own context arrives stamped, so the list and the count share one set. - [Fact] - public void TheBounds_AreStampedBeforeAnyRead_AndByTheDrillDown() - { - var collect = Read("deprecated", "Dashboard", "Analysis", "SqlServerFactCollector.cs"); - var stamp = collect.IndexOf("await SqlServerLatestValueBounds.EnsureAsync(_connectionString, context);", StringComparison.Ordinal); - var firstRead = collect.IndexOf("await Collect", StringComparison.Ordinal); - Assert.True(stamp >= 0 && stamp < firstRead, "the bounds must be stamped before the first read"); - - var drill = MethodBody(Read("deprecated", "Dashboard", "Analysis", "SqlServerDrillDownCollector.Storage.cs"), "CollectAutogrowthPercentFiles"); - Assert.Contains("await SqlServerLatestValueBounds.EnsureAsync(_connectionString, context);", drill); - } - - /// - /// A day, or twice the collector's interval if that is longer — the daily collector keeps its fact for two - /// days instead of flapping between runs, and every default cadence keeps the flat day. Frequency 0 on the - /// Dashboard is "every master-collector tick", not on-load, so it takes the floor; so does a collector the - /// schedule has no row for. - /// - [Fact] - public void TheBounds_AreADayOrTwiceTheScheduledInterval() - { - var end = new DateTime(2026, 3, 1, 12, 0, 0); - var starts = SqlServerLatestValueBounds.Starts(end, new Dictionary - { - ["database_size_stats_collector"] = 1440, - ["file_io_stats_collector"] = 1, - ["memory_clerks_stats_collector"] = 0, - }); - - Assert.Equal(end.AddHours(-48), starts[SqlServerLatestValueBounds.DatabaseSizeStats]); - Assert.Equal(end.AddHours(-24), starts[SqlServerLatestValueBounds.FileIoStats]); - Assert.Equal(end.AddHours(-24), starts[SqlServerLatestValueBounds.MemoryClerks]); - Assert.Equal(end.AddHours(-24), starts[SqlServerLatestValueBounds.MemoryStats]); - } - - /// The fact and the drill-down that lists its files must agree on WHICH files, or the list names - /// a database the count never counted. - [Fact] - public void TheAutogrowthFact_AndItsDrillDown_ShareOneBound() - { - var fact = MethodBody(Read("deprecated", "Dashboard", "Analysis", "SqlServerFactCollector.Storage.cs"), "CollectFileAutogrowthFactsAsync"); - var drill = MethodBody(Read("deprecated", "Dashboard", "Analysis", "SqlServerDrillDownCollector.Storage.cs"), "CollectAutogrowthPercentFiles"); - - const string Bound = " WHERE database_name NOT IN ('master', 'msdb', 'model', 'tempdb')\r\n AND collection_time >= @lookbackStart\r\n AND collection_time <= @endTime"; - Assert.Contains(Normalize(Bound), Normalize(fact)); - Assert.Contains(Normalize(Bound), Normalize(drill)); - } - - /// The method's text from its signature to the next member's signature (or the end of the file). - private static string MethodBody(string src, string method) - { - var start = src.IndexOf($"private async Task {method}(", StringComparison.Ordinal); - Assert.True(start >= 0, $"method not found: {method}"); - var next = src.IndexOf("private async Task ", start + method.Length, StringComparison.Ordinal); - return next < 0 ? src[start..] : src[start..next]; - } - - private static string Normalize(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal); - - private static string Read(params string[] pathParts) - { - var root = FindRepoRoot(); - Assert.True(root is not null, $"Could not locate the repo root (a directory containing deprecated/Dashboard/Dashboard.csproj) by walking up from {AppContext.BaseDirectory}."); - var path = Path.Combine(new[] { root! }.Concat(pathParts).ToArray()); - Assert.True(File.Exists(path), $"Source file not found: {path}"); - return File.ReadAllText(path); - } - - /// Walks up from the test output directory to the repo root — the directory holding the Dashboard project. Mirrors DashboardMirrorPinTests. - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (File.Exists(Path.Combine(dir.FullName, "deprecated", "Dashboard", "Dashboard.csproj"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/McpSchemaCompatTests.cs b/deprecated/Dashboard.Tests/McpSchemaCompatTests.cs deleted file mode 100644 index 75a23b2034..0000000000 --- a/deprecated/Dashboard.Tests/McpSchemaCompatTests.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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 System.Reflection; -using System.Text.Json; -using Microsoft.Extensions.DependencyInjection; -using ModelContextProtocol.Server; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Golden-sample tests for the Gemini-compatible MCP tool schema transform (issue #1074), covering the -/// Dashboard tool surface. Mirrors Lite.Tests/McpSchemaCompatTests.cs against Dashboard's tool classes, -/// which differ from Lite's. See that file for the full rationale. -/// -public class McpSchemaCompatTests -{ - /// All Dashboard MCP tool classes, discovered by their [McpServerToolType] attribute. - private static List DashboardToolTypes() => - typeof(PerformanceMonitorDashboard.Mcp.McpAlertTools).Assembly - .GetTypes() - .Where(t => t.GetCustomAttribute() is not null) - .OrderBy(t => t.FullName, StringComparer.Ordinal) - .ToList(); - - private static bool IsServiceParameter(Type t) => - !t.IsPrimitive && t != typeof(string) && !t.IsEnum && t != typeof(decimal) && - t != typeof(DateTime) && t != typeof(DateTimeOffset) && t != typeof(Guid) && t != typeof(TimeSpan); - - private static readonly MethodInfo GeminiCompatibleToolsMethod = - typeof(McpSchemaCompat).GetMethod( - nameof(McpSchemaCompat.WithGeminiCompatibleTools), - BindingFlags.Public | BindingFlags.Static)!; - - private static readonly MethodInfo StockWithToolsMethod = - typeof(McpServerBuilderExtensions).GetMethods(BindingFlags.Public | BindingFlags.Static) - .First(m => m.Name == nameof(McpServerBuilderExtensions.WithTools) - && m.IsGenericMethodDefinition - && m.GetParameters() is { Length: 2 } p - && p[1].ParameterType == typeof(JsonSerializerOptions)); - - private static List BuildProtocolTools(MethodInfo openGenericRegister, bool stock) - { - var toolTypes = DashboardToolTypes(); - var services = new ServiceCollection(); - - var serviceParamTypes = toolTypes - .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) - .Where(m => m.GetCustomAttribute() is not null) - .SelectMany(m => m.GetParameters()) - .Select(p => p.ParameterType) - .Where(IsServiceParameter) - .Distinct(); - - foreach (var serviceType in serviceParamTypes) - { - services.AddSingleton(serviceType, _ => null!); - } - - var builder = services.AddMcpServer(); - - foreach (var toolType in toolTypes) - { - var closed = openGenericRegister.MakeGenericMethod(toolType); - var args = stock ? new object?[] { builder, null } : new object?[] { builder }; - closed.Invoke(null, args); - } - - using var provider = services.BuildServiceProvider(); - return provider.GetServices().Select(t => t.ProtocolTool).ToList(); - } - - private static List FindViolations(string toolName, JsonElement schema) - { - var violations = new List(); - Walk(schema, toolName); - return violations; - - void Walk(JsonElement element, string path) - { - switch (element.ValueKind) - { - case JsonValueKind.Object: - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type") && property.Value.ValueKind == JsonValueKind.Array) - { - violations.Add($"{path}: union type {property.Value.GetRawText()}"); - } - - if (property.NameEquals("default")) - { - violations.Add($"{path}: default = {property.Value.GetRawText()}"); - } - - Walk(property.Value, $"{path}.{property.Name}"); - } - break; - - case JsonValueKind.Array: - var index = 0; - foreach (var item in element.EnumerateArray()) - { - Walk(item, $"{path}[{index++}]"); - } - break; - } - } - } - - [Fact] - public void GeminiCompatibleTools_EmitNoUnionTypesOrDefaultKeywords() - { - var tools = BuildProtocolTools(GeminiCompatibleToolsMethod, stock: false); - - Assert.NotEmpty(tools); - - var allViolations = tools - .SelectMany(t => FindViolations(t.Name, t.InputSchema)) - .ToList(); - - Assert.True( - allViolations.Count == 0, - "Gemini-incompatible schema keywords leaked into tools/list:\n" + string.Join("\n", allViolations)); - } - - [Fact] - public void StockWithTools_WouldEmitUnionTypesOrDefaults_ProvingTransformIsNecessary() - { - var tools = BuildProtocolTools(StockWithToolsMethod, stock: true); - - var violationCount = tools.Sum(t => FindViolations(t.Name, t.InputSchema).Count); - - Assert.True( - violationCount > 0, - "Expected the stock SDK registration to emit union types / default keywords; it did not. " + - "If the SDK changed, McpSchemaCompat may no longer be needed."); - } - - [Fact] - public void GeminiCompatibleTools_ExposeSameToolCountAsStock() - { - var gemini = BuildProtocolTools(GeminiCompatibleToolsMethod, stock: false); - var stock = BuildProtocolTools(StockWithToolsMethod, stock: true); - - Assert.Equal( - stock.Select(t => t.Name).OrderBy(n => n, StringComparer.Ordinal), - gemini.Select(t => t.Name).OrderBy(n => n, StringComparer.Ordinal)); - } -} diff --git a/deprecated/Dashboard.Tests/MissingIndexAdvisoryTests.cs b/deprecated/Dashboard.Tests/MissingIndexAdvisoryTests.cs deleted file mode 100644 index 19c4c385c4..0000000000 --- a/deprecated/Dashboard.Tests/MissingIndexAdvisoryTests.cs +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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.Analysis; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Controls; -using PerformanceMonitorDashboard.Services.Recommendations; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// WS4: missing-index advisory — the COPY-PASTE-ONLY recommendation. A MISSING_INDEX finding's -/// drill-down carries the SQL Server-suggested CREATE INDEX statement(s); the drill-down is -/// ephemeral (not persisted / not read back), so the statements ride the persisted -/// (FactKey "MISSING_INDEX") through to the reader — exactly like the -/// autogrowth advisory, but with NO handler so it never offers Apply. These tests cover the builder, -/// the persisted-action round-trip, the reader mapping (copy-paste set, Remediation null), and the -/// card affordances (Copy fix shown, Apply hidden, incident affordances preserved). -/// -public class MissingIndexAdvisoryTests -{ - private const string CreateStmt = - "CREATE NONCLUSTERED INDEX [ix_Orders_CustomerId] ON [dbo].[Orders] ([CustomerId]) INCLUDE ([OrderDate]);"; - - private static AnalysisFinding MissingIndexFinding(List? rows = null) => new() - { - ServerId = 1, - ServerName = "TestServer", - Category = "missing_index", - StoryPath = "MISSING_INDEX", - StoryPathHash = "missingidx000001", - RootFactKey = "MISSING_INDEX", - Severity = 0.4, - DrillDown = new Dictionary - { - // SqlServerDrillDownCollector "missing_indexes": { table, impact, create_statement }. - ["missing_indexes"] = rows ?? new List - { - new { table = "dbo.Orders", impact = 87.3, create_statement = CreateStmt } - } - } - }; - - // ── Builder + extractor ─────────────────────────────────────────────────────── - - [Fact] - public void BuildMissingIndexAction_ProducesAdviseActionWithTargets() - { - var action = FactRemediation.BuildMissingIndexAction(MissingIndexFinding()); - - Assert.NotNull(action); - Assert.Equal("MISSING_INDEX", action!.FactKey); - Assert.Equal("advise", action.Action); - Assert.Empty(action.Targets); // not a force-plan action - Assert.NotNull(action.MissingIndexTargets); - var t = Assert.Single(action.MissingIndexTargets!); - Assert.Equal("dbo.Orders", t.Table); - Assert.Equal(87.3, t.Impact); - Assert.Equal(CreateStmt, t.CreateStatement); - } - - [Fact] - public void BuildMissingIndexAction_WrongRootFactKey_ReturnsNull() - { - var finding = MissingIndexFinding(); - finding.RootFactKey = "PLAN_WARNING"; // a sibling advisory, not missing-index - Assert.Null(FactRemediation.BuildMissingIndexAction(finding)); - } - - [Fact] - public void BuildMissingIndexAction_NoDrillDownOrEmpty_ReturnsNull() - { - Assert.Null(FactRemediation.BuildMissingIndexAction(new AnalysisFinding { RootFactKey = "MISSING_INDEX" })); - Assert.Null(FactRemediation.BuildMissingIndexAction(MissingIndexFinding(new List()))); - } - - [Fact] - public void ExtractMissingIndexTargets_SkipsRowsWithoutCreateStatement_AndCapsAtFive() - { - // A row with no create_statement has nothing to copy → skipped. - var noStmt = FactRemediation.ExtractMissingIndexTargets(MissingIndexFinding(new List - { - new { table = "dbo.A", impact = 10.0, create_statement = "" } - })); - Assert.Empty(noStmt); - - var many = Enumerable.Range(1, 8) - .Select(i => (object)new { table = $"dbo.T{i}", impact = (double)i, create_statement = $"CREATE INDEX ix{i} ON dbo.T{i}(c);" }) - .ToList(); - Assert.Equal(5, FactRemediation.ExtractMissingIndexTargets(MissingIndexFinding(many)).Count); - } - - // ── Persisted-action round-trip (the drill-down is ephemeral; the action must survive) ── - - [Fact] - public void SerializeAction_RoundTrips_MissingIndexTargets() - { - var action = FactRemediation.BuildMissingIndexAction(MissingIndexFinding()); - var json = AlertContextSerializer.SerializeAction(action); - var back = AlertContextSerializer.DeserializeAction(json); - - Assert.NotNull(back); - Assert.Equal("MISSING_INDEX", back!.FactKey); - var t = Assert.Single(back.MissingIndexTargets!); - Assert.Equal("dbo.Orders", t.Table); - Assert.Equal(87.3, t.Impact); - Assert.Equal(CreateStmt, t.CreateStatement); - } - - // ── Reader: copy-paste set, Remediation deliberately null (no Apply) ──────────── - - [Fact] - public void MapEngineFinding_MissingIndex_IsCopyOnly() - { - var finding = MissingIndexFinding(); - // Mirror AnalysisService: the built action is attached before persistence/read. - finding.Remediation = FactRemediation.BuildMissingIndexAction(finding); - - var item = RecommendationsReader.MapEngineFinding(finding); - - Assert.Contains(CreateStmt, item.CopyPasteSql); // the CREATE is the copy-paste payload - Assert.Null(item.Remediation); // copy-only — never Apply - Assert.True(item.IsMissingIndexAdvisory); - Assert.Equal(RecommendationSetting.None, item.Setting); // stays a non-de-duping incident - } - - [Fact] - public void MapEngineFinding_MissingIndex_JoinsMultipleCreateStatements() - { - var finding = MissingIndexFinding(new List - { - new { table = "dbo.A", impact = 50.0, create_statement = "CREATE INDEX ixa ON dbo.A(c);" }, - new { table = "dbo.B", impact = 40.0, create_statement = "CREATE INDEX ixb ON dbo.B(c);" } - }); - finding.Remediation = FactRemediation.BuildMissingIndexAction(finding); - - var item = RecommendationsReader.MapEngineFinding(finding); - Assert.Contains("CREATE INDEX ixa ON dbo.A(c);", item.CopyPasteSql); - Assert.Contains("CREATE INDEX ixb ON dbo.B(c);", item.CopyPasteSql); - } - - // ── Card affordances: Copy fix shown, Apply hidden, incident affordances preserved ── - - [Fact] - public void CardViewModel_MissingIndex_ShowsCopyFix_NotApply_StillIncident() - { - var finding = MissingIndexFinding(); - finding.Remediation = FactRemediation.BuildMissingIndexAction(finding); - var vm = new RecommendationCardViewModel(RecommendationsReader.MapEngineFinding(finding)); - - Assert.True(vm.ShowCopyFix); // the CREATE INDEX is copyable - Assert.False(vm.ShowApply); // copy-only — no handler, no Apply button - Assert.True(vm.IsIncident); // stays an incident... - Assert.True(vm.ShowAskAi); // ...so Ask-AI... - Assert.True(vm.ShowOpenInActiveQueries); // ...and Open-in-Active-Queries remain - } -} diff --git a/deprecated/Dashboard.Tests/OverviewComparisonWindowOffsetTests.cs b/deprecated/Dashboard.Tests/OverviewComparisonWindowOffsetTests.cs deleted file mode 100644 index fd0569b8e5..0000000000 --- a/deprecated/Dashboard.Tests/OverviewComparisonWindowOffsetTests.cs +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using PerformanceMonitorDashboard.Controls; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #4305 (mirrors Lite's #4296, PR #4309): the Server Trends tab's correlated-lanes "Compare to" ghost-line -/// overlay ( / -/// , called from -/// ResourceMetricsContent.RefreshServerTrendsAsync) built its current window from -/// DateTime.UtcNow under a PRESET range -- a UTC basis -- while the correlated lanes' own reads -/// (DatabaseService.GetCpuUtilizationAsync, GetTotalWaitStatsTrendAsync, etc.) treat a -/// supplied fromDate/toDate as SERVER-LOCAL: their preset-range SQL branch filters collection_time against -/// SYSDATETIME(), not SYSUTCDATETIME() (every collect.* table's collection_time column defaults to -/// SYSDATETIME(), confirmed across install/02_create_tables.sql, 03_create_config_tables.sql and -/// 06_ensure_collection_table.sql). On a server not on UTC that shifted the reference window, and -/// CorrelatedTimelineLanesControl.RefreshAsync's timeShift and ComparisonLabel had the -/// identical fallback, shifting the ghost line's X-axis alignment and its "N days ago" label the same way. -/// A custom range was already correct (ServerTab's pickers convert to server time via -/// ServerTimeHelper.DisplayTimeToServerTime before RefreshServerTrendsAsync ever sees fromDate/toDate). -/// -public class OverviewComparisonWindowOffsetTests -{ - private static readonly DateTime FixedUtcNow = new(2026, 3, 10, 16, 0, 0, DateTimeKind.Utc); - - /// - /// Preset range (fromDate/toDate both null): the current window end is the SERVER's local now, not - /// FixedUtcNow itself -- proving the offset actually applies (the pre-#4305 bug was end == raw UTC now - /// on any server with a non-zero offset). - /// - [Theory] - [InlineData(300)] // UTC+5 - [InlineData(-420)] // UTC-7 - public void GetCurrentWindowServerLocal_PresetRange_AppliesServerOffset(int utcOffsetMinutes) - { - var (start, end) = CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal( - hoursBack: 6, fromDate: null, toDate: null, FixedUtcNow, utcOffsetMinutes); - - var expectedEnd = FixedUtcNow.AddMinutes(utcOffsetMinutes); - Assert.Equal(expectedEnd, end); - Assert.Equal(expectedEnd.AddHours(-6), start); - Assert.NotEqual(FixedUtcNow, end); - } - - /// Custom range: fromDate/toDate pass through untouched, on either side of UTC. - [Theory] - [InlineData(300)] - [InlineData(-420)] - public void GetCurrentWindowServerLocal_CustomRange_UsesSuppliedBoundsVerbatim(int utcOffsetMinutes) - { - var from = new DateTime(2026, 3, 10, 9, 0, 0, DateTimeKind.Unspecified); - var to = new DateTime(2026, 3, 10, 17, 0, 0, DateTimeKind.Unspecified); - - var (start, end) = CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal( - hoursBack: 6, from, to, FixedUtcNow, utcOffsetMinutes); - - Assert.Equal(from, start); - Assert.Equal(to, end); - } - - /// - /// Under a preset range, on a server east AND west of UTC, the reference window is the current - /// SERVER-LOCAL window shifted back exactly 1 day (Yesterday) or 7 days (Last week / Same day last - /// week), and CurrentFrom - From (the timeShift RefreshAsync applies) is EXACTLY that -- not off - /// by the server's offset, and not off by a live-clock sampling gap, because CurrentFrom rides along - /// from the SAME current-window computation refFrom was built from. - /// - [Theory] - [InlineData(300)] - [InlineData(-420)] - public void GetOverviewComparisonRange_PresetRange_ShiftsServerLocalWindowExactly(int utcOffsetMinutes) - { - var (currentStart, currentEnd) = CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal( - hoursBack: 6, null, null, FixedUtcNow, utcOffsetMinutes); - - var yesterday = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 1, hoursBack: 6, null, null, FixedUtcNow, utcOffsetMinutes); - Assert.NotNull(yesterday); - Assert.Equal(currentStart.AddDays(-1), yesterday!.Value.From); - Assert.Equal(currentEnd.AddDays(-1), yesterday.Value.To); - Assert.Equal(currentStart, yesterday.Value.CurrentFrom); - Assert.Equal(TimeSpan.FromDays(1), yesterday.Value.CurrentFrom - yesterday.Value.From); - - var lastWeek = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 2, hoursBack: 6, null, null, FixedUtcNow, utcOffsetMinutes); - Assert.NotNull(lastWeek); - Assert.Equal(currentStart.AddDays(-7), lastWeek!.Value.From); - Assert.Equal(TimeSpan.FromDays(7), lastWeek.Value.CurrentFrom - lastWeek.Value.From); - - var sameDayLastWeek = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 3, hoursBack: 6, null, null, FixedUtcNow, utcOffsetMinutes); - Assert.Equal(lastWeek, sameDayLastWeek); - - Assert.Null(CorrelatedTimelineLanesControl.GetOverviewComparisonRange(0, 6, null, null, FixedUtcNow, utcOffsetMinutes)); - Assert.Null(CorrelatedTimelineLanesControl.GetOverviewComparisonRange(-1, 6, null, null, FixedUtcNow, utcOffsetMinutes)); - } - - /// Same as above, under a custom range (fromDate/toDate supplied, already server-local). - [Theory] - [InlineData(300)] - [InlineData(-420)] - public void GetOverviewComparisonRange_CustomRange_ShiftsSuppliedWindowExactly(int utcOffsetMinutes) - { - var from = new DateTime(2026, 3, 10, 9, 0, 0, DateTimeKind.Unspecified); - var to = new DateTime(2026, 3, 10, 17, 0, 0, DateTimeKind.Unspecified); - - var lastWeek = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 2, hoursBack: 6, from, to, FixedUtcNow, utcOffsetMinutes); - Assert.NotNull(lastWeek); - Assert.Equal(from.AddDays(-7), lastWeek!.Value.From); - Assert.Equal(to.AddDays(-7), lastWeek.Value.To); - Assert.Equal(from, lastWeek.Value.CurrentFrom); - Assert.Equal(TimeSpan.FromDays(7), lastWeek.Value.CurrentFrom - lastWeek.Value.From); - } - - /// - /// #4305's source pin. Confirmed by running this test against this branch's parent commit (pre-#4305): - /// it failed on all three call-site assertions -- CompareToCombo_SelectionChanged fed - /// ResourceMetricsContent the shared, UTC-preset-fallback GetComparisonRange() result, and - /// RefreshAsync's timeShift/ComparisonLabel both sampled DateTime.UtcNow directly. - /// - [Fact] - public void OverviewComparisonCallSites_UseServerLocalHelper_NotBareUtcNowFallback() - { - var serverTabSource = Read("deprecated", "Dashboard", "ServerTab.xaml.cs"); - var resourceMetricsSource = Read("deprecated", "Dashboard", "Controls", "ResourceMetricsContent.xaml.cs"); - var lanesSource = Read("deprecated", "Dashboard", "Controls", "CorrelatedTimelineLanesControl.xaml.cs"); - - Assert.False(serverTabSource.Contains("await ResourceMetricsContent.SetComparisonRangeAsync(comparisonRange);"), - "CompareToCombo_SelectionChanged still feeds ResourceMetricsContent the shared GetComparisonRange() " + - "tuple, whose preset-range fallback is a raw UTC now -- wrong basis for the correlated lanes' " + - "server-local reads (#4305)."); - Assert.Contains("await ResourceMetricsContent.SetComparisonRangeAsync(CompareToCombo.SelectedIndex);", serverTabSource); - - Assert.Contains("CorrelatedTimelineLanesControl.GetOverviewComparisonRange(", resourceMetricsSource); - Assert.DoesNotContain("(DateTime From, DateTime To)? ComparisonRange { get; set; }", resourceMetricsSource); - - Assert.False(lanesSource.Contains("var timeShift = (fromDate ?? DateTime.UtcNow.AddHours(-hoursBack)) - refFrom;"), - "RefreshAsync's timeShift still falls back to a raw DateTime.UtcNow (#4305)."); - Assert.Contains("var timeShift = comparisonRange.Value.CurrentFrom - refFrom;", lanesSource); - - Assert.False(lanesSource.Contains("var currentStart = fromDate ?? DateTime.UtcNow.AddHours(-hoursBack);"), - "ComparisonLabel still falls back to a raw DateTime.UtcNow (#4305)."); - Assert.Contains("var daysBack = (range.CurrentFrom - range.From).TotalDays;", lanesSource); - } - - /* ---------------- helpers (mirrors DashboardMirrorPinTests) ---------------- */ - - private static string Read(params string[] pathParts) - { - var root = FindRepoRoot(); - Assert.True(root is not null, $"Could not locate the repo root (a directory containing deprecated/Dashboard/Dashboard.csproj) by walking up from {AppContext.BaseDirectory}."); - var path = Path.Combine(new[] { root! }.Concat(pathParts).ToArray()); - Assert.True(File.Exists(path), $"Source file not found: {path}"); - return File.ReadAllText(path); - } - - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (File.Exists(Path.Combine(dir.FullName, "deprecated", "Dashboard", "Dashboard.csproj"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/PerfmonPerSecondSqlTests.cs b/deprecated/Dashboard.Tests/PerfmonPerSecondSqlTests.cs deleted file mode 100644 index 26de1de269..0000000000 --- a/deprecated/Dashboard.Tests/PerfmonPerSecondSqlTests.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Performance Monitor Dashboard - * Copyright (c) 2026 Darling Data, LLC - * Licensed under the MIT License - see LICENSE file for details - */ - -using PerformanceMonitorDashboard.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #3527/#3561: cntr_value_delta spans one COLLECTION INTERVAL, not one second — read raw, the -/// perfmon analysis reads overstate by the cadence (60x at 60s, 300x at 5min). All three reads -/// must divide by the row's measured sample_interval_seconds and skip interval <= 0 rows -/// (no delta was knowable: first sighting, reset, gap) — together or the baseline comparison is -/// cross-unit. The Dashboard has no test database, so these pin the SQL text, the mirror of the -/// Darling twin's #3560 pins (PgFactCollector.PerfmonSql / PgAnomalyDetector.BatchRequestWindowSql). -/// -public class PerfmonPerSecondSqlTests -{ - /* ---------------- read 1: the fact collector ---------------- */ - - [Fact] - public void PerfmonFactSql_SelectsTheMeasuredInterval_AndFiltersUnknowableRows() - { - var sql = SqlServerFactCollector.PerfmonSql; - - /* The interval rides both the CTE and the outer select so the C# division has its divisor. */ - Assert.Contains("sample_interval_seconds,", sql); - Assert.Contains("SELECT counter_name, cntr_value, cntr_value_delta, sample_interval_seconds", sql); - - /* Interval <= 0 rows are filtered INSIDE the CTE, so rn = 1 lands on the newest row a rate - can honestly be derived from — a counter with only interval-0 rows emits no fact, never 0. */ - Assert.Contains("AND sample_interval_seconds > 0", sql); - var filterAt = sql.IndexOf("AND sample_interval_seconds > 0", System.StringComparison.Ordinal); - var rnFilterAt = sql.IndexOf("FROM latest WHERE rn = 1", System.StringComparison.Ordinal); - Assert.True(filterAt >= 0 && filterAt < rnFilterAt, "the interval filter must sit inside the latest CTE, before rn = 1"); - } - - /* ---------------- read 2: the anomaly detector's window ---------------- */ - - [Fact] - public void BatchRequestWindow_DividesByMeasuredInterval_AndSkipsUnknowableRows() - { - var sql = SqlServerAnomalyDetector.BatchRequestWindowSql; - - Assert.Contains("AVG(cntr_value_delta * 1.0 / NULLIF(sample_interval_seconds, 0))", sql); - Assert.Contains("MAX(cntr_value_delta * 1.0 / NULLIF(sample_interval_seconds, 0))", sql); - Assert.Contains("sample_interval_seconds > 0", sql); - - /* A raw AVG/MAX of the delta is exactly the #3527 defect — pin its absence. */ - Assert.DoesNotContain("AVG(cntr_value_delta)", sql); - Assert.DoesNotContain("MAX(cntr_value_delta)", sql); - } - - /* ---------------- read 3: the baseline arm ---------------- */ - - [Fact] - public void BatchRequestBaseline_PopulationIsPerSecond_RestartSignatureStaysRaw() - { - var sql = SqlServerBaselineProvider.GetBaselineQuery(SqlServerMetricNames.BatchRequests); - - Assert.NotNull(sql); - - /* The baseline population is the per-second rate, in the detector's window unit. */ - Assert.Contains("cntr_value_delta * 1.0 / NULLIF(sample_interval_seconds, 0) AS v", sql); - Assert.Contains("AVG(v) AS mean_val", sql); - Assert.Contains("STDEV(v) AS stddev_val", sql); - Assert.Contains("AND sample_interval_seconds > 0", sql); - - /* The restart signature stays on the RAW delta: its > 1000 bar predates the division and - marks a counter reset regardless of cadence. */ - Assert.Contains("LAG(cntr_value_delta) OVER (ORDER BY collection_time) AS prev_value", sql); - Assert.Contains("WHERE NOT (cntr_value_delta = 0 AND ISNULL(prev_value, 0) > 1000)", sql); - - /* A raw AVG/STDEV of the delta is exactly the #3527 defect — pin its absence. */ - Assert.DoesNotContain("AVG(cntr_value_delta)", sql); - Assert.DoesNotContain("STDEV(cntr_value_delta)", sql); - } - - /* ---------------- the consistency constraint ---------------- */ - - /// - /// The whole fix is the three reads agreeing: the window statistic, the baseline population, - /// and the fact value all divide by the measured interval, or the z-score compares across - /// units. The fact collector's division happens in C# (delta / sample_interval_seconds after - /// the SQL delivers the divisor), so its SQL is pinned for the divisor column and the - /// interval filter; the two aggregate reads divide in the SQL itself. - /// - [Fact] - public void AllThreeReads_FilterUnknowableRows() - { - var factSql = SqlServerFactCollector.PerfmonSql; - var windowSql = SqlServerAnomalyDetector.BatchRequestWindowSql; - var baselineSql = SqlServerBaselineProvider.GetBaselineQuery(SqlServerMetricNames.BatchRequests); - - Assert.Contains("sample_interval_seconds > 0", factSql); - Assert.Contains("sample_interval_seconds > 0", windowSql); - Assert.Contains("sample_interval_seconds > 0", baselineSql); - } -} diff --git a/deprecated/Dashboard.Tests/PlanAdvisoryAggregatorTests.cs b/deprecated/Dashboard.Tests/PlanAdvisoryAggregatorTests.cs deleted file mode 100644 index a0139e6243..0000000000 --- a/deprecated/Dashboard.Tests/PlanAdvisoryAggregatorTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Collections.Generic; -using PerformanceMonitor.PlanAnalysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// WS4: the shared PlanAdvisoryAggregator parses collected plan XML into missing-index / warning -/// aggregates that drive the MISSING_INDEX / PLAN_WARNING facts and drill-down. These cover its -/// resilience contract — a malformed, empty, or null plan never throws and is simply skipped, so -/// one bad plan can't abort the fact-collection batch. -/// -/// The real parse→emit over production SHOWPLAN XML is exercised by the live analysis path (the -/// collectors run the same ShowPlanParser the Plan Viewer/drill-down already use), not a hand-built -/// fixture: there are no plan-XML fixtures in the repo and the parser's structural/namespace -/// expectations make a faithful minimal one fragile and misleading. -/// -public class PlanAdvisoryAggregatorTests -{ - [Fact] - public void Summarize_EmptyInput_ReturnsZeros() - { - var summary = PlanAdvisoryAggregator.Summarize(new List()); - - Assert.Equal(0, summary.MissingIndexCount); - Assert.Equal(0, summary.WarningCount); - Assert.Equal(0, summary.CriticalCount); - Assert.Equal(0.0, summary.MaxImpact); - } - - [Fact] - public void Extract_MalformedOrNullPlans_AreSkipped_NoThrow() - { - var plans = new List - { - null!, - "", - " ", - "", - "truncated...", - "{\"json\":true}" - }; - - var ex = Record.Exception(() => - { - var details = PlanAdvisoryAggregator.Extract(plans); - Assert.Empty(details.MissingIndexes); - Assert.Empty(details.Warnings); - }); - - Assert.Null(ex); - } -} diff --git a/deprecated/Dashboard.Tests/PlanRegressionDrillDownMirrorTests.cs b/deprecated/Dashboard.Tests/PlanRegressionDrillDownMirrorTests.cs deleted file mode 100644 index bf26dc3cb0..0000000000 --- a/deprecated/Dashboard.Tests/PlanRegressionDrillDownMirrorTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using System.Text.RegularExpressions; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #3902, the frozen Dashboard's mirror of the Darling/Lite drill-down fixes. -/// -/// The regressed-queries drill-down re-ran the PLAN_REGRESSION fact's whole detection to list its top -/// five, deduplicating the Query Store slice a second time in the same pass. The fact now stamps the -/// (database, query_id) pairs it reported on AnalysisContext.PlanRegressionOffenders, and the -/// drill-down restricts its dedup to them, reading the whole slice only when there is no fact to follow. -/// -/// The parameter-sensitivity drill-down carried each row's compressed varbinary(max) statement through -/// its window sort to print five. It now carries the row's clustered key and fetches the text for the five -/// rows it prints. -/// -/// Pinned on the source text, the only idiom this project has for its SQL-Server-side reads (there is no -/// test database). The old and new SQL were also run side by side on a scratch database on SQL Server 2016 -/// (compatibility level 130, the oldest the product supports) and returned identical rows for all three reads. -/// -public class PlanRegressionDrillDownMirrorTests -{ - private const string FactFile = "SqlServerFactCollector.QueryPerf.cs"; - private const string DrillFile = "SqlServerDrillDownCollector.Queries.cs"; - - [Fact] - public void ThePlanRegressionFact_StampsTheQueriesItReported_AfterClearingAnyEarlierStamp() - { - var body = Normalize(MethodBody(Read(FactFile), "CollectPlanRegressionFactsAsync")); - - /* Cleared before the read, stamped after it: a read that fails leaves "not known", never a stale list. */ - var cleared = body.IndexOf("context.PlanRegressionOffenders = null;", StringComparison.Ordinal); - var tried = body.IndexOf("\n try\n", StringComparison.Ordinal); - var stamped = body.IndexOf("context.PlanRegressionOffenders = offenders;", StringComparison.Ordinal); - Assert.True(cleared >= 0 && cleared < tried, "the stamp must be cleared before the read"); - Assert.True(stamped > tried, "the stamp must be written after the read"); - - /* The database is appended after the eight columns the reader takes by ordinal, and read at ordinal 8. */ - Assert.Matches(new Regex(@"regression_factor,\s+database_name\s+FROM compared"), StripComments(body)); - Assert.Contains("reader.GetString(8)", body, StringComparison.Ordinal); - } - - [Fact] - public void TheRegressedQueriesDrillDown_RestrictsItsDedupToTheOffenders_AndReadsTheWholeSliceWithoutThem() - { - var body = Normalize(MethodBody(Read(DrillFile), "CollectRegressedQueries")); - - /* Spliced into the dedup's own WHERE, right after the window bound and before the CTE closes: a filter - anywhere later would still deduplicate the whole slice first. */ - Assert.Contains( - "AND server_last_execution_time >= @windowStart\" + offenderFilter + @\"\n),\nplan_agg AS", - body, - StringComparison.Ordinal); - - /* No stamp, or an empty one, is no filter at all. */ - Assert.Contains("context.PlanRegressionOffenders is { Count: > 0 } reported ? reported : null", body, StringComparison.Ordinal); - Assert.Contains("var offenderFilter = string.Empty;", body, StringComparison.Ordinal); - - /* One parameter per value, never values spliced into the text. */ - Assert.Contains("\"\\n AND database_name IN (\"", body, StringComparison.Ordinal); - Assert.Contains("\"\\n AND query_id IN (\"", body, StringComparison.Ordinal); - Assert.Contains("new SqlParameter(\"@offenderDatabase\" + i, databases[i])", body, StringComparison.Ordinal); - Assert.Contains("new SqlParameter(\"@offenderQueryId\" + i, queryIds[i])", body, StringComparison.Ordinal); - } - - [Fact] - public void TheParameterSensitivityDrillDown_FetchesTextForThePrintedRowsOnly() - { - var sql = StripComments(MethodBody(Read(DrillFile), "CollectParameterSensitiveQueries")); - - var windowStart = sql.IndexOf("WITH latest AS", StringComparison.Ordinal); - var cut = sql.IndexOf("FETCH NEXT 5 ROWS ONLY", StringComparison.Ordinal); - var decompress = sql.IndexOf("DECOMPRESS(qs.query_text)", StringComparison.Ordinal); - Assert.True(windowStart >= 0 && cut > windowStart, "the windowed CTE and the cut should both still be there"); - - /* The window and the cut carry no text... */ - Assert.DoesNotContain("query_text", sql[windowStart..cut], StringComparison.Ordinal); - - /* ...the text is decompressed after the cut, from the same row, by its clustered key. */ - Assert.True(decompress > cut, "the text must be fetched after FETCH NEXT 5 ROWS ONLY"); - Assert.Contains("qs.collection_time = o.collection_time", sql, StringComparison.Ordinal); - Assert.Contains("qs.collection_id = o.collection_id", sql, StringComparison.Ordinal); - } - - /// The method's text from its signature to the next member's signature (or the end of the file). - private static string MethodBody(string src, string method) - { - var start = src.IndexOf($"private async Task {method}(", StringComparison.Ordinal); - Assert.True(start >= 0, $"method not found: {method}"); - var next = src.IndexOf("private async Task ", start + method.Length, StringComparison.Ordinal); - return next < 0 ? src[start..] : src[start..next]; - } - - /// SQL line comments out, so a pin cannot pass on prose that names the shape it forbids. - private static string StripComments(string text) => Regex.Replace(text, @"--[^\r\n]*", string.Empty); - - private static string Normalize(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal); - - private static string Read(string file) - { - var root = FindRepoRoot(); - Assert.True(root is not null, $"Could not locate the repo root (a directory containing deprecated/Dashboard/Dashboard.csproj) by walking up from {AppContext.BaseDirectory}."); - var path = Path.Combine(root!, "deprecated", "Dashboard", "Analysis", file); - Assert.True(File.Exists(path), $"Source file not found: {path}"); - return File.ReadAllText(path); - } - - /// Walks up from the test output directory to the repo root — the directory holding the Dashboard project. Mirrors DashboardMirrorPinTests. - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (File.Exists(Path.Combine(dir.FullName, "deprecated", "Dashboard", "Dashboard.csproj"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/QueryComparisonWindowOffsetTests.cs b/deprecated/Dashboard.Tests/QueryComparisonWindowOffsetTests.cs deleted file mode 100644 index f1a162f895..0000000000 --- a/deprecated/Dashboard.Tests/QueryComparisonWindowOffsetTests.cs +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using PerformanceMonitorDashboard.Controls; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #4313 (follows #4305/#4317's fix for the Overview ghost line): the Query Stats / Proc Stats / Query -/// Store comparison grids built their current window from DateTime.UtcNow under a preset range -- -/// ServerTab.xaml.cs's GetComparisonRange and QueryPerformanceContent.Comparison.cs's -/// RefreshComparisonAsync both had the identical ?? DateTime.UtcNow fallback -- while the reads they -/// feed (DatabaseService.QueryPerformance.Comparison.cs's GetQueryStatsComparisonAsync, -/// GetProcedureStatsComparisonAsync, GetQueryStoreComparisonAsync) filter on collection_time, which is -/// server-local (collect.query_stats/proc_stats/query_store_stats default it to SYSDATETIME()). A third -/// spot, CorrelatedTimelineLanesControl.xaml.cs's RefreshAsync baseline referenceTime, had the same -/// fallback feeding SqlServerBaselineProvider.GetBaselineAsync's hour-of-day/day-of-week bucket match, -/// also against collection_time. All three now go through GetCurrentWindowServerLocal / -/// GetOverviewComparisonRange (#4305's shared, already-tested server-local window logic) instead of an -/// independent UTC-anchored resample. A custom range was already correct (ServerTab's pickers convert to -/// server time via ServerTimeHelper.DisplayTimeToServerTime before GetComparisonRange/RefreshComparisonAsync -/// ever see fromDate/toDate). -/// -public class QueryComparisonWindowOffsetTests -{ - private static readonly DateTime FixedUtcNow = new(2026, 3, 10, 16, 0, 0, DateTimeKind.Utc); - - /// - /// The grids' current window (what GetComparisonRange/RefreshComparisonAsync now compute via - /// GetCurrentWindowServerLocal) under a preset range, on a server east and west of UTC: end is the - /// server's local now, not FixedUtcNow itself. - /// - [Theory] - [InlineData(300)] // UTC+5 - [InlineData(-420)] // UTC-7 - public void GridsCurrentWindow_PresetRange_UsesServerLocalNow(int utcOffsetMinutes) - { - var (start, end) = CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal( - hoursBack: 24, fromDate: null, toDate: null, FixedUtcNow, utcOffsetMinutes); - - var expectedEnd = FixedUtcNow.AddMinutes(utcOffsetMinutes); - Assert.Equal(expectedEnd, end); - Assert.Equal(expectedEnd.AddHours(-24), start); - Assert.NotEqual(FixedUtcNow, end); - } - - /// The grids' current window under a custom range: supplied bounds pass through verbatim. - [Theory] - [InlineData(300)] - [InlineData(-420)] - public void GridsCurrentWindow_CustomRange_UsesSuppliedBoundsVerbatim(int utcOffsetMinutes) - { - var from = new DateTime(2026, 3, 10, 9, 0, 0, DateTimeKind.Unspecified); - var to = new DateTime(2026, 3, 10, 17, 0, 0, DateTimeKind.Unspecified); - - var (start, end) = CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal( - hoursBack: 24, from, to, FixedUtcNow, utcOffsetMinutes); - - Assert.Equal(from, start); - Assert.Equal(to, end); - } - - /// - /// GetComparisonRange's three dropdown options (Yesterday / Last week / Same day last week), east and - /// west of UTC, under a preset range: the grids' baseline (From, To) shifts the SERVER-LOCAL current - /// window back exactly 1 or 7 days, not a UTC-anchored one. - /// - [Theory] - [InlineData(300)] - [InlineData(-420)] - public void GetComparisonRangeEquivalent_PresetRange_ShiftsServerLocalWindow(int utcOffsetMinutes) - { - var (currentStart, currentEnd) = CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal( - hoursBack: 24, null, null, FixedUtcNow, utcOffsetMinutes); - - var yesterday = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 1, hoursBack: 24, null, null, FixedUtcNow, utcOffsetMinutes); - Assert.NotNull(yesterday); - Assert.Equal(currentStart.AddDays(-1), yesterday!.Value.From); - Assert.Equal(currentEnd.AddDays(-1), yesterday.Value.To); - - var lastWeek = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 2, hoursBack: 24, null, null, FixedUtcNow, utcOffsetMinutes); - Assert.NotNull(lastWeek); - Assert.Equal(currentStart.AddDays(-7), lastWeek!.Value.From); - Assert.Equal(currentEnd.AddDays(-7), lastWeek.Value.To); - - var sameDayLastWeek = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 3, hoursBack: 24, null, null, FixedUtcNow, utcOffsetMinutes); - Assert.Equal(lastWeek, sameDayLastWeek); - - Assert.Null(CorrelatedTimelineLanesControl.GetOverviewComparisonRange(0, 24, null, null, FixedUtcNow, utcOffsetMinutes)); - } - - /// Same as above under a custom range (fromDate/toDate supplied, already server-local). - [Theory] - [InlineData(300)] - [InlineData(-420)] - public void GetComparisonRangeEquivalent_CustomRange_ShiftsSuppliedWindow(int utcOffsetMinutes) - { - var from = new DateTime(2026, 3, 10, 9, 0, 0, DateTimeKind.Unspecified); - var to = new DateTime(2026, 3, 10, 17, 0, 0, DateTimeKind.Unspecified); - - var lastWeek = CorrelatedTimelineLanesControl.GetOverviewComparisonRange( - 2, hoursBack: 24, from, to, FixedUtcNow, utcOffsetMinutes); - Assert.NotNull(lastWeek); - Assert.Equal(from.AddDays(-7), lastWeek!.Value.From); - Assert.Equal(to.AddDays(-7), lastWeek.Value.To); - } - - /// - /// #4313's source pin. Confirmed by hand-reverting each call site to its pre-fix line, running this - /// test (it fails on the reverted assertion), then restoring: ServerTab.xaml.cs's GetComparisonRange, - /// QueryPerformanceContent.Comparison.cs's RefreshComparisonAsync, and CorrelatedTimelineLanesControl's - /// baseline referenceTime all used a bare ?? DateTime.UtcNow preset-range fallback before #4313. - /// Scoped to the Dashboard's copy only -- Lite's CorrelatedTimelineLanesControl.xaml.cs mirror keeps - /// the same pattern pending its own follow-up issue (filed from #4313, not fixed here). - /// - [Fact] - public void GridComparisonCallSites_UseServerLocalHelper_NotBareUtcNowFallback() - { - var serverTabSource = Read("deprecated", "Dashboard", "ServerTab.xaml.cs"); - var queryPerfComparisonSource = Read("deprecated", "Dashboard", "Controls", "QueryPerformanceContent.Comparison.cs"); - var lanesSource = Read("deprecated", "Dashboard", "Controls", "CorrelatedTimelineLanesControl.xaml.cs"); - - Assert.False(serverTabSource.Contains("var currentEnd = _globalToDate ?? DateTime.UtcNow;"), - "GetComparisonRange still falls back to a raw UTC now under a preset range (#4313)."); - Assert.Contains("Controls.CorrelatedTimelineLanesControl.GetOverviewComparisonRange(", serverTabSource); - - Assert.False(queryPerfComparisonSource.Contains("var currentEnd = _queryStatsToDate ?? DateTime.UtcNow;"), - "RefreshComparisonAsync still falls back to a raw UTC now under a preset range (#4313)."); - Assert.Contains("CorrelatedTimelineLanesControl.GetCurrentWindowServerLocal(", queryPerfComparisonSource); - - Assert.False(lanesSource.Contains("var referenceTime = fromDate ?? DateTime.UtcNow.AddHours(-hoursBack);"), - "RefreshAsync's baseline referenceTime still falls back to a raw UTC now (#4313)."); - Assert.Contains("var referenceTime = GetCurrentWindowServerLocal(", lanesSource); - } - - /* ---------------- helpers (mirrors OverviewComparisonWindowOffsetTests) ---------------- */ - - private static string Read(params string[] pathParts) - { - var root = FindRepoRoot(); - Assert.True(root is not null, $"Could not locate the repo root (a directory containing deprecated/Dashboard/Dashboard.csproj) by walking up from {AppContext.BaseDirectory}."); - var path = Path.Combine(new[] { root! }.Concat(pathParts).ToArray()); - Assert.True(File.Exists(path), $"Source file not found: {path}"); - return File.ReadAllText(path); - } - - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (File.Exists(Path.Combine(dir.FullName, "deprecated", "Dashboard", "Dashboard.csproj"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/RecommendationDeduperTests.cs b/deprecated/Dashboard.Tests/RecommendationDeduperTests.cs deleted file mode 100644 index c7b9441efb..0000000000 --- a/deprecated/Dashboard.Tests/RecommendationDeduperTests.cs +++ /dev/null @@ -1,780 +0,0 @@ -/* - * 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.Analysis; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services.Recommendations; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// WS1a coverage for the PURE Recommendations data layer (no DB): the cross-store de-dupe -/// (C3) and canonical severity mapping. Every test synthesizes -/// lists (or scalars) and calls the static / the -/// mappers directly. The actual two-store read is NOT -/// unit-tested here (it needs a live DB — see the PR's integration list). -/// -public class RecommendationDeduperTests -{ - // ---- builders --------------------------------------------------------- - - private static RecommendationItem EngineItem( - RecommendationSetting setting, - string? db, - double rawSeverity = 0.3, - string title = "engine") - { - var band = RecommendationDeduper.FromEngineSeverity(rawSeverity); - return new RecommendationItem - { - Source = RecommendationSource.Engine, - CanonicalSeverity = band, - RawSeverity = rawSeverity, - Database = db, - Title = title, - ProblemArea = "db_config", - Setting = setting, - StoryPathHash = "hash-" + title - }; - } - - private static RecommendationItem LegacyItem( - RecommendationSetting setting, - string? db, - CanonicalSeverity band = CanonicalSeverity.Warning, - string title = "legacy") - { - return new RecommendationItem - { - Source = RecommendationSource.Legacy, - CanonicalSeverity = band, - RawSeverity = RecommendationDeduper.LegacyRawSeverity(band), - Database = db, - Title = title, - ProblemArea = "Database Configuration", - Setting = setting - }; - } - - // ---- de-dupe: collisions --------------------------------------------- - - [Fact] - public void Merge_AutoShrink_SameDb_BothStores_KeepsEngineOnly() - { - var engine = new[] { EngineItem(RecommendationSetting.AutoShrink, "MyDb") }; - var legacy = new[] { LegacyItem(RecommendationSetting.AutoShrink, "MyDb") }; - - var result = RecommendationDeduper.Merge(engine, legacy); - - var row = Assert.Single(result); - Assert.Equal(RecommendationSetting.AutoShrink, row.Setting); - Assert.Equal(RecommendationSource.Engine, row.Source); - } - - [Fact] - public void Merge_AutoClose_SameDb_BothStores_KeepsEngineOnly() - { - var engine = new[] { EngineItem(RecommendationSetting.AutoClose, "MyDb") }; - var legacy = new[] { LegacyItem(RecommendationSetting.AutoClose, "MyDb") }; - - var result = RecommendationDeduper.Merge(engine, legacy); - - var row = Assert.Single(result); - Assert.Equal(RecommendationSetting.AutoClose, row.Setting); - Assert.Equal(RecommendationSource.Engine, row.Source); - } - - [Fact] - public void Merge_QueryStore_SameDb_BothStores_KeepsLegacyOnly() - { - // Synthesize an engine QS row even though prod does not emit one today — the de-dupe - // must still prefer the legacy row for QueryStore (the engine has no QS Apply). - var engine = new[] { EngineItem(RecommendationSetting.QueryStore, "MyDb") }; - var legacy = new[] { LegacyItem(RecommendationSetting.QueryStore, "MyDb") }; - - var result = RecommendationDeduper.Merge(engine, legacy); - - var row = Assert.Single(result); - Assert.Equal(RecommendationSetting.QueryStore, row.Setting); - Assert.Equal(RecommendationSource.Legacy, row.Source); - } - - [Fact] - public void Merge_SameSetting_DifferentDatabases_KeepsBoth() - { - var engine = new[] { EngineItem(RecommendationSetting.AutoShrink, "DbOne") }; - var legacy = new[] { LegacyItem(RecommendationSetting.AutoShrink, "DbTwo") }; - - var result = RecommendationDeduper.Merge(engine, legacy); - - Assert.Equal(2, result.Count); - Assert.Contains(result, r => r.Source == RecommendationSource.Engine && r.Database == "DbOne"); - Assert.Contains(result, r => r.Source == RecommendationSource.Legacy && r.Database == "DbTwo"); - } - - [Fact] - public void Merge_DatabaseNameMatch_IsCaseAndWhitespaceInsensitive() - { - // " MyDb " (engine) vs "mydb" (legacy) must be treated as the SAME database. - var engine = new[] { EngineItem(RecommendationSetting.AutoShrink, " MyDb ") }; - var legacy = new[] { LegacyItem(RecommendationSetting.AutoShrink, "mydb") }; - - var result = RecommendationDeduper.Merge(engine, legacy); - - var row = Assert.Single(result); - Assert.Equal(RecommendationSource.Engine, row.Source); - } - - // ---- de-dupe: pass-through (Setting=None) ---------------------------- - - [Fact] - public void Merge_NoneSettingRows_NeverDedupe() - { - // A memory-pressure legacy row (None) + an engine CPU finding (None) both pass through. - var legacyMemory = LegacyItem(RecommendationSetting.None, "MyDb", - band: CanonicalSeverity.Critical, title: "Memory Pressure"); - var engineCpu = EngineItem(RecommendationSetting.None, "MyDb", - rawSeverity: 1.6, title: "High CPU"); - - var result = RecommendationDeduper.Merge(new[] { engineCpu }, new[] { legacyMemory }); - - Assert.Equal(2, result.Count); - Assert.Contains(result, r => r.Title == "Memory Pressure" && r.Source == RecommendationSource.Legacy); - Assert.Contains(result, r => r.Title == "High CPU" && r.Source == RecommendationSource.Engine); - } - - [Fact] - public void Merge_TwoNoneRows_SameDb_AreNotCollapsed() - { - // Even with identical (db) the None setting must never key together. - var a = LegacyItem(RecommendationSetting.None, "MyDb", title: "A"); - var b = LegacyItem(RecommendationSetting.None, "MyDb", title: "B"); - - var result = RecommendationDeduper.Merge(Array.Empty(), new[] { a, b }); - - Assert.Equal(2, result.Count); - } - - [Fact] - public void Merge_NonOverlappingSettings_AllKept() - { - var engine = new[] - { - EngineItem(RecommendationSetting.Rcsi, "MyDb"), - EngineItem(RecommendationSetting.PageVerify, "MyDb"), - EngineItem(RecommendationSetting.AutoShrink, "MyDb") - }; - var legacy = new[] - { - LegacyItem(RecommendationSetting.QueryStore, "MyDb") - }; - - var result = RecommendationDeduper.Merge(engine, legacy); - - Assert.Equal(4, result.Count); - Assert.Contains(result, r => r.Setting == RecommendationSetting.Rcsi); - Assert.Contains(result, r => r.Setting == RecommendationSetting.PageVerify); - Assert.Contains(result, r => r.Setting == RecommendationSetting.AutoShrink && r.Source == RecommendationSource.Engine); - Assert.Contains(result, r => r.Setting == RecommendationSetting.QueryStore && r.Source == RecommendationSource.Legacy); - } - - // ---- de-dupe: ordering ---------------------------------------------- - - [Fact] - public void Merge_SortsBySeverityDescending() - { - var info = EngineItem(RecommendationSetting.None, "DbA", rawSeverity: 0.3, title: "info"); - var critical = EngineItem(RecommendationSetting.None, "DbB", rawSeverity: 1.8, title: "critical"); - var warning = LegacyItem(RecommendationSetting.None, "DbC", - band: CanonicalSeverity.Warning, title: "warning"); - - var result = RecommendationDeduper.Merge(new[] { info, critical }, new[] { warning }); - - Assert.Equal(CanonicalSeverity.Critical, result[0].CanonicalSeverity); - Assert.Equal(CanonicalSeverity.Warning, result[1].CanonicalSeverity); - Assert.Equal(CanonicalSeverity.Info, result[2].CanonicalSeverity); - } - - [Fact] - public void Merge_OrderIndependent_SameWinnerRegardlessOfInputOrder() - { - var engine = EngineItem(RecommendationSetting.AutoShrink, "MyDb"); - var legacy = LegacyItem(RecommendationSetting.AutoShrink, "MyDb"); - - var forward = RecommendationDeduper.Merge(new[] { engine }, new[] { legacy }); - var legacyOnly = RecommendationDeduper.Merge(Array.Empty(), - new[] { legacy }); // legacy alone -> legacy survives (no engine to prefer) - - Assert.Equal(RecommendationSource.Engine, Assert.Single(forward).Source); - // With only the legacy row present, it must still surface (collision resolver falls back). - Assert.Equal(RecommendationSource.Legacy, Assert.Single(legacyOnly).Source); - } - - [Fact] - public void Merge_EmptyInputs_ReturnsEmpty() - { - var result = RecommendationDeduper.Merge( - Array.Empty(), Array.Empty()); - Assert.Empty(result); - } - - // ---- canonical severity: engine boundaries --------------------------- - - [Theory] - [InlineData(0.0, CanonicalSeverity.Info)] - [InlineData(0.74, CanonicalSeverity.Info)] - [InlineData(0.75, CanonicalSeverity.Warning)] - [InlineData(1.49, CanonicalSeverity.Warning)] - [InlineData(1.5, CanonicalSeverity.Critical)] - [InlineData(2.0, CanonicalSeverity.Critical)] - public void FromEngineSeverity_BoundaryCases(double severity, CanonicalSeverity expected) - { - Assert.Equal(expected, RecommendationDeduper.FromEngineSeverity(severity)); - } - - // ---- RCSI card severity scales with the contention it would relieve ---- - - [Theory] - [InlineData(0, 0, CanonicalSeverity.Info)] // gated in (rw>=50) but minimal magnitude - [InlineData(9, 0, CanonicalSeverity.Info)] // just under the Warning blocking threshold - [InlineData(10, 0, CanonicalSeverity.Warning)] // notable reader/writer blocking - [InlineData(0, 1, CanonicalSeverity.Warning)] // a deadlock escalates off Info - [InlineData(99, 9, CanonicalSeverity.Warning)] // just under Critical on both axes - [InlineData(100, 0, CanonicalSeverity.Critical)] // extreme blocking - [InlineData(0, 10, CanonicalSeverity.Critical)] // many deadlocks - public void RcsiSeverityBand_ScalesWithContention(int blocking, int deadlocks, CanonicalSeverity expected) - { - // rwPct doesn't affect the band (the >=50% reader/writer gate already decided the card - // exists); the band reflects magnitude. 80 here is just a representative gated value. - var band = RecommendationsReader.RcsiSeverityBand(new RcsiInactionFigures(blocking, deadlocks, 80)); - Assert.Equal(expected, band); - } - - // ---- canonical severity: legacy text --------------------------------- - - [Theory] - [InlineData("CRITICAL", CanonicalSeverity.Critical)] - [InlineData("critical", CanonicalSeverity.Critical)] - [InlineData(" WARNING ", CanonicalSeverity.Warning)] - [InlineData("INFO", CanonicalSeverity.Info)] - [InlineData("", CanonicalSeverity.Info)] - [InlineData(null, CanonicalSeverity.Info)] - [InlineData("something-unknown", CanonicalSeverity.Info)] - public void FromLegacySeverity_TextMapping(string? severity, CanonicalSeverity expected) - { - Assert.Equal(expected, RecommendationDeduper.FromLegacySeverity(severity)); - } - - // ---- mapper-side setting derivation (feeds the de-dupe) -------------- - - [Fact] - public void SettingFromAction_DbConfigAutoShrink_MapsAutoShrink() - { - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] { new DbConfigTarget("MyDb", DbConfigSetting.AutoShrinkOff, "ON") }); - - Assert.Equal(RecommendationSetting.AutoShrink, RecommendationsReader.SettingFromAction(action)); - } - - [Fact] - public void SettingFromAction_DbConfigAutoClose_MapsAutoClose() - { - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] { new DbConfigTarget("MyDb", DbConfigSetting.AutoCloseOff, "ON") }); - - Assert.Equal(RecommendationSetting.AutoClose, RecommendationsReader.SettingFromAction(action)); - } - - [Fact] - public void SettingFromAction_RcsiFactKey_MapsRcsi() - { - var action = new RemediationAction( - "RCSI", "set", Array.Empty(), - new[] { new DbConfigTarget("MyDb", DbConfigSetting.ReadCommittedSnapshotOn, "OFF") }); - - Assert.Equal(RecommendationSetting.Rcsi, RecommendationsReader.SettingFromAction(action)); - } - - [Fact] - public void SettingFromAction_ForcePlan_MapsNone() - { - var action = new RemediationAction( - "PLAN_REGRESSION", "force", - new[] { new ForcePlanTarget("MyDb", 1, 2) }); - - Assert.Equal(RecommendationSetting.None, RecommendationsReader.SettingFromAction(action)); - } - - [Fact] - public void SettingFromAction_Null_MapsNone() - { - Assert.Equal(RecommendationSetting.None, RecommendationsReader.SettingFromAction(null)); - } - - [Theory] - [InlineData("Database Configuration", "ALTER DATABASE [x] SET AUTO_SHRINK OFF;", RecommendationSetting.AutoShrink)] - [InlineData("Database Configuration", "ALTER DATABASE [x] SET AUTO_CLOSE OFF;", RecommendationSetting.AutoClose)] - [InlineData("Query Store Configuration", "ALTER DATABASE [x] SET QUERY_STORE = ON;", RecommendationSetting.QueryStore)] - [InlineData("Query Store Configuration", "ALTER DATABASE [x] SET QUERY_STORE (OPERATION_MODE = READ_WRITE);", RecommendationSetting.QueryStore)] - public void SettingFromLegacy_ConfigArea_ParsesAlterKeyword( - string problemArea, string investigateQuery, RecommendationSetting expected) - { - Assert.Equal(expected, RecommendationsReader.SettingFromLegacy(problemArea, investigateQuery)); - } - - [Fact] - public void SettingFromLegacy_NonConfigArea_MapsNone() - { - // A memory-pressure row whose SQL incidentally mentions a keyword must NOT de-dupe: - // only the two config problem-areas are eligible. - Assert.Equal(RecommendationSetting.None, - RecommendationsReader.SettingFromLegacy("Memory", "SELECT 'AUTO_SHRINK';")); - } - - [Fact] - public void SettingFromLegacy_ConfigArea_NoKeyword_MapsNone() - { - Assert.Equal(RecommendationSetting.None, - RecommendationsReader.SettingFromLegacy("Database Configuration", "SELECT 1;")); - } - - [Fact] - public void SettingFromLegacy_ConfigArea_NullSql_MapsNone() - { - Assert.Equal(RecommendationSetting.None, - RecommendationsReader.SettingFromLegacy("Database Configuration", null)); - } - - // ---- mapper-side copy-paste + full engine mapping -------------------- - - [Fact] - public void BuildCopyPasteFromAction_DbConfig_RendersAlterStatements() - { - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] - { - new DbConfigTarget("My]Db", DbConfigSetting.AutoShrinkOff, "ON"), - new DbConfigTarget("My]Db", DbConfigSetting.AutoCloseOff, "ON") - }); - - var sql = RecommendationsReader.BuildCopyPasteFromAction(action); - - Assert.NotNull(sql); - // Identifier bracket-doubling (QUOTENAME-equivalent) is applied. - Assert.Contains("ALTER DATABASE [My]]Db] SET AUTO_SHRINK OFF;", sql); - Assert.Contains("ALTER DATABASE [My]]Db] SET AUTO_CLOSE OFF;", sql); - } - - [Fact] - public void BuildCopyPasteFromAction_ForcePlan_ReturnsNull() - { - var action = new RemediationAction( - "PLAN_REGRESSION", "force", new[] { new ForcePlanTarget("MyDb", 1, 2) }); - - Assert.Null(RecommendationsReader.BuildCopyPasteFromAction(action)); - } - - [Fact] - public void MapEngineFinding_DbConfig_CarriesSettingActionAndHash() - { - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] { new DbConfigTarget("MyDb", DbConfigSetting.AutoShrinkOff, "ON") }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = "MyDb", - Severity = 0.3, - Category = "db_config", - StoryText = "AUTO_SHRINK is on", - RootFactKey = "DB_CONFIG", - StoryPathHash = "abc123", - StoryPath = "config>db_config>MyDb", - Remediation = action - }; - - var item = RecommendationsReader.MapEngineFinding(finding); - - Assert.Equal(RecommendationSource.Engine, item.Source); - Assert.Equal(RecommendationSetting.AutoShrink, item.Setting); - Assert.Equal(CanonicalSeverity.Info, item.CanonicalSeverity); // 0.3 -> Info - Assert.Same(action, item.Remediation); - Assert.Equal("abc123", item.StoryPathHash); - Assert.Equal("config>db_config>MyDb", item.StoryPath); // carried for the mute record - Assert.NotNull(item.CopyPasteSql); - Assert.Contains("AUTO_SHRINK OFF", item.CopyPasteSql); - } - - // ---- per-(db,setting) fan-out of DB_CONFIG findings ------------------- - - [Fact] - public void MapEngineFindings_DbConfig_SingleSafeTarget_FansToPerDbCardWithSlicedApply() - { - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] { new DbConfigTarget("MyDb", DbConfigSetting.AutoShrinkOff, "ON") }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = null, // DB_CONFIG is SERVER-scoped - Severity = 0.3, - Category = "database_config", - RootFactKey = "DB_CONFIG", - StoryPathHash = "abc123", - StoryPath = "config>db_config", - Remediation = action - }; - - var item = Assert.Single(RecommendationsReader.MapEngineFindings(finding)); - - Assert.Equal(RecommendationSource.Engine, item.Source); - Assert.Equal("MyDb", item.Database); // from the target, NOT the null finding db - Assert.Equal(RecommendationSetting.AutoShrink, item.Setting); - Assert.Contains("AUTO_SHRINK", item.Title); - Assert.Contains("MyDb", item.Title); - Assert.NotNull(item.CopyPasteSql); - Assert.Contains("AUTO_SHRINK OFF", item.CopyPasteSql); - // The Apply action is sliced to exactly this one (db, setting). - Assert.NotNull(item.Remediation); - var target = Assert.Single(item.Remediation!.DbConfigTargets!); - Assert.Equal("MyDb", target.Database); - Assert.Equal(DbConfigSetting.AutoShrinkOff, target.Setting); - Assert.Equal("abc123", item.StoryPathHash); // mute key carried from the finding - } - - [Fact] - public void MapEngineFindings_DbConfig_MultipleTargets_FansOutOnePerTarget() - { - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] - { - new DbConfigTarget("Db1", DbConfigSetting.AutoShrinkOff, "ON"), - new DbConfigTarget("Db2", DbConfigSetting.AutoCloseOff, "ON"), - new DbConfigTarget("Db3", DbConfigSetting.PageVerifyChecksum, "NONE") - }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = null, - Severity = 0.3, - Category = "database_config", - RootFactKey = "DB_CONFIG", - StoryPathHash = "h", - StoryPath = "p", - Remediation = action - }; - - var items = RecommendationsReader.MapEngineFindings(finding); - - Assert.Equal(3, items.Count); - // Each card is per-(db, setting); each Apply action is sliced to one target. - Assert.All(items, i => Assert.Single(i.Remediation!.DbConfigTargets!)); - Assert.Contains(items, i => i.Database == "Db1" && i.Setting == RecommendationSetting.AutoShrink); - Assert.Contains(items, i => i.Database == "Db2" && i.Setting == RecommendationSetting.AutoClose); - Assert.Contains(items, i => i.Database == "Db3" && i.Setting == RecommendationSetting.PageVerify); - } - - [Fact] - public void MapEngineFindings_DbConfig_NoSafeTargets_FallsBackToSingleGenericCard() - { - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = null, - Severity = 0.3, - Category = "database_config", - StoryText = "config issues", - RootFactKey = "DB_CONFIG", - StoryPathHash = "h", - StoryPath = "p", - Remediation = null // e.g. only RCSI-off (not a safe target) — no safe action persisted - }; - - var item = Assert.Single(RecommendationsReader.MapEngineFindings(finding)); - Assert.Equal(RecommendationSetting.None, item.Setting); // generic advise card, never de-dupes - Assert.Null(item.Remediation); - } - - [Fact] - public void MapEngineFindings_NonDbConfig_ReturnsSingleItemUnchanged() - { - var action = new RemediationAction( - "FILE_AUTOGROWTH_PERCENT", "set", Array.Empty(), - FileGrowthTargets: new[] { new FileGrowthTarget("MyDb", "MyDb_data", 120000, 10, 512) }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = "MyDb", - Severity = 0.3, - Category = "config", - StoryText = "Large file(s) growing in percentage steps", - RootFactKey = "FILE_AUTOGROWTH_PERCENT", - StoryPathHash = "fa", - StoryPath = "fa", - Remediation = action - }; - - var item = Assert.Single(RecommendationsReader.MapEngineFindings(finding)); - Assert.Equal(RecommendationSetting.None, item.Setting); - Assert.Same(action, item.Remediation); // same single action, NOT sliced - } - - // ---- per-db RCSI fan-out of DB_CONFIG findings (destructive, consent-gated) ---- - - [Fact] - public void MapEngineFindings_DbConfig_RcsiTargets_FanToPerDbRcsiCardsWithRcsiAction() - { - // A DB_CONFIG finding whose action carries TWO per-db RCSI targets fans to TWO RCSI - // cards — each a distinct FactKey="RCSI" action (dispatches to RcsiHandler + the two- - // sided consent gate) carrying THAT db's real inaction figures. - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - DbConfigTargets: Array.Empty(), - RcsiTargets: new[] - { - new RcsiTarget("Sales", new RcsiInactionFigures(40, 2, 85)), - new RcsiTarget("Orders", new RcsiInactionFigures(12, 0, 30)) - }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = null, // DB_CONFIG is SERVER-scoped - Severity = 0.3, - Category = "database_config", - RootFactKey = "DB_CONFIG", - StoryPathHash = "h", - StoryPath = "p", - Remediation = action - }; - - var items = RecommendationsReader.MapEngineFindings(finding); - - Assert.Equal(2, items.Count); - Assert.All(items, i => - { - Assert.Equal(RecommendationSource.Engine, i.Source); - Assert.Equal(RecommendationSetting.Rcsi, i.Setting); - Assert.NotNull(i.Remediation); - Assert.Equal("RCSI", i.Remediation!.FactKey); // dispatches to RcsiHandler - Assert.NotNull(i.Remediation.RcsiFigures); // real figures for the consent dialog - Assert.Contains("READ_COMMITTED_SNAPSHOT ON", i.CopyPasteSql); - Assert.Contains(i.Database!, i.Title); // Title names the db - // The reconstructed action's single target is THIS db with the RCSI setting. - var target = Assert.Single(i.Remediation.DbConfigTargets!); - Assert.Equal(i.Database, target.Database); - Assert.Equal(DbConfigSetting.ReadCommittedSnapshotOn, target.Setting); - Assert.Equal("h", i.StoryPathHash); - }); - - var sales = Assert.Single(items, i => i.Database == "Sales"); - Assert.Equal(40, sales.Remediation!.RcsiFigures!.BlockingEvents); - Assert.Equal(2, sales.Remediation.RcsiFigures.Deadlocks); - Assert.Equal(85, sales.Remediation.RcsiFigures.ReaderWriterPct); - - var orders = Assert.Single(items, i => i.Database == "Orders"); - Assert.Equal(12, orders.Remediation!.RcsiFigures!.BlockingEvents); - Assert.Equal(0, orders.Remediation.RcsiFigures.Deadlocks); - Assert.Equal(30, orders.Remediation.RcsiFigures.ReaderWriterPct); - } - - [Fact] - public void MapEngineFindings_DbConfig_SafeAndRcsiTargets_ProduceBothSetsOfCards() - { - // One DB_CONFIG finding carrying BOTH a safe AUTO_SHRINK target and an RCSI target must - // produce a safe-setting card AND an RCSI card (the two fan-outs are independent). - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - DbConfigTargets: new[] { new DbConfigTarget("Sales", DbConfigSetting.AutoShrinkOff, "ON") }, - RcsiTargets: new[] { new RcsiTarget("Orders", new RcsiInactionFigures(12, 3, 80)) }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = null, - Severity = 0.3, - Category = "database_config", - RootFactKey = "DB_CONFIG", - StoryPathHash = "h", - StoryPath = "p", - Remediation = action - }; - - var items = RecommendationsReader.MapEngineFindings(finding); - - Assert.Equal(2, items.Count); - // The safe AUTO_SHRINK card: DB_CONFIG action, AutoShrink setting. - var safe = Assert.Single(items, i => i.Setting == RecommendationSetting.AutoShrink); - Assert.Equal("Sales", safe.Database); - Assert.Equal("DB_CONFIG", safe.Remediation!.FactKey); - Assert.Contains("AUTO_SHRINK OFF", safe.CopyPasteSql); - // The destructive RCSI card: distinct FactKey="RCSI" action with figures. - var rcsi = Assert.Single(items, i => i.Setting == RecommendationSetting.Rcsi); - Assert.Equal("Orders", rcsi.Database); - Assert.Equal("RCSI", rcsi.Remediation!.FactKey); - Assert.Equal(12, rcsi.Remediation.RcsiFigures!.BlockingEvents); - Assert.Contains("READ_COMMITTED_SNAPSHOT ON", rcsi.CopyPasteSql); - } - - [Fact] - public void EngineDbConfigFanOut_DeDupesWithLegacyPerDbRow_EngineWinsWithApply() - { - // Engine: server-scoped DB_CONFIG finding carrying an AUTO_SHRINK target for MyDb. - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - new[] { new DbConfigTarget("MyDb", DbConfigSetting.AutoShrinkOff, "ON") }); - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = null, - Severity = 0.3, - Category = "database_config", - RootFactKey = "DB_CONFIG", - StoryPathHash = "h", - StoryPath = "p", - Remediation = action - }; - var engine = RecommendationsReader.MapEngineFindings(finding); - - // Legacy: the per-db AUTO_SHRINK row the frozen proc emits for the same database. - var legacy = RecommendationsReader.MapLegacyIssue(new CriticalIssueItem - { - Severity = "WARNING", - ProblemArea = "Database Configuration", - AffectedDatabase = "MyDb", - Message = "AUTO_SHRINK is enabled", - InvestigateQuery = "ALTER DATABASE [MyDb] SET AUTO_SHRINK OFF;" - }); - - var merged = RecommendationDeduper.Merge(engine, new[] { legacy }); - - // Before this fix the engine card had Database=null → keys differed → TWO cards (the - // legacy copy-only one is what the user saw). Now they collapse to ONE engine card - // that carries the Apply action. - var item = Assert.Single(merged); - Assert.Equal(RecommendationSource.Engine, item.Source); - Assert.NotNull(item.Remediation); - } - - // ---- WS3: percent-autogrowth advisory copy-paste flows through the reader ---- - - [Fact] - public void BuildCopyPasteFromAction_FileAutogrowth_RendersModifyFileStatements() - { - var action = new RemediationAction( - "FILE_AUTOGROWTH_PERCENT", "set", System.Array.Empty(), - FileGrowthTargets: new[] - { - // Bracket-doubling is exercised on both the db and the logical file name. - new FileGrowthTarget("My]Db", "data]1", 60000, 10, 512), - new FileGrowthTarget("My]Db", "log]1", 250000, 25, 1024) - }); - - var sql = RecommendationsReader.BuildCopyPasteFromAction(action); - - Assert.NotNull(sql); - Assert.Contains("ALTER DATABASE [My]]Db] MODIFY FILE (NAME = [data]]1], FILEGROWTH = 512MB);", sql); - Assert.Contains("ALTER DATABASE [My]]Db] MODIFY FILE (NAME = [log]]1], FILEGROWTH = 1024MB);", sql); - } - - [Fact] - public void MapEngineFinding_FileAutogrowth_CarriesCopyPasteAndNoDeDupeSetting() - { - var action = new RemediationAction( - "FILE_AUTOGROWTH_PERCENT", "set", System.Array.Empty(), - FileGrowthTargets: new[] { new FileGrowthTarget("MyDb", "MyDb_data", 120000, 10, 512) }); - - var finding = new AnalysisFinding - { - ServerId = 1, - ServerName = "S", - DatabaseName = "MyDb", - Severity = 0.3, - Category = "config", - StoryText = "Large file(s) growing in percentage steps", - RootFactKey = "FILE_AUTOGROWTH_PERCENT", - StoryPathHash = "fa9000", - StoryPath = "FILE_AUTOGROWTH_PERCENT", - Remediation = action - }; - - var item = RecommendationsReader.MapEngineFinding(finding); - - // Fix + copy-paste: the copy-paste flows, but the row never de-dupes (file-level, not a - // per-DB config-setting collision) and the action stays attached. - Assert.Equal(RecommendationSetting.None, item.Setting); - Assert.Same(action, item.Remediation); - Assert.NotNull(item.CopyPasteSql); - Assert.Contains("MODIFY FILE (NAME = [MyDb_data], FILEGROWTH = 512MB);", item.CopyPasteSql); - // Headline from the authored advice block. - Assert.Equal("Large file(s) growing in percentage steps", item.Title); - } - - [Fact] - public void MapLegacyIssue_MemoryPressure_IsNoneAndAdviseOnly() - { - var issue = new CriticalIssueItem - { - Severity = "CRITICAL", - ProblemArea = "Memory", - AffectedDatabase = string.Empty, - Message = "Memory pressure detected", - InvestigateQuery = "SELECT * FROM sys.dm_os_memory_clerks;" - }; - - var item = RecommendationsReader.MapLegacyIssue(issue); - - Assert.Equal(RecommendationSource.Legacy, item.Source); - Assert.Equal(RecommendationSetting.None, item.Setting); - Assert.Equal(CanonicalSeverity.Critical, item.CanonicalSeverity); - Assert.Null(item.Remediation); - Assert.Null(item.StoryPathHash); - Assert.Null(item.StoryPath); // legacy rows have no mute concept - Assert.Null(item.Database); // empty AffectedDatabase -> null - Assert.Equal("Memory pressure detected", item.AdviceText); - Assert.Equal("SELECT * FROM sys.dm_os_memory_clerks;", item.CopyPasteSql); - } - - [Fact] - public void MapLegacyIssue_DatabaseConfiguration_AutoShrink_DerivesSetting() - { - var issue = new CriticalIssueItem - { - Severity = "WARNING", - ProblemArea = "Database Configuration", - AffectedDatabase = "MyDb", - Message = "Auto shrink is enabled", - InvestigateQuery = "ALTER DATABASE [MyDb] SET AUTO_SHRINK OFF;" - }; - - var item = RecommendationsReader.MapLegacyIssue(issue); - - Assert.Equal(RecommendationSetting.AutoShrink, item.Setting); - Assert.Equal("MyDb", item.Database); - } -} diff --git a/deprecated/Dashboard.Tests/RecommendationsViewModelTests.cs b/deprecated/Dashboard.Tests/RecommendationsViewModelTests.cs deleted file mode 100644 index 0911d4baf8..0000000000 --- a/deprecated/Dashboard.Tests/RecommendationsViewModelTests.cs +++ /dev/null @@ -1,514 +0,0 @@ -/* - * 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.Analysis; -using PerformanceMonitorDashboard.Controls; -using PerformanceMonitorDashboard.Services.Recommendations; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// WS1b-1 coverage for the PURE, WPF-free Recommendations view-model: grouping a flat -/// (already de-duped + severity-sorted) list into the -/// Critical / Warning / Info collapsible sections; selecting the single top-level -/// (loading / insufficient-data / empty / loaded); the -/// incident-vs-config affordance predicates (Open-in-Active-Queries + Ask-AI for incidents, -/// Copy-fix for config rows; Apply/Mute visibility); and the Ask-AI prompt interpolation. The -/// WPF navigation + clipboard themselves are not unit-testable (they need a running Dashboard — -/// see the PR's visual-verification note). -/// -public class RecommendationsViewModelTests -{ - // ---- builders --------------------------------------------------------- - - private static RemediationAction DbConfigAction(DbConfigSetting setting, string db = "db1") => - new( - FactKey: "DB_CONFIG", - Action: "set", - Targets: Array.Empty(), - DbConfigTargets: new[] { new DbConfigTarget(db, setting) }); - - private static RecommendationItem Item( - CanonicalSeverity severity, - RecommendationSource source = RecommendationSource.Engine, - RecommendationSetting setting = RecommendationSetting.None, - RemediationAction? remediation = null, - string? sql = null, - string title = "rec", - string? db = null, - double rawSeverity = 0.3, - string? advice = null, - DateTime? windowStartUtc = null, - DateTime? windowEndUtc = null, - string? storyHash = "hash", - string? storyPath = "root>leaf", - string incidentId = "") - { - return new RecommendationItem - { - CanonicalSeverity = severity, - RawSeverity = rawSeverity, - Source = source, - Setting = setting, - Remediation = remediation, - CopyPasteSql = sql, - Title = title, - Database = db, - AdviceText = advice, - WindowStartUtc = windowStartUtc, - WindowEndUtc = windowEndUtc, - StoryPathHash = source == RecommendationSource.Engine ? storyHash : null, - StoryPath = source == RecommendationSource.Engine ? storyPath : null, - IncidentId = incidentId - }; - } - - private static RecommendationCardViewModel Card( - RecommendationItem item, string serverName = "SRV", int utcOffsetMinutes = 0) => - new(item, serverName, utcOffsetMinutes); - - // ---- state selection -------------------------------------------------- - - [Fact] - public void Loading_SelectsLoadingState() - { - var vm = RecommendationsViewModel.Loading(); - - Assert.Equal(RecommendationsState.Loading, vm.State); - Assert.Empty(vm.Sections); - } - - [Fact] - public void FromItems_EmptyList_SelectsEmptyState() - { - var vm = RecommendationsViewModel.FromItems(Array.Empty()); - - Assert.Equal(RecommendationsState.Empty, vm.State); - Assert.Empty(vm.Sections); - Assert.Equal(0, vm.TotalCount); - } - - [Fact] - public void FromItems_NonEmptyList_SelectsLoadedState() - { - var vm = RecommendationsViewModel.FromItems(new[] { Item(CanonicalSeverity.Warning) }); - - Assert.Equal(RecommendationsState.Loaded, vm.State); - Assert.Equal(1, vm.TotalCount); - } - - [Fact] - public void InsufficientData_WithEngineMessage_UsesIt() - { - var vm = RecommendationsViewModel.InsufficientData("need 1.0 days, have 0.5 days"); - - Assert.Equal(RecommendationsState.InsufficientData, vm.State); - Assert.Equal("need 1.0 days, have 0.5 days", vm.InsufficientDataMessage); - Assert.Empty(vm.Sections); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - public void InsufficientData_WithBlankMessage_FallsBackToDefault(string? engineMessage) - { - var vm = RecommendationsViewModel.InsufficientData(engineMessage); - - Assert.Equal(RecommendationsState.InsufficientData, vm.State); - Assert.Equal(RecommendationsViewModel.DefaultInsufficientDataMessage, vm.InsufficientDataMessage); - } - - // ---- grouping --------------------------------------------------------- - - [Fact] - public void FromItems_GroupsByIncidentId() - { - // Reader-sorted (severity desc); two findings share incident "inc1", a third is its own. - var items = new[] - { - Item(CanonicalSeverity.Critical, title: "c1", rawSeverity: 1.9, incidentId: "inc1"), - Item(CanonicalSeverity.Warning, title: "w1", rawSeverity: 1.0, incidentId: "inc1"), - Item(CanonicalSeverity.Warning, title: "w2", rawSeverity: 0.9, incidentId: "inc2"), - }; - - var vm = RecommendationsViewModel.FromItems(items); - - Assert.Equal(2, vm.Sections.Count); // two incidents - Assert.Equal(2, vm.Sections[0].Count); // inc1: c1 + w1 - Assert.Equal(CanonicalSeverity.Critical, vm.Sections[0].Severity); // primary = c1 - Assert.Single(vm.Sections[1].Cards); // inc2: w2 only - Assert.Equal(3, vm.TotalCount); - } - - [Fact] - public void FromItems_NoIncidentId_EachItemIsItsOwnGroup() - { - // Legacy / pre-incident_id rows carry no id, so each is a standalone single-card group. - var items = new[] - { - Item(CanonicalSeverity.Warning, title: "w1"), - Item(CanonicalSeverity.Warning, title: "w2"), - }; - - var vm = RecommendationsViewModel.FromItems(items); - - Assert.Equal(2, vm.Sections.Count); - Assert.All(vm.Sections, s => Assert.Single(s.Cards)); - } - - [Fact] - public void FromItems_PreservesReaderOrderWithinAnIncident() - { - // The reader returns severity-desc; within an incident the order must be preserved as-is. - var items = new[] - { - Item(CanonicalSeverity.Critical, title: "first", rawSeverity: 1.9, incidentId: "inc1"), - Item(CanonicalSeverity.Critical, title: "second", rawSeverity: 1.6, incidentId: "inc1"), - Item(CanonicalSeverity.Critical, title: "third", rawSeverity: 1.51, incidentId: "inc1"), - }; - - var vm = RecommendationsViewModel.FromItems(items); - - var titles = vm.Sections[0].Cards.Select(c => c.Title).ToArray(); - Assert.Equal(new[] { "first", "second", "third" }, titles); - } - - [Fact] - public void FromItems_CriticalAndWarningExpanded_InfoCollapsed_ByDefault() - { - var items = new[] - { - Item(CanonicalSeverity.Critical, title: "c"), - Item(CanonicalSeverity.Warning, title: "w"), - Item(CanonicalSeverity.Info, title: "i"), - }; - - var vm = RecommendationsViewModel.FromItems(items); - - Assert.True(vm.Sections.Single(s => s.Severity == CanonicalSeverity.Critical).IsExpanded); - Assert.True(vm.Sections.Single(s => s.Severity == CanonicalSeverity.Warning).IsExpanded); - Assert.False(vm.Sections.Single(s => s.Severity == CanonicalSeverity.Info).IsExpanded); - } - - [Fact] - public void IncidentHeader_NamesPrimaryFindingCountAndSeverity() - { - var items = new[] - { - Item(CanonicalSeverity.Critical, title: "SQL CPU pegged", rawSeverity: 1.9, incidentId: "inc1"), - Item(CanonicalSeverity.Warning, title: "Plan regression", rawSeverity: 1.0, incidentId: "inc1"), - }; - - var vm = RecommendationsViewModel.FromItems(items); - - Assert.Equal("SQL CPU pegged · 2 findings · CRITICAL", vm.Sections[0].Header); - } - - [Fact] - public void IncidentHeader_SingleFinding_OmitsCount() - { - var items = new[] { Item(CanonicalSeverity.Warning, title: "RCSI is OFF — Sales", incidentId: "inc1") }; - - var vm = RecommendationsViewModel.FromItems(items); - - Assert.Equal("RCSI is OFF — Sales · WARNING", vm.Sections[0].Header); - } - - [Fact] - public void FromItems_FlowsServerNameAndOffsetOntoCards() - { - var item = Item( - CanonicalSeverity.Critical, - windowStartUtc: new DateTime(2026, 6, 1, 10, 0, 0, DateTimeKind.Utc), - windowEndUtc: new DateTime(2026, 6, 1, 10, 30, 0, DateTimeKind.Utc)); - - var vm = RecommendationsViewModel.FromItems(new[] { item }, "PROD-SQL-01", utcOffsetMinutes: 60); - var card = vm.Sections[0].Cards[0]; - - Assert.Equal("PROD-SQL-01", card.ServerName); - // offset 60 → window shifts +1h into server-local in the Ask-AI prompt. - Assert.Contains("11:00", card.AskAiPrompt); - Assert.Contains("11:30", card.AskAiPrompt); - } - - // ---- incident vs config affordances ----------------------------------- - - [Fact] - public void IncidentRow_ShowsOpenInActiveQueriesAndAskAi_NotCopyFix() - { - // Setting == None => incident (CPU/memory/blocking/waits/plan-regression). - var card = Card(Item(CanonicalSeverity.Critical, setting: RecommendationSetting.None)); - - Assert.True(card.IsIncident); - Assert.False(card.IsConfigFix); - Assert.True(card.ShowOpenInActiveQueries); - Assert.True(card.ShowAskAi); - Assert.False(card.ShowCopyFix); - } - - [Theory] - [InlineData(RecommendationSetting.AutoShrink)] - [InlineData(RecommendationSetting.AutoClose)] - [InlineData(RecommendationSetting.QueryStore)] - [InlineData(RecommendationSetting.Rcsi)] - [InlineData(RecommendationSetting.PageVerify)] - public void ConfigFixRow_ShowsCopyFix_NotOpenInActiveQueriesOrAskAi(RecommendationSetting setting) - { - // Setting != None => standing config-fix; carries an ALTER → Copy fix. - var card = Card(Item( - CanonicalSeverity.Warning, - setting: setting, - sql: "ALTER DATABASE [db1] SET AUTO_SHRINK OFF;")); - - Assert.False(card.IsIncident); - Assert.True(card.IsConfigFix); - Assert.False(card.ShowOpenInActiveQueries); - Assert.False(card.ShowAskAi); - Assert.True(card.ShowCopyFix); - } - - [Fact] - public void ConfigFixRow_WithoutSql_DoesNotShowCopyFix() - { - var card = Card(Item(CanonicalSeverity.Warning, setting: RecommendationSetting.Rcsi, sql: null)); - - Assert.True(card.IsConfigFix); - Assert.False(card.ShowCopyFix); - } - - [Fact] - public void IncidentRow_DoesNotShowCopyFix_EvenIfSqlSomehowPresent() - { - // Defensive: an incident never offers Copy fix regardless of CopyPasteSql. - var card = Card(Item(CanonicalSeverity.Critical, setting: RecommendationSetting.None, sql: "SELECT 1;")); - - Assert.True(card.IsIncident); - Assert.False(card.ShowCopyFix); - } - - // ---- Apply visibility (Remediation != null) --------------------------- - - [Fact] - public void ShowApply_True_OnlyWhenRemediationPresent() - { - var withAction = Card(Item( - CanonicalSeverity.Warning, - setting: RecommendationSetting.AutoShrink, - remediation: DbConfigAction(DbConfigSetting.AutoShrinkOff))); - var withoutAction = Card(Item(CanonicalSeverity.Warning, remediation: null)); - - Assert.True(withAction.ShowApply); - Assert.False(withoutAction.ShowApply); - } - - [Fact] - public void ShowApply_True_ForIncidentWithRemediation() - { - // e.g. plan-regression / clear-plan: an incident (Setting==None) that still has an action. - var card = Card(Item( - CanonicalSeverity.Critical, - setting: RecommendationSetting.None, - remediation: new RemediationAction("CLEAR_PLAN", "clear", Array.Empty()))); - - Assert.True(card.IsIncident); - Assert.True(card.ShowApply); - } - - [Fact] - public void ShowApply_False_ForLegacyRow() - { - // Legacy rows never carry a built action, so Apply is never shown. - var legacy = Card(Item(CanonicalSeverity.Critical, source: RecommendationSource.Legacy, remediation: null)); - - Assert.False(legacy.ShowApply); - } - - [Fact] - public void AutogrowthFix_ShowsCopyFixAndApply_NotIncident() - { - // FILE_AUTOGROWTH_PERCENT: Setting==None, but the action carries typed FileGrowthTargets — - // a structured standing fix. It must read as a config fix (NOT a time-bound incident) that - // offers BOTH "Copy fix" AND Apply (the MODIFY FILE FILEGROWTH change is metadata-only, - // online, non-destructive — same class as AUTO_SHRINK OFF, now handled by - // FileAutogrowthHandler). It must never get the incident affordances: a large file growing - // by a percent should offer Copy fix / Apply, never "Open in Active Queries". - var card = Card(Item( - CanonicalSeverity.Info, - setting: RecommendationSetting.None, - remediation: new RemediationAction( - "FILE_AUTOGROWTH_PERCENT", "set", Array.Empty(), - FileGrowthTargets: new[] { new FileGrowthTarget("BigDb", "BigDb_data", 51200, 10, 1024) }), - sql: "ALTER DATABASE [BigDb] MODIFY FILE (NAME = [BigDb_data], FILEGROWTH = 1024MB);")); - - Assert.False(card.IsIncident); - Assert.False(card.ShowOpenInActiveQueries); // <-- the user's exact complaint - Assert.False(card.ShowAskAi); - Assert.True(card.ShowCopyFix); // the copy-paste MODIFY FILE fix - Assert.True(card.ShowApply); // autogrowth IS Apply-able (FileAutogrowthHandler) - } - - [Fact] - public void RcsiCard_ShowsApplyAndCopyFix_NotIncident() - { - // A per-db RCSI recommendation: Setting=Rcsi (config-fix, NOT a time-bound incident) with - // a distinct FactKey="RCSI" action. It must offer Apply (-> RcsiHandler + the two-sided - // consent gate) and Copy fix (the ALTER), and never the incident affordances. - var card = Card(Item( - CanonicalSeverity.Warning, - setting: RecommendationSetting.Rcsi, - remediation: new RemediationAction( - "RCSI", "set", Array.Empty(), - new[] { new DbConfigTarget("Sales", DbConfigSetting.ReadCommittedSnapshotOn, "OFF") }, - RcsiFigures: new RcsiInactionFigures(40, 2, 85)), - sql: "ALTER DATABASE [Sales] SET READ_COMMITTED_SNAPSHOT ON;", - db: "Sales")); - - Assert.False(card.IsIncident); - Assert.True(card.IsConfigFix); - Assert.True(card.ShowApply); - Assert.True(card.ShowCopyFix); - Assert.False(card.ShowOpenInActiveQueries); - Assert.False(card.ShowAskAi); - } - - // ---- Mute visibility (Source == Engine) ------------------------------- - - [Fact] - public void ShowMute_True_ForEngineRow() - { - var engine = Card(Item(CanonicalSeverity.Warning, source: RecommendationSource.Engine)); - - Assert.True(engine.ShowMute); - } - - [Fact] - public void ShowMute_False_ForLegacyRow() - { - var legacy = Card(Item(CanonicalSeverity.Warning, source: RecommendationSource.Legacy)); - - Assert.False(legacy.ShowMute); - } - - // ---- Ask-AI prompt generation ----------------------------------------- - - [Fact] - public void BuildAskAiPrompt_InterpolatesServerTitleAndWindow() - { - var from = new DateTime(2026, 6, 1, 14, 5, 0); - var to = new DateTime(2026, 6, 1, 15, 30, 0); - - var prompt = RecommendationsViewModel.BuildAskAiPrompt("PROD\\SQL2022", "High CXPACKET waits", from, to); - - Assert.Contains("server \"PROD\\SQL2022\"", prompt); - Assert.Contains("\"High CXPACKET waits\"", prompt); - Assert.Contains("2026-06-01 14:05", prompt); - Assert.Contains("15:30", prompt); - Assert.Contains("PerformanceMonitor MCP tools", prompt); - Assert.Contains("analyze_server", prompt); - Assert.Contains("get_analysis_findings", prompt); - } - - [Fact] - public void Card_AskAiPrompt_UsesItemTitleAndServerName() - { - var item = Item( - CanonicalSeverity.Critical, - title: "Blocking storm", - windowStartUtc: new DateTime(2026, 6, 2, 9, 0, 0, DateTimeKind.Utc), - windowEndUtc: new DateTime(2026, 6, 2, 9, 15, 0, DateTimeKind.Utc)); - - var card = Card(item, serverName: "SQLBOX", utcOffsetMinutes: 0); - - Assert.Contains("server \"SQLBOX\"", card.AskAiPrompt); - Assert.Contains("\"Blocking storm\"", card.AskAiPrompt); - Assert.Contains("2026-06-02 09:00", card.AskAiPrompt); - Assert.Contains("09:15", card.AskAiPrompt); - } - - [Fact] - public void Card_AskAiPrompt_WithNoWindow_UsesNowAnchoredFallback() - { - // No producer window → a 2h band ending "now" (server-local). Just assert it renders a - // well-formed prompt (no crash, contains the fixed scaffolding + the title). - var card = Card(Item(CanonicalSeverity.Critical, title: "Memory pressure"), serverName: "S1"); - - Assert.Contains("server \"S1\"", card.AskAiPrompt); - Assert.Contains("\"Memory pressure\"", card.AskAiPrompt); - Assert.Contains("PerformanceMonitor MCP tools", card.AskAiPrompt); - } - - // ---- deep-link window passthrough ------------------------------------- - - [Fact] - public void Card_ExposesRawUtcWindow_ForDeepLink() - { - var su = new DateTime(2026, 6, 1, 10, 0, 0, DateTimeKind.Utc); - var eu = new DateTime(2026, 6, 1, 10, 30, 0, DateTimeKind.Utc); - var card = Card(Item(CanonicalSeverity.Critical, windowStartUtc: su, windowEndUtc: eu)); - - Assert.Equal(su, card.WindowStartUtc); - Assert.Equal(eu, card.WindowEndUtc); - } - - // ---- card display flags ---------------------------------------------- - - [Fact] - public void Card_DatabaseBracketed_WrapsOrCollapses() - { - var withDb = Card(Item(CanonicalSeverity.Warning, db: "Sales")); - var serverScoped = Card(Item(CanonicalSeverity.Warning, db: null)); - - Assert.True(withDb.HasDatabase); - Assert.Equal("[Sales]", withDb.DatabaseBracketed); - - Assert.False(serverScoped.HasDatabase); - Assert.Equal(string.Empty, serverScoped.DatabaseBracketed); - } - - [Theory] - [InlineData(CanonicalSeverity.Critical, "CRITICAL")] - [InlineData(CanonicalSeverity.Warning, "WARNING")] - [InlineData(CanonicalSeverity.Info, "INFO")] - public void Card_SeverityLabel_MatchesBand(CanonicalSeverity severity, string expected) - { - var card = Card(Item(severity)); - Assert.Equal(expected, card.SeverityLabel); - } - - [Fact] - public void EngineCard_ExposesMuteKeyInputs_HashAndPath() - { - // The Mute handler keys on the underlying item's StoryPathHash (the mute key) and carries - // StoryPath (the operator-facing label). Both must round-trip through the card for engine rows. - var card = Card(Item( - CanonicalSeverity.Warning, - source: RecommendationSource.Engine, - storyHash: "h-42", - storyPath: "blocking>rcsi>Sales")); - - Assert.True(card.ShowMute); - Assert.Equal("h-42", card.Item.StoryPathHash); - Assert.Equal("blocking>rcsi>Sales", card.Item.StoryPath); - } - - [Fact] - public void LegacyCard_HasNoMuteKeyInputs() - { - // Legacy rows never mute: no hash, no path, no Mute button. - var card = Card(Item(CanonicalSeverity.Warning, source: RecommendationSource.Legacy)); - - Assert.False(card.ShowMute); - Assert.Null(card.Item.StoryPathHash); - Assert.Null(card.Item.StoryPath); - } -} diff --git a/deprecated/Dashboard.Tests/RemediationApplyServiceTests.cs b/deprecated/Dashboard.Tests/RemediationApplyServiceTests.cs deleted file mode 100644 index a3b20d49c2..0000000000 --- a/deprecated/Dashboard.Tests/RemediationApplyServiceTests.cs +++ /dev/null @@ -1,865 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using PerformanceMonitor.Analysis; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard; -using PerformanceMonitorDashboard.Models; -using PerformanceMonitorDashboard.Services.Remediation; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// PR-B coverage for the gated Apply Fix orchestrator: the confirm gate (the -/// privileged handler is unreachable unless confirm() returns true), M3 fail-closed -/// server resolution, applied-but-unlogged permanent-vs-transient surfacing (LOW-2), -/// and the AlertDetailWindow view-model gating (CanApply). -/// -public class RemediationApplyServiceTests -{ - private static readonly ServerConnection Server = - new() { Id = "11111111-1111-1111-1111-111111111111", ServerName = "SQL2022", DisplayName = "Prod SQL2022" }; - - private static RemediationAction ForceAction(double regression = 7.5) => - new("PLAN_REGRESSION", "force", new List { new("AdventureWorks", 4242, 17, RegressionFactor: regression) }); - - private static RemediationApplyService BuildService( - FakeExecutor exec, - IRemediationHandler? handler = null, - Func>? classifier = null) - { - var handlers = handler is null ? new[] { (IRemediationHandler)new ForcePlanHandler() } : new[] { handler }; - var registry = new RemediationHandlerRegistry(handlers); - return new RemediationApplyService(serverManager: null!, registry, _ => exec, classifier); - } - - private static RemediationApplyService BuildServiceNoHandler(FakeExecutor exec) => - new(serverManager: null!, new RemediationHandlerRegistry(Array.Empty()), _ => exec, null); - - // ── Confirm gate ──────────────────────────────────────────────────────────── - - [Fact] - public async Task Gate_ConfirmFalse_NeverReachesHandler() - { - var exec = new FakeExecutor(); - var service = BuildService(exec); - - var report = await service.ApplyAsync( - ForceAction(), Server, previewSql: "preview", operatorIdentity: "DOM\\op", sourceAlertRef: "ref", - confirm: _ => Task.FromResult(false), CancellationToken.None); - - Assert.Equal(RemediationRunStatus.NotConfirmed, report.Status); - Assert.Empty(report.Targets); - Assert.Equal(0, exec.ForceCalls); // the privileged path was never entered - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task Gate_ConfirmTrue_ReachesHandlerExactlyOnce() - { - var exec = new FakeExecutor(); - var confirmCalls = 0; - var service = BuildService(exec); - - var report = await service.ApplyAsync( - ForceAction(), Server, "preview", "DOM\\op", "ref", - confirm: req => { confirmCalls++; return Task.FromResult(true); }, CancellationToken.None); - - Assert.Equal(1, confirmCalls); - Assert.Equal(RemediationRunStatus.Ran, report.Status); - Assert.Equal(1, exec.ForceCalls); - Assert.Equal(RemediationStatus.Success, Assert.Single(report.Targets).Status); - } - - [Fact] - public async Task Gate_ConfirmRequest_CarriesServerRegressionAndCaveat() - { - var exec = new FakeExecutor(); - var service = BuildService(exec); - RemediationConfirmRequest? captured = null; - - await service.ApplyAsync(ForceAction(regression: 9.0), Server, "preview", "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, CancellationToken.None); - - Assert.NotNull(captured); - Assert.Equal("Prod SQL2022", captured!.ServerDisplayName); - Assert.Equal("preview", captured.PreviewSql); - Assert.Equal(9.0, Assert.Single(captured.Targets).RegressionFactor); - Assert.Contains("still the better choice", RemediationConfirmRequest.StillBetterCaveat); - } - - [Fact] - public async Task Apply_NoHandler_ReturnsNoHandler_NeverConfirms() - { - var exec = new FakeExecutor(); - var service = BuildServiceNoHandler(exec); - var confirmed = false; - - var report = await service.ApplyAsync(ForceAction(), Server, "preview", "DOM\\op", "ref", - confirm: _ => { confirmed = true; return Task.FromResult(true); }, CancellationToken.None); - - Assert.Equal(RemediationRunStatus.NoHandler, report.Status); - Assert.False(confirmed); - Assert.Equal(0, exec.ForceCalls); - } - - [Fact] - public async Task Unapply_ConfirmTrue_ReachesUnforce() - { - var exec = new FakeExecutor { PriorForce = true }; - var service = BuildService(exec); - - var report = await service.UnapplyAsync(ForceAction(), Server, "DOM\\op", "ref", - confirm: _ => Task.FromResult(true), CancellationToken.None); - - Assert.Equal(RemediationRunStatus.Ran, report.Status); - Assert.True(report.IsUnapply); - Assert.Equal(1, exec.UnforceCalls); - } - - // ── Apply-only enforcement (m-1 / m-C): un-apply for SupportsUnapply==false ── - - [Fact] - public async Task Unapply_HandlerDoesNotSupport_ShortCircuits_NeverConfirms_NeverReachesHandler() - { - var exec = new FakeExecutor(); - var handler = new DbConfigHandler(); // SupportsUnapply == false - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { handler }), _ => exec, null); - - var confirmed = false; - var dbConfigAction = new RemediationAction("DB_CONFIG", "set", - Array.Empty(), - new List { new("Foo", DbConfigSetting.AutoShrinkOff, "ON") }); - - // Even if a future mis-wired caller invokes UnapplyAsync, it must fail SAFE - // (clean report, no NotSupportedException) and never confirm or mutate. - var report = await service.UnapplyAsync(dbConfigAction, Server, "DOM\\op", "ref", - confirm: _ => { confirmed = true; return Task.FromResult(true); }, CancellationToken.None); - - Assert.Equal(RemediationRunStatus.UnapplyNotSupported, report.Status); - Assert.True(report.IsUnapply); - Assert.False(confirmed); // the gate was never even shown - Assert.Equal(0, exec.SetDbCalls); - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task Apply_DbConfig_ConfirmRequest_RendersDbConfigRows_NoQueryId() - { - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new DbConfigHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - var action = new RemediationAction("DB_CONFIG", "set", Array.Empty(), - new List { new("Foo", DbConfigSetting.AutoShrinkOff, "ON") }); - - await service.ApplyAsync(action, Server, previewSql: null, "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, CancellationToken.None); - - Assert.NotNull(captured); - Assert.Equal("DB_CONFIG", captured!.FactKey); - var row = Assert.Single(captured.Targets); - Assert.Contains("AUTO_SHRINK OFF", row.StatusTitle); - Assert.True(captured.AnyActionable); // a DB_CONFIG Ok is actionable - // The fallback preview renders the ALTER statement, not sp_query_store_*. - Assert.Contains("ALTER DATABASE [Foo] SET AUTO_SHRINK OFF;", captured.PreviewSql); - Assert.DoesNotContain("sp_query_store", captured.PreviewSql); - } - - [Fact] - public async Task Apply_DbConfig_AllAlreadyDesired_NotActionable() - { - // Preflight all-AlreadyInDesiredState => AnyActionable false => Apply disabled. - var exec = new FakeExecutor(); // PreflightDbConfigAsync returns Ok by default; - // override via a handler driven by a preflight that's already-desired: - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new DbConfigHandler() }), - _ => new AlreadyDesiredExecutor(), null); - RemediationConfirmRequest? captured = null; - - var action = new RemediationAction("DB_CONFIG", "set", Array.Empty(), - new List { new("Foo", DbConfigSetting.AutoShrinkOff, "OFF") }); - - await service.ApplyAsync(action, Server, previewSql: null, "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, CancellationToken.None); - - Assert.NotNull(captured); - Assert.False(captured!.AnyActionable); - Assert.Equal(RemediationDisposition.AlreadyInDesiredState, Assert.Single(captured.Targets).Disposition); - } - - // ── LOW-2: applied-but-unlogged permanent vs transient ─────────────────────── - - [Fact] - public async Task Apply_AppliedButUnlogged_PermanentClassification_Surfaced() - { - var exec = new FakeExecutor { AuditWriteResult = false }; // force succeeds, audit INSERT fails - var classifierCalls = 0; - var service = BuildService(exec, classifier: (_, _) => { classifierCalls++; return Task.FromResult(AuditWriteFailureKind.Permanent); }); - - var report = await service.ApplyAsync(ForceAction(), Server, "preview", "DOM\\op", "ref", - confirm: _ => Task.FromResult(true), CancellationToken.None); - - var t = Assert.Single(report.Targets); - Assert.True(t.AppliedButUnlogged); - Assert.Equal(AuditWriteFailureKind.Permanent, t.AuditFailureKind); - Assert.Equal(1, classifierCalls); - } - - [Fact] - public async Task Apply_AppliedButUnlogged_TransientClassification_Surfaced() - { - var exec = new FakeExecutor { AuditWriteResult = false }; - var service = BuildService(exec, classifier: (_, _) => Task.FromResult(AuditWriteFailureKind.Transient)); - - var report = await service.ApplyAsync(ForceAction(), Server, "preview", "DOM\\op", "ref", - confirm: _ => Task.FromResult(true), CancellationToken.None); - - var t = Assert.Single(report.Targets); - Assert.True(t.AppliedButUnlogged); - Assert.Equal(AuditWriteFailureKind.Transient, t.AuditFailureKind); - } - - [Fact] - public async Task Apply_Success_AuditWritten_DoesNotClassify() - { - var exec = new FakeExecutor { AuditWriteResult = true }; - var classifierCalls = 0; - var service = BuildService(exec, classifier: (_, _) => { classifierCalls++; return Task.FromResult(AuditWriteFailureKind.Permanent); }); - - var report = await service.ApplyAsync(ForceAction(), Server, "preview", "DOM\\op", "ref", - confirm: _ => Task.FromResult(true), CancellationToken.None); - - var t = Assert.Single(report.Targets); - Assert.False(t.AppliedButUnlogged); - Assert.Equal(AuditWriteFailureKind.None, t.AuditFailureKind); - Assert.Equal(0, classifierCalls); // classifier only runs for an unlogged target - } - - // ── M3 fail-closed server resolution ───────────────────────────────────────── - - private static List Servers(params (string id, string name)[] defs) => - defs.Select(d => new ServerConnection { Id = d.id, ServerName = d.name, DisplayName = d.name }).ToList(); - - [Fact] - public void Resolve_GuidMatch_Resolves() - { - var servers = Servers(("guid-a", "SQL2022"), ("guid-b", "SQL2019")); - var r = RemediationApplyService.ResolveServer("guid-a", "SQL2022", servers); - - Assert.True(r.IsResolved); - Assert.False(r.ResolvedByName); - Assert.Equal("guid-a", r.Server!.Id); - } - - [Fact] - public void Resolve_IntIdFallback_GuidMiss_ResolvesByUniqueName() - { - // The notify-time resolver wrote the finding's int id ("3"); GetServerById misses. - var servers = Servers(("guid-a", "SQL2022"), ("guid-b", "SQL2019")); - var r = RemediationApplyService.ResolveServer("3", "SQL2022", servers); - - Assert.True(r.IsResolved); - Assert.True(r.ResolvedByName); - Assert.Equal("guid-a", r.Server!.Id); - } - - [Fact] - public void Resolve_EmptyServerId_ResolvesByUniqueName() - { - var servers = Servers(("guid-a", "SQL2022")); - var r = RemediationApplyService.ResolveServer("", "SQL2022", servers); - - Assert.True(r.IsResolved); - Assert.True(r.ResolvedByName); - } - - [Fact] - public void Resolve_AmbiguousByName_FailsClosed() - { - var servers = Servers(("guid-a", "SQL2022"), ("guid-b", "SQL2022")); - var r = RemediationApplyService.ResolveServer("3", "SQL2022", servers); - - Assert.False(r.IsResolved); - Assert.Null(r.Server); - Assert.Contains("unambiguously", r.Reason); - } - - [Fact] - public void Resolve_Unresolved_FailsClosed() - { - var servers = Servers(("guid-a", "SQL2022")); - var r = RemediationApplyService.ResolveServer("3", "GhostServer", servers); - - Assert.False(r.IsResolved); - Assert.Null(r.Server); - Assert.False(string.IsNullOrEmpty(r.Reason)); - } - - [Fact] - public void HasHandlerFor_KnownAndUnknown() - { - var service = BuildService(new FakeExecutor()); - Assert.True(service.HasHandlerFor("PLAN_REGRESSION")); - Assert.False(service.HasHandlerFor("PARAMETER_SENSITIVITY")); - Assert.False(service.HasHandlerFor(null)); - } - - // ── AlertDetailWindow view-model gating (CanApply) ─────────────────────────── - - [Fact] - public void CanApply_RequiresKnownFix_ResolvedServer_AndNotBusy() - { - // Known fix + resolved server -> enabled. - var enabled = new AlertDetailWindow.DetailItemView { ShowApply = true }; - enabled.SetServerResolved(true); - Assert.True(enabled.CanApply); - - // Resolved-but-unknown-fix (ShowApply false) -> never enabled. - var noFix = new AlertDetailWindow.DetailItemView { ShowApply = false }; - noFix.SetServerResolved(true); - Assert.False(noFix.CanApply); - - // Known fix but server unresolved (M3) -> hard-disabled. - var unresolved = new AlertDetailWindow.DetailItemView { ShowApply = true }; - unresolved.SetServerResolved(false); - Assert.False(unresolved.CanApply); - - // Mid-run -> disabled. - var busy = new AlertDetailWindow.DetailItemView { ShowApply = true }; - busy.SetServerResolved(true); - busy.BeginRun("Applying…"); - Assert.False(busy.CanApply); - } - - // ── B3 Phase 3: informed-consent request threading (B-1) ───────────────────── - // - // The confirm dialog IS the trust boundary; the service trusts the callback. PR-A - // populates the request: RequiresInformedConsent = handler.IsDestructive and, when - // destructive, the two-sided Risks (FactRiskDisclosure). The XAML acknowledge-each- - // risk RENDERING/gating is PR-B. These tests verify the request is populated - // correctly so the PR-B dialog has what it needs. - - private static RemediationAction RcsiAction() => - new("RCSI", "set", Array.Empty(), - new List { new("Foo", DbConfigSetting.ReadCommittedSnapshotOn, "OFF") }); - - private static AnalysisFinding RcsiFinding(int? rwPct = 80) => new() - { - ServerId = 1, ServerName = "SQL2022", Category = "config_issues", - StoryPath = "DB_CONFIG", StoryPathHash = "dbconfig00000099", RootFactKey = "DB_CONFIG", - DrillDown = new Dictionary - { - ["config_issues"] = new List - { - new { database = "Foo", rcsi = false, query_store = true, auto_shrink = false, - auto_close = false, page_verify = "CHECKSUM", issues = new[] { "RCSI OFF" }, - rcsi_blocking_events = 12, rcsi_deadlocks = 3, rcsi_reader_writer_pct = rwPct } - } - } - }; - - [Fact] - public async Task Apply_Destructive_Request_RequiresInformedConsent_CarriesRisks() - { - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new RcsiHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - await service.ApplyAsync(RcsiAction(), Server, previewSql: "ALTER DATABASE [Foo] SET READ_COMMITTED_SNAPSHOT ON;", - "DOM\\op", "ref", confirm: req => { captured = req; return Task.FromResult(false); }, - CancellationToken.None, finding: RcsiFinding()); - - Assert.NotNull(captured); - Assert.Equal("RCSI", captured!.FactKey); - Assert.True(captured.RequiresInformedConsent); - Assert.NotNull(captured.Risks); - Assert.NotEmpty(captured.Risks!.RisksOfChanging); - Assert.NotEmpty(captured.Risks.RisksOfNotChanging); - // The RCSI confirm row title is the friendly one (m-2), not the raw enum name. - Assert.Contains("Read Committed Snapshot Isolation", Assert.Single(captured.Targets).StatusTitle); - } - - [Fact] - public async Task Apply_NonDestructive_Request_NoConsent_NoRisks() - { - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new DbConfigHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - var action = new RemediationAction("DB_CONFIG", "set", Array.Empty(), - new List { new("Foo", DbConfigSetting.AutoShrinkOff, "ON") }); - - await service.ApplyAsync(action, Server, previewSql: null, "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, CancellationToken.None); - - Assert.NotNull(captured); - Assert.False(captured!.RequiresInformedConsent); - Assert.Null(captured.Risks); - } - - [Fact] - public async Task Apply_Destructive_WriterWriter_Risks_SayRcsiWontResolve() - { - // The honest-both-directions property survives the service threading: a low - // reader/writer pct yields the "RCSI does NOT resolve this" inaction line. - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new RcsiHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - await service.ApplyAsync(RcsiAction(), Server, previewSql: "preview", "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, - CancellationToken.None, finding: RcsiFinding(rwPct: 8)); - - Assert.Contains(captured!.Risks!.RisksOfNotChanging, r => r.Text.Contains("RCSI does NOT resolve")); - } - - // ── Clear-cached-plan: destructive request threading + reachability (PR-B) ────── - - private static RemediationAction ClearPlanAction() => - new("CLEAR_PLAN", "clear", Array.Empty(), - ClearPlanTargets: new[] { new ClearPlanTarget("AdventureWorks", "0xABCDEF0123456789", 45.0, 9.0, 5.0, "0x06") }, - ClearPlanFigures: new ClearPlanFigures(45.0, 9.0, 5.0, 62, false, false)); - - [Fact] - public async Task Apply_ClearPlan_RequiresInformedConsent_CarriesRisks_AndPerQueryTarget() - { - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new ClearPlanHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - await service.ApplyAsync(ClearPlanAction(), Server, previewSql: "DBCC FREEPROCCACHE();", - "DOM\\op", "ref", confirm: req => { captured = req; return Task.FromResult(false); }, - CancellationToken.None); - - Assert.NotNull(captured); - Assert.Equal("CLEAR_PLAN", captured!.FactKey); - Assert.True(captured.RequiresInformedConsent); - Assert.NotNull(captured.Risks); - Assert.NotEmpty(captured.Risks!.RisksOfChanging); - Assert.NotEmpty(captured.Risks.RisksOfNotChanging); - // The confirm preview carries the per-query target (the per-HANDLE list is resolved - // live at apply); it shows the query hash + the anomaly figures. - var target = Assert.Single(captured.Targets); - Assert.Contains("0xABCDEF0123456789", target.StatusTitle); - Assert.Contains("5.0x", target.StatusTitle); - // Gate refused (confirm == false): the privileged DBCC path was never entered. - Assert.Equal(0, exec.ClearPlanCalls); - } - - [Fact] - public async Task Apply_ClearPlan_ConfirmTrue_ReachesClearProcCache_NotForceOrSetDb() - { - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new ClearPlanHandler() }), _ => exec, null); - - var report = await service.ApplyAsync(ClearPlanAction(), Server, previewSql: "preview", - "DOM\\op", "ref", confirm: _ => Task.FromResult(true), CancellationToken.None); - - Assert.Equal(RemediationRunStatus.Ran, report.Status); - Assert.Equal(1, exec.ClearPlanCalls); // routed to the DBCC executor method - Assert.Equal(0, exec.ForceCalls); // NOT the force-plan path - Assert.Equal(0, exec.SetDbCalls); // NOT the always-safe DB-config path - } - - [Fact] - public async Task Apply_AlwaysSafe_DbConfig_CannotExecute_ClearPlanTarget() - { - // Cross-routing guard: an action that (illegitimately) carries CLEAR_PLAN targets but - // is keyed to the always-safe DB_CONFIG handler must NOT reach the DBCC executor. - // DbConfigHandler iterates ONLY DbConfigTargets — a CLEAR_PLAN payload is inert to it, - // and the registry would never hand a CLEAR_PLAN fact key to DbConfigHandler anyway. - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new DbConfigHandler() }), _ => exec, null); - - var crossAction = new RemediationAction("DB_CONFIG", "set", Array.Empty(), - DbConfigTargets: null, - RcsiFigures: null, - ClearPlanTargets: new[] { new ClearPlanTarget("AdventureWorks", "0xABCDEF0123456789") }); - - await service.ApplyAsync(crossAction, Server, previewSql: "preview", "DOM\\op", "ref", - confirm: _ => Task.FromResult(true), CancellationToken.None); - - Assert.Equal(0, exec.ClearPlanCalls); // the DBCC path is unreachable via DB_CONFIG - } - - // ── HARD gate-enforcement (B-1, MANDATORY): the acknowledge-each-risk predicate ── - // - // The dialog IS the trust boundary; the confirm callback returns true ONLY when the - // gate is satisfied. The dialog's exact enablement predicate is the pure, testable - // RemediationConfirmWindow.ComputeConfirmEnabled. These prove: a destructive request - // keeps Apply DISABLED until ALL risk checkboxes are checked; a subset leaves it - // disabled; un-checking any one re-disables; and the by-name ack combines (BOTH - // required for a destructive by-name target). - - [Fact] - public void Gate_Destructive_Disabled_UntilAllRiskBoxesChecked() - { - // 5 risk boxes (e.g. 3 changing + 2 not-changing). Disabled until ALL are ticked. - for (var checkedCount = 0; checkedCount < 5; checkedCount++) - { - var allChecked = checkedCount == 5; // never true in this loop (0..4) - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: allChecked, - resolvedByName: false, byNameAck: false, riskBoxCount: 5), - $"Apply must stay DISABLED with a subset ({checkedCount}/5) of risk boxes checked."); - } - - // All boxes checked -> enabled (no by-name complication). - Assert.True(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: false, byNameAck: false, riskBoxCount: 5)); - } - - [Fact] - public void Gate_Destructive_UncheckingAnyBox_ReDisables() - { - // Enabled with all checked... - Assert.True(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: false, byNameAck: false, riskBoxCount: 4)); - // ...then un-checking ANY box (allRiskBoxesChecked flips false) re-disables. - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: false, - resolvedByName: false, byNameAck: false, riskBoxCount: 4)); - } - - [Fact] - public void Gate_Destructive_ByName_RequiresBoth_RiskBoxesAndByNameAck() - { - // Risk boxes all checked but by-name NOT acked -> still disabled. - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: true, byNameAck: false, riskBoxCount: 4)); - // By-name acked but a risk box still unchecked -> still disabled. - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: false, - resolvedByName: true, byNameAck: true, riskBoxCount: 4)); - // BOTH satisfied -> enabled. - Assert.True(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: true, byNameAck: true, riskBoxCount: 4)); - } - - [Fact] - public void Gate_NotActionable_NeverEnabled_EvenWithAllConsent() - { - // Audit-absent / nothing-applyable: baseActionable false hard-blocks regardless - // of consent (the consent gate is ADDITIVE to AnyActionable, never a replacement). - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: false, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: false, byNameAck: false, riskBoxCount: 4)); - } - - [Fact] - public void Gate_Destructive_ZeroRiskBoxes_FailsClosed() - { - // FAIL CLOSED (LOW-1): a destructive (requiresConsent) request with NO rendered - // risk boxes must keep Apply DISABLED, even though allRiskBoxesChecked is vacuously - // true (List.TrueForAll on an empty list) and the base apply-ability holds. A - // future destructive handler whose disclosure is empty/null can never enable Apply - // with zero acknowledged checkboxes. - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: false, byNameAck: false, riskBoxCount: 0)); - // Still fails closed even if the (irrelevant) by-name ack is satisfied. - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: true, byNameAck: true, riskBoxCount: 0)); - // One real risk box, all checked -> enabled (the guard only blocks the empty case). - Assert.True(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: true, allRiskBoxesChecked: true, - resolvedByName: false, byNameAck: false, riskBoxCount: 1)); - } - - [Fact] - public void Gate_NonDestructive_Unaffected_ByConsentArm() - { - // A non-destructive (requiresConsent false) request ignores the risk-box arm: - // base actionable + (by-name ack if resolved-by-name) is the whole predicate, - // exactly as before Phase 3 — no regression for force-plan / always-safe. - Assert.True(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: false, allRiskBoxesChecked: false, - resolvedByName: false, byNameAck: false, riskBoxCount: 0)); - Assert.False(RemediationConfirmWindow.ComputeConfirmEnabled( - baseActionable: true, requiresConsent: false, allRiskBoxesChecked: false, - resolvedByName: true, byNameAck: false, riskBoxCount: 0)); - } - - // ── Real figures survive persistence to apply time (CRITICAL correctness) ───── - // - // The UI apply call site passes NO finding; only the persisted RemediationAction - // survives. The RCSI figures must therefore ride the action through the AlertContext - // serialize -> deserialize round-trip, so the dialog shows the REAL blocking numbers, - // not the weak-case baseline. - - [Fact] - public async Task Apply_Destructive_RealFigures_SurvivePersistence_NoFindingAtApplyTime() - { - // 1. Build the action the way AnalysisNotificationService does (finding in hand). - var finding = RcsiFinding(rwPct: 80); - var builtAction = FactRemediation.BuildRcsiAction(finding); - Assert.NotNull(builtAction); - Assert.NotNull(builtAction!.RcsiFigures); - Assert.Equal(12, builtAction.RcsiFigures!.BlockingEvents); - - // 2. Round-trip it through the persisted AlertContext (the only thing that - // survives to the UI apply call site). - var ctx = new AlertContext(); - ctx.Details.Add(new AlertDetailItem { Heading = "Enable RCSI (advanced)", IsCodeBlock = true, Remediation = builtAction }); - Assert.True(AlertContextSerializer.TryDeserialize(AlertContextSerializer.Serialize(ctx), out var round)); - var persistedAction = round.Details[0].Remediation!; - Assert.NotNull(persistedAction.RcsiFigures); - Assert.Equal(12, persistedAction.RcsiFigures!.BlockingEvents); - Assert.Equal(3, persistedAction.RcsiFigures.Deadlocks); - Assert.Equal(80, persistedAction.RcsiFigures.ReaderWriterPct); - - // 3. Apply with the PERSISTED action and NO finding (exactly the UI call site). - // The confirm request's Risks must show the REAL figures, not weak-case. - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new RcsiHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - await service.ApplyAsync(persistedAction, Server, previewSql: "preview", "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, - CancellationToken.None /* finding defaults to null — the UI apply call site */); - - Assert.NotNull(captured!.Risks); - Assert.Contains(captured.Risks!.RisksOfNotChanging, - r => r.Text.Contains("12") && r.Text.Contains("blocked-process events") && r.Text.Contains("3 deadlocks")); - Assert.Contains(captured.Risks.RisksOfNotChanging, r => r.Text.Contains("80%") && r.Text.Contains("RCSI eliminates")); - // NOT the weak-case baseline (proves the real figures reached the dialog). - Assert.DoesNotContain(captured.Risks.RisksOfNotChanging, r => r.Text.Contains("Little or no reader/writer blocking")); - } - - [Fact] - public void RcsiTargets_OnDbConfigAction_SurviveAlertContextRoundTrip_WithFigures() - { - // The per-db RCSI targets carried on a DB_CONFIG action (for the read-time card fan-out) - // must survive the AlertContext serialize -> deserialize round-trip with their figures - // intact — otherwise the Recommendations reader fans no RCSI cards after persistence. - var action = new RemediationAction( - "DB_CONFIG", "set", Array.Empty(), - DbConfigTargets: new[] { new DbConfigTarget("Sales", DbConfigSetting.AutoShrinkOff, "ON") }, - RcsiTargets: new[] - { - new RcsiTarget("Sales", new RcsiInactionFigures(40, 2, 85)), - new RcsiTarget("Orders", new RcsiInactionFigures(12, 0, null)) - }); - - var ctx = new AlertContext(); - ctx.Details.Add(new AlertDetailItem { Heading = "DB config", IsCodeBlock = true, Remediation = action }); - Assert.True(AlertContextSerializer.TryDeserialize(AlertContextSerializer.Serialize(ctx), out var round)); - var persisted = round.Details[0].Remediation!; - - // Safe target preserved... - Assert.Single(persisted.DbConfigTargets!); - // ...and the two RCSI targets with their figures. - Assert.Equal(2, persisted.RcsiTargets!.Count); - var sales = Assert.Single(persisted.RcsiTargets, t => t.Database == "Sales"); - Assert.Equal(40, sales.Figures.BlockingEvents); - Assert.Equal(2, sales.Figures.Deadlocks); - Assert.Equal(85, sales.Figures.ReaderWriterPct); - var orders = Assert.Single(persisted.RcsiTargets, t => t.Database == "Orders"); - Assert.Equal(12, orders.Figures.BlockingEvents); - Assert.Null(orders.Figures.ReaderWriterPct); // nullable pct round-trips as null - } - - [Fact] - public async Task Apply_Destructive_NoFiguresNoFinding_ShowsWeakCaseBaseline() - { - // Genuinely no data: an action WITHOUT figures + no finding -> weak-case baseline. - var bareAction = RcsiAction(); // built without RcsiFigures - Assert.Null(bareAction.RcsiFigures); - var exec = new FakeExecutor(); - var service = new RemediationApplyService(serverManager: null!, - new RemediationHandlerRegistry(new IRemediationHandler[] { new RcsiHandler() }), _ => exec, null); - RemediationConfirmRequest? captured = null; - - await service.ApplyAsync(bareAction, Server, previewSql: "preview", "DOM\\op", "ref", - confirm: req => { captured = req; return Task.FromResult(false); }, CancellationToken.None); - - Assert.Contains(captured!.Risks!.RisksOfNotChanging, r => r.Text.Contains("Little or no reader/writer blocking")); - } - - // ── Fake executor (PR-B-local) ─────────────────────────────────────────────── - - private sealed class FakeExecutor : IRemediationExecutor - { - public bool AuditTableExists = true; - public bool PriorForce = true; - public bool AuditWriteResult = true; - - public int ForceCalls; - public int UnforceCalls; - public readonly List AuditRecords = new(); - - public Task PreflightForcePlanAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(new TargetPreflight - { - Database = database, QueryId = queryId, PlanId = planId, - CurrentDatabase = database, HasAlter = true, QueryStoreState = "READ_WRITE", - PlanPresent = true, ExecutingLogin = "PerfMonLogin" - }); - - public Task AuditTableExistsAsync(CancellationToken ct) => Task.FromResult(AuditTableExists); - public Task HasPriorForceAsync(string database, long queryId, long planId, CancellationToken ct) => Task.FromResult(PriorForce); - - public Task ForcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - { - ForceCalls++; - return Task.FromResult(new ForcePlanOutcome - { - Database = database, QueryId = queryId, PlanId = planId, - Status = RemediationStatus.Success, Forced = true, ExecutingLogin = "PerfMonLogin", GateSpid = 55, ExecSpid = 55 - }); - } - - public Task UnforcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - { - UnforceCalls++; - return Task.FromResult(new ForcePlanOutcome - { - Database = database, QueryId = queryId, PlanId = planId, - Status = RemediationStatus.Success, Forced = true, ExecutingLogin = "PerfMonLogin", GateSpid = 55, ExecSpid = 55 - }); - } - - public int SetDbCalls; - - public Task PreflightDbConfigAsync(string database, DbConfigSetting setting, CancellationToken ct) - => Task.FromResult(new DbConfigPreflight - { - Database = database, Setting = setting, DatabaseExists = true, HasAlter = true, - AlreadyInDesiredState = false, ExecutingLogin = "PerfMonLogin", CurrentValue = "ON" - }); - - public Task SetDatabaseOptionAsync(string database, DbConfigSetting setting, RemediationIdentity identity, CancellationToken ct) - { - SetDbCalls++; - return Task.FromResult(new DbConfigOutcome - { - Database = database, Setting = setting, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "PerfMonLogin", PriorValue = "ON", GeneratedSql = "ALTER DATABASE [x] SET AUTO_SHRINK OFF;", - GateSpid = 55, ExecSpid = 55 - }); - } - - public int ClearPlanCalls; - - public Task ClearProcCacheAsync(string queryHash, RemediationIdentity identity, CancellationToken ct) - { - ClearPlanCalls++; - return Task.FromResult(new ClearPlanOutcome - { - QueryHash = queryHash, Status = RemediationStatus.Success, Cleared = true, HandlesCleared = 1, - ExecutingLogin = "PerfMonLogin", Message = "Cleared 1 cached plan(s).", - GeneratedSql = "DBCC FREEPROCCACHE(0xDEADBEEF);", PriorValue = "1 plan(s) cached for this query hash", - GateSpid = 55, ExecSpid = 55 - }); - } - - public int SetFileCalls; - - public Task PreflightFileGrowthAsync(string database, string logicalFileName, int growthMb, CancellationToken ct) - => Task.FromResult(new FileGrowthPreflight - { - Database = database, LogicalFileName = logicalFileName, RecommendedGrowthMb = growthMb, - DatabaseExists = true, FileExists = true, HasAlter = true, AlreadyInDesiredState = false, - ExecutingLogin = "PerfMonLogin", CurrentValue = "percent" - }); - - public Task SetFileGrowthAsync(string database, string logicalFileName, int growthMb, RemediationIdentity identity, CancellationToken ct) - { - SetFileCalls++; - return Task.FromResult(new FileGrowthOutcome - { - Database = database, LogicalFileName = logicalFileName, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "PerfMonLogin", PriorValue = "percent", - GeneratedSql = $"ALTER DATABASE [{database}] MODIFY FILE (NAME = [{logicalFileName}], FILEGROWTH = {growthMb}MB);", - GateSpid = 55, ExecSpid = 55 - }); - } - - public int SetServerConfigCalls; - - public Task PreflightServerConfigAsync(ServerConfigSetting setting, long recommendedValue, CancellationToken ct) - => Task.FromResult(new ServerConfigPreflight - { - Setting = setting, RecommendedValue = recommendedValue, - Executable = setting is ServerConfigSetting.Maxdop or ServerConfigSetting.CostThreshold, - HasPermission = true, AlreadyInDesiredState = false, ExecutingLogin = "PerfMonLogin", CurrentValue = 0 - }); - - public Task SetServerConfigAsync(ServerConfigSetting setting, long value, RemediationIdentity identity, CancellationToken ct) - { - SetServerConfigCalls++; - return Task.FromResult(new ServerConfigOutcome - { - Setting = setting, Status = RemediationStatus.Success, Applied = true, ExecutingLogin = "PerfMonLogin", - PriorValue = 0, GeneratedSql = "EXEC sys.sp_configure N'show advanced options', 1; RECONFIGURE; EXEC sys.sp_configure N'max degree of parallelism', @value; RECONFIGURE;", - GateSpid = 55, ExecSpid = 55 - }); - } - - public Task WriteAuditAsync(RemediationAuditRecord record, CancellationToken ct) - { - AuditRecords.Add(record); - return Task.FromResult(AuditWriteResult); - } - } - - /// Executor whose DB-config preflight always reports already-in-desired-state. - private sealed class AlreadyDesiredExecutor : IRemediationExecutor - { - public Task PreflightForcePlanAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(new TargetPreflight { Database = database }); - public Task AuditTableExistsAsync(CancellationToken ct) => Task.FromResult(true); - public Task HasPriorForceAsync(string database, long queryId, long planId, CancellationToken ct) => Task.FromResult(false); - public Task ForcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ForcePlanOutcome { Database = database }); - public Task UnforcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ForcePlanOutcome { Database = database }); - public Task PreflightDbConfigAsync(string database, DbConfigSetting setting, CancellationToken ct) - => Task.FromResult(new DbConfigPreflight - { - Database = database, Setting = setting, DatabaseExists = true, HasAlter = true, - AlreadyInDesiredState = true, ExecutingLogin = "PerfMonLogin", CurrentValue = "OFF" - }); - public Task SetDatabaseOptionAsync(string database, DbConfigSetting setting, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new DbConfigOutcome { Database = database, Setting = setting, Status = RemediationStatus.Skipped }); - public Task ClearProcCacheAsync(string queryHash, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ClearPlanOutcome { QueryHash = queryHash, Status = RemediationStatus.Skipped }); - public Task PreflightFileGrowthAsync(string database, string logicalFileName, int growthMb, CancellationToken ct) - => Task.FromResult(new FileGrowthPreflight - { - Database = database, LogicalFileName = logicalFileName, RecommendedGrowthMb = growthMb, - DatabaseExists = true, FileExists = true, HasAlter = true, AlreadyInDesiredState = true, - ExecutingLogin = "PerfMonLogin", CurrentValue = "percent" - }); - public Task SetFileGrowthAsync(string database, string logicalFileName, int growthMb, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new FileGrowthOutcome { Database = database, LogicalFileName = logicalFileName, Status = RemediationStatus.Skipped }); - public Task PreflightServerConfigAsync(ServerConfigSetting setting, long recommendedValue, CancellationToken ct) - => Task.FromResult(new ServerConfigPreflight - { - Setting = setting, RecommendedValue = recommendedValue, - Executable = setting is ServerConfigSetting.Maxdop or ServerConfigSetting.CostThreshold, - HasPermission = true, AlreadyInDesiredState = true, ExecutingLogin = "PerfMonLogin", CurrentValue = recommendedValue - }); - public Task SetServerConfigAsync(ServerConfigSetting setting, long value, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ServerConfigOutcome { Setting = setting, Status = RemediationStatus.Skipped }); - public Task WriteAuditAsync(RemediationAuditRecord record, CancellationToken ct) => Task.FromResult(true); - } -} diff --git a/deprecated/Dashboard.Tests/RemediationContractTests.cs b/deprecated/Dashboard.Tests/RemediationContractTests.cs deleted file mode 100644 index 05071cb2a3..0000000000 --- a/deprecated/Dashboard.Tests/RemediationContractTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Linq; -using PerformanceMonitorDashboard.Services.Remediation; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Contract between the remediation BUILDERS (FactRemediation.Build*Action and the recommendations -/// reader) and the registered HANDLERS. Every Apply-able RemediationAction carries a FactKey, and -/// RemediationApplyService dispatches on it; a FactKey with no registered handler makes Apply -/// silently no-op — the "shipped half-built" failure class. These tests fail loudly if the handler -/// set drifts from the agreed Apply-able key set, forcing a conscious update whenever a builder or -/// handler is added or removed. -/// -/// Scope note: this locks the HANDLER side (registry integrity + the documented Apply-able set). -/// The complementary dynamic check — feeding real detector drill-down output through each builder -/// and asserting it still yields a non-null, dispatchable action (the autogrowth-CTE-drift class) — -/// lives in (the captured-fixture golden-sample). -/// -public class RemediationContractTests -{ - // The agreed Apply-able fact keys. Each is produced by a FactRemediation builder or the - // recommendations reader: PLAN_REGRESSION, DB_CONFIG, FILE_AUTOGROWTH_PERCENT and SERVER_CONFIG - // are always-safe; RCSI and CLEAR_PLAN are destructive (behind the informed-consent gate). - // Adding or removing a builder/handler? Update this list deliberately — that is the contract. - private static readonly string[] ApplyableFactKeys = - { - "PLAN_REGRESSION", - "DB_CONFIG", - "FILE_AUTOGROWTH_PERCENT", - "SERVER_CONFIG", - "RCSI", - "CLEAR_PLAN", - }; - - [Fact] - public void DefaultHandlers_HaveDistinctNonEmptyFactKeys() - { - var keys = RemediationApplyService.CreateDefaultHandlers().Select(h => h.FactKey).ToList(); - - Assert.DoesNotContain(keys, string.IsNullOrWhiteSpace); - Assert.Equal(keys.Count, keys.Distinct().Count()); // no two handlers claim the same key - } - - [Fact] - public void HandlerFactKeys_ExactlyMatch_ApplyableContract() - { - var handlerKeys = RemediationApplyService.CreateDefaultHandlers() - .Select(h => h.FactKey) - .ToHashSet(); - - var orphanBuilderKeys = ApplyableFactKeys.Except(handlerKeys).ToList(); // builder key, no handler -> silent no-op - var deadHandlerKeys = handlerKeys.Except(ApplyableFactKeys).ToList(); // handler, no producing builder -> dead - - Assert.True(orphanBuilderKeys.Count == 0, - $"Apply-able fact key(s) with NO registered handler (Apply would silently no-op): {string.Join(", ", orphanBuilderKeys)}"); - Assert.True(deadHandlerKeys.Count == 0, - $"Registered handler(s) with no Apply-able builder key (dead handler / contract drift): {string.Join(", ", deadHandlerKeys)}"); - } - - [Fact] - public void EveryApplyableFactKey_ResolvesThroughTheRegistry() - { - // The registry is the actual dispatch point used by RunAsync; prove each contract key - // resolves through it exactly as production constructs it. - var registry = new RemediationHandlerRegistry(RemediationApplyService.CreateDefaultHandlers()); - - foreach (var key in ApplyableFactKeys) - Assert.True(registry.TryGet(key) is not null, $"No handler resolves for Apply-able fact key '{key}'."); - } -} diff --git a/deprecated/Dashboard.Tests/RemediationGoldenSampleTests.cs b/deprecated/Dashboard.Tests/RemediationGoldenSampleTests.cs deleted file mode 100644 index c8c7bc1805..0000000000 --- a/deprecated/Dashboard.Tests/RemediationGoldenSampleTests.cs +++ /dev/null @@ -1,320 +0,0 @@ -/* - * 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.Collections.Generic; -using System.Linq; -using PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Services.Remediation; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// The DYNAMIC golden-sample half of the remediation contract — the follow-up named in -/// 's scope note. It feeds a representative detector -/// drill-down — shaped to match what the drill-down COLLECTORS actually emit -/// (SqlServerDrillDownCollector on Dashboard / DrillDownCollector on Lite, with the -/// shared extractors reading it) — through each builder in the EXACT -/// order AnalysisService.AnalyzeAsync applies them, and asserts the builder yields a -/// non-null action, carrying its target list, whose FactKey resolves through the production -/// handler registry. -/// -/// -/// This is the "autogrowth-CTE-drift" guard at the dynamic level: if a builder stops reading a -/// drill-down key the detector emits (a rename, a typo, an extractor refactor), the action comes -/// back null or target-less and the matching test fails loudly — instead of Apply silently -/// no-opping in production. locks the STATIC -/// handler<->key set; this locks that real drill-down still flows through to a DISPATCHABLE -/// action, and that every registered Apply-able key has a fixture proving it. -/// -/// -/// -/// Residual limitation (documented, not silently accepted): the fixtures are captured from the -/// collector emit at authoring time (each cites its emit site). They catch BUILDER-side drift -/// immediately; a future COLLECTOR-side key rename is caught only when these fixtures are -/// regenerated against the new emit — the fixtures ARE the contract, so keep them in sync with the -/// cited emit sites. (A drill-down key-name constant set shared by collector and builder would make -/// this automatic; that is a larger refactor, out of scope here.) -/// -/// -public class RemediationGoldenSampleTests -{ - // The production dispatch point (RemediationApplyService builds the v1 registry from this). - private static readonly RemediationHandlerRegistry Registry = - new(RemediationApplyService.CreateDefaultHandlers()); - - /// - /// A built action is "dispatchable" when it is non-null, carries the expected fact key, and - /// that key resolves through the production handler registry — i.e. Apply will route to a real - /// handler instead of silently no-opping (RemediationRunStatus.NoHandler). - /// - private static void AssertDispatchable(RemediationAction? action, string expectedFactKey) - { - Assert.NotNull(action); - Assert.Equal(expectedFactKey, action!.FactKey); - Assert.NotNull(Registry.TryGet(action.FactKey)); - } - - // ── PLAN_REGRESSION → BuildAction → FactKey "PLAN_REGRESSION" (ForcePlanHandler) ────────────── - // Drill-down: SqlServerDrillDownCollector "regressed_queries"; read by ExtractPlanRegressionTargets - // (database / query_id / best_plan_id / *_plan_hash / *_cpu_per_exec_us / regression_factor). - private static AnalysisFinding PlanRegression() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "plan_regression", - StoryPath = "PLAN_REGRESSION", StoryPathHash = "golden_planreg01", - RootFactKey = "PLAN_REGRESSION", - DrillDown = new Dictionary - { - ["regressed_queries"] = new List - { - new - { - database = "AdventureWorks", query_id = 4242L, best_plan_id = 17L, - latest_plan_hash = "0xDEAD", best_plan_hash = "0xBEEF", - latest_cpu_per_exec_us = 9000.0, best_cpu_per_exec_us = 1200.0, - regression_factor = 7.5 - } - } - } - }; - - [Fact] - public void PlanRegression_DrillDown_BuildsDispatchableForceAction() - { - var action = FactRemediation.BuildAction(PlanRegression()); - AssertDispatchable(action, "PLAN_REGRESSION"); - Assert.NotEmpty(action!.Targets); - } - - // ── DB_CONFIG → BuildAction → FactKey "DB_CONFIG" (DbConfigHandler) ──────────────────────────── - // Drill-down: SqlServerDrillDownCollector "config_issues"; read by ExtractDbConfigTargets - // (database / auto_shrink / auto_close / page_verify — the structured typed fields, never the - // human "issues" strings). - private static AnalysisFinding DbConfig() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "config_issues", - StoryPath = "DB_CONFIG", StoryPathHash = "golden_dbconfig1", - RootFactKey = "DB_CONFIG", - DrillDown = new Dictionary - { - ["config_issues"] = new List - { - new - { - database = "Foo", recovery_model = "FULL", rcsi = true, query_store = true, - issues = new[] { "auto_shrink ON" }, - auto_shrink = true, auto_close = false, page_verify = "CHECKSUM" - } - } - } - }; - - [Fact] - public void DbConfig_DrillDown_BuildsDispatchableSetAction() - { - var action = FactRemediation.BuildAction(DbConfig()); - AssertDispatchable(action, "DB_CONFIG"); - Assert.NotNull(action!.DbConfigTargets); - Assert.NotEmpty(action.DbConfigTargets!); - } - - // ── RCSI → BuildRcsiAction → FactKey "RCSI" (RcsiHandler, destructive) ───────────────────────── - // Drill-down: SqlServerDrillDownCollector "config_issues" with rcsi == false + the §3.3 - // enrichment (rcsi_blocking_events / rcsi_deadlocks / rcsi_reader_writer_pct) and a - // reader/writer share above FactRiskDisclosure.ReaderWriterMeaningfulPct; read by CollectRcsiTargets. - private static AnalysisFinding RcsiOff() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "config_issues", - StoryPath = "DB_CONFIG", StoryPathHash = "golden_rcsioff01", - RootFactKey = "DB_CONFIG", - DrillDown = new Dictionary - { - ["config_issues"] = new List - { - new - { - database = "Foo", recovery_model = "FULL", rcsi = false, query_store = true, - issues = new[] { "RCSI OFF" }, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - rcsi_blocking_events = 12, rcsi_deadlocks = 3, rcsi_reader_writer_pct = 80 - } - } - } - }; - - [Fact] - public void Rcsi_DrillDown_BuildsDispatchableRcsiAction() - { - var action = FactRemediation.BuildRcsiAction(RcsiOff()); - AssertDispatchable(action, "RCSI"); - Assert.NotNull(action!.DbConfigTargets); - Assert.Equal(DbConfigSetting.ReadCommittedSnapshotOn, action.DbConfigTargets!.Single().Setting); - } - - // ── CLEAR_PLAN → BuildClearPlanAction → FactKey "CLEAR_PLAN" (ClearPlanHandler, destructive) ──── - // Drill-down: SqlServerDrillDownCollector "abnormal_cpu_plans" on a CPU finding; read by - // BuildClearPlanAction (query_hash 0x… / database / current+baseline_cpu_per_exec_ms / - // anomaly_ratio / cpu_percent / *_cofired / latest_plan_handle). - private static AnalysisFinding ClearPlan() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "cpu", - StoryPath = "CPU_SQL_PERCENT", StoryPathHash = "golden_clearpln1", - RootFactKey = "CPU_SQL_PERCENT", - DrillDown = new Dictionary - { - ["abnormal_cpu_plans"] = new List - { - new - { - query_hash = "0x1A2B3C4D5E6F7080", database = "Foo", - current_cpu_per_exec_ms = 500.0, baseline_cpu_per_exec_ms = 50.0, - anomaly_ratio = 10.0, cpu_percent = 40, - latest_plan_handle = "0x06000100ABCDEF", - plan_regression_cofired = false, parameter_sensitivity_cofired = false - } - } - } - }; - - [Fact] - public void ClearPlan_DrillDown_BuildsDispatchableClearAction() - { - var action = FactRemediation.BuildClearPlanAction(ClearPlan()); - AssertDispatchable(action, "CLEAR_PLAN"); - Assert.NotNull(action!.ClearPlanTargets); - Assert.NotEmpty(action.ClearPlanTargets!); - } - - // ── FILE_AUTOGROWTH_PERCENT → BuildFileAutogrowthAction → FactKey "FILE_AUTOGROWTH_PERCENT" - // (FileAutogrowthHandler) ───────────────────────────────────────────────────────────────── - // Drill-down: SqlServerDrillDownCollector "autogrowth_percent_files"; read by - // ExtractFileGrowthTargets (database / logical_file_name / total_size_mb / growth_pct / file_type). - // This is the canonical "CTE-drift" sentinel: if the collector's CTE column → drill-down key - // mapping drifts from these names, the builder yields no targets and this fails. - private static AnalysisFinding FileAutogrowth() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "config_issues", - StoryPath = "FILE_AUTOGROWTH_PERCENT", StoryPathHash = "golden_autogro01", - RootFactKey = "FILE_AUTOGROWTH_PERCENT", - DrillDown = new Dictionary - { - ["autogrowth_percent_files"] = new List - { - new - { - database = "Foo", logical_file_name = "Foo_data", file_type = "ROWS", - total_size_mb = 51200.0, growth_pct = 10 - } - } - } - }; - - [Fact] - public void FileAutogrowth_DrillDown_BuildsDispatchableSetAction() - { - var action = FactRemediation.BuildFileAutogrowthAction(FileAutogrowth()); - AssertDispatchable(action, "FILE_AUTOGROWTH_PERCENT"); - Assert.NotNull(action!.FileGrowthTargets); - Assert.NotEmpty(action.FileGrowthTargets!); - } - - // ── SERVER_CONFIG → BuildServerConfigAction → FactKey "SERVER_CONFIG" (ServerConfigHandler) ───── - // Drill-down: SqlServerDrillDownCollector "server_config" on a CONFIG_* finding; read by - // ExtractServerConfigTargets (setting maxdop/ctfp/max_memory/min_memory / current_value / - // edition / cores_per_socket). - private static AnalysisFinding ServerConfig() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "config", - StoryPath = "SERVER_CONFIG → CONFIG_MAXDOP", StoryPathHash = "golden_srvconf01", - RootFactKey = "CONFIG_MAXDOP", - DrillDown = new Dictionary - { - ["server_config"] = new List - { - new { setting = "maxdop", current_value = 0L, edition = 3, cores_per_socket = 16 } - } - } - }; - - [Fact] - public void ServerConfig_DrillDown_BuildsDispatchableSetAction() - { - var action = FactRemediation.BuildServerConfigAction(ServerConfig()); - AssertDispatchable(action, "SERVER_CONFIG"); - Assert.NotNull(action!.ServerConfigTargets); - Assert.Equal(ServerConfigSetting.Maxdop, action.ServerConfigTargets!.Single().Setting); - } - - // ── MISSING_INDEX → BuildMissingIndexAction → FactKey "MISSING_INDEX" (WS4; COPY-ONLY) ───────── - // The drill-down → builder drift guard for the one COPY-PASTE-ONLY advisory: a non-null action - // carrying its CREATE-statement targets, but deliberately NOT registry-dispatchable — creating an - // index is a judgement call, so there is no handler and no Apply (the reader renders the CREATE as - // copy-paste and leaves the card's Remediation null). Drill-down: SqlServerDrillDownCollector / - // Lite DrillDownCollector "missing_indexes" ({ table, impact, create_statement }). - private static AnalysisFinding MissingIndex() => new() - { - ServerId = 1, ServerName = "GoldenServer", Category = "missing_index", - StoryPath = "MISSING_INDEX", StoryPathHash = "golden_missidx01", - RootFactKey = "MISSING_INDEX", - DrillDown = new Dictionary - { - ["missing_indexes"] = new List - { - new - { - table = "dbo.Orders", impact = 87.3, - create_statement = "CREATE NONCLUSTERED INDEX [ix_Orders_CustomerId] ON [dbo].[Orders] ([CustomerId]);" - } - } - } - }; - - [Fact] - public void MissingIndex_DrillDown_BuildsCopyOnlyAdvisoryAction_NotDispatchable() - { - var action = FactRemediation.BuildMissingIndexAction(MissingIndex()); - Assert.NotNull(action); - Assert.Equal("MISSING_INDEX", action!.FactKey); - Assert.NotNull(action.MissingIndexTargets); - Assert.NotEmpty(action.MissingIndexTargets!); - // Copy-only: NO handler resolves it — the reader surfaces copy-paste and shows no Apply. - Assert.Null(Registry.TryGet(action.FactKey)); - } - - // ── Completeness: every registered Apply-able key has a golden fixture ───────────────────────── - [Fact] - public void EveryRegisteredHandlerKey_IsExercisedByAGoldenFixture() - { - // Every key the production registry dispatches must have a golden fixture proving real - // drill-down still flows through to a dispatchable action. A new Apply-able handler with no - // golden fixture here fails loudly — the dynamic complement to RemediationContractTests' - // static handler<->key check, which forces a fixture whenever the Apply-able surface grows. - var handlerKeys = RemediationApplyService.CreateDefaultHandlers() - .Select(h => h.FactKey) - .ToHashSet(); - - // Each builder is invoked exactly as AnalysisService.AnalyzeAsync orders the chain. - var produced = new[] - { - FactRemediation.BuildAction(PlanRegression()), - FactRemediation.BuildAction(DbConfig()), - FactRemediation.BuildRcsiAction(RcsiOff()), - FactRemediation.BuildClearPlanAction(ClearPlan()), - FactRemediation.BuildFileAutogrowthAction(FileAutogrowth()), - FactRemediation.BuildServerConfigAction(ServerConfig()), - } - .Where(a => a is not null) - .Select(a => a!.FactKey) - .ToHashSet(); - - var uncovered = handlerKeys.Except(produced).ToList(); - Assert.True(uncovered.Count == 0, - "Registered Apply-able handler key(s) with NO golden-sample fixture producing a " + - $"dispatchable action: {string.Join(", ", uncovered)}"); - } -} diff --git a/deprecated/Dashboard.Tests/RemediationTests.cs b/deprecated/Dashboard.Tests/RemediationTests.cs deleted file mode 100644 index f93adb321e..0000000000 --- a/deprecated/Dashboard.Tests/RemediationTests.cs +++ /dev/null @@ -1,2074 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Services; -using PerformanceMonitorDashboard.Services.Remediation; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// PR-A coverage for the privileged "Apply Fix" core (no UI): the structured -/// extractor + render-stability, the self-gating handler against a faked executor -/// (fail-closed permission, audit-table hard block, freshness/skip dispositions, -/// per-target independence, gate re-derivation, applied-but-unlogged), un-apply -/// restriction, the registry, and the "no caller reaches the executor" guard. -/// The single-connection (R2-MOD-1) guarantee is an executor-level/real-server -/// concern (SPID equality) and cannot be proven against a faked executor. -/// -public class RemediationTests -{ - private static AnalysisFinding PlanRegressionFinding(List? rows = null) => new() - { - ServerId = 1, - ServerName = "TestServer", - Category = "plan_regression", - StoryPath = "PLAN_REGRESSION", - StoryPathHash = "planreg000000001", - RootFactKey = "PLAN_REGRESSION", - DrillDown = new Dictionary - { - ["regressed_queries"] = rows ?? new List - { - new - { - database = "AdventureWorks", - query_id = 4242L, - best_plan_id = 17L, - latest_plan_hash = "0xDEAD", - best_plan_hash = "0xBEEF", - latest_cpu_per_exec_us = 9000.0, - best_cpu_per_exec_us = 1200.0, - regression_factor = 7.5 - } - } - } - }; - - private static RemediationAction ForceAction(params ForcePlanTarget[] targets) => - new("PLAN_REGRESSION", "force", targets.ToList()); - - private static ForcePlanTarget Target(string db = "AdventureWorks", long q = 4242, long p = 17) => - new(db, q, p); - - private static readonly RemediationIdentity Identity = - new("TESTDOMAIN\\tester", "Analysis: plan_regression [abcd1234]"); - - [Fact] - public void Extract_SkipsRowsFailingGuards() - { - var finding = PlanRegressionFinding(new List - { - new { database = "", query_id = 1L, best_plan_id = 1L }, - new { database = "Db", query_id = 0L, best_plan_id = 1L }, - new { database = "Db", query_id = 1L, best_plan_id = 0L }, - new { database = "Good", query_id = 5L, best_plan_id = 9L } - }); - - var targets = FactRemediation.ExtractPlanRegressionTargets(finding); - - var only = Assert.Single(targets); - Assert.Equal("Good", only.Database); - Assert.Equal(5, only.QueryId); - Assert.Equal(9, only.PlanId); - } - - [Fact] - public void Extract_CapsAtFiveTargets() - { - var rows = Enumerable.Range(1, 8) - .Select(i => (object)new { database = $"Db{i}", query_id = (long)i, best_plan_id = (long)(i + 100) }) - .ToList(); - - var targets = FactRemediation.ExtractPlanRegressionTargets(PlanRegressionFinding(rows)); - - Assert.Equal(5, targets.Count); - Assert.Equal("Db1", targets[0].Database); - Assert.Equal("Db5", targets[4].Database); - } - - [Fact] - public void BuildAction_PlanRegression_ProducesForceActionWithTargets() - { - var action = FactRemediation.BuildAction(PlanRegressionFinding()); - - Assert.NotNull(action); - Assert.Equal("PLAN_REGRESSION", action!.FactKey); - Assert.Equal("force", action.Action); - var t = Assert.Single(action.Targets); - Assert.Equal("AdventureWorks", t.Database); - Assert.Equal(4242, t.QueryId); - Assert.Equal(17, t.PlanId); - Assert.Equal(7.5, t.RegressionFactor); - } - - [Fact] - public void BuildAction_ParameterSensitivity_ReturnsNull() - { - var finding = PlanRegressionFinding(); - finding.RootFactKey = "PARAMETER_SENSITIVITY"; - Assert.Null(FactRemediation.BuildAction(finding)); - } - - [Fact] - public void BuildAction_UnknownKeyOrNoTargets_ReturnsNull() - { - var unknown = PlanRegressionFinding(); - unknown.RootFactKey = "ZZZ_TEST"; - Assert.Null(FactRemediation.BuildAction(unknown)); - - Assert.Null(FactRemediation.BuildAction(PlanRegressionFinding(new List()))); - } - - [Fact] - public void GenerateForFinding_RenderStability_ByteForByte() - { - const string expected = - "-- Database: AdventureWorks\n" + - "-- query_id = 4242, forcing plan_id = 17\n" + - "-- latest plan hash: 0xDEAD (cpu/exec 9000 us)\n" + - "-- best plan hash: 0xBEEF (cpu/exec 1200 us)\n" + - "-- regression factor: 7.5x\n" + - "USE [AdventureWorks];\n" + - "EXEC sys.sp_query_store_force_plan @query_id = 4242, @plan_id = 17;\n" + - "\n" + - "-- To back out:\n" + - "-- EXEC sys.sp_query_store_unforce_plan @query_id = 4242, @plan_id = 17;"; - - var actual = FactRemediation.GenerateForFinding(PlanRegressionFinding()); - - Assert.NotNull(actual); - Assert.Equal(expected, actual!.Replace("\r\n", "\n")); - } - - [Fact] - public void Registry_ResolvesForcePlanHandler_AndMissesUnknown() - { - var registry = new RemediationHandlerRegistry(new IRemediationHandler[] { new ForcePlanHandler() }); - - Assert.IsType(registry.TryGet("PLAN_REGRESSION")); - Assert.Null(registry.TryGet("PARAMETER_SENSITIVITY")); - Assert.Null(registry.TryGet(null)); - } - - [Fact] - public async Task Apply_Success_ForcesAndWritesSuccessAudit() - { - var exec = new FakeExecutor(); - var result = await new ForcePlanHandler().ApplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - - var outcome = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, outcome.Status); - Assert.True(outcome.AuditWritten); - Assert.False(outcome.AppliedButUnlogged); - Assert.Equal(1, exec.ForceCalls); - - var row = Assert.Single(exec.AuditRecords); - Assert.Equal("force", row.Action); - Assert.Equal("success", row.Result); - Assert.Equal("TESTDOMAIN\\tester", row.OperatorIdentity); - Assert.Contains("sp_query_store_force_plan", row.GeneratedSql); - } - - [Fact] - public async Task Apply_HasAlterZero_FailsClosed_NoElevation_AuditSkipped() - { - var exec = new FakeExecutor - { - ForceFunc = (db, q, p) => new ForcePlanOutcome - { - Database = db, QueryId = q, PlanId = p, - Status = RemediationStatus.PermissionDenied, Forced = false, Message = "lacks ALTER" - } - }; - - var result = await new ForcePlanHandler().ApplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - - var outcome = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.PermissionDenied, outcome.Status); - Assert.False(outcome.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - Assert.Equal(1, exec.ForceCalls); - } - - [Fact] - public async Task Apply_AuditTableAbsent_HardBlocks_NoMutation_NoAuditNoUnloggedWarning() - { - var exec = new FakeExecutor { AuditTableExists = false }; - - var result = await new ForcePlanHandler().ApplyAsync( - ForceAction(Target(), Target("Other", 9, 9)), exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.False(o.AuditWritten); - Assert.False(o.AppliedButUnlogged); - Assert.Contains("3.0.0", o.Message); - }); - Assert.Equal(0, exec.ForceCalls); - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task Apply_Skipped_IsNotForced_AndAuditedSkipped() - { - var exec = new FakeExecutor - { - ForceFunc = (db, q, p) => new ForcePlanOutcome - { - Database = db, QueryId = q, PlanId = p, Status = RemediationStatus.Skipped, Forced = false, Message = "already forced" - } - }; - - var result = await new ForcePlanHandler().ApplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - - var outcome = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Skipped, outcome.Status); - Assert.False(outcome.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - } - - [Fact] - public async Task Apply_GateChangesAfterPreflight_AbortsTarget() - { - var exec = new FakeExecutor - { - PreflightFunc = (db, q, p) => new TargetPreflight - { - Database = db, QueryId = q, PlanId = p, - CurrentDatabase = db, HasAlter = true, QueryStoreState = "READ_WRITE", - PlanPresent = true, IsForcedPlan = false, ForceFailureCount = 0 - }, - ForceFunc = (db, q, p) => new ForcePlanOutcome - { - Database = db, QueryId = q, PlanId = p, Status = RemediationStatus.Skipped, Forced = false, Message = "plan vanished" - } - }; - - var handler = new ForcePlanHandler(); - var pre = await handler.PreflightAsync(ForceAction(Target()), exec, CancellationToken.None); - Assert.Equal(RemediationDisposition.Ok, pre.Targets.Single().Disposition); - - var result = await handler.ApplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - Assert.NotEqual(RemediationStatus.Success, result.Outcomes.Single().Status); - } - - [Fact] - public async Task Apply_OneTargetThrows_OthersStillRun() - { - var exec = new FakeExecutor - { - ForceFunc = (db, q, p) => - { - if (q == 1) throw new InvalidOperationException("boom"); - return new ForcePlanOutcome { Database = db, QueryId = q, PlanId = p, Status = RemediationStatus.Success, Forced = true }; - } - }; - - var result = await new ForcePlanHandler().ApplyAsync( - ForceAction(Target("A", 1, 1), Target("B", 2, 2)), exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.Equal(RemediationStatus.Error, result.Outcomes[0].Status); - Assert.Equal(RemediationStatus.Success, result.Outcomes[1].Status); - } - - [Fact] - public async Task Apply_ForceSucceedsButAuditWriteFails_FlagsAppliedButUnlogged() - { - var exec = new FakeExecutor { AuditWriteResult = false }; - - var result = await new ForcePlanHandler().ApplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - - var outcome = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, outcome.Status); - Assert.False(outcome.AuditWritten); - Assert.True(outcome.AppliedButUnlogged); - } - - [Theory] - [InlineData("Other", true, "READ_WRITE", true, false, 0, RemediationDisposition.BlockWrongDatabase)] - [InlineData("AdventureWorks", false, "READ_WRITE", true, false, 0, RemediationDisposition.BlockNoAlter)] - [InlineData("AdventureWorks", true, "READ_ONLY", true, false, 0, RemediationDisposition.BlockQueryStoreOff)] - [InlineData("AdventureWorks", true, "READ_WRITE", false, false, 0, RemediationDisposition.BlockStale)] - [InlineData("AdventureWorks", true, "READ_WRITE", true, true, 0, RemediationDisposition.AlreadyForced)] - [InlineData("AdventureWorks", true, "READ_WRITE", true, false, 3, RemediationDisposition.WarnFailing)] - [InlineData("AdventureWorks", true, "READ_WRITE", true, false, 0, RemediationDisposition.Ok)] - public async Task Preflight_ClassifiesDisposition( - string currentDb, bool hasAlter, string qsState, bool planPresent, bool isForced, long failCount, RemediationDisposition expected) - { - var exec = new FakeExecutor - { - PreflightFunc = (db, q, p) => new TargetPreflight - { - Database = db, QueryId = q, PlanId = p, - CurrentDatabase = currentDb, HasAlter = hasAlter, QueryStoreState = qsState, - PlanPresent = planPresent, IsForcedPlan = isForced, ForceFailureCount = failCount - } - }; - - var pre = await new ForcePlanHandler().PreflightAsync(ForceAction(Target()), exec, CancellationToken.None); - Assert.Equal(expected, pre.Targets.Single().Disposition); - } - - [Fact] - public async Task Preflight_AuditTableAbsent_OverridesPerTargetDisposition() - { - var exec = new FakeExecutor - { - AuditTableExists = false, - PreflightFunc = (db, q, p) => new TargetPreflight - { - Database = db, QueryId = q, PlanId = p, - CurrentDatabase = db, HasAlter = true, QueryStoreState = "READ_WRITE", PlanPresent = true - } - }; - - var pre = await new ForcePlanHandler().PreflightAsync(ForceAction(Target()), exec, CancellationToken.None); - Assert.False(pre.AuditTableExists); - Assert.Equal(RemediationDisposition.BlockAuditTableAbsent, pre.Targets.Single().Disposition); - } - - [Fact] - public async Task Unapply_NoPriorForce_Skips_NoUnforce() - { - var exec = new FakeExecutor { PriorForce = false }; - - var result = await new ForcePlanHandler().UnapplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - - Assert.Equal(RemediationStatus.Skipped, result.Outcomes.Single().Status); - Assert.Equal(0, exec.UnforceCalls); - } - - [Fact] - public async Task Unapply_WithPriorForce_Unforces_AuditsUnforce() - { - var exec = new FakeExecutor { PriorForce = true }; - - var result = await new ForcePlanHandler().UnapplyAsync(ForceAction(Target()), exec, Identity, CancellationToken.None); - - Assert.Equal(RemediationStatus.Success, result.Outcomes.Single().Status); - Assert.Equal(1, exec.UnforceCalls); - Assert.Equal("unforce", Assert.Single(exec.AuditRecords).Action); - } - - // ════════════════════════════════════════════════════════════════════════════ - // B3 Phase 2 — always-safe DB-config fixes (DB_CONFIG) - // ════════════════════════════════════════════════════════════════════════════ - - private static AnalysisFinding DbConfigFinding(List? rows = null) => new() - { - ServerId = 1, - ServerName = "TestServer", - Category = "config_issues", - StoryPath = "DB_CONFIG", - StoryPathHash = "dbconfig00000001", - RootFactKey = "DB_CONFIG", - DrillDown = new Dictionary - { - ["config_issues"] = rows ?? new List - { - new { database = "Foo", recovery_model = "FULL", rcsi = true, query_store = true, - issues = new[] { "auto_shrink ON", "auto_close ON" }, - auto_shrink = true, auto_close = true, page_verify = "CHECKSUM" } - } - } - }; - - private static RemediationAction DbConfigAction(params DbConfigTarget[] targets) => - new("DB_CONFIG", "set", Array.Empty(), targets.ToList()); - - // ── Extractor: only the three safe settings, NEVER RCSI ────────────────────── - - [Fact] - public void ExtractDbConfig_EmitsOnlySafeSettings_NeverRcsi() - { - var finding = DbConfigFinding(new List - { - new { database = "Db1", rcsi = false, query_store = false, - auto_shrink = true, auto_close = true, page_verify = "NONE", - issues = new[] { "auto_shrink ON", "auto_close ON", "RCSI OFF", "page_verify=NONE" } } - }); - - var targets = FactRemediation.ExtractDbConfigTargets(finding); - - // 3 safe targets (shrink, close, page_verify) — RCSI is NEVER emitted. - Assert.Equal(3, targets.Count); - Assert.Contains(targets, t => t.Setting == DbConfigSetting.AutoShrinkOff && t.CurrentValue == "ON"); - Assert.Contains(targets, t => t.Setting == DbConfigSetting.AutoCloseOff && t.CurrentValue == "ON"); - Assert.Contains(targets, t => t.Setting == DbConfigSetting.PageVerifyChecksum && t.CurrentValue == "NONE"); - // No enum value for RCSI exists, but assert defensively none slipped through as page_verify. - Assert.All(targets, t => Assert.True(Enum.IsDefined(typeof(DbConfigSetting), t.Setting))); - } - - [Fact] - public void ExtractDbConfig_PageVerifyChecksum_IsNotEmitted() - { - var finding = DbConfigFinding(new List - { - new { database = "Db1", rcsi = true, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new string[0] } - }); - - Assert.Empty(FactRemediation.ExtractDbConfigTargets(finding)); - } - - [Fact] - public void ExtractDbConfig_EmptyDatabase_IsSkipped() - { - var finding = DbConfigFinding(new List - { - new { database = "", rcsi = true, query_store = true, auto_shrink = true, auto_close = false, page_verify = "CHECKSUM", issues = new string[0] } - }); - - Assert.Empty(FactRemediation.ExtractDbConfigTargets(finding)); - } - - [Fact] - public void ExtractDbConfig_MultipleDatabases_MultipleTargets() - { - var finding = DbConfigFinding(new List - { - new { database = "A", rcsi = true, query_store = true, auto_shrink = true, auto_close = false, page_verify = "CHECKSUM", issues = new string[0] }, - new { database = "B", rcsi = true, query_store = true, auto_shrink = false, auto_close = false, page_verify = "TORN_PAGE_DETECTION", issues = new string[0] } - }); - - var targets = FactRemediation.ExtractDbConfigTargets(finding); - Assert.Equal(2, targets.Count); - Assert.Equal("A", targets[0].Database); - Assert.Equal(DbConfigSetting.AutoShrinkOff, targets[0].Setting); - Assert.Equal("B", targets[1].Database); - Assert.Equal(DbConfigSetting.PageVerifyChecksum, targets[1].Setting); - Assert.Equal("TORN_PAGE_DETECTION", targets[1].CurrentValue); - } - - [Fact] - public void BuildAction_DbConfig_OnlyRcsi_ReturnsNull() - { - // A DB whose only issue is RCSI OFF yields no safe target → no action → no Apply button. - var finding = DbConfigFinding(new List - { - new { database = "Db1", rcsi = false, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "RCSI OFF" } } - }); - - Assert.Null(FactRemediation.BuildAction(finding)); - } - - [Fact] - public void BuildAction_DbConfig_ProducesSetActionWithTargets() - { - var action = FactRemediation.BuildAction(DbConfigFinding()); - - Assert.NotNull(action); - Assert.Equal("DB_CONFIG", action!.FactKey); - Assert.Equal("set", action.Action); - Assert.Empty(action.Targets); // force-plan list is empty for DB_CONFIG - Assert.NotNull(action.DbConfigTargets); - Assert.Equal(2, action.DbConfigTargets!.Count); // shrink + close - } - - // ── Render-stability golden (incl. "was X" + RCSI-excluded note) ───────────── - - [Fact] - public void GenerateForFinding_DbConfig_RenderStability_ByteForByte() - { - var finding = DbConfigFinding(new List - { - new { database = "Foo", rcsi = false, query_store = true, - auto_shrink = true, auto_close = true, page_verify = "NONE", - issues = new[] { "auto_shrink ON", "auto_close ON", "RCSI OFF", "page_verify=NONE" } } - }); - - const string expected = - "-- Database: Foo\n" + - "ALTER DATABASE [Foo] SET AUTO_SHRINK OFF; -- was ON\n" + - "ALTER DATABASE [Foo] SET AUTO_CLOSE OFF; -- was ON\n" + - "ALTER DATABASE [Foo] SET PAGE_VERIFY CHECKSUM; -- was NONE\n" + - "-- NOTE: [Foo] also has RCSI OFF — intentionally NOT auto-fixed (test on a copy first)."; - - var actual = FactRemediation.GenerateForFinding(finding); - Assert.NotNull(actual); - Assert.Equal(expected, actual!.Replace("\r\n", "\n")); - } - - // ── Handler: audit-absent hard block, fail-closed, freshness-skip, db-not-found, success ── - - [Fact] - public async Task DbConfig_AuditTableAbsent_HardBlocks_NoMutation_NoAudit() - { - var exec = new FakeExecutor { AuditTableExists = false }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON"), - new DbConfigTarget("Bar", DbConfigSetting.AutoCloseOff, "ON")), - exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.False(o.AuditWritten); - Assert.Contains("3.0.0", o.Message); - }); - Assert.Equal(0, exec.SetDbCalls); - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task DbConfig_PermissionDenied_FailsClosed_AuditSkipped() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.PermissionDenied, Applied = false, - Message = "lacks ALTER", PriorValue = "ON" - } - }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.PermissionDenied, o.Status); - Assert.False(o.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - Assert.Equal(1, exec.SetDbCalls); - } - - [Fact] - public async Task DbConfig_AlreadyDesired_Skips_NoMutationFlag_AuditSkipped() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.Skipped, Applied = false, - Message = "already desired", PriorValue = "OFF" - } - }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "OFF")), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Skipped, o.Status); - Assert.False(o.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - } - - [Fact] - public async Task DbConfig_DatabaseNotFound_Blocks_AuditAborted() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.Blocked, Applied = false, - Message = "not found", PriorValue = null - } - }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Gone", DbConfigSetting.AutoShrinkOff, "ON")), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.Equal("aborted", Assert.Single(exec.AuditRecords).Result); - } - - [Fact] - public async Task DbConfig_Success_AppliesAndAudits_NullIds_PriorValue_PreciseAction() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "sa", PriorValue = "ON", - GeneratedSql = "ALTER DATABASE [Foo] SET AUTO_SHRINK OFF;", GateSpid = 7, ExecSpid = 7 - } - }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.True(o.AuditWritten); - Assert.False(o.AppliedButUnlogged); - - var row = Assert.Single(exec.AuditRecords); - Assert.Equal("DB_CONFIG", row.FactKey); - Assert.Equal("set_auto_shrink_off", row.Action); // precise taxonomy (24/19/18 chars) - Assert.Equal("success", row.Result); - Assert.Null(row.QueryId); // B-1: DB_CONFIG rows have no IDs - Assert.Null(row.PlanId); - Assert.Equal("ON", row.PriorValue); - Assert.Contains("ALTER DATABASE", row.GeneratedSql); - } - - [Fact] - public async Task DbConfig_AppliesButAuditFails_FlagsAppliedButUnlogged() - { - var exec = new FakeExecutor { AuditWriteResult = false }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.False(o.AuditWritten); - Assert.True(o.AppliedButUnlogged); - } - - [Fact] - public async Task DbConfig_OneTargetThrows_OthersStillRun() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => - { - if (db == "A") throw new InvalidOperationException("boom"); - return new DbConfigOutcome { Database = db, Setting = s, Status = RemediationStatus.Success, Applied = true, PriorValue = "ON" }; - } - }; - - var result = await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("A", DbConfigSetting.AutoShrinkOff, "ON"), - new DbConfigTarget("B", DbConfigSetting.AutoCloseOff, "ON")), - exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.Equal(RemediationStatus.Error, result.Outcomes[0].Status); - Assert.Equal(RemediationStatus.Success, result.Outcomes[1].Status); - } - - [Fact] - public async Task DbConfig_PreciseTaxonomy_AllThreeSettings() - { - var exec = new FakeExecutor(); - await new DbConfigHandler().ApplyAsync( - DbConfigAction( - new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON"), - new DbConfigTarget("Foo", DbConfigSetting.AutoCloseOff, "ON"), - new DbConfigTarget("Foo", DbConfigSetting.PageVerifyChecksum, "NONE")), - exec, Identity, CancellationToken.None); - - var actions = exec.AuditRecords.Select(r => r.Action).ToList(); - Assert.Contains("set_auto_shrink_off", actions); - Assert.Contains("set_auto_close_off", actions); - Assert.Contains("set_page_verify_checksum", actions); // 24 chars — needs varchar(32) + param(32) - } - - // ── Preflight dispositions ─────────────────────────────────────────────────── - - [Theory] - [InlineData(false, true, false, RemediationDisposition.BlockDatabaseNotFound)] - [InlineData(true, false, false, RemediationDisposition.BlockNoAlter)] - [InlineData(true, true, true, RemediationDisposition.AlreadyInDesiredState)] - [InlineData(true, true, false, RemediationDisposition.Ok)] - public async Task DbConfig_Preflight_ClassifiesDisposition(bool exists, bool hasAlter, bool alreadyDesired, RemediationDisposition expected) - { - var exec = new FakeExecutor - { - DbPreflightFunc = (db, s) => new DbConfigPreflight - { - Database = db, Setting = s, DatabaseExists = exists, HasAlter = hasAlter, - AlreadyInDesiredState = alreadyDesired, CurrentValue = "ON" - } - }; - - var pre = await new DbConfigHandler().PreflightAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), exec, CancellationToken.None); - Assert.Equal(expected, pre.Targets.Single().Disposition); - } - - [Fact] - public async Task DbConfig_Preflight_AuditTableAbsent_OverridesDisposition() - { - var exec = new FakeExecutor { AuditTableExists = false }; - - var pre = await new DbConfigHandler().PreflightAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), exec, CancellationToken.None); - - Assert.False(pre.AuditTableExists); - Assert.Equal(RemediationDisposition.BlockAuditTableAbsent, pre.Targets.Single().Disposition); - } - - // ── Apply-only enforcement (m-1) + SupportsUnapply ─────────────────────────── - - [Fact] - public void DbConfig_SupportsUnapply_IsFalse_NotDestructive() - { - var handler = new DbConfigHandler(); - Assert.False(handler.SupportsUnapply); - Assert.False(handler.IsDestructive); - } - - [Fact] - public async Task DbConfig_UnapplyAsync_Throws() - { - await Assert.ThrowsAsync(() => - new DbConfigHandler().UnapplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), new FakeExecutor(), Identity, CancellationToken.None)); - } - - [Fact] - public void CoreMachineryMarkers_CoverNewPrivilegedSurface() - { - // M-2: the reachability guard must list the new handler + executor methods, - // or a future UI/MCP file referencing them would silently pass the guard. - Assert.Contains("DbConfigHandler", CoreMachineryMarkers); - Assert.Contains("SetDatabaseOptionAsync", CoreMachineryMarkers); - Assert.Contains("PreflightDbConfigAsync", CoreMachineryMarkers); - } - - [Fact] - public void Registry_ResolvesDbConfigHandler() - { - var registry = new RemediationHandlerRegistry(new IRemediationHandler[] { new ForcePlanHandler(), new DbConfigHandler() }); - Assert.IsType(registry.TryGet("DB_CONFIG")); - Assert.IsType(registry.TryGet("PLAN_REGRESSION")); - } - - [Fact] - public void Rcsi_Handler_IsRegistered_AndReachableThroughGate() - { - // PR-B makes RCSI LIVE: the PRODUCTION wiring registers RcsiHandler so the Apply - // affordance can appear and route to the destructive handler — but ONLY through - // the gated RemediationApplyService facade (proven by the Gate_* behavioural tests - // and the reachability guards CoreMachinery_OnlyReferencedInRemediationCore + - // GatedEntry_ReferencedOnlyBySanctionedUiPath). - var productionRegistry = new RemediationHandlerRegistry( - new IRemediationHandler[] { new ForcePlanHandler(), new DbConfigHandler(), new RcsiHandler() }); - Assert.IsType(productionRegistry.TryGet("RCSI")); - - // Assert at the source level that the PRODUCTION wiring now constructs RcsiHandler. - var dir = FindDashboardSourceDir(); - var serviceSrc = File.ReadAllText(Path.Combine(dir, "Services", "Remediation", "RemediationApplyService.cs")); - Assert.Contains("new RcsiHandler()", serviceSrc); - - // The always-safe DbConfigHandler still routes ONLY DB_CONFIG — never RCSI — so - // the two affordances can never cross at the registry/handler layer. - Assert.IsType(productionRegistry.TryGet("DB_CONFIG")); - Assert.NotEqual("RCSI", productionRegistry.TryGet("DB_CONFIG")!.FactKey); - } - - [Fact] - public void CoreMachineryMarkers_Include_RcsiHandler() - { - // m-3: the destructive handler must be in the reachability guard. - Assert.Contains("RcsiHandler", CoreMachineryMarkers); - } - - // ════════════════════════════════════════════════════════════════════════════ - // B3 PHASE 3 — RCSI destructive-consent privileged core (PR-A; UNREGISTERED) - // ════════════════════════════════════════════════════════════════════════════ - - /// A DB_CONFIG finding with RCSI OFF + the §3.3 enrichment present. - private static AnalysisFinding RcsiOffFinding(int blocking = 12, int deadlocks = 3, int? rwPct = 80, string db = "Foo") => new() - { - ServerId = 1, - ServerName = "TestServer", - Category = "config_issues", - StoryPath = "DB_CONFIG", - StoryPathHash = "dbconfig00000099", - RootFactKey = "DB_CONFIG", - DrillDown = new Dictionary - { - ["config_issues"] = new List - { - new { database = db, recovery_model = "FULL", rcsi = false, query_store = true, - issues = new[] { "RCSI OFF" }, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - rcsi_blocking_events = blocking, rcsi_deadlocks = deadlocks, - rcsi_reader_writer_pct = rwPct } - } - } - }; - - private static RemediationAction RcsiAction(string db = "Foo") => - new("RCSI", "set", Array.Empty(), new[] { new DbConfigTarget(db, DbConfigSetting.ReadCommittedSnapshotOn, "OFF") }); - - // ── RcsiHandler invariants ─────────────────────────────────────────────────── - - [Fact] - public void Rcsi_Handler_IsDestructive_And_ApplyOnly() - { - var handler = new RcsiHandler(); - Assert.Equal("RCSI", handler.FactKey); - Assert.True(handler.IsDestructive); // the first (and only) true in the codebase - Assert.False(handler.SupportsUnapply); - } - - [Fact] - public async Task Rcsi_UnapplyAsync_Throws() - { - await Assert.ThrowsAsync(() => - new RcsiHandler().UnapplyAsync(RcsiAction(), new FakeExecutor(), Identity, CancellationToken.None)); - } - - // ── Executor RCSI arm: own builder, no-injection, same-string (against the - // executor's OWN BuildAlterStatement — not the display renderer) ─────────── - - [Fact] - public void Rcsi_Build_SetClause_IsHardcodedLiteral_RegardlessOfName() - { - foreach (var name in new[] { "Db", "Db]; DROP TABLE x--", "[weird]", "Ünîçödé" }) - { - var stmt = DatabaseService.BuildAlterStatement(name, DbConfigSetting.ReadCommittedSnapshotOn); - Assert.EndsWith("SET READ_COMMITTED_SNAPSHOT ON;", stmt); - } - } - - [Theory] - [InlineData("normal")] - [InlineData("has]bracket")] - [InlineData("has]]double")] - [InlineData("ev;il-- GO DROP")] - [InlineData("'; ALTER DATABASE master SET")] - public void Rcsi_Build_BracketsIdentifierInert_NoInjection(string name) - { - var stmt = DatabaseService.BuildAlterStatement(name, DbConfigSetting.ReadCommittedSnapshotOn); - var expectedToken = "[" + name.Replace("]", "]]") + "]"; - Assert.Equal($"ALTER DATABASE {expectedToken} SET READ_COMMITTED_SNAPSHOT ON;", stmt); - } - - [Fact] - public void Rcsi_Build_SameString_ValidatedNameIsBracketedExactly() - { - const string validated = " Padded Name "; - var stmt = DatabaseService.BuildAlterStatement(validated, DbConfigSetting.ReadCommittedSnapshotOn); - Assert.Equal("ALTER DATABASE [ Padded Name ] SET READ_COMMITTED_SNAPSHOT ON;", stmt); - Assert.NotEqual(stmt, DatabaseService.BuildAlterStatement(validated.TrimEnd(), DbConfigSetting.ReadCommittedSnapshotOn)); - } - - [Fact] - public void Rcsi_SetClause_ExecutorAndService_AreReadCommittedSnapshotOn() - { - // m-1: all clause-builder copies render the RCSI arm (executor's own builder). - Assert.EndsWith("SET READ_COMMITTED_SNAPSHOT ON;", - DatabaseService.BuildAlterStatement("X", DbConfigSetting.ReadCommittedSnapshotOn)); - } - - [Fact] - public void Rcsi_SettingTitle_IsFriendly_NotRawEnumName() - { - // m-2: a RCSI confirm row must not render "ReadCommittedSnapshotOn". - Assert.Equal("Read Committed Snapshot Isolation", - DbConfigHandler.SettingTitle(DbConfigSetting.ReadCommittedSnapshotOn)); - } - - // ── RcsiHandler apply behaviours against the faked executor ────────────────── - - [Fact] - public async Task Rcsi_AuditTableAbsent_HardBlocks_NoMutation_NoAudit() - { - var exec = new FakeExecutor { AuditTableExists = false }; - var result = await new RcsiHandler().ApplyAsync(RcsiAction(), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.False(o.AuditWritten); - Assert.Equal(0, exec.SetDbCalls); - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task Rcsi_PermissionDenied_FailsClosed_NoElevation() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.PermissionDenied, Applied = false, - Message = "lacks ALTER", PriorValue = "OFF" - } - }; - var result = await new RcsiHandler().ApplyAsync(RcsiAction(), exec, Identity, CancellationToken.None); - - Assert.Equal(RemediationStatus.PermissionDenied, Assert.Single(result.Outcomes).Status); - Assert.Equal(1, exec.SetDbCalls); - } - - [Fact] - public async Task Rcsi_AlreadyOn_Skips_ConsentAcknowledgedStillTrue() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.Skipped, Applied = false, - Message = "already on", PriorValue = "ON", GateSpid = 7, ExecSpid = 7 - } - }; - var result = await new RcsiHandler().ApplyAsync(RcsiAction(), exec, Identity, CancellationToken.None); - - Assert.Equal(RemediationStatus.Skipped, Assert.Single(result.Outcomes).Status); - var rec = Assert.Single(exec.AuditRecords); - Assert.Equal("skipped", rec.Result); - Assert.True(rec.ConsentAcknowledged); // gate was satisfied to reach apply - Assert.Equal("RCSI", rec.FactKey); - Assert.Equal("set_rcsi_on", rec.Action); - } - - [Fact] - public async Task Rcsi_Success_WritesAudit_ConsentAcknowledgedTrue_PriorValueOff() - { - var exec = new FakeExecutor - { - SetDbFunc = (db, s) => new DbConfigOutcome - { - Database = db, Setting = s, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "sa", PriorValue = "OFF", - GeneratedSql = "ALTER DATABASE [Foo] SET READ_COMMITTED_SNAPSHOT ON;", GateSpid = 9, ExecSpid = 9 - } - }; - var result = await new RcsiHandler().ApplyAsync(RcsiAction(), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.True(o.AuditWritten); - var rec = Assert.Single(exec.AuditRecords); - Assert.True(rec.ConsentAcknowledged); - Assert.Equal("OFF", rec.PriorValue); - Assert.Equal("success", rec.Result); - } - - [Fact] - public async Task DbConfig_And_ForcePlan_WriteConsentAcknowledgedFalse() - { - // Regression-guard: the non-destructive paths must persist consent_acknowledged = 0. - var exec = new FakeExecutor(); - await new DbConfigHandler().ApplyAsync( - DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), exec, Identity, CancellationToken.None); - Assert.All(exec.AuditRecords, r => Assert.False(r.ConsentAcknowledged)); - - var exec2 = new FakeExecutor(); - await new ForcePlanHandler().ApplyAsync( - new RemediationAction("PLAN_REGRESSION", "force", new List { Target() }), - exec2, Identity, CancellationToken.None); - Assert.All(exec2.AuditRecords, r => Assert.False(r.ConsentAcknowledged)); - } - - // ── BuildRcsiAction (M2-1 boolean polarity) + BuildAction regression-guard ─── - - [Fact] - public void BuildRcsiAction_EmitsOnRcsiOff_WithEnrichment() - { - var action = FactRemediation.BuildRcsiAction(RcsiOffFinding()); - Assert.NotNull(action); - Assert.Equal("RCSI", action!.FactKey); - Assert.Equal("set", action.Action); - Assert.Empty(action.Targets); - var t = Assert.Single(action.DbConfigTargets!); - Assert.Equal(DbConfigSetting.ReadCommittedSnapshotOn, t.Setting); - Assert.Equal("OFF", t.CurrentValue); - Assert.Equal("Foo", t.Database); - } - - [Fact] - public void BuildRcsiAction_ReturnsNull_WhenRcsiOn() - { - // M2-1: rcsi == true means RCSI is ON — the affordance must NOT appear. - var finding = DbConfigFinding(new List - { - new { database = "Foo", rcsi = true, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new string[0], - rcsi_blocking_events = 99, rcsi_deadlocks = 9, rcsi_reader_writer_pct = 90 } - }); - Assert.Null(FactRemediation.BuildRcsiAction(finding)); - } - - [Fact] - public void BuildRcsiAction_ReturnsNull_WhenEnrichmentAbsent() - { - // RCSI off but no §3.3 enrichment (legacy alert) → no affordance. - var finding = DbConfigFinding(new List - { - new { database = "Foo", rcsi = false, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "RCSI OFF" } } - }); - Assert.Null(FactRemediation.BuildRcsiAction(finding)); - } - - [Fact] - public void BuildAction_NeverPutsRcsiInSafeTargets_ButCarriesRcsiTargets() - { - // The always-safe BuildAction must STILL never put RCSI in the EXECUTED DbConfigTargets - // (DbConfigHandler runs those). RCSI is now CARRIED on the action's RcsiTargets purely so - // the Recommendations reader can fan per-db RCSI cards — never executed from here. On an - // enriched, CONTENDED RCSI-off finding the action exists (so the reader can fan), has NO - // safe DbConfigTargets, and carries exactly the one RCSI target. - var rcsiOnly = FactRemediation.BuildAction(RcsiOffFinding()); - Assert.NotNull(rcsiOnly); - Assert.Equal("DB_CONFIG", rcsiOnly!.FactKey); - Assert.True(rcsiOnly.DbConfigTargets is null || rcsiOnly.DbConfigTargets.Count == 0); - var carried = Assert.Single(rcsiOnly.RcsiTargets!); - Assert.Equal("Foo", carried.Database); - Assert.Equal(12, carried.Figures.BlockingEvents); - - // And a mixed finding (RCSI off + a safe setting) yields the safe target in - // DbConfigTargets (never RCSI) AND carries the RCSI target separately. - var mixed = DbConfigFinding(new List - { - new { database = "Foo", rcsi = false, query_store = true, - auto_shrink = true, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "auto_shrink ON", "RCSI OFF" }, - rcsi_blocking_events = 1, rcsi_deadlocks = 0, rcsi_reader_writer_pct = 50 } - }); - var safe = FactRemediation.BuildAction(mixed); - Assert.NotNull(safe); - Assert.Equal("DB_CONFIG", safe!.FactKey); - Assert.NotEmpty(safe.DbConfigTargets!); - Assert.All(safe.DbConfigTargets!, t => Assert.NotEqual(DbConfigSetting.ReadCommittedSnapshotOn, t.Setting)); - Assert.Single(safe.RcsiTargets!); // RCSI carried for the card fan-out, not executed - } - - [Fact] - public void CollectRcsiTargets_OnlyReaderWriterContention_WriterWriterAndUnknownExcluded() - { - // RCSI only relieves reader-vs-writer blocking. The gate is the reader/writer SHARE - // (>= FactRiskDisclosure.ReaderWriterMeaningfulPct), NOT raw blocking/deadlock counts: - // - reader/writer-dominant -> recommended - // - writer/writer-dominant -> NOT recommended, even with HEAVY blocking (RCSI does - // nothing for X/IX/U vs X/IX/U contention) - // - no blocked-process detail -> NOT recommended (pct null — can't confirm RCSI helps) - var finding = DbConfigFinding(new List - { - new { database = "ReaderWriter", rcsi = false, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "RCSI OFF" }, - rcsi_blocking_events = 40, rcsi_deadlocks = 2, rcsi_reader_writer_pct = 85 }, - new { database = "WriterWriter", rcsi = false, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "RCSI OFF" }, - // Heavy blocking + deadlocks, but almost all writer/writer — RCSI won't relieve it. - rcsi_blocking_events = 500, rcsi_deadlocks = 12, rcsi_reader_writer_pct = 15 }, - new { database = "Unknown", rcsi = false, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "RCSI OFF" }, - rcsi_blocking_events = 30, rcsi_deadlocks = 0, rcsi_reader_writer_pct = (int?)null }, - new { database = "AtThreshold", rcsi = false, query_store = true, - auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - issues = new[] { "RCSI OFF" }, - rcsi_blocking_events = 10, rcsi_deadlocks = 0, rcsi_reader_writer_pct = 50 } - }); - - var collected = FactRemediation.CollectRcsiTargets(finding); - - Assert.Equal(2, collected.Count); - Assert.DoesNotContain(collected, t => t.Database == "WriterWriter"); // heavy blocking, but writer/writer - Assert.DoesNotContain(collected, t => t.Database == "Unknown"); // no reader/writer detail captured - var rw = Assert.Single(collected, t => t.Database == "ReaderWriter"); - Assert.Equal(40, rw.Figures.BlockingEvents); - Assert.Equal(85, rw.Figures.ReaderWriterPct); - Assert.Single(collected, t => t.Database == "AtThreshold"); // pct == threshold qualifies - - // BuildAction carries exactly the two reader/writer targets (no safe DbConfigTargets here). - var action = FactRemediation.BuildAction(finding); - Assert.NotNull(action); - Assert.Equal(2, action!.RcsiTargets!.Count); - Assert.True(action.DbConfigTargets is null || action.DbConfigTargets.Count == 0); - } - - // ── FactRiskDisclosure: two-sided, honest-both-directions, golden prose ────── - - [Fact] - public void RiskDisclosure_Null_ForNonDestructiveFactKey() - { - Assert.Null(FactRiskDisclosure.GetForAction(DbConfigAction(new DbConfigTarget("Foo", DbConfigSetting.AutoShrinkOff, "ON")), DbConfigFinding())); - Assert.Null(FactRiskDisclosure.GetForAction(new RemediationAction("PLAN_REGRESSION", "force", new List { Target() }), null)); - } - - [Fact] - public void RiskDisclosure_Rcsi_HasAtLeastOneOfEachSide() - { - var d = FactRiskDisclosure.GetForAction(RcsiAction(), RcsiOffFinding()); - Assert.NotNull(d); - Assert.NotEmpty(d!.RisksOfChanging); - Assert.NotEmpty(d.RisksOfNotChanging); - // The validated identifier is substituted, bracketed. - Assert.Contains(d.RisksOfChanging, r => r.Text.Contains("[Foo]")); - } - - [Fact] - public void RiskDisclosure_HighReaderWriterPct_SaysRcsiEliminates() - { - var d = FactRiskDisclosure.GetForAction(RcsiAction(), RcsiOffFinding(blocking: 50, deadlocks: 4, rwPct: 85))!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("85%") && r.Text.Contains("RCSI eliminates")); - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("50") && r.Text.Contains("blocked-process events") && r.Text.Contains("4 deadlocks")); - } - - [Fact] - public void RiskDisclosure_LowReaderWriterPct_SaysRcsiWontResolveThis() - { - // Writer/writer-dominant: the honest-both-directions safety feature. - var d = FactRiskDisclosure.GetForAction(RcsiAction(), RcsiOffFinding(blocking: 40, deadlocks: 2, rwPct: 10))!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("10%") && r.Text.Contains("RCSI does NOT resolve")); - Assert.DoesNotContain(d.RisksOfNotChanging, r => r.Text.Contains("RCSI eliminates")); - } - - [Fact] - public void RiskDisclosure_NoData_ShowsWeakCaseBaseline() - { - var d = FactRiskDisclosure.GetForAction(RcsiAction(), RcsiOffFinding(blocking: 0, deadlocks: 0, rwPct: null))!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("Little or no reader/writer blocking")); - } - - [Fact] - public void RiskDisclosure_NullFinding_DegradesToWeakCaseBaseline() - { - var d = FactRiskDisclosure.GetForAction(RcsiAction(), null)!; - Assert.NotEmpty(d.RisksOfChanging); - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("Little or no reader/writer blocking")); - } - - [Fact] - public void RiskDisclosure_Rcsi_GoldenProse_ChangingSide() - { - var d = FactRiskDisclosure.GetForAction(RcsiAction(), RcsiOffFinding())!; - Assert.Equal(3, d.RisksOfChanging.Count); - Assert.StartsWith("Enabling RCSI on [Foo] takes a brief exclusive database lock", d.RisksOfChanging[0].Text); - Assert.Contains("row-version load to tempdb", d.RisksOfChanging[1].Text); - Assert.Contains("Reader/writer concurrency semantics change", d.RisksOfChanging[2].Text); - } - - // ════════════════════════════════════════════════════════════════════════════ - // CLEAR CACHED PLAN (DBCC FREEPROCCACHE) — destructive privileged core (PR-A; - // UNREGISTERED). The two catastrophic axes: never-bare/null-handle-guard, and the - // ALTER-SERVER-STATE fail-closed gate. Plus the §2a row-level detector exclusion. - // ════════════════════════════════════════════════════════════════════════════ - - /// A CPU finding carrying an abnormal_cpu_plans drill-down with one qualifying row. - private static AnalysisFinding CpuFinding(List? rows = null, string rootKey = "CPU_SQL_PERCENT") => new() - { - ServerId = 1, - ServerName = "TestServer", - Category = "cpu", - StoryPath = rootKey, - StoryPathHash = "cpuplan000000001", - RootFactKey = rootKey, - DrillDown = new Dictionary - { - ["abnormal_cpu_plans"] = rows ?? new List - { - new - { - query_hash = "0xABCDEF0123456789", - database = "AdventureWorks", - current_cpu_per_exec_ms = 45.0, - baseline_cpu_per_exec_ms = 9.0, - anomaly_ratio = 5.0, - execution_count = 1200L, - total_cpu_ms = 54000.0, - latest_plan_handle = "0x06000100ABCD", - query_text = "SELECT * FROM dbo.BigTable WHERE x = @p", - cpu_percent = 62, - plan_regression_cofired = false, - parameter_sensitivity_cofired = false - } - } - } - }; - - private static RemediationAction ClearAction(string hash = "0xABCDEF0123456789", string db = "AdventureWorks") => - new("CLEAR_PLAN", "clear", Array.Empty(), - ClearPlanTargets: new[] { new ClearPlanTarget(db, hash, 45.0, 9.0, 5.0, "0x06") }, - ClearPlanFigures: new ClearPlanFigures(45.0, 9.0, 5.0, 62, false, false)); - - // ── BuildClearPlanAction (parallel builder) + BuildAction-unchanged guard ──── - - [Fact] - public void BuildClearPlanAction_EmitsOnAbnormalCpuPlans() - { - var action = FactRemediation.BuildClearPlanAction(CpuFinding()); - Assert.NotNull(action); - Assert.Equal("CLEAR_PLAN", action!.FactKey); - Assert.Equal("clear", action.Action); - Assert.Empty(action.Targets); - Assert.Null(action.DbConfigTargets); - var t = Assert.Single(action.ClearPlanTargets!); - Assert.Equal("0xABCDEF0123456789", t.QueryHash); - Assert.Equal("AdventureWorks", t.Database); - Assert.Equal(5.0, t.AnomalyRatio); - // The figures are carried for the at-apply dialog (no finding in hand). - Assert.NotNull(action.ClearPlanFigures); - Assert.Equal(45.0, action.ClearPlanFigures!.CurrentCpuPerExecMs); - Assert.Equal(62, action.ClearPlanFigures.CpuPercent); - } - - [Fact] - public void BuildClearPlanAction_CpuSpikeRootKey_AlsoEmits() - { - var action = FactRemediation.BuildClearPlanAction(CpuFinding(rootKey: "CPU_SPIKE")); - Assert.NotNull(action); - Assert.Equal("CLEAR_PLAN", action!.FactKey); - } - - [Fact] - public void BuildClearPlanAction_ReturnsNull_WhenNoDrillDown() - { - var finding = CpuFinding(); - finding.DrillDown = new Dictionary(); // no abnormal_cpu_plans - Assert.Null(FactRemediation.BuildClearPlanAction(finding)); - } - - [Fact] - public void BuildClearPlanAction_ReturnsNull_WhenNotCpuFinding() - { - var finding = CpuFinding(); - finding.RootFactKey = "PLAN_REGRESSION"; - Assert.Null(FactRemediation.BuildClearPlanAction(finding)); - } - - [Fact] - public void BuildClearPlanAction_RejectsRowsWithoutValidQueryHash() - { - // A row whose query_hash is blank / not a hex handle can never become a target — - // it could never resolve a plan handle (defends the never-resolve-garbage edge). - var action = FactRemediation.BuildClearPlanAction(CpuFinding(new List - { - new { query_hash = "", database = "Db", current_cpu_per_exec_ms = 10.0, baseline_cpu_per_exec_ms = 1.0, - anomaly_ratio = 10.0, execution_count = 5L, total_cpu_ms = 5000.0, latest_plan_handle = "", - query_text = "", cpu_percent = 10, plan_regression_cofired = false, parameter_sensitivity_cofired = false }, - new { query_hash = "notahex", database = "Db", current_cpu_per_exec_ms = 10.0, baseline_cpu_per_exec_ms = 1.0, - anomaly_ratio = 10.0, execution_count = 5L, total_cpu_ms = 5000.0, latest_plan_handle = "", - query_text = "", cpu_percent = 10, plan_regression_cofired = false, parameter_sensitivity_cofired = false } - })); - Assert.Null(action); - } - - [Fact] - public void BuildAction_Unchanged_NeverEmitsClearPlan_OnCpuFinding() - { - // The regression guard (§9): the parallel builder does not leak into BuildAction — - // a CPU finding carrying abnormal_cpu_plans yields NO action from BuildAction. - Assert.Null(FactRemediation.BuildAction(CpuFinding())); - } - - // ── FactRiskDisclosure CLEAR_PLAN arm (two-sided, real figures, both steers) ── - - [Fact] - public void RiskDisclosure_ClearPlan_HasAtLeastOneOfEachSide_RealFigures() - { - var d = FactRiskDisclosure.GetForAction(ClearAction(), CpuFinding()); - Assert.NotNull(d); - Assert.NotEmpty(d!.RisksOfChanging); - Assert.NotEmpty(d.RisksOfNotChanging); - // Real figures substituted from the carried ClearPlanFigures. - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("5.0x") && r.Text.Contains("45.0 ms") && r.Text.Contains("9.0 ms") && r.Text.Contains("62%")); - // The changing side discloses the recompile + not-guaranteed-better + per-handle blast radius. - Assert.Contains(d.RisksOfChanging, r => r.Text.Contains("forces a recompile")); - Assert.Contains(d.RisksOfChanging, r => r.Text.Contains("NOT guaranteed to produce a better plan")); - Assert.Contains(d.RisksOfChanging, r => r.Text.Contains("EVERY currently-cached plan")); - } - - [Fact] - public void RiskDisclosure_ClearPlan_PlanRegressionCoFired_SteersToForce() - { - var action = new RemediationAction("CLEAR_PLAN", "clear", Array.Empty(), - ClearPlanTargets: new[] { new ClearPlanTarget("Db", "0xAA") }, - ClearPlanFigures: new ClearPlanFigures(40.0, 8.0, 5.0, 50, PlanRegressionCoFired: true, ParameterSensitivityCoFired: false)); - var d = FactRiskDisclosure.GetForAction(action, null)!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("forcing it") && r.Text.Contains("more durable")); - Assert.DoesNotContain(d.RisksOfNotChanging, r => r.Text.Contains("parameter-sensitive")); - } - - [Fact] - public void RiskDisclosure_ClearPlan_ParameterSensitivityCoFired_SaysWontDurablyHelp() - { - var action = new RemediationAction("CLEAR_PLAN", "clear", Array.Empty(), - ClearPlanTargets: new[] { new ClearPlanTarget("Db", "0xAA") }, - ClearPlanFigures: new ClearPlanFigures(40.0, 8.0, 5.0, 50, PlanRegressionCoFired: false, ParameterSensitivityCoFired: true)); - var d = FactRiskDisclosure.GetForAction(action, null)!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("parameter-sensitive") && r.Text.Contains("WON'T durably")); - } - - [Fact] - public void RiskDisclosure_ClearPlan_FiguresSurvivePersistence_NoFinding() - { - // The RcsiInactionFigures analog: with NO finding (apply-time), the carried - // ClearPlanFigures still render the real numbers. - var d = FactRiskDisclosure.GetForAction(ClearAction(), null)!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("5.0x") && r.Text.Contains("62%")); - } - - // ── ClearPlanHandler invariants ────────────────────────────────────────────── - - [Fact] - public void ClearPlan_Handler_IsDestructive_And_ApplyOnly() - { - var handler = new ClearPlanHandler(); - Assert.Equal("CLEAR_PLAN", handler.FactKey); - Assert.True(handler.IsDestructive); // the second true in the codebase - Assert.False(handler.SupportsUnapply); // you cannot un-clear a cache - } - - [Fact] - public async Task ClearPlan_UnapplyAsync_Throws() - { - await Assert.ThrowsAsync(() => - new ClearPlanHandler().UnapplyAsync(ClearAction(), new FakeExecutor(), Identity, CancellationToken.None)); - } - - [Fact] - public void ClearPlan_Handler_IsRegistered_AndReachableThroughGate() - { - // PR-B makes CLEAR_PLAN LIVE: the PRODUCTION wiring registers ClearPlanHandler so the - // "Clear cached plan (advanced)" affordance can appear and route to the destructive - // handler — but ONLY through the gated RemediationApplyService facade (proven by the - // Gate_* behavioural tests + the reachability guards CoreMachinery_OnlyReferencedInRemediationCore - // and GatedEntry_ReferencedOnlyBySanctionedUiPath). - var productionRegistry = new RemediationHandlerRegistry( - new IRemediationHandler[] { new ForcePlanHandler(), new DbConfigHandler(), new RcsiHandler(), new ClearPlanHandler() }); - Assert.IsType(productionRegistry.TryGet("CLEAR_PLAN")); - - // Assert at the source level that the PRODUCTION wiring now constructs ClearPlanHandler. - var dir = FindDashboardSourceDir(); - var serviceSrc = File.ReadAllText(Path.Combine(dir, "Services", "Remediation", "RemediationApplyService.cs")); - Assert.Contains("new ClearPlanHandler()", serviceSrc); - - // The destructive CLEAR_PLAN handler can NEVER be reached through the always-safe - // force-plan / DB-config handlers, nor cross with the other destructive (RCSI) one: - // every fact key resolves to its OWN distinct handler type. - Assert.IsType(productionRegistry.TryGet("PLAN_REGRESSION")); - Assert.IsType(productionRegistry.TryGet("DB_CONFIG")); - Assert.IsType(productionRegistry.TryGet("RCSI")); - Assert.NotEqual("CLEAR_PLAN", productionRegistry.TryGet("DB_CONFIG")!.FactKey); - Assert.NotEqual("CLEAR_PLAN", productionRegistry.TryGet("PLAN_REGRESSION")!.FactKey); - Assert.NotEqual("CLEAR_PLAN", productionRegistry.TryGet("RCSI")!.FactKey); - } - - [Fact] - public void CoreMachineryMarkers_Include_ClearPlanSurface() - { - Assert.Contains("ClearPlanHandler", CoreMachineryMarkers); - Assert.Contains("ClearProcCacheAsync", CoreMachineryMarkers); - } - - // ── ClearPlanHandler apply behaviours against the faked executor ───────────── - - [Fact] - public async Task ClearPlan_AuditTableAbsent_HardBlocks_NoMutation_NoAudit() - { - var exec = new FakeExecutor { AuditTableExists = false }; - var result = await new ClearPlanHandler().ApplyAsync(ClearAction(), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.False(o.AuditWritten); - Assert.Equal(0, exec.ClearPlanCalls); // no DBCC path even attempted - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task ClearPlan_PermissionDenied_FailsClosed_NoElevation() - { - // The DOMINANT runtime path: the least-privilege login lacks ALTER SERVER STATE. - var exec = new FakeExecutor - { - ClearPlanFunc = h => new ClearPlanOutcome - { - QueryHash = h, Status = RemediationStatus.PermissionDenied, Cleared = false, HandlesCleared = 0, - ExecutingLogin = "PerfMonLogin", - Message = "lacks ALTER SERVER STATE ... GRANT ALTER SERVER STATE TO [PerfMonLogin];", - PriorValue = "0 plans (permission denied)" - } - }; - var result = await new ClearPlanHandler().ApplyAsync(ClearAction(), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.PermissionDenied, o.Status); - Assert.Equal(1, exec.ClearPlanCalls); - var rec = Assert.Single(exec.AuditRecords); - Assert.Equal("skipped", rec.Result); // PermissionDenied audits as skipped - Assert.True(rec.ConsentAcknowledged); - Assert.Equal("CLEAR_PLAN", rec.FactKey); - Assert.Equal("clear_cached_plan", rec.Action); - Assert.Null(rec.QueryId); - Assert.Null(rec.PlanId); - Assert.Contains("GRANT ALTER SERVER STATE", rec.ErrorMessage); - } - - [Fact] - public async Task ClearPlan_NoSurvivingHandle_Skips() - { - var exec = new FakeExecutor - { - ClearPlanFunc = h => new ClearPlanOutcome - { - QueryHash = h, Status = RemediationStatus.Skipped, Cleared = false, HandlesCleared = 0, - ExecutingLogin = "sa", Message = "No cached plan is currently present", PriorValue = "0 plans (no surviving handle)" - } - }; - var result = await new ClearPlanHandler().ApplyAsync(ClearAction(), exec, Identity, CancellationToken.None); - - Assert.Equal(RemediationStatus.Skipped, Assert.Single(result.Outcomes).Status); - var rec = Assert.Single(exec.AuditRecords); - Assert.Equal("skipped", rec.Result); - Assert.True(rec.ConsentAcknowledged); - } - - [Fact] - public async Task ClearPlan_Success_WritesAudit_ConsentTrue_NullIds_Action() - { - var exec = new FakeExecutor(); // default success outcome - var result = await new ClearPlanHandler().ApplyAsync(ClearAction(), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.True(o.AuditWritten); - var rec = Assert.Single(exec.AuditRecords); - Assert.Equal("success", rec.Result); - Assert.True(rec.ConsentAcknowledged); - Assert.Equal("clear_cached_plan", rec.Action); - Assert.Null(rec.QueryId); - Assert.Null(rec.PlanId); - Assert.Contains("DBCC FREEPROCCACHE", rec.GeneratedSql); - // The audited action string fits the VarChar(32) @action param (17 chars). - Assert.True(rec.Action.Length <= 32); - } - - // ── Never-bare / null-handle-guard structural assertions (M-1) ─────────────── - // - // The single-connection SPID equality + the actual DBCC text are executor/real-server - // concerns (cannot be exercised against a faked executor). These assert, at the SOURCE - // level, that the executor ONLY ever builds the single-`@plan_handle` form, binds the - // handle as a typed param, filters plan_handle IS NOT NULL, rejects null/zero-length in - // C# before any DBCC string, and never emits the bare/whole-cache form. - - [Fact] - public void Executor_NeverEmitsBareFreeProcCache_OnlyTypedSingleHandleForm() - { - var dir = FindDashboardSourceDir(); - var src = File.ReadAllText(Path.Combine(dir, "Services", "DatabaseService.Remediation.cs")); - - // The ONLY DBCC text is the single-handle form with a typed @plan_handle param. - Assert.Contains("DBCC FREEPROCCACHE(@plan_handle)", src); - Assert.Contains("@plan_handle", src); - Assert.Contains("SqlDbType.VarBinary, 64", src); - - // The catastrophic bare/whole-cache form must NOT appear anywhere: no - // no-argument FREEPROCCACHE statement and no empty-arg form. - Assert.DoesNotContain("FREEPROCCACHE;", src); - Assert.DoesNotContain("FREEPROCCACHE ;", src); - Assert.DoesNotContain("FREEPROCCACHE()", src); // no empty-arg form - - // The live resolve filters plan_handle IS NOT NULL (the BAD_ACTOR precedent), - // and the C# guard rejects null/zero-length BEFORE any DBCC string is built. - Assert.Contains("plan_handle IS NOT NULL", src); - Assert.Contains("handle.Length == 0", src); - } - - [Fact] - public void Executor_GateIsNamedAlterServerState_FailClosed() - { - var dir = FindDashboardSourceDir(); - var src = File.ReadAllText(Path.Combine(dir, "Services", "DatabaseService.Remediation.cs")); - - // The NAMED server permission, fail-closed via ISNULL(...,0). NOT the generic - // (NULL,NULL,'ALTER') token (which returns NULL even for sysadmin). - Assert.Contains("HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER SERVER STATE')", src); - Assert.Contains("ISNULL(HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER SERVER STATE'), 0)", src); - Assert.DoesNotContain("HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER')", src); - // PermissionDenied carries grant guidance. - Assert.Contains("GRANT ALTER SERVER STATE", src); - } - - [Fact] - public void Executor_HexHandleParse_RejectsMalformed_NeverThrows() - { - // The query_hash → binary(8) bind path: a typed param, never concatenated. A - // malformed value parses to null (→ Skip), never a DBCC string. - Assert.Null(DatabaseService.TryParseHexHandle(null)); - Assert.Null(DatabaseService.TryParseHexHandle("")); - Assert.Null(DatabaseService.TryParseHexHandle("0x")); - Assert.Null(DatabaseService.TryParseHexHandle("0xABC")); // odd length - Assert.Null(DatabaseService.TryParseHexHandle("0xZZ")); // not hex - var ok = DatabaseService.TryParseHexHandle("0xABCDEF0123456789"); - Assert.NotNull(ok); - Assert.Equal(8, ok!.Length); - // No "0x" prefix is also accepted (raw hex). - Assert.Equal(8, DatabaseService.TryParseHexHandle("ABCDEF0123456789")!.Length); - } - - // ── Detector row-level exclusion (§2a / R2-MOD-A / R2-MOD-B) ───────────────── - // - // The production detector runs this logic as T-SQL against collect.query_stats; the - // PlanCacheAnomalyDetector reference encodes the SAME row-level exclusion + per-exec - // math so the catastrophic correctness rules are headlessly guarded. - - private static readonly DateTime ServerUp = new(2026, 6, 1, 0, 0, 0, DateTimeKind.Utc); - private static readonly DateTime CurrentStart = new(2026, 6, 1, 12, 0, 0, DateTimeKind.Utc); - - private static PlanCacheAnomalyDetector.StatRow Row( - string hash, string plan, DateTime t, long workerUs, long execs, - DateTime? serverStart = null, string sqlH = "S1", int so = 0, int eo = -1) => - new(hash, sqlH, so, eo, plan, t, serverStart ?? ServerUp, workerUs, execs); - - [Fact] - public void Detector_LeakyFirstCollection_YieldsNoTarget() - { - // R2-MOD-A: a plan_handle whose GLOBAL-first collection is the FIRST in-window row, - // carrying delta = full cumulative raw total. The leaky "≥2 in-window" gate would - // wrongly pass it; the row-level exclusion drops it. There is no earlier collection - // for (sql_handle, offsets, plan_handle) → not a real-delta row → excluded. - var rows = new List - { - // baseline window: a normal plan at low per-exec CPU, WITH a real prior. - Row("0xQ1", "P0", CurrentStart.AddHours(-10), 1_000_000, 1000), // first-collection of P0 (no prior) — excluded - Row("0xQ1", "P0", CurrentStart.AddHours(-9), 10_000, 1000), // real delta: 10us/exec - // current window: a NEW plan_handle P1 whose FIRST collected row carries 6h of - // accumulated CPU as one delta (the contamination this feature targets). - Row("0xQ1", "P1", CurrentStart.AddHours(1), 6_000_000_000, 1000), // first-collection of P1 — excluded - }; - - var results = PlanCacheAnomalyDetector.Evaluate(rows, CurrentStart); - // The only real-delta row is the one baseline row; current window has no real-delta - // rows → no current execs → no anomaly. The fake 6h spike never counts. - Assert.Empty(results); - } - - [Fact] - public void Detector_ServerRestartRow_YieldsNoTarget() - { - // R2-MOD-B: the first post-restart row (server_start_time >= prior collection_time) - // carries delta = full cumulative raw total. The row-level predicate requires the - // prior collection_time > this row's server_start_time, so a post-restart row is - // excluded even though an earlier collection exists. - var restart = CurrentStart.AddMinutes(30); // server restarted mid-window - var rows = new List - { - Row("0xQ2", "P0", CurrentStart.AddHours(-9), 9_000, 1000), // first-collection — excluded - Row("0xQ2", "P0", CurrentStart.AddHours(-8), 9_000, 1000, ServerUp), // real delta (prior at -9 > ServerUp) - // post-restart row: huge raw total; prior collection (-8) is BEFORE the new - // server_start_time (restart), so it is NOT a real-delta row → excluded. - Row("0xQ2", "P0", CurrentStart.AddHours(1), 9_000_000_000, 1000, restart), - }; - - var results = PlanCacheAnomalyDetector.Evaluate(rows, CurrentStart); - Assert.Empty(results); - } - - [Fact] - public void Detector_SyntheticMassRestart_ProducesNoTargetsEnMasse() - { - // A mass restart: MANY plan_handles each with a first-post-restart raw-total row in - // the current window. None has a real-delta current row → no targets en masse. - var restart = CurrentStart.AddMinutes(15); - var rows = new List(); - for (int i = 0; i < 50; i++) - { - var hash = "0xQ" + i.ToString("X"); - var plan = "P" + i; - // a real baseline so each query has a baseline per-exec - rows.Add(Row(hash, plan, CurrentStart.AddHours(-9), 5_000, 500, ServerUp, sqlH: "S" + i)); - rows.Add(Row(hash, plan, CurrentStart.AddHours(-8), 5_000, 500, ServerUp, sqlH: "S" + i)); - // the mass post-restart contaminated row in the current window - rows.Add(Row(hash, plan, CurrentStart.AddMinutes(20), 8_000_000_000, 500, restart, sqlH: "S" + i)); - } - - var results = PlanCacheAnomalyDetector.Evaluate(rows, CurrentStart); - Assert.Empty(results); - } - - [Fact] - public void Detector_GenuinePerExecJump_OnRealDeltaRows_EmitsTarget() - { - // A genuine per-exec jump on REAL-prior-delta rows (an earlier collection exists, - // after server_start_time) DOES emit a target. Baseline ~10us/exec; current - // ~50us/exec = 5x, material CPU. - var rows = new List - { - Row("0xHOT", "P0", CurrentStart.AddHours(-9), 9_999_999, 1000), // first-collection — excluded - Row("0xHOT", "P0", CurrentStart.AddHours(-8), 10_000_000, 1000), // baseline real delta: 10us/exec - Row("0xHOT", "P0", CurrentStart.AddHours(-7), 10_000_000, 1000), // baseline real delta: 10us/exec - Row("0xHOT", "P0", CurrentStart.AddHours(1), 50_000_000, 1000), // current real delta: 50us/exec - }; - - var results = PlanCacheAnomalyDetector.Evaluate(rows, CurrentStart); - var hit = Assert.Single(results); - Assert.Equal("0xHOT", hit.QueryHash); - Assert.True(hit.AnomalyRatio >= 4.5 && hit.AnomalyRatio <= 5.5, $"ratio was {hit.AnomalyRatio}"); - Assert.True(hit.CurrentCpuPerExecMs > hit.BaselineCpuPerExecMs); - } - - [Fact] - public void Detector_StableExpensiveQuery_NoTarget() - { - // A query that is expensive but STABLE (high but unchanging per-exec) is NOT a - // clear-plan candidate — the anomaly gate (ratio < T) excludes it. - var rows = new List - { - Row("0xSTABLE", "P0", CurrentStart.AddHours(-9), 100_000_000, 1000), // first-collection — excluded - Row("0xSTABLE", "P0", CurrentStart.AddHours(-8), 100_000_000, 1000), // baseline 100us/exec - Row("0xSTABLE", "P0", CurrentStart.AddHours(1), 105_000_000, 1000), // current 105us/exec — ~1.05x - }; - - Assert.Empty(PlanCacheAnomalyDetector.Evaluate(rows, CurrentStart)); - } - - [Fact] - public void Detector_AnomalousButTrivialCpu_NoTarget() - { - // Abnormal per-exec ratio but below the materiality floor → no target (clearing - // a trivial-CPU query is pointless). - var rows = new List - { - Row("0xTINY", "P0", CurrentStart.AddHours(-9), 100, 10), // first-collection — excluded - Row("0xTINY", "P0", CurrentStart.AddHours(-8), 100, 10), // baseline 10us/exec - Row("0xTINY", "P0", CurrentStart.AddHours(1), 5_000, 10), // current 500us/exec = 50x but only 5ms total - }; - - Assert.Empty(PlanCacheAnomalyDetector.Evaluate(rows, CurrentStart)); - } - - // ── cpu_percent fix (PR-A security review LOW-1) ───────────────────────────── - // - // The live detector ran in T-SQL against collect.query_stats; the cpu_percent SHARE is - // computed in that SQL (numerator/denominator over the SAME §2a real-delta rows). These - // source-level assertions guard that PR-B replaced the hardcoded 0 with the real share. - - [Fact] - public void Detector_CpuPercent_IsRealWindowShare_NotHardcodedZero() - { - var dir = FindDashboardSourceDir(); - // CollectAbnormalCpuPlans lives in a per-domain partial (SqlServerDrillDownCollector.Queries.cs) - // after the partial-class split; read every partial so the assertions hold wherever it sits. - var src = string.Concat( - Directory.GetFiles(Path.Combine(dir, "Analysis"), "SqlServerDrillDownCollector*.cs") - .OrderBy(p => p, StringComparer.Ordinal) - .Select(File.ReadAllText)); - - // The CollectAbnormalCpuPlans detector must NO LONGER hardcode cpu_percent = 0. - Assert.DoesNotContain("cpu_percent = 0,", src); - - // It computes the real share: a window_total CTE (same §2a real-delta exclusion) as - // the denominator, and cpu_percent = the per-query current_total_cpu_ms / that total. - Assert.Contains("window_total", src); - Assert.Contains("cpu_percent =", src); - Assert.Contains("w.current_total_cpu_ms / NULLIF(wt.total_cpu_ms, 0)", src); - Assert.Contains("CROSS JOIN window_total AS wt", src); - } - - [Fact] - public void ClearPlanFigures_CarryRealCpuPercent_Through_BuildClearPlanAction() - { - // The carried path (NOT the live finding): a finding whose abnormal_cpu_plans row - // has a real cpu_percent flows that number onto ClearPlanFigures, and the disclosure - // renders it — so the dialog/disclosure show the real % at apply time. - var action = FactRemediation.BuildClearPlanAction(CpuFinding(new List - { - new { query_hash = "0xABCDEF0123456789", database = "Db", current_cpu_per_exec_ms = 45.0, - baseline_cpu_per_exec_ms = 9.0, anomaly_ratio = 5.0, execution_count = 1200L, - total_cpu_ms = 54000.0, latest_plan_handle = "0x06", query_text = "q", - cpu_percent = 73, plan_regression_cofired = false, parameter_sensitivity_cofired = false } - })); - Assert.NotNull(action); - Assert.Equal(73, action!.ClearPlanFigures!.CpuPercent); - Assert.NotEqual(0, action.ClearPlanFigures.CpuPercent); - - var d = FactRiskDisclosure.GetForAction(action, null)!; - Assert.Contains(d.RisksOfNotChanging, r => r.Text.Contains("73%")); - } - - // ── Full lock-mode vocabulary classifier (M-1) ─────────────────────────────── - - [Theory] - [InlineData("S", RcsiLockClass.Reader)] - [InlineData("IS", RcsiLockClass.Reader)] - [InlineData("RangeS-S", RcsiLockClass.Reader)] - [InlineData("RangeS-U", RcsiLockClass.Reader)] - [InlineData("X", RcsiLockClass.Writer)] - [InlineData("IX", RcsiLockClass.Writer)] - [InlineData("U", RcsiLockClass.Writer)] - [InlineData("UIX", RcsiLockClass.Writer)] - [InlineData("RangeX-X", RcsiLockClass.Writer)] - [InlineData("RangeI-N", RcsiLockClass.Writer)] - [InlineData("Sch-S", RcsiLockClass.Excluded)] - [InlineData("Sch-M", RcsiLockClass.Excluded)] - [InlineData("BU", RcsiLockClass.Excluded)] - [InlineData("IU", RcsiLockClass.Excluded)] - [InlineData("SIU", RcsiLockClass.Excluded)] - [InlineData("SIX", RcsiLockClass.Excluded)] - [InlineData("", RcsiLockClass.Excluded)] - [InlineData(null, RcsiLockClass.Excluded)] - public void LockModeClassifier_FullVocabulary(string? lockMode, RcsiLockClass expected) - { - Assert.Equal(expected, RcsiLockModeClassifier.Classify(lockMode)); - } - - // ── Drill-down enrichment parity (types only, per M-2) ─────────────────────── - - [Fact] - public void DrillDownEnrichment_RcsiFields_TypeParity_DashboardVsLite() - { - // The Dashboard shape carries real ints + a nullable int; the Lite shape carries - // 0/0/null. The shared extractor (FactRiskDisclosure) must read BOTH shapes with - // identical field NAMES and TYPES (int / int / nullable-int). Round-trip via JSON - // (mirrors how the collectors serialize the anonymous objects). - var dashboardRow = new - { - database = "Foo", recovery_model = "FULL", rcsi = false, query_store = true, - issues = new[] { "RCSI OFF" }, auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - rcsi_blocking_events = 12, rcsi_deadlocks = 3, rcsi_reader_writer_pct = (int?)80 - }; - var liteRow = new - { - database = "Foo", recovery_model = "FULL", rcsi = false, query_store = true, - issues = new[] { "RCSI OFF" }, auto_shrink = false, auto_close = false, page_verify = "CHECKSUM", - rcsi_blocking_events = 0, rcsi_deadlocks = 0, rcsi_reader_writer_pct = (int?)null - }; - - var dash = System.Text.Json.JsonSerializer.SerializeToElement((object)dashboardRow); - var lite = System.Text.Json.JsonSerializer.SerializeToElement((object)liteRow); - foreach (var field in new[] { "rcsi_blocking_events", "rcsi_deadlocks", "rcsi_reader_writer_pct" }) - { - Assert.True(dash.TryGetProperty(field, out var dv), $"Dashboard shape missing {field}"); - Assert.True(lite.TryGetProperty(field, out var lv), $"Lite shape missing {field}"); - // counts are Number on both; pct is Number on Dashboard and Null on Lite (nullable int) - Assert.Equal(System.Text.Json.JsonValueKind.Number, dv.ValueKind); - if (field == "rcsi_reader_writer_pct") - Assert.Equal(System.Text.Json.JsonValueKind.Null, lv.ValueKind); - else - Assert.Equal(System.Text.Json.JsonValueKind.Number, lv.ValueKind); - } - } - - // ── §1 identifier safety: no-injection / QUOTENAME / same-string (M-1) ─────── - // - // These run against the EXECUTOR's OWN statement builder (DatabaseService. - // BuildAlterStatement), NOT the display renderer (m-B). The builder is the exact - // composition SetDatabaseOptionAsync uses for the executed statement. - - [Theory] - [InlineData(DbConfigSetting.AutoShrinkOff, "SET AUTO_SHRINK OFF")] - [InlineData(DbConfigSetting.AutoCloseOff, "SET AUTO_CLOSE OFF")] - [InlineData(DbConfigSetting.PageVerifyChecksum, "SET PAGE_VERIFY CHECKSUM")] - public void Build_SetClause_IsHardcodedLiteral_RegardlessOfName(DbConfigSetting setting, string expectedClause) - { - // The SET clause is byte-identical regardless of the (pathological) db name. - foreach (var name in new[] { "Db", "Db]; DROP TABLE x--", "[weird]", "Ünîçödé" }) - { - var stmt = DatabaseService.BuildAlterStatement(name, setting); - Assert.Contains(expectedClause + ";", stmt); - Assert.EndsWith(expectedClause + ";", stmt); - } - } - - [Theory] - [InlineData("normal")] - [InlineData("has]bracket")] - [InlineData("has]]double")] - [InlineData("ev;il-- GO DROP")] - [InlineData("'; ALTER DATABASE master SET")] - [InlineData("Ünîçödé​")] // unicode + zero-width - public void Build_BracketsIdentifierInert_NoInjection(string name) - { - var stmt = DatabaseService.BuildAlterStatement(name, DbConfigSetting.AutoShrinkOff); - - // The identifier is bracketed with ]-doubling; the whole thing is one ALTER - // with exactly one bracketed token and the hardcoded clause. - var expectedToken = "[" + name.Replace("]", "]]") + "]"; - Assert.Equal($"ALTER DATABASE {expectedToken} SET AUTO_SHRINK OFF;", stmt); - - // No un-doubled close-bracket can prematurely end the identifier: the only - // ']' runs in the statement are the doubled ones we produced plus the final. - // Reconstruct: stripping the known prefix/suffix yields exactly the token. - Assert.StartsWith("ALTER DATABASE [", stmt); - } - - [Fact] - public void Build_SameString_ValidatedNameIsBracketedExactly() - { - // M-1: the bracketed token is byte-identical to the validated name passed in - // — an implementer cannot validate one variable and bracket a trimmed/cased one. - const string validated = " Padded Name "; // deliberate surrounding whitespace - var stmt = DatabaseService.BuildAlterStatement(validated, DbConfigSetting.AutoCloseOff); - Assert.Equal("ALTER DATABASE [ Padded Name ] SET AUTO_CLOSE OFF;", stmt); - - // A name differing only by trailing whitespace produces a DIFFERENT statement, - // proving the builder brackets exactly what it was given (no normalization). - var stmt2 = DatabaseService.BuildAlterStatement(validated.TrimEnd(), DbConfigSetting.AutoCloseOff); - Assert.NotEqual(stmt, stmt2); - } - - [Fact] - public void Build_DisplayRenderer_NotExecuted_ExecutorHasOwnBuilder() - { - // m-B: the executor's builder is byte-identical to the display QUOTENAME but - // is its OWN routine in the Dashboard assembly (not the private Analysis one). - // Spot-check parity on a ]-containing name. - var stmt = DatabaseService.BuildAlterStatement("a]b", DbConfigSetting.PageVerifyChecksum); - Assert.Equal("ALTER DATABASE [a]]b] SET PAGE_VERIFY CHECKSUM;", stmt); - } - - // ── Reachability-with-gate guard (replaces PR-A's no-caller guard) ────────── - // - // PR-A asserted the privileged machinery had NO non-core caller. PR-B adds a - // legitimate caller (the Apply Fix UI), so "no caller" can no longer hold. The - // invariant becomes "reachable ONLY through the gate," proven in two parts: - // - // A. The core machinery TYPES + force/unforce methods (handler, registry, - // executor, ForcePlanAsync/UnforcePlanAsync) are still referenced ONLY - // inside the remediation core — the UI never touches them directly. - // B. The single gated entry point (RemediationApplyService) is referenced - // outside the core ONLY by the sanctioned Apply Fix UI files. That facade - // runs the operator confirm before any handler.ApplyAsync (proven - // behaviourally by Gate_* in RemediationApplyServiceTests). - // - // Together: the UI reaches the privileged executor only via RemediationApplyService, - // and RemediationApplyService reaches the handler only after confirm() == true. - - private static readonly string[] CoreMachineryMarkers = - { - "ForcePlanAsync", "UnforcePlanAsync", - "RemediationHandlerRegistry", "DatabaseServiceRemediationExecutor", - "ForcePlanHandler", "IRemediationExecutor", "IRemediationHandler", - // B3 Phase 2 privileged surface (M-2): the new handler + executor methods - // must be reachable ONLY through the gate, exactly like the force-plan ones. - "DbConfigHandler", "SetDatabaseOptionAsync", "PreflightDbConfigAsync", - // B3 Phase 3 (m-3): the destructive RCSI handler must be reachable ONLY through - // the gate. It is UNREGISTERED in PR-A (dead-code-safe), but the marker still - // guards against any UI/MCP/menu file referencing it directly. - "RcsiHandler", - // Clear-cached-plan (DBCC FREEPROCCACHE) destructive core: the new handler + the - // DISTINCTIVE executor method name. UNREGISTERED in PR-A (dead-code-safe); the - // markers still guard against any UI/MCP/menu file referencing the privileged - // surface directly. ClearProcCacheAsync is distinctive enough not to substring- - // false-match an unrelated reference. - "ClearPlanHandler", "ClearProcCacheAsync", - // WS3 percent-autogrowth always-safe core: the new handler + the DISTINCTIVE - // executor method name. Reachable ONLY through the gate, exactly like DbConfigHandler. - "FileAutogrowthHandler", "SetFileGrowthAsync", "PreflightFileGrowthAsync", - // WS3 server-level config always-safe core (MAXDOP/CTFP sp_configure): the new handler + the - // DISTINCTIVE executor method names. Reachable ONLY through the gate, exactly like DbConfigHandler. - "ServerConfigHandler", "SetServerConfigAsync", "PreflightServerConfigAsync", - }; - - [Fact] - public void CoreMachinery_OnlyReferencedInRemediationCore() - { - var dashboardDir = FindDashboardSourceDir(); - - var offenders = new List(); - foreach (var file in Directory.EnumerateFiles(dashboardDir, "*.cs", SearchOption.AllDirectories)) - { - var rel = Path.GetRelativePath(dashboardDir, file).Replace('\\', '/'); - if (rel.StartsWith("bin/") || rel.StartsWith("obj/")) - continue; - - var allowed = - rel.StartsWith("Services/Remediation/") || - rel == "Services/DatabaseService.Remediation.cs"; - if (allowed) - continue; - - var text = File.ReadAllText(file); - if (CoreMachineryMarkers.Any(text.Contains)) - offenders.Add(rel); - } - - Assert.True(offenders.Count == 0, - "The privileged remediation machinery (force/unforce, handler, registry, executor) " + - "must be reached ONLY through RemediationApplyService — no UI/MCP/menu/command file " + - "may reference the machinery types directly. Offending files: " + string.Join(", ", offenders)); - } - - [Fact] - public void GatedEntry_ReferencedOnlyBySanctionedUiPath() - { - var dashboardDir = FindDashboardSourceDir(); - - // The ONLY files outside the remediation core allowed to reach the gated - // facade. Any other file gaining a reference to RemediationApplyService is a - // new, unreviewed path to the privileged executor and must fail the build. - var sanctioned = new HashSet(StringComparer.Ordinal) - { - "MainWindow.xaml.cs", // constructs + injects the service - "Controls/AlertsHistoryContent.xaml.cs", // threads it into the alert detail dialog - "AlertDetailWindow.xaml.cs", // invokes Apply/Un-apply via the service - "RemediationConfirmWindow.xaml.cs", // the confirm modal (gate UI) - "ServerTab.xaml.cs", // forwards it to the Recommendations sub-tab (WS1b-2) - "Controls/RecommendationsContent.xaml.cs", // invokes Apply via the service (WS1b-2) - }; - - var offenders = new List(); - foreach (var file in Directory.EnumerateFiles(dashboardDir, "*.cs", SearchOption.AllDirectories)) - { - var rel = Path.GetRelativePath(dashboardDir, file).Replace('\\', '/'); - if (rel.StartsWith("bin/") || rel.StartsWith("obj/")) - continue; - if (rel.StartsWith("Services/Remediation/")) - continue; - if (sanctioned.Contains(rel)) - continue; - - var text = File.ReadAllText(file); - if (text.Contains("RemediationApplyService")) - offenders.Add(rel); - } - - Assert.True(offenders.Count == 0, - "Only the sanctioned Apply Fix UI path may reference RemediationApplyService. " + - "A new reference is an unreviewed path to the privileged executor. Offending files: " + - string.Join(", ", offenders)); - } - - private static string FindDashboardSourceDir() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - while (dir is not null) - { - var candidate = Path.Combine(dir.FullName, "Dashboard", "Services", "Remediation", "ForcePlanHandler.cs"); - if (File.Exists(candidate)) - return Path.Combine(dir.FullName, "Dashboard"); - dir = dir.Parent; - } - throw new DirectoryNotFoundException("Could not locate the Dashboard source directory from " + AppContext.BaseDirectory); - } - - private sealed class FakeExecutor : IRemediationExecutor - { - public bool AuditTableExists = true; - public bool PriorForce = true; - public bool AuditWriteResult = true; - public Func? PreflightFunc; - public Func? ForceFunc; - - public int ForceCalls; - public int UnforceCalls; - public readonly List AuditRecords = new(); - - public Task PreflightForcePlanAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(PreflightFunc?.Invoke(database, queryId, planId) ?? new TargetPreflight - { - Database = database, QueryId = queryId, PlanId = planId, - CurrentDatabase = database, HasAlter = true, QueryStoreState = "READ_WRITE", PlanPresent = true - }); - - public Task AuditTableExistsAsync(CancellationToken ct) => Task.FromResult(AuditTableExists); - - public Task HasPriorForceAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(PriorForce); - - public Task ForcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - { - ForceCalls++; - return Task.FromResult(ForceFunc?.Invoke(database, queryId, planId) ?? new ForcePlanOutcome - { - Database = database, QueryId = queryId, PlanId = planId, - Status = RemediationStatus.Success, Forced = true, ExecutingLogin = "sa", GateSpid = 55, ExecSpid = 55 - }); - } - - public Task UnforcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - { - UnforceCalls++; - return Task.FromResult(new ForcePlanOutcome - { - Database = database, QueryId = queryId, PlanId = planId, - Status = RemediationStatus.Success, Forced = true, ExecutingLogin = "sa", GateSpid = 55, ExecSpid = 55 - }); - } - - // ── DB-config seams (Phase 2) ──────────────────────────────────────────── - public Func? DbPreflightFunc; - public Func? SetDbFunc; - public int SetDbCalls; - - public Task PreflightDbConfigAsync(string database, DbConfigSetting setting, CancellationToken ct) - => Task.FromResult(DbPreflightFunc?.Invoke(database, setting) ?? new DbConfigPreflight - { - Database = database, Setting = setting, DatabaseExists = true, HasAlter = true, - AlreadyInDesiredState = false, ExecutingLogin = "sa", CurrentValue = "ON" - }); - - public Task SetDatabaseOptionAsync(string database, DbConfigSetting setting, RemediationIdentity identity, CancellationToken ct) - { - SetDbCalls++; - return Task.FromResult(SetDbFunc?.Invoke(database, setting) ?? new DbConfigOutcome - { - Database = database, Setting = setting, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "sa", PriorValue = "ON", GeneratedSql = "ALTER DATABASE [x] SET AUTO_SHRINK OFF;", - GateSpid = 55, ExecSpid = 55 - }); - } - - // ── Clear-cached-plan seam (DBCC FREEPROCCACHE) ────────────────────────── - public Func? ClearPlanFunc; - public int ClearPlanCalls; - - public Task ClearProcCacheAsync(string queryHash, RemediationIdentity identity, CancellationToken ct) - { - ClearPlanCalls++; - return Task.FromResult(ClearPlanFunc?.Invoke(queryHash) ?? new ClearPlanOutcome - { - QueryHash = queryHash, Status = RemediationStatus.Success, Cleared = true, HandlesCleared = 1, - ExecutingLogin = "sa", Message = "Cleared 1 cached plan(s).", - GeneratedSql = "DBCC FREEPROCCACHE(0xDEADBEEF);", PriorValue = "1 plan(s) cached for this query hash", - GateSpid = 55, ExecSpid = 55 - }); - } - - // ── Server-config seam (sp_configure MAXDOP/CTFP + RECONFIGURE) ─────────── - // Default-only here; the behavioural server-config coverage (and its own injectable - // fake) lives in ServerConfigHandlerTests. These satisfy the interface so this shared - // fake still compiles. - public Task PreflightServerConfigAsync(ServerConfigSetting setting, long recommendedValue, CancellationToken ct) - => Task.FromResult(new ServerConfigPreflight - { - Setting = setting, RecommendedValue = recommendedValue, - Executable = setting is ServerConfigSetting.Maxdop or ServerConfigSetting.CostThreshold, - HasPermission = true, AlreadyInDesiredState = false, ExecutingLogin = "sa", CurrentValue = 0 - }); - - public Task SetServerConfigAsync(ServerConfigSetting setting, long value, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ServerConfigOutcome - { - Setting = setting, Status = RemediationStatus.Success, Applied = true, ExecutingLogin = "sa", - PriorValue = 0, GeneratedSql = "EXEC sys.sp_configure N'show advanced options', 1; RECONFIGURE; EXEC sys.sp_configure N'max degree of parallelism', @value; RECONFIGURE;", - GateSpid = 55, ExecSpid = 55 - }); - - // ── Percent-autogrowth seam (ALTER DATABASE … MODIFY FILE FILEGROWTH) ───── - // Default-only here; the behavioural file-growth coverage (and its own injectable - // fake) lives in FileAutogrowthHandlerTests. These satisfy the interface so this - // shared force-plan/DB-config/clear-plan fake still compiles. - public Task PreflightFileGrowthAsync(string database, string logicalFileName, int growthMb, CancellationToken ct) - => Task.FromResult(new FileGrowthPreflight - { - Database = database, LogicalFileName = logicalFileName, RecommendedGrowthMb = growthMb, - DatabaseExists = true, FileExists = true, HasAlter = true, AlreadyInDesiredState = false, - ExecutingLogin = "sa", CurrentValue = "percent" - }); - - public Task SetFileGrowthAsync(string database, string logicalFileName, int growthMb, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new FileGrowthOutcome - { - Database = database, LogicalFileName = logicalFileName, Status = RemediationStatus.Success, Applied = true, - ExecutingLogin = "sa", PriorValue = "percent", - GeneratedSql = $"ALTER DATABASE [{database}] MODIFY FILE (NAME = [{logicalFileName}], FILEGROWTH = {growthMb}MB);", - GateSpid = 55, ExecSpid = 55 - }); - - public Task WriteAuditAsync(RemediationAuditRecord record, CancellationToken ct) - { - AuditRecords.Add(record); - return Task.FromResult(AuditWriteResult); - } - } -} diff --git a/deprecated/Dashboard.Tests/ServerConfigHandlerTests.cs b/deprecated/Dashboard.Tests/ServerConfigHandlerTests.cs deleted file mode 100644 index 657ad5f7a0..0000000000 --- a/deprecated/Dashboard.Tests/ServerConfigHandlerTests.cs +++ /dev/null @@ -1,361 +0,0 @@ -/* - * 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 System.Threading; -using System.Threading.Tasks; -using PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Services.Remediation; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Coverage for the always-safe server-config handler (SERVER_CONFIG, WS3): the self-gating -/// against a faked executor — audit-table hard block for the -/// executable settings (no mutation), the happy path running sp_configure for MAXDOP/CTFP and -/// writing one audit row per attempt, the advise-only memory settings recording an outcome WITHOUT -/// running sp_configure (and without needing the audit table), per-target independence, the -/// preflight dispositions, and the apply-only un-apply restriction. Mirrors the DB-config / -/// file-autogrowth handler tests; the single-connection (R2-MOD-1) guarantee is an executor concern -/// (SPID equality) not provable here. -/// -public class ServerConfigHandlerTests -{ - private static readonly RemediationIdentity Identity = - new("TESTDOMAIN\\tester", "Analysis: server_config [abcd1234]"); - - private static RemediationAction ServerAction(params ServerConfigTarget[] targets) => - new("SERVER_CONFIG", "set", Array.Empty(), - ServerConfigTargets: targets.ToList()); - - private static ServerConfigTarget MaxdopTarget(long current = 0, long recommended = 8) => - new(ServerConfigSetting.Maxdop, current, recommended); - - private static ServerConfigTarget CtfpTarget(long current = 5, long recommended = 50) => - new(ServerConfigSetting.CostThreshold, current, recommended); - - private static ServerConfigTarget MaxMemTarget() => - new(ServerConfigSetting.MaxServerMemory, 2147483647, 2147483647); - - private static ServerConfigTarget MinMemTarget() => - new(ServerConfigSetting.MinServerMemory, 24000, 24000); - - // ── Handler contract ──────────────────────────────────────────────────────── - - [Fact] - public void FactKey_IsServerConfig() - { - Assert.Equal("SERVER_CONFIG", new ServerConfigHandler().FactKey); - } - - [Fact] - public void NotDestructive_AndApplyOnly() - { - var handler = new ServerConfigHandler(); - Assert.False(handler.IsDestructive); // sp_configure MAXDOP/CTFP is online metadata - Assert.False(handler.SupportsUnapply); // no sensible reverse for MAXDOP/CTFP - } - - [Fact] - public async Task UnapplyAsync_Throws() - { - await Assert.ThrowsAsync(() => - new ServerConfigHandler().UnapplyAsync( - ServerAction(MaxdopTarget()), new FakeServerConfigExecutor(), Identity, CancellationToken.None)); - } - - [Fact] - public void Registry_ResolvesServerConfigHandler() - { - var registry = new RemediationHandlerRegistry( - new IRemediationHandler[] { new ForcePlanHandler(), new DbConfigHandler(), new ServerConfigHandler() }); - Assert.IsType(registry.TryGet("SERVER_CONFIG")); - } - - // ── Apply: executable settings (MAXDOP / CTFP) ──────────────────────────────── - - [Fact] - public async Task HappyPath_RunsSpConfigure_ForMaxdopAndCtfp_AndAudits() - { - var exec = new FakeServerConfigExecutor(); // default success - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxdopTarget(0, 8), CtfpTarget(5, 50)), exec, Identity, CancellationToken.None); - - // One SetServerConfigAsync per executable target, each with its own recommended value. - Assert.Equal(2, exec.SetCalls); - Assert.Contains((ServerConfigSetting.Maxdop, 8L), exec.SetArgs); - Assert.Contains((ServerConfigSetting.CostThreshold, 50L), exec.SetArgs); - - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.True(o.AuditWritten); - Assert.False(o.AppliedButUnlogged); - }); - - // Audit rows: one per attempt, the precise taxonomy, server sentinel db, non-consent. - Assert.Equal(2, exec.AuditRecords.Count); - Assert.All(exec.AuditRecords, r => - { - Assert.Equal("SERVER_CONFIG", r.FactKey); - Assert.Equal("success", r.Result); - Assert.False(r.ConsentAcknowledged); - Assert.Null(r.QueryId); - Assert.Null(r.PlanId); - Assert.False(string.IsNullOrEmpty(r.TargetDatabase)); // NOT NULL column sentinel - }); - Assert.Contains(exec.AuditRecords, r => r.Action == "set_maxdop"); - Assert.Contains(exec.AuditRecords, r => r.Action == "set_cost_threshold"); - } - - [Fact] - public async Task AuditTableAbsent_HardBlocks_ExecutableTargets_NoMutation() - { - var exec = new FakeServerConfigExecutor { AuditTableExists = false }; - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxdopTarget(), CtfpTarget()), exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Blocked, o.Status); - Assert.False(o.AuditWritten); - Assert.Contains("3.0.0", o.Message); - }); - Assert.Equal(0, exec.SetCalls); // NOT mutated - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task PermissionDenied_FailsClosed_AuditSkipped() - { - var exec = new FakeServerConfigExecutor - { - SetFunc = (setting, value) => new ServerConfigOutcome - { - Setting = setting, Status = RemediationStatus.PermissionDenied, Applied = false, - Message = "lacks ALTER SETTINGS", PriorValue = 0 - } - }; - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxdopTarget()), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.PermissionDenied, o.Status); - Assert.False(o.AppliedButUnlogged); - Assert.Equal("skipped", Assert.Single(exec.AuditRecords).Result); - Assert.Equal(1, exec.SetCalls); - } - - [Fact] - public async Task AppliesButAuditFails_FlagsAppliedButUnlogged() - { - var exec = new FakeServerConfigExecutor { AuditWriteResult = false }; - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxdopTarget()), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Success, o.Status); - Assert.False(o.AuditWritten); - Assert.True(o.AppliedButUnlogged); - } - - [Fact] - public async Task OneTargetThrows_OthersStillRun() - { - var exec = new FakeServerConfigExecutor - { - SetFunc = (setting, value) => - { - if (setting == ServerConfigSetting.Maxdop) throw new InvalidOperationException("boom"); - return new ServerConfigOutcome { Setting = setting, Status = RemediationStatus.Success, Applied = true, PriorValue = 5 }; - } - }; - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxdopTarget(), CtfpTarget()), exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.Contains(result.Outcomes, o => o.Status == RemediationStatus.Error); - Assert.Contains(result.Outcomes, o => o.Status == RemediationStatus.Success); - Assert.Equal(2, exec.AuditRecords.Count); // error target still audited - } - - // ── Advise-only memory settings: NEVER run sp_configure ─────────────────────── - - [Fact] - public async Task MemoryTargets_AreAdviseOnly_NoMutation_NoAudit() - { - var exec = new FakeServerConfigExecutor(); - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxMemTarget(), MinMemTarget()), exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.All(result.Outcomes, o => - { - Assert.Equal(RemediationStatus.Skipped, o.Status); - Assert.Contains("advise-only", o.Message); - Assert.False(o.AuditWritten); - }); - Assert.Equal(0, exec.SetCalls); // executor never touched for memory - Assert.Empty(exec.AuditRecords); - } - - [Fact] - public async Task MemoryTargets_AdviseOnly_EvenWhenAuditTableAbsent() - { - // Advise-only targets never mutate and never need the audit table, so an absent table must - // still yield a clean advise-only result (not a spurious block). - var exec = new FakeServerConfigExecutor { AuditTableExists = false }; - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxMemTarget()), exec, Identity, CancellationToken.None); - - var o = Assert.Single(result.Outcomes); - Assert.Equal(RemediationStatus.Skipped, o.Status); - Assert.Contains("advise-only", o.Message); - Assert.Equal(0, exec.SetCalls); - } - - [Fact] - public async Task MixedTargets_MaxdopApplied_MemoryAdviseOnly() - { - var exec = new FakeServerConfigExecutor(); - - var result = await new ServerConfigHandler().ApplyAsync( - ServerAction(MaxdopTarget(0, 8), MaxMemTarget()), exec, Identity, CancellationToken.None); - - Assert.Equal(2, result.Outcomes.Count); - Assert.Equal(1, exec.SetCalls); // only MAXDOP ran sp_configure - Assert.Contains((ServerConfigSetting.Maxdop, 8L), exec.SetArgs); - Assert.DoesNotContain(exec.SetArgs, a => a.Item1 == ServerConfigSetting.MaxServerMemory); - // One success audit (MAXDOP); memory advise-only writes nothing. - Assert.Single(exec.AuditRecords); - Assert.Equal("set_maxdop", exec.AuditRecords[0].Action); - } - - // ── Preflight dispositions ──────────────────────────────────────────────────── - - [Theory] - [InlineData(true, false, RemediationDisposition.Ok)] // has perm, not already -> ready - [InlineData(true, true, RemediationDisposition.AlreadyInDesiredState)] // already at recommended - [InlineData(false, false, RemediationDisposition.BlockNoAlter)] // no permission - public async Task Preflight_ClassifiesExecutableDisposition(bool hasPerm, bool alreadyDesired, RemediationDisposition expected) - { - var exec = new FakeServerConfigExecutor - { - PreflightFunc = (setting, rec) => new ServerConfigPreflight - { - Setting = setting, RecommendedValue = rec, Executable = true, - HasPermission = hasPerm, AlreadyInDesiredState = alreadyDesired, CurrentValue = 0 - } - }; - - var pre = await new ServerConfigHandler().PreflightAsync( - ServerAction(MaxdopTarget()), exec, CancellationToken.None); - Assert.Equal(expected, pre.Targets.Single().Disposition); - } - - [Fact] - public async Task Preflight_MemoryTarget_IsAdviseOnlyDisposition() - { - var exec = new FakeServerConfigExecutor(); - - var pre = await new ServerConfigHandler().PreflightAsync( - ServerAction(MaxMemTarget()), exec, CancellationToken.None); - - Assert.Equal(RemediationDisposition.AdviseOnly, pre.Targets.Single().Disposition); - } - - [Fact] - public async Task Preflight_AuditTableAbsent_OverridesExecutableDisposition_NotAdviseOnly() - { - var exec = new FakeServerConfigExecutor { AuditTableExists = false }; - - var pre = await new ServerConfigHandler().PreflightAsync( - ServerAction(MaxdopTarget(), MaxMemTarget()), exec, CancellationToken.None); - - Assert.False(pre.AuditTableExists); - // Executable MAXDOP blocked by absent table; advise-only memory stays AdviseOnly. - Assert.Contains(pre.Targets, t => t.Disposition == RemediationDisposition.BlockAuditTableAbsent); - Assert.Contains(pre.Targets, t => t.Disposition == RemediationDisposition.AdviseOnly); - } - - /// - /// A standalone fake of exercising only the audit + the - /// server-config seam; the other members return harmless defaults. - /// - private sealed class FakeServerConfigExecutor : IRemediationExecutor - { - public bool AuditTableExists = true; - public bool AuditWriteResult = true; - - public Func? PreflightFunc; - public Func? SetFunc; - public int SetCalls; - public readonly List<(ServerConfigSetting Setting, long Value)> SetArgs = new(); - public readonly List AuditRecords = new(); - - public Task AuditTableExistsAsync(CancellationToken ct) => Task.FromResult(AuditTableExists); - - public Task PreflightServerConfigAsync(ServerConfigSetting setting, long recommendedValue, CancellationToken ct) - => Task.FromResult(PreflightFunc?.Invoke(setting, recommendedValue) ?? new ServerConfigPreflight - { - Setting = setting, RecommendedValue = recommendedValue, - Executable = setting is ServerConfigSetting.Maxdop or ServerConfigSetting.CostThreshold, - HasPermission = true, AlreadyInDesiredState = false, ExecutingLogin = "sa", CurrentValue = 0 - }); - - public Task SetServerConfigAsync(ServerConfigSetting setting, long value, RemediationIdentity identity, CancellationToken ct) - { - SetCalls++; - SetArgs.Add((setting, value)); - return Task.FromResult(SetFunc?.Invoke(setting, value) ?? new ServerConfigOutcome - { - Setting = setting, Status = RemediationStatus.Success, Applied = true, ExecutingLogin = "sa", - PriorValue = 0, GeneratedSql = $"EXEC sys.sp_configure N'...', {value}; RECONFIGURE;", - GateSpid = 55, ExecSpid = 55 - }); - } - - public Task WriteAuditAsync(RemediationAuditRecord record, CancellationToken ct) - { - AuditRecords.Add(record); - return Task.FromResult(AuditWriteResult); - } - - // ── Unused seams (harmless defaults) ────────────────────────────────────── - public Task PreflightForcePlanAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(new TargetPreflight { Database = database, QueryId = queryId, PlanId = planId }); - public Task HasPriorForceAsync(string database, long queryId, long planId, CancellationToken ct) - => Task.FromResult(false); - public Task ForcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ForcePlanOutcome { Database = database, QueryId = queryId, PlanId = planId, Status = RemediationStatus.Success }); - public Task UnforcePlanAsync(string database, long queryId, long planId, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ForcePlanOutcome { Database = database, QueryId = queryId, PlanId = planId, Status = RemediationStatus.Success }); - public Task PreflightDbConfigAsync(string database, DbConfigSetting setting, CancellationToken ct) - => Task.FromResult(new DbConfigPreflight { Database = database, Setting = setting }); - public Task SetDatabaseOptionAsync(string database, DbConfigSetting setting, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new DbConfigOutcome { Database = database, Setting = setting, Status = RemediationStatus.Success }); - public Task PreflightFileGrowthAsync(string database, string logicalFileName, int growthMb, CancellationToken ct) - => Task.FromResult(new FileGrowthPreflight { Database = database, LogicalFileName = logicalFileName, RecommendedGrowthMb = growthMb }); - public Task SetFileGrowthAsync(string database, string logicalFileName, int growthMb, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new FileGrowthOutcome { Database = database, LogicalFileName = logicalFileName, Status = RemediationStatus.Success }); - public Task ClearProcCacheAsync(string queryHash, RemediationIdentity identity, CancellationToken ct) - => Task.FromResult(new ClearPlanOutcome { QueryHash = queryHash, Status = RemediationStatus.Success }); - } -} diff --git a/deprecated/Dashboard.Tests/ServerConfigRecommendationTests.cs b/deprecated/Dashboard.Tests/ServerConfigRecommendationTests.cs deleted file mode 100644 index e4bcb22cd4..0000000000 --- a/deprecated/Dashboard.Tests/ServerConfigRecommendationTests.cs +++ /dev/null @@ -1,293 +0,0 @@ -/* - * 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.Analysis; -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Controls; -using PerformanceMonitorDashboard.Services.Recommendations; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// WS3 server-level config: the FactRemediation builder (topology-based MAXDOP / flat CTFP / -/// advise-only memory), the persisted-action DTO round-trip, the Recommendations reader fan-out -/// (one card per ServerConfigTarget; MAXDOP/CTFP carry Apply, memory cards are copy-paste only), and -/// the card affordance model (Copy + Apply / Copy-only, NOT incidents). -/// -public class ServerConfigRecommendationTests -{ - // ── Builder: edition-aware capped MAXDOP, flat CTFP, advise-only memory ──────── - - private static AnalysisFinding ServerConfigFinding(string rootKey, object row) => new() - { - ServerId = 1, - ServerName = "SQL2022", - Category = "config", - StoryPath = rootKey, - StoryPathHash = "sc000001", - RootFactKey = rootKey, - DrillDown = new Dictionary - { - ["server_config"] = new List { row } - } - }; - - [Theory] - // MAXDOP is topology-based: min(cores-per-socket, 8). Edition is NOT consulted. - [InlineData(16, 8)] // > 8 cores per socket -> capped at 8 - [InlineData(8, 8)] // exactly 8 -> 8 - [InlineData(4, 4)] // <= 8 -> the core count - [InlineData(2, 2)] // small box -> 2 - [InlineData(1, 1)] // single core -> 1 - [InlineData(0, 8)] // cores unknown -> the safe general cap of 8 - public void BuildServerConfig_Maxdop_TopologyBased_CappedAt8(int cores, long expectedRecommended) - { - // edition is supplied to mirror the production row shape but is no longer consulted. - var finding = ServerConfigFinding("CONFIG_MAXDOP", - new { setting = "maxdop", current_value = 0, edition = 3, cores_per_socket = cores }); - - var action = FactRemediation.BuildServerConfigAction(finding); - - Assert.NotNull(action); - Assert.Equal("SERVER_CONFIG", action!.FactKey); - var t = Assert.Single(action.ServerConfigTargets!); - Assert.Equal(ServerConfigSetting.Maxdop, t.Setting); - Assert.Equal(0, t.CurrentValue); - Assert.Equal(expectedRecommended, t.RecommendedValue); - } - - [Fact] - public void BuildServerConfig_Ctfp_RecommendsFifty() - { - var finding = ServerConfigFinding("CONFIG_CTFP", - new { setting = "ctfp", current_value = 5, edition = 2, cores_per_socket = 8 }); - - var action = FactRemediation.BuildServerConfigAction(finding); - - var t = Assert.Single(action!.ServerConfigTargets!); - Assert.Equal(ServerConfigSetting.CostThreshold, t.Setting); - Assert.Equal(5, t.CurrentValue); - Assert.Equal(50, t.RecommendedValue); - } - - [Fact] - public void BuildServerConfig_MaxMemory_AdviseOnly_CarriesCurrent() - { - var finding = ServerConfigFinding("CONFIG_MAX_MEMORY_MB", - new { setting = "max_memory", current_value = 2147483647L, edition = 2, cores_per_socket = 8 }); - - var action = FactRemediation.BuildServerConfigAction(finding); - - var t = Assert.Single(action!.ServerConfigTargets!); - Assert.Equal(ServerConfigSetting.MaxServerMemory, t.Setting); - // Advise-only: recommended carries current (the executor refuses to apply it). - Assert.Equal(2147483647L, t.CurrentValue); - Assert.Equal(2147483647L, t.RecommendedValue); - } - - [Fact] - public void BuildServerConfig_MinMemory_AdviseOnly() - { - var finding = ServerConfigFinding("CONFIG_MIN_MAX_MEMORY_NARROW", - new { setting = "min_memory", current_value = 24000L, edition = 2, cores_per_socket = 8 }); - - var action = FactRemediation.BuildServerConfigAction(finding); - - var t = Assert.Single(action!.ServerConfigTargets!); - Assert.Equal(ServerConfigSetting.MinServerMemory, t.Setting); - Assert.Equal(24000L, t.CurrentValue); - } - - [Fact] - public void BuildServerConfig_NoDrillDown_ReturnsNull() - { - var finding = new AnalysisFinding { ServerId = 1, ServerName = "S", RootFactKey = "CONFIG_MAXDOP" }; - Assert.Null(FactRemediation.BuildServerConfigAction(finding)); - } - - [Fact] - public void BuildSpConfigureStatement_RendersHardcodedNameAndValue() - { - Assert.Equal( - "EXEC sys.sp_configure N'max degree of parallelism', 8;\nRECONFIGURE;", - FactRemediation.BuildSpConfigureStatement(ServerConfigSetting.Maxdop, 8)); - Assert.Equal( - "EXEC sys.sp_configure N'cost threshold for parallelism', 50;\nRECONFIGURE;", - FactRemediation.BuildSpConfigureStatement(ServerConfigSetting.CostThreshold, 50)); - } - - // ── DTO round-trip (persisted remediation_action_json) ──────────────────────── - - [Fact] - public void ServerConfigAction_RoundTripsThroughDto() - { - var action = new RemediationAction( - "SERVER_CONFIG", "set", Array.Empty(), - ServerConfigTargets: new[] - { - new ServerConfigTarget(ServerConfigSetting.Maxdop, 0, 8), - new ServerConfigTarget(ServerConfigSetting.MaxServerMemory, 2147483647, 2147483647) - }); - - var json = AlertContextSerializer.SerializeAction(action); - Assert.NotNull(json); - var restored = AlertContextSerializer.DeserializeAction(json); - - Assert.NotNull(restored); - Assert.Equal("SERVER_CONFIG", restored!.FactKey); - Assert.NotNull(restored.ServerConfigTargets); - Assert.Equal(2, restored.ServerConfigTargets!.Count); - - var maxdop = Assert.Single(restored.ServerConfigTargets, t => t.Setting == ServerConfigSetting.Maxdop); - Assert.Equal(0, maxdop.CurrentValue); - Assert.Equal(8, maxdop.RecommendedValue); - - var mem = Assert.Single(restored.ServerConfigTargets, t => t.Setting == ServerConfigSetting.MaxServerMemory); - Assert.Equal(2147483647L, mem.CurrentValue); - } - - [Fact] - public void LegacyActionWithoutServerConfig_DeserializesNull() - { - // A force-plan action (no ServerConfigTargets) must round-trip with the new field null — - // backward compatibility for legacy persisted contexts. - var action = new RemediationAction("PLAN_REGRESSION", "force", - new[] { new ForcePlanTarget("Db", 1, 2) }); - var restored = AlertContextSerializer.DeserializeAction(AlertContextSerializer.SerializeAction(action)); - Assert.NotNull(restored); - Assert.Null(restored!.ServerConfigTargets); - } - - // ── Reader fan-out: one card per target; MAXDOP/CTFP Apply, memory copy-only ─── - - private static AnalysisFinding RootedFinding(string rootKey, RemediationAction action) => new() - { - ServerId = 1, - ServerName = "SQL2022", - DatabaseName = null, // server-scoped - Severity = 0.4, - Category = "config", - RootFactKey = rootKey, - StoryPathHash = "h", - StoryPath = "p", - Remediation = action - }; - - [Fact] - public void Reader_FansAllFourServerConfigCards_WithCorrectAffordances() - { - // One synthetic finding carrying all four targets — exercises the reader's fan loop directly - // (each CONFIG_* roots its own finding in production; the loop turns N targets into N cards). - var action = new RemediationAction( - "SERVER_CONFIG", "set", Array.Empty(), - ServerConfigTargets: new[] - { - new ServerConfigTarget(ServerConfigSetting.Maxdop, 0, 8), - new ServerConfigTarget(ServerConfigSetting.CostThreshold, 5, 50), - new ServerConfigTarget(ServerConfigSetting.MaxServerMemory, 2147483647, 2147483647), - new ServerConfigTarget(ServerConfigSetting.MinServerMemory, 24000, 24000), - }); - - var items = RecommendationsReader.MapEngineFindings(RootedFinding("CONFIG_MAXDOP", action)); - - Assert.Equal(4, items.Count); - Assert.All(items, i => - { - Assert.Equal(RecommendationSource.Engine, i.Source); - Assert.Null(i.Database); // server-scoped - Assert.Equal(RecommendationSetting.None, i.Setting); // never de-dupes - Assert.True(i.IsServerConfigAdvisory); - Assert.False(string.IsNullOrEmpty(i.CopyPasteSql)); // every card has copy-paste - Assert.Contains("SQL2022", i.Title); // title names the server - }); - - // MAXDOP card: Apply present (single-target SERVER_CONFIG action), title + copy-paste. - var maxdop = Assert.Single(items, i => i.Title.StartsWith("MAXDOP is 0")); - Assert.NotNull(maxdop.Remediation); - Assert.Equal("SERVER_CONFIG", maxdop.Remediation!.FactKey); - var mt = Assert.Single(maxdop.Remediation.ServerConfigTargets!); - Assert.Equal(ServerConfigSetting.Maxdop, mt.Setting); - Assert.Equal(8, mt.RecommendedValue); - Assert.Contains("max degree of parallelism", maxdop.CopyPasteSql); - - // CTFP card: Apply present. - var ctfp = Assert.Single(items, i => i.Title.StartsWith("Cost Threshold for Parallelism is 5")); - Assert.NotNull(ctfp.Remediation); - Assert.Equal(ServerConfigSetting.CostThreshold, Assert.Single(ctfp.Remediation!.ServerConfigTargets!).Setting); - Assert.Contains("cost threshold for parallelism", ctfp.CopyPasteSql); - - // max memory card: NO Apply (advise-only), copy-paste only. - var maxMem = Assert.Single(items, i => i.Title.StartsWith("max server memory is unconfigured")); - Assert.Null(maxMem.Remediation); - Assert.Contains("max server memory (MB)", maxMem.CopyPasteSql); - - // min memory card: NO Apply. - var minMem = Assert.Single(items, i => i.Title.StartsWith("min server memory is pinned near max")); - Assert.Null(minMem.Remediation); - Assert.Contains("min server memory (MB)", minMem.CopyPasteSql); - } - - // ── Affordance model: Copy + Apply (MAXDOP/CTFP), Copy-only (memory), NOT incidents ── - - private static RecommendationCardViewModel Card(RecommendationItem item) => new(item, "SQL2022"); - - [Fact] - public void MaxdopCard_ShowsCopyFixAndApply_NotIncident() - { - var item = new RecommendationItem - { - CanonicalSeverity = CanonicalSeverity.Warning, - RawSeverity = 0.4, - Source = RecommendationSource.Engine, - Setting = RecommendationSetting.None, - IsServerConfigAdvisory = true, - Title = "MAXDOP is 0 — SQL2022", - CopyPasteSql = "EXEC sys.sp_configure N'max degree of parallelism', 8;\nRECONFIGURE;", - Remediation = new RemediationAction("SERVER_CONFIG", "set", Array.Empty(), - ServerConfigTargets: new[] { new ServerConfigTarget(ServerConfigSetting.Maxdop, 0, 8) }), - StoryPathHash = "h" - }; - var card = Card(item); - - Assert.False(card.IsIncident); - Assert.False(card.ShowOpenInActiveQueries); - Assert.False(card.ShowAskAi); - Assert.True(card.ShowCopyFix); - Assert.True(card.ShowApply); - } - - [Fact] - public void MaxMemoryCard_ShowsCopyFixOnly_NoApply_NotIncident() - { - // The advise-only memory card carries NO Remediation, but IsServerConfigAdvisory keeps it a - // config fix (Copy fix) rather than a time-bound incident — and Apply is hidden (no action). - var item = new RecommendationItem - { - CanonicalSeverity = CanonicalSeverity.Warning, - RawSeverity = 0.4, - Source = RecommendationSource.Engine, - Setting = RecommendationSetting.None, - IsServerConfigAdvisory = true, - Title = "max server memory is unconfigured — SQL2022", - CopyPasteSql = "EXEC sys.sp_configure N'max server memory (MB)', 28672;\nRECONFIGURE;", - Remediation = null, - StoryPathHash = "h" - }; - var card = Card(item); - - Assert.False(card.IsIncident); // NOT a time-bound incident - Assert.False(card.ShowOpenInActiveQueries); // no incident affordances - Assert.False(card.ShowAskAi); - Assert.True(card.ShowCopyFix); // copy-paste shown - Assert.False(card.ShowApply); // advise-only — no Apply - } -} diff --git a/deprecated/Dashboard.Tests/ServerHealthStatusCollectorVerdictTests.cs b/deprecated/Dashboard.Tests/ServerHealthStatusCollectorVerdictTests.cs deleted file mode 100644 index 9e051bb102..0000000000 --- a/deprecated/Dashboard.Tests/ServerHealthStatusCollectorVerdictTests.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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.Collections.Generic; -using PerformanceMonitorDashboard.Models; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Pins the Overview health card's collector verdict ( / -/// ) — #2784, the Dashboard sibling of the WPF viewer and -/// web (#2779/#2783) parity fix. The verdict used to key ONLY on the failing count, so an offline server — -/// whose collectors have gone stale, leaving FailedCollectorCount at 0 — rendered a green "OK / Healthy: 0, -/// Failing: 0". It now reads a neutral "Stale" off the live IsOnline signal, while a real failure on a -/// reachable server and a plain healthy server are unchanged. -/// #3653 (#3635's class, mirrored): an ONLINE server with zero collectors banded — the -/// report.collection_health SUM came back NULL, or the read failed and left both counts at 0 — is -/// UNMEASURED, not healthy: Unknown, "--", "No collector banded yet". Any collector banded is unchanged. -/// -public class ServerHealthStatusCollectorVerdictTests -{ - [Fact] - public void OnlineServer_WithNoCollectorBanded_IsUnknown_NotGreenOk() - { - var unbanded = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, HealthyCollectorCount = 0, FailedCollectorCount = 0 }; - Assert.Equal(HealthSeverity.Unknown, unbanded.CollectorSeverity); - Assert.Equal("--", unbanded.CollectorDisplayText); - Assert.Equal("No collector banded yet", unbanded.CollectorDetailText); - - /* A failing count with no healthy denominator is still a Warning: a failure was observed even if the - population was not. */ - var failingOnly = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, HealthyCollectorCount = 0, FailedCollectorCount = 1 }; - Assert.Equal(HealthSeverity.Warning, failingOnly.CollectorSeverity); - Assert.Equal("1 failed", failingOnly.CollectorDisplayText); - - /* One collector banded lifts the verdict — the (0, 0) arm is exactly zero, not a threshold. */ - var oneBanded = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, HealthyCollectorCount = 1, FailedCollectorCount = 0 }; - Assert.Equal(HealthSeverity.Healthy, oneBanded.CollectorSeverity); - Assert.Equal("OK", oneBanded.CollectorDisplayText); - Assert.Equal("Healthy: 1, Failing: 0", oneBanded.CollectorDetailText); - } - - [Fact] - public void FirstCollectionLanding_RaisesPropertyChanged_ForCollectorVerdict() - { - // The verdict now depends on the healthy count too (0 -> N is Unknown -> Healthy), so the first - // collection landing must repaint the dot / value / detail, not only the detail line it used to. - var status = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, HealthyCollectorCount = 0, FailedCollectorCount = 0 }; - var raised = new List(); - status.PropertyChanged += (_, e) => raised.Add(e.PropertyName ?? ""); - - status.HealthyCollectorCount = 30; - - Assert.Equal(HealthSeverity.Healthy, status.CollectorSeverity); - Assert.Contains(nameof(ServerHealthStatus.CollectorSeverity), raised); - Assert.Contains(nameof(ServerHealthStatus.CollectorDisplayText), raised); - Assert.Contains(nameof(ServerHealthStatus.CollectorDetailText), raised); - } - - [Fact] - public void OfflineServer_CollectorsReadStaleNeutral_NotGreenOk() - { - var offline = new ServerHealthStatus(new ServerConnection()) { IsOnline = false, HealthyCollectorCount = 0, FailedCollectorCount = 0 }; - Assert.Equal("Stale", offline.CollectorDisplayText); - Assert.Equal("No recent collection", offline.CollectorDetailText); - Assert.Equal(HealthSeverity.Unknown, offline.CollectorSeverity); // neutral, NOT green Healthy - - // Offline wins over a leftover stale failing count too — every count is unmeasured once the server is - // dark, so a "2 failing" left over from the last collection must not keep reading as an active failure. - var offlineWithStaleFailures = new ServerHealthStatus(new ServerConnection()) { IsOnline = false, FailedCollectorCount = 2 }; - Assert.Equal("Stale", offlineWithStaleFailures.CollectorDisplayText); - Assert.Equal(HealthSeverity.Unknown, offlineWithStaleFailures.CollectorSeverity); - } - - [Fact] - public void ReachableServer_RealFailureStillRed_HealthyStillOk() - { - var failing = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, HealthyCollectorCount = 28, FailedCollectorCount = 2 }; - Assert.Equal("2 failed", failing.CollectorDisplayText); - Assert.Equal(HealthSeverity.Warning, failing.CollectorSeverity); - - var healthy = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, HealthyCollectorCount = 30, FailedCollectorCount = 0 }; - Assert.Equal("OK", healthy.CollectorDisplayText); - Assert.Equal("Healthy: 30, Failing: 0", healthy.CollectorDetailText); - Assert.Equal(HealthSeverity.Healthy, healthy.CollectorSeverity); - - // Not-yet-connection-checked (IsOnline null) keeps the pre-#2784 reading — the "Stale" verdict is for - // a KNOWN-offline server only, mirroring the web's `is_online === false`. - var notChecked = new ServerHealthStatus(new ServerConnection()) { HealthyCollectorCount = 30, FailedCollectorCount = 0 }; - Assert.Equal("OK", notChecked.CollectorDisplayText); - Assert.Equal(HealthSeverity.Healthy, notChecked.CollectorSeverity); - } - - [Fact] - public void GoingOffline_RaisesPropertyChanged_ForCollectorVerdict() - { - // The collector verdict now depends on IsOnline, so flipping the connection must repaint the dot / - // value / detail — without these notifications the live-bound row would keep showing the stale "OK". - var status = new ServerHealthStatus(new ServerConnection()) { IsOnline = true, FailedCollectorCount = 0 }; - var raised = new List(); - status.PropertyChanged += (_, e) => raised.Add(e.PropertyName ?? ""); - - status.IsOnline = false; - - Assert.Contains(nameof(ServerHealthStatus.CollectorSeverity), raised); - Assert.Contains(nameof(ServerHealthStatus.CollectorDisplayText), raised); - Assert.Contains(nameof(ServerHealthStatus.CollectorDetailText), raised); - } -} diff --git a/deprecated/Dashboard.Tests/ServerManagerDetectionQueryTests.cs b/deprecated/Dashboard.Tests/ServerManagerDetectionQueryTests.cs deleted file mode 100644 index 2a32528db1..0000000000 --- a/deprecated/Dashboard.Tests/ServerManagerDetectionQueryTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #1535 regression guard (Full Dashboard): the connectivity probe's edition-detection query must -/// read engine edition from permission-free scalars ONLY, never from sys.dm_os_sys_info. The -/// Dashboard rejects Azure SQL DB (EngineEdition 5) as unsupported; before the split, an Azure login -/// lacking VIEW DATABASE STATE threw the combined query, so the edition never registered and the -/// server was mis-handled instead of cleanly rejected with the "use the Lite edition" message. This -/// pins the decoupling; sqlserver_start_time (the one column that needs the DMV) lives in its -/// own best-effort read. -/// -public class ServerManagerDetectionQueryTests -{ - [Fact] - public void DetectionQuery_DoesNotDependOnDmOsSysInfo() - { - Assert.DoesNotContain("dm_os_sys_info", ServerManager.DetectionQueryText, StringComparison.Ordinal); - Assert.DoesNotContain("sqlserver_start_time", ServerManager.DetectionQueryText, StringComparison.Ordinal); - } - - [Fact] - public void DetectionQuery_DetectsEngineEditionViaServerProperty() - { - Assert.Contains("SERVERPROPERTY('EngineEdition')", ServerManager.DetectionQueryText, StringComparison.Ordinal); - } - - [Fact] - public void StartTimeQuery_IsolatesTheOnlyReadThatNeedsDmOsSysInfo() - { - Assert.Contains("sqlserver_start_time", ServerManager.ServerStartTimeQueryText, StringComparison.Ordinal); - Assert.Contains("sys.dm_os_sys_info", ServerManager.ServerStartTimeQueryText, StringComparison.Ordinal); - } -} diff --git a/deprecated/Dashboard.Tests/ServerPropertiesResilienceTests.cs b/deprecated/Dashboard.Tests/ServerPropertiesResilienceTests.cs deleted file mode 100644 index 247afb05cd..0000000000 --- a/deprecated/Dashboard.Tests/ServerPropertiesResilienceTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -using PerformanceMonitorDashboard.Analysis; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// WS5 version-skew resilience: the server_properties SELECT references the server-health columns -/// only when the DB has them, so a not-yet-upgraded server (Dashboard updated before that server's -/// PerformanceMonitor DB got the WS5 upgrade) reads the core hardware columns without a bind error -/// — keeping SERVER_HARDWARE flowing — instead of the whole collector throwing. -/// -public class ServerPropertiesResilienceTests -{ - [Fact] - public void Query_AllHealthColumns_SelectsThemPlusCore() - { - var sql = SqlServerFactCollector.BuildServerPropertiesQuery(hasLpim: true, hasIfi: true, hasDumps: true); - - Assert.Contains("lock_pages_in_memory", sql); - Assert.Contains("instant_file_initialization_enabled", sql); - Assert.Contains("memory_dump_count", sql); - Assert.Contains("cpu_count", sql); - Assert.Contains("FROM collect.server_properties", sql); - } - - [Fact] - public void Query_NoHealthColumns_OmitsThem_ButKeepsCore() - { - var sql = SqlServerFactCollector.BuildServerPropertiesQuery(hasLpim: false, hasIfi: false, hasDumps: false); - - // The WS5 columns must NOT be referenced — that is what avoids the bind error on a - // not-yet-upgraded server. - Assert.DoesNotContain("lock_pages_in_memory", sql); - Assert.DoesNotContain("instant_file_initialization_enabled", sql); - Assert.DoesNotContain("memory_dump_count", sql); - - // The core hardware columns are still selected, so SERVER_HARDWARE keeps flowing. - Assert.Contains("cpu_count", sql); - Assert.Contains("product_version", sql); - Assert.Contains("FROM collect.server_properties", sql); - } - - // The point of per-column probing: a partial / out-of-order schema (some columns present, some - // not) selects EXACTLY the present ones and never references an absent one — so the previous - // all-or-nothing assumption (and its coupling to the migration's column order) can't bite. - [Theory] - [InlineData(true, false, true)] // lpim + dumps present, ifi absent - [InlineData(false, true, false)] // ifi only - [InlineData(true, false, false)] // lpim only - [InlineData(false, false, true)] // dumps only - public void Query_PartialSubset_ReferencesOnlyPresentColumns(bool hasLpim, bool hasIfi, bool hasDumps) - { - var sql = SqlServerFactCollector.BuildServerPropertiesQuery(hasLpim, hasIfi, hasDumps); - - Assert.Equal(hasLpim, sql.Contains("lock_pages_in_memory")); - Assert.Equal(hasIfi, sql.Contains("instant_file_initialization_enabled")); - Assert.Equal(hasDumps, sql.Contains("memory_dump_count")); - Assert.Contains("cpu_count", sql); // core columns always present - } -} diff --git a/deprecated/Dashboard.Tests/SqlServerFindingStoreMappingTests.cs b/deprecated/Dashboard.Tests/SqlServerFindingStoreMappingTests.cs deleted file mode 100644 index 1479f8e771..0000000000 --- a/deprecated/Dashboard.Tests/SqlServerFindingStoreMappingTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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 PerformanceMonitor.Analysis; -using PerformanceMonitorDashboard.Analysis; -using Xunit; - -namespace Dashboard.Tests; - -/// -/// Pins the story→finding mapping the Dashboard finding store persists — extracted (and made -/// testable) after the Darling PgFindingStore port surfaced that this mapping dropped -/// DatabaseName, storing NULL database_name on every finding since the store shipped. -/// -public sealed class SqlServerFindingStoreMappingTests -{ - [Fact] - public void MapStoryToFinding_PreservesDatabaseName_AndConvertsWindowToUtc() - { - var story = new AnalysisStory - { - DatabaseName = "StackOverflow2010", - Severity = 70, - Confidence = 0.9, - Category = "Concurrency", - StoryPath = "BLOCKING_STORM", - StoryPathHash = "abc123", - IncidentId = "inc-1", - StoryText = "story", - RootFactKey = "BLOCKING", - RootFactValue = 42, - FactCount = 3, - }; - var context = new AnalysisContext - { - ServerId = 7, - ServerName = "SQL2022", - TimeRangeStart = new DateTime(2026, 7, 2, 10, 0, 0), - TimeRangeEnd = new DateTime(2026, 7, 2, 14, 0, 0), - ServerUtcOffset = TimeSpan.FromHours(-4), - }; - var analysisTime = new DateTime(2026, 7, 2, 14, 5, 0, DateTimeKind.Utc); - - var finding = SqlServerFindingStore.MapStoryToFinding(story, context, analysisTime, 99); - - Assert.Equal("StackOverflow2010", finding.DatabaseName); /* the fixed drop */ - Assert.Equal(99, finding.FindingId); - Assert.Equal(7, finding.ServerId); - Assert.Equal("SQL2022", finding.ServerName); - /* Server-local window − offset = UTC (offset here is −4h, so UTC = local + 4h). */ - Assert.Equal(new DateTime(2026, 7, 2, 14, 0, 0), finding.TimeRangeStart); - Assert.Equal(new DateTime(2026, 7, 2, 18, 0, 0), finding.TimeRangeEnd); - Assert.Equal(70, finding.Severity); - Assert.Equal("BLOCKING_STORM", finding.StoryPath); - Assert.Equal("inc-1", finding.IncidentId); - Assert.Equal(3, finding.FactCount); - } - - [Fact] - public void GetMutedHashesSql_HonorsGlobalNull_AndLegacyZeroServerId() - { - /* An all-servers mute persists server_id = NULL (the canonical global marker); legacy rows - written by the pre-fix MCP "all servers" tool path used server_id = 0. The reader must honor - both, plus the per-server id, so an all-servers mute actually mutes everywhere. */ - Assert.Contains("server_id = @serverId", SqlServerFindingStore.GetMutedHashesSql, StringComparison.Ordinal); - Assert.Contains("server_id IS NULL", SqlServerFindingStore.GetMutedHashesSql, StringComparison.Ordinal); - Assert.Contains("server_id = 0", SqlServerFindingStore.GetMutedHashesSql, StringComparison.Ordinal); - } - - [Fact] - public void CleanupOldFindingsSql_PurgesByAnalysisTime_FromFindingsTable() - { - /* Findings retention (scheduled once per 24h by AnalysisScheduler — the store declared this - cleanup but nothing called it, so config.analysis_findings grew unbounded). Pin the purge - target + predicate: it must DELETE from the findings table, keyed on analysis_time against - the @cutoff parameter — never the muted registry. */ - Assert.Contains("DELETE FROM config.analysis_findings", SqlServerFindingStore.CleanupOldFindingsSql, StringComparison.Ordinal); - Assert.Contains("analysis_time < @cutoff", SqlServerFindingStore.CleanupOldFindingsSql, StringComparison.Ordinal); - Assert.DoesNotContain("analysis_muted", SqlServerFindingStore.CleanupOldFindingsSql, StringComparison.Ordinal); - } -} diff --git a/deprecated/Dashboard.Tests/ThemeParityTests.cs b/deprecated/Dashboard.Tests/ThemeParityTests.cs deleted file mode 100644 index 37e0092ee5..0000000000 --- a/deprecated/Dashboard.Tests/ThemeParityTests.cs +++ /dev/null @@ -1,212 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Xml.Linq; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Cross-app theme-parity guard. The WPF brush/color dictionaries are NOT shared: Dashboard and Lite -/// each ship their own Themes/{Dark,Light,CoolBreeze}Theme.xaml — six separate files, hand-synced with -/// no enforcement. Their shared palette keys currently match, but nothing keeps them in sync, so a color -/// tweak applied to one app can silently drift the two apart. -/// -/// For each theme this parses the x:Key -> color map from both apps' same-theme file and asserts that -/// every key present in BOTH (the intersection) resolves to the same color. Keys that exist in only one -/// app (e.g. Dashboard's TimeRangeSlicer-only brushes) are allowed and ignored — only the overlap is -/// asserted, so either app may add app-specific resources without tripping the guard. -/// -public class ThemeParityTests -{ - private static readonly XNamespace X = "http://schemas.microsoft.com/winfx/2006/xaml"; - - [Theory] - [InlineData("Dark")] - [InlineData("Light")] - [InlineData("CoolBreeze")] - public void SharedThemeKeys_HaveIdenticalColors_AcrossApps(string theme) - { - var repoRoot = FindRepoRoot(); - Assert.True(repoRoot is not null, - $"Could not locate the repo root (a directory containing both {DashboardThemesPath} and Lite\\Themes) " + - $"by walking up from {AppContext.BaseDirectory}."); - - var dashboardFile = Path.Combine(repoRoot!, DashboardThemesPath, $"{theme}Theme.xaml"); - var liteFile = Path.Combine(repoRoot!, "Lite", "Themes", $"{theme}Theme.xaml"); - Assert.True(File.Exists(dashboardFile), $"Dashboard theme file not found: {dashboardFile}"); - Assert.True(File.Exists(liteFile), $"Lite theme file not found: {liteFile}"); - - var dashboard = LoadColorMap(dashboardFile); - var lite = LoadColorMap(liteFile); - - var shared = dashboard.Keys - .Intersect(lite.Keys) - .OrderBy(k => k, StringComparer.Ordinal) - .ToList(); - - // Guard against a parser regression (e.g. a XAML namespace change) silently turning this into a - // vacuous pass: the two apps share dozens of palette keys today, so an empty intersection is a bug. - Assert.True(shared.Count > 0, - $"No shared color/brush keys parsed for the {theme} theme — the parser or the theme files changed shape."); - - var mismatches = shared - .Where(k => !string.Equals(dashboard[k], lite[k], StringComparison.Ordinal)) - .Select(k => $" {k}: Dashboard={dashboard[k]} Lite={lite[k]}") - .ToList(); - - Assert.True(mismatches.Count == 0, - $"{theme} theme: {mismatches.Count} shared color/brush key(s) differ between Dashboard\\Themes\\{theme}Theme.xaml " + - $"and Lite\\Themes\\{theme}Theme.xaml. Re-sync the two palettes:\n" + string.Join("\n", mismatches)); - } - - /// - /// Parses a theme ResourceDictionary into a map of x:Key -> normalized #AARRGGBB color. Handles the two - /// resource forms used in these files: standalone <Color x:Key="...">#hex</Color> and - /// <SolidColorBrush x:Key="..." Color="#hex | {StaticResource SomeColor}"/>, resolving a brush's - /// {StaticResource} reference back to the underlying <Color> hex. Entries whose color cannot be - /// resolved to a concrete value (e.g. a reference to a non-Color resource) are omitted from the map. - /// First definition wins, so the top-of-file palette is preferred over any template-local re-key. - /// - private static Dictionary LoadColorMap(string xamlPath) - { - var doc = XDocument.Load(xamlPath); - - // Pass 1: literal resources. - var colors = new Dictionary(StringComparer.Ordinal); - foreach (var el in doc.Descendants().Where(e => e.Name.LocalName == "Color")) - { - var key = (string?)el.Attribute(X + "Key"); - if (key is null || colors.ContainsKey(key)) - { - continue; - } - colors[key] = el.Value.Trim(); - } - - // Pass 2: resources (Color is an unprefixed attribute, so no namespace). - var brushes = new Dictionary(StringComparer.Ordinal); - foreach (var el in doc.Descendants().Where(e => e.Name.LocalName == "SolidColorBrush")) - { - var key = (string?)el.Attribute(X + "Key"); - var color = (string?)el.Attribute("Color"); - if (key is null || color is null || brushes.ContainsKey(key)) - { - continue; - } - brushes[key] = color.Trim(); - } - - var map = new Dictionary(StringComparer.Ordinal); - foreach (var pair in colors) - { - var norm = NormalizeColor(pair.Value); - if (norm is not null) - { - map[pair.Key] = norm; - } - } - foreach (var pair in brushes) - { - var resolved = ResolveColor(pair.Value, colors); - var norm = resolved is null ? null : NormalizeColor(resolved); - if (norm is not null) - { - map[pair.Key] = norm; - } - } - return map; - } - - private static readonly Regex StaticResourceRef = - new(@"^\{StaticResource\s+([^}]+)\}$", RegexOptions.Compiled); - - /// - /// Resolves a brush Color value to a literal color token, following one or more {StaticResource X} hops - /// into the <Color> table. Returns null when the chain dead-ends at a key that is not a <Color>. - /// - private static string? ResolveColor(string value, Dictionary colors, int depth = 0) - { - if (depth > 10) - { - return null; - } - - var trimmed = value.Trim(); - var match = StaticResourceRef.Match(trimmed); - if (!match.Success) - { - return trimmed; - } - - var refKey = match.Groups[1].Value.Trim(); - return colors.TryGetValue(refKey, out var inner) - ? ResolveColor(inner, colors, depth + 1) - : null; - } - - /// - /// Normalizes a color token to canonical upper-case #AARRGGBB so equivalent spellings (#RGB, #ARGB, - /// #RRGGBB, #AARRGGBB — WPF treats a missing alpha as fully opaque) compare equal. Non-hex named colors - /// (e.g. White, Transparent) are upper-cased as-is so they still compare. Returns null for empty input. - /// - private static string? NormalizeColor(string? raw) - { - if (string.IsNullOrWhiteSpace(raw)) - { - return null; - } - - var c = raw.Trim(); - var match = Regex.Match(c, "^#([0-9A-Fa-f]+)$"); - if (!match.Success) - { - return c.ToUpperInvariant(); - } - - var h = match.Groups[1].Value.ToUpperInvariant(); - h = h.Length switch - { - 3 => "FF" + string.Concat(h.Select(ch => $"{ch}{ch}")), // #RGB -> #FFRRGGBB - 4 => string.Concat(h.Select(ch => $"{ch}{ch}")), // #ARGB -> #AARRGGBB - 6 => "FF" + h, // #RRGGBB -> #FFRRGGBB - _ => h, - }; - - // Anything that did not land on a clean 8-digit ARGB (e.g. a malformed 5/7-digit token) falls back - // to the upper-cased original so it still compares deterministically rather than being dropped. - return h.Length == 8 ? "#" + h : c.ToUpperInvariant(); - } - - /// Repo-relative path to the Dashboard's theme folder — under deprecated/ since #1612. - private static readonly string DashboardThemesPath = Path.Combine("deprecated", "Dashboard", "Themes"); - - /// - /// Walks up from the test output directory to the repo root — the directory that contains both - /// Dashboard\Themes and Lite\Themes. Mirrors Installer.Tests' FindInstallDirectory walk-up. - /// - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (Directory.Exists(Path.Combine(dir.FullName, DashboardThemesPath)) && - Directory.Exists(Path.Combine(dir.FullName, "Lite", "Themes"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/TopCpuQueriesTextMirrorTests.cs b/deprecated/Dashboard.Tests/TopCpuQueriesTextMirrorTests.cs deleted file mode 100644 index 276d08e971..0000000000 --- a/deprecated/Dashboard.Tests/TopCpuQueriesTextMirrorTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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.IO; -using System.Linq; -using System.Text.RegularExpressions; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// #3959, the frozen Dashboard's mirror of the Darling/Lite top-CPU drill-down fix. The read took -/// MAX(query_text) over every window row's compressed varbinary(max) statement to print five -/// groups. It now ranks and cuts to five without the text and reads the text for those five, the same -/// MAX over the same rows. -/// -/// Pinned on the source text, the only idiom this project has for its SQL-Server-side reads (there is no -/// test database). The old and new SQL were also run side by side on a scratch database on SQL Server 2016 -/// (compatibility level 130, the oldest the product supports) and returned identical rows, NULL -/// query_hash groups included. -/// -public class TopCpuQueriesTextMirrorTests -{ - [Fact] - public void TheTopCpuDrillDown_RanksWithoutTheText_AndReadsItForThePrintedGroups() - { - var sql = Regex.Replace( - MethodBody(Read("SqlServerDrillDownCollector.Queries.cs"), "CollectTopCpuQueries"), - @"--[^\r\n]*", - string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal); - - var ranking = sql.IndexOf("WITH top_queries AS", StringComparison.Ordinal); - var rankingEnd = sql.IndexOf("\n)\nSELECT", ranking + 1, StringComparison.Ordinal); - var apply = sql.IndexOf("OUTER APPLY", StringComparison.Ordinal); - Assert.True(ranking >= 0 && rankingEnd > ranking && apply > rankingEnd, "the ranking CTE should precede the text read"); - - /* The ranking and cut carry no text... */ - Assert.DoesNotContain("query_text", sql[ranking..rankingEnd], StringComparison.Ordinal); - Assert.Contains("SELECT TOP (5)", sql[ranking..rankingEnd], StringComparison.Ordinal); - - /* ...the text is the same MAX, read per printed group under the window's own filter, NULL-safe on the - nullable hash (IS NOT DISTINCT FROM needs SQL Server 2022). */ - var text = sql[apply..]; - Assert.Contains("SELECT MAX(qs.query_text) AS query_text", text, StringComparison.Ordinal); - Assert.Contains("qs.collection_time >= @startTime AND qs.collection_time <= @endTime", text, StringComparison.Ordinal); - Assert.Contains("qs.total_worker_time_delta > 0", text, StringComparison.Ordinal); - Assert.Contains("(qs.query_hash = t.query_hash OR (qs.query_hash IS NULL AND t.query_hash IS NULL))", text, StringComparison.Ordinal); - Assert.Contains("LEFT(CAST(DECOMPRESS(x.query_text) AS NVARCHAR(MAX)), 500) AS query_text", sql, StringComparison.Ordinal); - } - - /// The method's text from its signature to the next member's signature (or the end of the file). - private static string MethodBody(string src, string method) - { - var start = src.IndexOf($"private async Task {method}(", StringComparison.Ordinal); - Assert.True(start >= 0, $"method not found: {method}"); - var next = src.IndexOf("private async Task ", start + method.Length, StringComparison.Ordinal); - return next < 0 ? src[start..] : src[start..next]; - } - - private static string Read(string file) - { - var root = FindRepoRoot(); - Assert.True(root is not null, $"Could not locate the repo root (a directory containing deprecated/Dashboard/Dashboard.csproj) by walking up from {AppContext.BaseDirectory}."); - var path = Path.Combine(root!, "deprecated", "Dashboard", "Analysis", file); - Assert.True(File.Exists(path), $"Source file not found: {path}"); - return File.ReadAllText(path); - } - - /// Walks up from the test output directory to the repo root — the directory holding the Dashboard project. Mirrors DashboardMirrorPinTests. - private static string? FindRepoRoot() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - for (int i = 0; i < 10 && dir is not null; i++) - { - if (File.Exists(Path.Combine(dir.FullName, "deprecated", "Dashboard", "Dashboard.csproj"))) - { - return dir.FullName; - } - dir = dir.Parent; - } - return null; - } -} diff --git a/deprecated/Dashboard.Tests/WebhookPayloadBrandingTests.cs b/deprecated/Dashboard.Tests/WebhookPayloadBrandingTests.cs deleted file mode 100644 index cd5c0beec6..0000000000 --- a/deprecated/Dashboard.Tests/WebhookPayloadBrandingTests.cs +++ /dev/null @@ -1,42 +0,0 @@ -using PerformanceMonitor.Notifications; -using PerformanceMonitorDashboard.Services; -using Xunit; - -namespace PerformanceMonitorDashboard.Tests; - -/// -/// Identical-output invariant for Plan E Stage E3c: the shared WebhookAlertService payload -/// builders, fed Dashboard's wired AlertBranding (via EmailAlertService.Branding), must -/// reproduce Dashboard's pre-E3c Teams/Slack payloads — edition string "Performance Monitor -/// Dashboard" and NO snooze hint (Dashboard's AlertBranding.SnoozeHint is null). -/// -public class WebhookPayloadBrandingTests -{ - [Fact] - public void BuildTeamsPayload_DashboardBranding_IncludesEditionAndOmitsSnooze() - { - var branding = EmailAlertService.Branding; - Assert.Equal("Performance Monitor Dashboard", branding.EditionName); - Assert.Null(branding.SnoozeHint); - - var payload = WebhookAlertService.BuildTeamsPayload( - "High CPU", "TestServer", "95%", "90%", branding); - - Assert.Contains("Performance Monitor Dashboard", payload); - Assert.DoesNotContain("Performance Monitor Lite", payload); - // Lite's snooze hint must never appear under Dashboard branding. - Assert.DoesNotContain("Manage Mute Rules", payload); - } - - [Fact] - public void BuildSlackPayload_DashboardBranding_IncludesEditionAndOmitsSnooze() - { - var branding = EmailAlertService.Branding; - - var payload = WebhookAlertService.BuildSlackPayload( - "High CPU", "TestServer", "95%", "90%", branding); - - Assert.Contains("Sent by Performance Monitor Dashboard", payload); - Assert.DoesNotContain("Manage Mute Rules", payload); - } -} diff --git a/deprecated/Dashboard.Tests/packages.lock.json b/deprecated/Dashboard.Tests/packages.lock.json deleted file mode 100644 index 6f2d84bae0..0000000000 --- a/deprecated/Dashboard.Tests/packages.lock.json +++ /dev/null @@ -1,947 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net10.0-windows7.0": { - "xunit.v3": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "TdjM2OAx7w/0E88E6PgaigLoTbQaxbSR3HF/8p92plchTjf29jPHW27ylvEOz+Nx8CvPwWKGQlOR1fDv6/Qh5A==", - "dependencies": { - "xunit.v3.mtp-v2": "[4.0.2]" - } - }, - "Azure.Core": { - "type": "Transitive", - "resolved": "1.51.1", - "contentHash": "JRANrRvN5O5FFRh+pMUb8qqWU7jBQ39qXEbVr7Rkb1/s7rqc6RSzVHKGBz5Ro1gDy2WSGjG5YEOJKpPIBiCMcA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "10.0.2", - "System.ClientModel": "1.9.0", - "System.Memory.Data": "10.0.1" - } - }, - "Azure.Identity": { - "type": "Transitive", - "resolved": "1.18.0", - "contentHash": "HiTpL2XRANXSPyrIkaq7eNDthi99UFbbJwMfpkkbVcdo3Au6yl3vPNWveoa4nO24JTcwyyXATZHn+eVnrVAWEQ==", - "dependencies": { - "Azure.Core": "1.51.1", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.3", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.3", - "Microsoft.Identity.Client": "4.78.0", - "Microsoft.Identity.Client.Extensions.Msal": "4.78.0" - } - }, - "HarfBuzzSharp": { - "type": "Transitive", - "resolved": "8.3.1.1", - "contentHash": "tLZN66oe/uiRPTZfrCU4i8ScVGwqHNh5MHrXj0yVf4l7Mz0FhTGnQ71RGySROTmdognAs0JtluHkL41pIabWuQ==", - "dependencies": { - "HarfBuzzSharp.NativeAssets.Win32": "8.3.1.1", - "HarfBuzzSharp.NativeAssets.macOS": "8.3.1.1" - } - }, - "HarfBuzzSharp.NativeAssets.Linux": { - "type": "Transitive", - "resolved": "8.3.1.1", - "contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg==" - }, - "HarfBuzzSharp.NativeAssets.macOS": { - "type": "Transitive", - "resolved": "8.3.1.1", - "contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ==" - }, - "HarfBuzzSharp.NativeAssets.Win32": { - "type": "Transitive", - "resolved": "8.3.1.1", - "contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA==" - }, - "Microsoft.ApplicationInsights": { - "type": "Transitive", - "resolved": "2.23.0", - "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "10.0.2", - "contentHash": "qE5JhRoeJbAipLqpUCZyNfNwnpAvUttXgIQDnTiJ15d8ji+/bPgoPkB3xLzK5cQTobN2D2ditUesUlDHb7p3Pg==" - }, - "Microsoft.Bcl.Cryptography": { - "type": "Transitive", - "resolved": "9.0.18", - "contentHash": "42XcqOGj0jTNW6FphUEuhNLCdVQsYbYCf2pPlkWdz1uDyxxirpcxyjg7pWIBgPCjzk6rv/irgLya/2tDJKIpYg==" - }, - "Microsoft.Data.SqlClient.Extensions.Abstractions": { - "type": "Transitive", - "resolved": "7.1.1", - "contentHash": "qP/zUOCJwfKqWNC9o+TWqltfNbLnZi1APNpJZgj0yeEJhoI+h+eoQLX+331yZHNOlDxdafZLP5arW/yrS1jAAw==", - "dependencies": { - "Microsoft.Data.SqlClient.Internal.Logging": "[7.1.1, 8.0.0)" - } - }, - "Microsoft.Data.SqlClient.Internal.Logging": { - "type": "Transitive", - "resolved": "7.1.1", - "contentHash": "bVqbATLnHQngue7U9K7GRnzvfdDa7IyiBU2vijfU2vBMBSZrAnQp/wXqNSfaVonckSaMXUk07wfujTqy9IVMdw==" - }, - "Microsoft.Data.SqlClient.SNI.runtime": { - "type": "Transitive", - "resolved": "7.1.0", - "contentHash": "rWunOb6Dby0lcI82PohARcRbF+4x4wNKxnKRSHXhuwZMu8/cCS68DCfhceq4bv1gUEfoL5dWXHYnfxVvLQUN+Q==" - }, - "Microsoft.Extensions.AI.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h4DX/TdJU4fk1GGaf19n6Kujkj6VXbGeL4UEOsQ8+ZJC5fVApPauokCtvBP684BYbczUYZQNfo1mbmyHG4WVSg==" - }, - "Microsoft.Extensions.Caching.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "UOJqcdNMoFcV/5RUcOlVKq9pPmbrcmbpLx5iYz9QtrmMcWRQzlL5Q/NZRfbPPLNyIEc1HWjjs5Z7nIwqewU1sg==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" - } - }, - "Microsoft.Extensions.Caching.Memory": { - "type": "Transitive", - "resolved": "9.0.18", - "contentHash": "ZQ+x93CRR8DOGT+YPP4YXvwTAJ0MfvAghs5cwCSvtZFiORSfprAw9f67d0QDhf6PCIYyFsMKFB+PI3p9lpiMUQ==", - "dependencies": { - "Microsoft.Extensions.Caching.Abstractions": "9.0.18", - "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.18", - "Microsoft.Extensions.Logging.Abstractions": "9.0.18", - "Microsoft.Extensions.Options": "9.0.18", - "Microsoft.Extensions.Primitives": "9.0.18" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Binder": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.CommandLine": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "/9IqkBeB7mE1enbN4Cfeu4HFPU9uR1JSJh2qwXfwr7SYBxETkTKRht/LoPfajmmlh+BJlH3jm79CLhQPFb9ovw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.EnvironmentVariables": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "jB0UiYjpnneoBH1ZeXPlHYt4zUme6SZlnstL6gsH/0O/d5rOuN5lSIlOIfxXzapl8tAi7QmYOEogP09g/wcHzA==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.FileExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "NBIfm8vWNi3UJ9OI9thvREJeV6KzEdPjQ4ONdH+yPWutGBpVnwLbXiEqdEFaGAFYpAluGCfyCwKFgH9pd2scfw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Physical": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.UserSecrets": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "z+dvl9uQnNzvq6Xco+UQyeujpP/BHs+ahHLPCBMxR5GW6M4JcsN1tupEgn5uWgR1fGCfmxS4QJEMt6eyizXGUA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Json": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Physical": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" - }, - "Microsoft.Extensions.Diagnostics": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.FileProviders.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "rAqf2Em2ZjLqNbcLJlboQnXNyJP604F960TsCKNiP00Ur6ExIc1mcwmNb8L2eTRT8RC8UKx/GjecoWcW2Sj7bw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.FileProviders.Physical": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "dcp6eCIk6ZpE3CTNmIna0ifgxsPel/MtOc23/Y/AJlD9SZZr7bhlKK2DAXYlrz81yMkMi6el/LHHUFKCZ3ufuQ==", - "dependencies": { - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.FileSystemGlobbing": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.FileSystemGlobbing": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "xt6c/PWLL6+CiBiZA3PWRSfkwcPh+HCwiOLrgSUkhzBT7lrT/+QpIKPeuCQyDPspwOuG1q0cbJhuiGpRjr4UNQ==" - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "p6NUEkmlaB+FujQZTtyNBKFULQO+Fj8SKuYdYHASQso+RkeYdFDPNsMM4mtOHqx1GZNQnZm/inmsqGkja/Dw2w==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Configuration": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "CfFSNbVSXSl8UTH453c0HoY5owcpaY1PMh1xsB+3NWcEq6WUSPHRotydbnMJtmw7Kybp6cTba8e+/uaJI52ANw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Console": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "8Qx57p3sUAajSZHLQf8eihZqMtSIeI4fZ1JVpL4fvg4QqSbbgJkN0X0owX1cVJJRW2Xw4uqtVv9F7LgdXOBQHQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging.Configuration": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Debug": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "8e79uonXzgIsZbdgc5pa2Ybk5W+vUbd+gfGS50E+BW9ApRv9s0qL1DTyqLv7VQEPxTHS/l8Y0AtS7K8do+TczQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.EventLog": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4HbWayQiJdw0lYthC45rElah2mJJeSlHDu3rcIrinGe95JdOt6I/vWQTNUFXiujIsHv3Z8MyA79ZC5P1Ww+jNg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.EventSource": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "Q06Q90D3qnrsKtf1QlaMELCED3ZdMV5SGIRIERUQTTSCoqTNKSitx3KMRgLdxBeqI5ZcbOu5InOu6xQ6o6zmUg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Options": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Options.ConfigurationExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.Identity.Client": { - "type": "Transitive", - "resolved": "4.84.2", - "contentHash": "Va9FjmABSgj/lcUfHH0pBNQkmS7SNyepz2ERV7Yynp6QgEYpFdSqR6Vzy1WWipN8GS5pBHuXoZbqaDWuARCrHQ==", - "dependencies": { - "Microsoft.IdentityModel.Abstractions": "8.14.0" - } - }, - "Microsoft.Identity.Client.Broker": { - "type": "Transitive", - "resolved": "4.84.2", - "contentHash": "928ySLeGz1xtvydwq6h9tv7TbxrtA4ZzavLKUqRJh0PW6BGcEJwpI8W8vf2PlQdYemGm/oyGjdzYzdY/I8r/4A==", - "dependencies": { - "Microsoft.Identity.Client": "4.84.2", - "Microsoft.Identity.Client.NativeInterop": "0.20.6" - } - }, - "Microsoft.Identity.Client.Extensions.Msal": { - "type": "Transitive", - "resolved": "4.78.0", - "contentHash": "DYU9o+DrDQuyZxeq91GBA9eNqBvA3ZMkLzQpF7L9dTk6FcIBM1y1IHXWqiKXTvptPF7CZE59upbyUoa+FJ5eiA==", - "dependencies": { - "Microsoft.Identity.Client": "4.78.0" - } - }, - "Microsoft.Identity.Client.NativeInterop": { - "type": "Transitive", - "resolved": "0.20.6", - "contentHash": "noyfdMfVxyWpM6xUDmlW6gUvZ5ci24z7Qoy15JvynTQfZV5vTD2NEdsnT5Gy4ngViwgdIp5iRjRy10jAKXFAgw==" - }, - "Microsoft.IdentityModel.Abstractions": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "gSxKLWRZzBpIsEoeUPkxfywNCCvRvl7hkq146XHPk5vOQc9izSf1I+uL1vh4y2U19QPxd9Z8K/8AdWyxYz2lSg==" - }, - "Microsoft.IdentityModel.JsonWebTokens": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "prBU72cIP4V8E9fhN+o/YdskTsLeIcnKPbhZf0X6mD7fdxoZqnS/NdEkSr+9Zp+2q7OZBOMfNBKGbTbhXODO4w==", - "dependencies": { - "Microsoft.IdentityModel.Tokens": "8.16.0" - } - }, - "Microsoft.IdentityModel.Logging": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "MTzXmETkNQPACR7/XCXM1OGM6oU9RkyibqeJRtO9Ndew2LnGjMf9Atqj2VSf4XC27X0FQycUAlzxxEgQMWn2xQ==", - "dependencies": { - "Microsoft.IdentityModel.Abstractions": "8.16.0" - } - }, - "Microsoft.IdentityModel.Protocols": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "UFrU7d46UTsPQTa2HIEIpB9H1uJe1BW9FLw5uhEJ2ZuKdur8bcUA/bO5caq5dlBt5gNJeRIB3QQXYNs5fCQCZA==", - "dependencies": { - "Microsoft.IdentityModel.Tokens": "8.16.0" - } - }, - "Microsoft.IdentityModel.Protocols.OpenIdConnect": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "h4yVXyJsEBBX5lg2G5ftMsi5JzcNEGAzrNphA6DQ6eOd8P0s+cDCOyPwVTYLePZvJL5unbPvYIvzrbTXzFjXnQ==", - "dependencies": { - "Microsoft.IdentityModel.Protocols": "8.16.0", - "System.IdentityModel.Tokens.Jwt": "8.16.0" - } - }, - "Microsoft.IdentityModel.Tokens": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "rtViGJcGsN7WcfUNErwNeQgjuU5cJNl6FDQsfi9TncwO+Epzn0FTfBsg3YuFW1Q0Ch/KPxaVdjLw3/+5Z5ceFQ==", - "dependencies": { - "Microsoft.Extensions.Logging.Abstractions": "10.0.0", - "Microsoft.IdentityModel.Logging": "8.16.0" - } - }, - "Microsoft.SqlServer.Server": { - "type": "Transitive", - "resolved": "1.0.0", - "contentHash": "N4KeF3cpcm1PUHym1RmakkzfkEv3GRMyofVv40uXsQhCQeglr2OHNcUk2WOG51AKpGO8ynGpo9M/kFXSzghwug==" - }, - "Microsoft.Testing.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "mu2iyoHovwl0q1mGeeRU0h8+LALXC7HqbxniLa1shTKYdJGl+KPoCEgjWIQ8MLzk1tlTGPOfg1JsxdH3RxhMCA==", - "dependencies": { - "Microsoft.ApplicationInsights": "2.23.0", - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Extensions.TrxReport.Abstractions": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "DYTZAguaHz0wNJdHDTTGYOXtnlDoLoIbTMDKSApNNcytm55DJcnwpwELfQGLk5DB5QlgaEjNhnGo1Pu5QvL5VA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Platform": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "FAMaFFWnULW+hDHMb40Qzhcgz9cAU2/EtgRCBNX/DdQoKo0sPG2EiY+w7bQdl/BgHnf/DbpXLbf5Xy0o15M8NA==" - }, - "Microsoft.Testing.Platform.MSBuild": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "lYawcAwY+h76rQmpma2n0HaL8zkOFbbKapso0Eb+uOAUQn7333pIByLftEuiO67csAoZufHNMwi6PqhNemWQXA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Win32.Registry": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" - }, - "ModelContextProtocol.Core": { - "type": "Transitive", - "resolved": "2.3.0", - "contentHash": "EDpbQholhVWoNumb0Ab3oGv9LmXOLgaD5ixEIUkrnzpnqD0TJCSHTJ5G71/J1KlrQ98aWDclWTPMffKTnCJoMw==", - "dependencies": { - "Microsoft.Extensions.AI.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" - } - }, - "OpenTK": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "fp9ZI6akO4ZuIGzuUE0QRU5zRJhXbSXa5racehFoTdvodhRDecXCOcH68mRsZaMwnxLO9ECnf2LGM9BmiJKvhw==", - "dependencies": { - "OpenTK.Audio.OpenAL": "4.9.4", - "OpenTK.Compute": "4.9.4", - "OpenTK.Core": "4.9.4", - "OpenTK.Graphics": "4.9.4", - "OpenTK.Input": "4.9.4", - "OpenTK.Mathematics": "4.9.4", - "OpenTK.Windowing.Common": "4.9.4", - "OpenTK.Windowing.Desktop": "4.9.4", - "OpenTK.Windowing.GraphicsLibraryFramework": "4.9.4" - } - }, - "OpenTK.Audio.OpenAL": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "N/SCeFrLJ3ckUbshyfsonbtjmDxh55urGiR+Fe1iPkTWyEW5OKfQRoIOZyjEva/4eRqOXdt3bV2ka4IJ2+JvZw==", - "dependencies": { - "OpenTK.Core": "[4.9.4, 4.10.0)", - "OpenTK.Mathematics": "[4.9.4, 4.10.0)" - } - }, - "OpenTK.Compute": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "30G+/9mtrUJwX5xcRyz2qcujQ2s+wDm+C7qg6jDsLyGWUdND3j/vD+nlQ6tuKuAow51zWduFVujPkaS8VrBinQ==" - }, - "OpenTK.Core": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "/4Mn3ABf1xNfHMzDFUapVY2K4PG3oP/oWTQJlK0JacT20HwsNe/HPIAhnAJWz27EM3ukOJDtqyQRukvQKqkcLw==" - }, - "OpenTK.GLWpfControl": { - "type": "Transitive", - "resolved": "4.3.3", - "contentHash": "mbKt+ZApqYk/Ym4Ph0dnI+hfSnyXn/gWW6Ys6l3C+fMlgXLYaWpbQ+/3yNm6G1lJ3vteXGxtoMJPFYlaXi/tQw==", - "dependencies": { - "OpenTK": "[4.8.2, 5.0.0)" - } - }, - "OpenTK.Graphics": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "yZeq5swIsRnNzifVA9fLtl+qMAQvmYiF1b7U/XQLARmmU4PYQ23lPNahqAdD22XzA21ew7eG3yDyPLkYw+hDBA==", - "dependencies": { - "OpenTK.Core": "[4.9.4, 4.10.0)", - "OpenTK.Mathematics": "[4.9.4, 4.10.0)" - } - }, - "OpenTK.Input": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "njbC7fySQEK30rjOQ1uRjlycEkLw+UVoPT3nRQ8uBPNLotDgr47NEcPEjmJyX1ll+pm/wmtcvJIYHBRi1HbOqg==" - }, - "OpenTK.Mathematics": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "2ucF25RVJzdSLXUHgjAgB058gVfSgerrR5pLCn9J+Bnyqi45NrBfPu9wyTT35ZCjYwLJCu/HJMnzKFLjq+uFIA==" - }, - "OpenTK.redist.glfw": { - "type": "Transitive", - "resolved": "3.4.0.44", - "contentHash": "HEjbdk0wWxSRrXHl3DSmrA8trecndgJpAHHloJJ1vPseNfeu/ynmrH/LturU1KguRn4r3IzZ81UIp5xRjnyahg==" - }, - "OpenTK.Windowing.Common": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "xNjvKjoptAh6w5/YYIx/9sNv3/A2VVlTahlekTlLP+qfNyig+0jBuLHO4bWELWZ7Ta3Y1m/2Pvk0Z1KCG8VZOA==", - "dependencies": { - "OpenTK.Core": "[4.9.4, 4.10.0)", - "OpenTK.Mathematics": "[4.9.4, 4.10.0)" - } - }, - "OpenTK.Windowing.Desktop": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "LBX4jwCneISIBST2vWYLI8cdR8tLwHNcswK1decElbTAXMB+H6uFIoF41ld+af4q3TsHpjR5fyP2ilbTK3T0rA==", - "dependencies": { - "OpenTK.Core": "[4.9.4, 4.10.0)", - "OpenTK.Mathematics": "[4.9.4, 4.10.0)", - "OpenTK.Windowing.Common": "[4.9.4, 4.10.0)", - "OpenTK.Windowing.GraphicsLibraryFramework": "[4.9.4, 4.10.0)" - } - }, - "OpenTK.Windowing.GraphicsLibraryFramework": { - "type": "Transitive", - "resolved": "4.9.4", - "contentHash": "wNlxnPrD7veMV8EGTTi/sCDeg5V8w/18vC0aw0Ao69eNneD7YSq9Ad+C389rVA957eHNR6Xieu/5qzHQeEOyxQ==", - "dependencies": { - "OpenTK.Core": "[4.9.4, 4.10.0)", - "OpenTK.redist.glfw": "3.4.0.44" - } - }, - "ScottPlot": { - "type": "Transitive", - "resolved": "5.1.59", - "contentHash": "a2xnmMNfhspakKobDfAX5s1GPLFgmEXtRewR9p6bWM91QuCxF5SjHnDbixAcZoU50LPicrCe04sWzIVzdSrmNw==", - "dependencies": { - "HarfBuzzSharp.NativeAssets.Linux": "8.3.1.1", - "SkiaSharp": "3.119.0", - "SkiaSharp.HarfBuzz": "3.119.0", - "SkiaSharp.NativeAssets.Linux.NoDependencies": "3.119.0" - } - }, - "SkiaSharp": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "gR9yVoOta2Mc1Rxt15LD65AckfHMfwjIs/3kkD59C9bT2nYYISsE6uz3t4aMPNHA6CgsIL0Ssn+jE5OVilZ1yw==", - "dependencies": { - "SkiaSharp.NativeAssets.Win32": "3.119.0", - "SkiaSharp.NativeAssets.macOS": "3.119.0" - } - }, - "SkiaSharp.HarfBuzz": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "5ocGzl+RYEZFnUPUbModshnEFvKTku4hTtOBsLvy5MCK2KAHjq5Nw2+uAVUx79Rjh0z8fTojT6ZVav8MJgW0ug==", - "dependencies": { - "HarfBuzzSharp": "8.3.1.1", - "SkiaSharp": "3.119.0" - } - }, - "SkiaSharp.NativeAssets.Linux.NoDependencies": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "e92vdqf1VOETPjy1T67Fs1zPxfGMM1nbrpt69GM5foXSI/iIbq6L9avPz/bl/DbWtb81D0yF/NKjRmXuOZoLcg==" - }, - "SkiaSharp.NativeAssets.macOS": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "YE1vNn0Nyw2PWtv7hw1PYkKJO0itFiQp9vSqGppZUKzQJqwp28a2jgdCMPfYtOiR8KCnDgZqQoynqJRRaE2ZVg==" - }, - "SkiaSharp.NativeAssets.Win32": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "IwC9yx36lOdXVT2DjgmWHl1qkVspfj8ctd4+li8CNnvqdfaTolXCOh6TLznURcPAvzatx9K/tLOB7zT6T8EA9w==" - }, - "SkiaSharp.Views.Desktop.Common": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "KST7Q3n+X5BhDj1aKTJXk9tITWWznveka9n+pBjOtE53Omc+wlZR0s4fQStybWCVVaWG9eaeOMaw93J3zEMklA==", - "dependencies": { - "SkiaSharp": "3.119.0" - } - }, - "SkiaSharp.Views.WPF": { - "type": "Transitive", - "resolved": "3.119.0", - "contentHash": "1Dmj9RlBW/gvmJwSUER+N9plA/kcWOgiL5g3q2DB+USVQav8rQtfOZIQZ1Wt/AqhwepOacv1M6pZKDWtXmwDAg==", - "dependencies": { - "OpenTK": "3.3.1", - "OpenTK.GLWpfControl": "3.3.0", - "SkiaSharp": "3.119.0", - "SkiaSharp.Views.Desktop.Common": "3.119.0" - } - }, - "System.ClientModel": { - "type": "Transitive", - "resolved": "1.9.0", - "contentHash": "1wdwKtMMMEFEYsxJmtrOd3G+7zVOVO3MlVZAsbKv9H0PnIx6J27fYAarMn0eQS0vKJPQL018DOb7YRK1O97p0A==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.2", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.2", - "Microsoft.Extensions.Logging.Abstractions": "10.0.2", - "System.Memory.Data": "10.0.1" - } - }, - "System.IdentityModel.Tokens.Jwt": { - "type": "Transitive", - "resolved": "8.16.0", - "contentHash": "rrs2u7DRMXQG2yh0oVyF/vLwosfRv20Ld2iEpYcKwQWXHjfV+gFXNQsQ9p008kR9Ou4pxBs68Q6/9zC8Gi1wjg==", - "dependencies": { - "Microsoft.IdentityModel.JsonWebTokens": "8.16.0", - "Microsoft.IdentityModel.Tokens": "8.16.0" - } - }, - "System.Memory.Data": { - "type": "Transitive", - "resolved": "10.0.1", - "contentHash": "BZC4mhdL569AXV56ep9YO6ShjhxFXGP7SwVX0Bc/e0dJPWnS6aBEXZJXqh64RVx8HquqWHkJUINBydLRQ1yq0g==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.1", - "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" - }, - "System.Threading.RateLimiting": { - "type": "Transitive", - "resolved": "9.0.18", - "contentHash": "pxuHw/tQXaHMRXEaKzzgpoGO8VeTPIzHbnp0KclXp6js5wPHn7VaqSCa8yRTAsZDcZ2XuIEnXGM2MbRDJFLBog==" - }, - "xunit.analyzers": { - "type": "Transitive", - "resolved": "2.2.0", - "contentHash": "dXMIIztipcAyL3a19gtUrih/RLrE33/4VJdICoinYqIXXo1KLtsMPsaQ9dO2pE8xajDguwE2kqVbBqE5/EoJ0Q==" - }, - "xunit.v3.assert": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "5PKRexYlvufWFdXenRcRGKqvaJBBZFJZpqUGlUs9p13eKEgVdOrLpkPknjzUvLY5kEUicK9871DIUDcCPA6AXA==" - }, - "xunit.v3.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "++CtT8daIf6qfieQev/8V88U3zViIDWou5cj+oWps1/Hf73UoaY/L0hKyi3v7Zlt3BmbU0pUc73zCB1GiB4nYA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "6.0.0" - } - }, - "xunit.v3.core.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XyPMcQRsnUQLhmBBRRgYWsuPc8TyiANzcXtqfzyWfDpPuyh3Q0K4oWozZYQKZRNGnqJ97ifD6qUDWhsEEe32uw==", - "dependencies": { - "Microsoft.Testing.Extensions.Telemetry": "2.5.1", - "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.1", - "Microsoft.Testing.Platform": "2.5.1", - "Microsoft.Testing.Platform.MSBuild": "2.5.1", - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.inproc.console": "[4.0.2]" - } - }, - "xunit.v3.extensibility.core": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "ARTt+pGyd86mdtiFBkKpyBQvRC3u0rr8oidBlII2GsAg7D6TfOsDFCsoQtFij83V5pE57m3whUIqT4xjiARXbQ==", - "dependencies": { - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XLV32FhkuvheBStvX0DvjfPEtI+4SOVcIhnlTS+549r8VfVwsjpWdkJtQmQ7D23PA+Zoaqo+sTjBkRSkidC6Tw==", - "dependencies": { - "xunit.analyzers": "2.2.0", - "xunit.v3.assert": "[4.0.2]", - "xunit.v3.core.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "YlYKVhTJVcwEgJ6rm59Pjf71lQqKwKxEHqVRxWUuwrwm/nxB/mNFP/lP4vlntDO3GclNnLT9BjYOpJH9gViGQg==", - "dependencies": { - "Microsoft.Win32.Registry": "[5.0.0]", - "System.Security.AccessControl": "[6.0.1]", - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.runner.inproc.console": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "cg4XNpCN4Ry9nswutknpreN3ckSUBwtjMRmEQSNK/sIKPo6KN5tDGGGCaHDm5HGA4yFVVtTJX65tLCsZArUNfQ==", - "dependencies": { - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.common": "[4.0.2]" - } - }, - "installer.core": { - "type": "Project", - "dependencies": { - "Microsoft.Data.SqlClient": "[7.1.1, )", - "Microsoft.Data.SqlClient.Extensions.Azure": "[7.1.1, )", - "Microsoft.Extensions.Logging.Abstractions": "[10.0.14, )" - } - }, - "performancemonitor.alerting": { - "type": "Project", - "dependencies": { - "PerformanceMonitor.Common": "[3.11.0, )", - "PerformanceMonitor.Notifications": "[3.11.0, )" - } - }, - "performancemonitor.analysis": { - "type": "Project", - "dependencies": { - "PerformanceMonitor.Common": "[3.11.0, )" - } - }, - "performancemonitor.common": { - "type": "Project", - "dependencies": { - "CredentialManagement": "[1.0.2, )", - "Microsoft.Extensions.Logging.Abstractions": "[10.0.14, )", - "ModelContextProtocol": "[2.3.0, )" - } - }, - "performancemonitor.notifications": { - "type": "Project", - "dependencies": { - "Microsoft.Extensions.Logging.Abstractions": "[10.0.14, )", - "PerformanceMonitor.Analysis": "[3.11.0, )" - } - }, - "performancemonitor.plananalysis": { - "type": "Project", - "dependencies": { - "Microsoft.Data.SqlClient": "[7.1.1, )", - "PerformanceMonitor.Common": "[3.11.0, )" - } - }, - "performancemonitor.ui": { - "type": "Project", - "dependencies": { - "PerformanceMonitor.Common": "[3.11.0, )", - "PerformanceMonitor.PlanAnalysis": "[3.11.0, )", - "ScottPlot.WPF": "[5.1.59, )" - } - }, - "PerformanceMonitorDashboard": { - "type": "Project", - "dependencies": { - "CredentialManagement": "[1.0.2, )", - "Hardcodet.NotifyIcon.Wpf": "[2.0.1, )", - "Installer.Core": "[3.11.0, )", - "Microsoft.Data.SqlClient": "[7.1.1, )", - "Microsoft.Data.SqlClient.Extensions.Azure": "[7.1.1, )", - "Microsoft.Extensions.Configuration": "[10.0.14, )", - "Microsoft.Extensions.Configuration.Json": "[10.0.14, )", - "Microsoft.Extensions.Hosting": "[10.0.14, )", - "ModelContextProtocol": "[2.3.0, )", - "ModelContextProtocol.AspNetCore": "[2.3.0, )", - "PerformanceMonitor.Alerting": "[3.11.0, )", - "PerformanceMonitor.Analysis": "[3.11.0, )", - "PerformanceMonitor.Common": "[3.11.0, )", - "PerformanceMonitor.Notifications": "[3.11.0, )", - "PerformanceMonitor.PlanAnalysis": "[3.11.0, )", - "PerformanceMonitor.Ui": "[3.11.0, )", - "ScottPlot.WPF": "[5.1.59, )", - "Velopack": "[1.2.161, )" - } - }, - "CredentialManagement": { - "type": "CentralTransitive", - "requested": "[1.0.2, )", - "resolved": "1.0.2", - "contentHash": "VkP04/jFXaxT3TkcRhzETYtOrznQxRmQ2J1XJdbXz47Bir7hIzPR7mFZk4GJQ4An4gozW+vonpf+iqTHomAkQw==" - }, - "Hardcodet.NotifyIcon.Wpf": { - "type": "CentralTransitive", - "requested": "[2.0.1, )", - "resolved": "2.0.1", - "contentHash": "dtxmeZXzV2GzSm91aZ3hqzgoeVoARSkDPVCYfhVUNyyKBWYxMgNC0EcLiSYxD4Uc4alq/2qb3SmV8DgAENLRLQ==" - }, - "Microsoft.Data.SqlClient": { - "type": "CentralTransitive", - "requested": "[7.1.1, )", - "resolved": "7.1.1", - "contentHash": "Moz4+bba/OdEM9I4jXWggduJ4sqoNcgVAQyXG/dNnGGvnS/YDr2fTjP83fg5YX3drgRki6fRAhR94P8dAZgZtQ==", - "dependencies": { - "Microsoft.Bcl.Cryptography": "9.0.18", - "Microsoft.Data.SqlClient.Extensions.Abstractions": "[7.1.1, 8.0.0)", - "Microsoft.Data.SqlClient.Internal.Logging": "[7.1.1, 8.0.0)", - "Microsoft.Data.SqlClient.SNI.runtime": "[7.1.0, 8.0.0)", - "Microsoft.Extensions.Caching.Memory": "9.0.18", - "Microsoft.IdentityModel.JsonWebTokens": "8.16.0", - "Microsoft.IdentityModel.Protocols.OpenIdConnect": "8.16.0", - "Microsoft.SqlServer.Server": "[1.0.0, 2.0.0)", - "System.Threading.RateLimiting": "9.0.18" - } - }, - "Microsoft.Data.SqlClient.Extensions.Azure": { - "type": "CentralTransitive", - "requested": "[7.1.1, )", - "resolved": "7.1.1", - "contentHash": "3/Z+6JJKGUw8+shNtftUSGOagt7XCbuhXknZjzXQfDr5aA4lUEMtU/MMNSiwMIrkviYslNKvFh1yWOArudDxQA==", - "dependencies": { - "Azure.Core": "1.51.1", - "Azure.Identity": "1.18.0", - "Microsoft.Data.SqlClient.Extensions.Abstractions": "[7.1.1, 8.0.0)", - "Microsoft.Data.SqlClient.Internal.Logging": "[7.1.1, 8.0.0)", - "Microsoft.Extensions.Caching.Memory": "8.0.1", - "Microsoft.Identity.Client": "4.84.2", - "Microsoft.Identity.Client.Broker": "4.84.2" - } - }, - "Microsoft.Extensions.Configuration": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Json": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "4Tn8eNg85x+ICDN4OLC7Dl/xvZNREZIf7VSOAdT4Q4KYf5Ip1zAk+0BAx8BsRTomgEpCYV4kKsNNnP/ZXUbQkw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.FileExtensions": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Hosting": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "q3f2GLZebtxWG/pDtckPrgIWV22pVmSLSLEkncdmbUz7Z6atwF2wn9ag5cZCc/ndcGe7ffHJom98scauFG+oNQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.Configuration.CommandLine": "10.0.14", - "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.14", - "Microsoft.Extensions.Configuration.FileExtensions": "10.0.14", - "Microsoft.Extensions.Configuration.Json": "10.0.14", - "Microsoft.Extensions.Configuration.UserSecrets": "10.0.14", - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.14", - "Microsoft.Extensions.FileProviders.Physical": "10.0.14", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Logging.Configuration": "10.0.14", - "Microsoft.Extensions.Logging.Console": "10.0.14", - "Microsoft.Extensions.Logging.Debug": "10.0.14", - "Microsoft.Extensions.Logging.EventLog": "10.0.14", - "Microsoft.Extensions.Logging.EventSource": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "ModelContextProtocol": { - "type": "CentralTransitive", - "requested": "[2.3.0, )", - "resolved": "2.3.0", - "contentHash": "PHZ0q8xTAoysqUKpA5gC0RGJSfwpZhfsNz+9Sw0X0RzFFVHjIE52sx6C+ogMn+LSE+FfiYiNscPJhM6q6DMT6Q==", - "dependencies": { - "Microsoft.Extensions.Caching.Abstractions": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "ModelContextProtocol.Core": "[2.3.0]" - } - }, - "ModelContextProtocol.AspNetCore": { - "type": "CentralTransitive", - "requested": "[2.3.0, )", - "resolved": "2.3.0", - "contentHash": "YaRK007jAIFYAGH65I2SPsXVHzaFDRBx+d3swxLCziRYysmk9zGCWm+Lqdt5geHq0wDwCcvwYkMzAOSUWLpajw==", - "dependencies": { - "ModelContextProtocol": "[2.3.0]" - } - }, - "ScottPlot.WPF": { - "type": "CentralTransitive", - "requested": "[5.1.59, )", - "resolved": "5.1.59", - "contentHash": "d6Mv5PFtp+SUH2r8vBCb/mKsR6kobsOX/8/oZYzZl+k3a9jv+BmxVZAkr1Vshq6457812HcNGppoNJ1pSJk5zQ==", - "dependencies": { - "OpenTK": "4.9.4", - "OpenTK.GLWpfControl": "4.3.3", - "ScottPlot": "5.1.59", - "SkiaSharp.Views.WPF": "3.119.0" - } - }, - "Velopack": { - "type": "CentralTransitive", - "requested": "[1.2.161, )", - "resolved": "1.2.161", - "contentHash": "OpHNacIumnkhaaX3ZlQ/TCR4YPOJvud2/PAOoWb6o+mIrLwIVA275I5wAgt4q/1O2VrJeDwR1qFQyqzG4lUArg==" - } - } - } -} \ No newline at end of file diff --git a/deprecated/Dashboard/AboutWindow.xaml b/deprecated/Dashboard/AboutWindow.xaml deleted file mode 100644 index 3d7298940d..0000000000 --- a/deprecated/Dashboard/AboutWindow.xaml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - GitHub Repository - - - - - Report an Issue - - - -