From 31c684427d16de9a2ea43fbc3282143b1867143d Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 04:22:47 -0500
Subject: [PATCH 01/14] Record each upgrade run in the store from a run file
the upgrade script writes (#9432)
---
.../DarlingUpgradeRunRecordTests.cs | 227 ++++++++++
Darling/Darling.Tests/RungRewindArtifacts.cs | 2 +
.../Darling.Tests/UpgradeRunPickupTests.cs | 185 ++++++++
.../Darling.Tests/ViewerDataServiceTests.cs | 105 +++--
.../DarlingWorker.Collection.cs | 3 +
.../DarlingWorker.Passes.cs | 4 +
.../DarlingWorker.UpgradeRun.cs | 83 ++++
.../PgMigrations.cs | 2 +
.../StorageVersion.cs | 2 +-
.../UpgradeRuns.cs | 395 ++++++++++++++++++
.../ViewerDataService.cs | 15 +-
Darling/tools/upgrade-darling.ps1 | 218 +++++++++-
docs/darling/store-tables.csv | 1 +
13 files changed, 1203 insertions(+), 39 deletions(-)
create mode 100644 Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
create mode 100644 Darling/Darling.Tests/UpgradeRunPickupTests.cs
create mode 100644 Darling/PerformanceMonitor.Darling.Service/DarlingWorker.UpgradeRun.cs
create mode 100644 Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
diff --git a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
new file mode 100644
index 0000000000..70df549300
--- /dev/null
+++ b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
@@ -0,0 +1,227 @@
+/*
+ * 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.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using Xunit;
+using static Darling.Tests.RepoFile;
+
+namespace Darling.Tests;
+
+///
+/// #9432: upgrade-darling.ps1 writes upgrade-run.json beside the install at the start of a run, rewrites it at the end
+/// with the result, and rewrites it to verified under -MarkVerified. The script needs an elevated shell and a registered service,
+/// so the functions that build and write the record are extracted and run under PowerShell against a temp folder, the way the other
+/// tests of this script run its functions. The end-to-end run of the script is not covered here: it is covered by the upgrade-shape
+/// check in CI, and the finally block that calls Close-DarlingUpgradeRun has no behaviour test of its own.
+///
+public sealed class DarlingUpgradeRunRecordTests
+{
+ private static readonly string[] FunctionNames =
+ {
+ "Get-DarlingBuildVersion", "New-DarlingUpgradeRun", "Complete-DarlingUpgradeRun", "Write-DarlingUpgradeRunFile",
+ "Read-DarlingUpgradeRunFile", "Set-DarlingUpgradeRunVerified", "Close-DarlingUpgradeRun",
+ };
+
+ private static string? PwshPath
+ {
+ get
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ var windowsPowerShell = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", "v1.0", "powershell.exe");
+ if (File.Exists(windowsPowerShell)) { return windowsPowerShell; }
+
+ var pwsh7 = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles") ?? @"C:\Program Files", "PowerShell", "7", "pwsh.exe");
+ return File.Exists(pwsh7) ? pwsh7 : null;
+ }
+
+ return File.Exists("/opt/homebrew/bin/pwsh") ? "/opt/homebrew/bin/pwsh"
+ : File.Exists("/usr/local/bin/pwsh") ? "/usr/local/bin/pwsh"
+ : null;
+ }
+ }
+
+ /// Runs the extracted functions plus under PowerShell and returns what the body wrote to the output.
+ private static string Run(string folder, string body)
+ {
+ var pwsh = PwshPath;
+ Assert.SkipUnless(pwsh is not null, "neither Windows PowerShell 5.1 nor pwsh is installed on this machine.");
+ var script = ReadRepoFile(Path.Combine("Darling", "tools", "upgrade-darling.ps1"));
+ var text = new StringBuilder();
+ text.AppendLine("$ErrorActionPreference = 'Stop'");
+ foreach (var name in FunctionNames) { text.AppendLine(Extract(script, name)); }
+ text.AppendLine("$root = '" + folder.Replace("'", "''") + "'");
+ text.AppendLine(body);
+ var driver = Path.Combine(folder, "driver.ps1");
+ File.WriteAllText(driver, text.ToString(), new UTF8Encoding(true));
+
+ using var process = Process.Start(new ProcessStartInfo(pwsh!, $"-NoProfile -ExecutionPolicy Bypass -File \"{driver}\"")
+ {
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ })!;
+ var output = process.StandardOutput.ReadToEnd();
+ var error = process.StandardError.ReadToEnd();
+ Assert.True(process.WaitForExit(120_000), "PowerShell did not finish");
+ Assert.True(process.ExitCode == 0, $"PowerShell failed: {error}{output}");
+ return output;
+ }
+
+ private static string Extract(string script, string name)
+ {
+ var start = script.IndexOf("function " + name, StringComparison.Ordinal);
+ Assert.True(start >= 0, $"upgrade-darling.ps1 no longer defines {name} (#9432)");
+ var open = script.IndexOf('{', start);
+ var depth = 0;
+ for (var i = open; i < script.Length; i++)
+ {
+ if (script[i] == '{') { depth++; }
+ else if (script[i] == '}' && --depth == 0) { return script.Substring(start, i - start + 1); }
+ }
+
+ Assert.Fail($"unbalanced braces while extracting {name}");
+ return string.Empty;
+ }
+
+ private static string NewFolder() => Directory.CreateTempSubdirectory("darling-9432-ps-").FullName;
+
+ private static void Cleanup(string folder)
+ {
+ try { Directory.Delete(folder, recursive: true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+
+ private static JsonElement ReadFile(string folder)
+ {
+ using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(folder, "upgrade-run.json")));
+ return document.RootElement.Clone();
+ }
+
+ [Fact]
+ public void TheStartFile_HoldsTheRunIdStateVersionsAndStartTime_AndNoLeftoverTempFile()
+ {
+ var folder = NewFolder();
+ try
+ {
+ Run(folder, "$run = New-DarlingUpgradeRun '3.14.0' '3.15.0' ([datetime]::UtcNow); $w = Write-DarlingUpgradeRunFile $root $run; if (-not $w.Ok) { throw $w.Reason }");
+ var file = ReadFile(folder);
+ Assert.True(Guid.TryParse(file.GetProperty("run_id").GetString(), out _));
+ Assert.Equal("in_progress", file.GetProperty("state").GetString());
+ Assert.Equal("3.14.0", file.GetProperty("tool_version").GetString());
+ Assert.Equal("3.15.0", file.GetProperty("target_build").GetString());
+ Assert.True(DateTime.TryParse(file.GetProperty("started_utc").GetString(), out _));
+ Assert.Equal(JsonValueKind.Null, file.GetProperty("ended_utc").ValueKind);
+ Assert.Equal(new[] { "upgrade-run.json" }, Directory.GetFiles(folder).Select(Path.GetFileName).Where(n => n != "driver.ps1").ToArray());
+ }
+ finally { Cleanup(folder); }
+ }
+
+ [Fact]
+ public void TheEndRewrite_OnSuccess_KeepsTheRunId_AndCarriesTheResult()
+ {
+ var folder = NewFolder();
+ try
+ {
+ Run(folder, "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run | Out-Null; Close-DarlingUpgradeRun $root $run $true 'clear' 'C:\\x\\_rollback_manual_1' '' | Out-Null");
+ var file = ReadFile(folder);
+ Assert.Equal("succeeded", file.GetProperty("state").GetString());
+ Assert.Equal(0, file.GetProperty("exit_code").GetInt32());
+ Assert.Equal("clear", file.GetProperty("stop_check").GetString());
+ Assert.Equal("C:\\x\\_rollback_manual_1", file.GetProperty("rollback_folder").GetString());
+ Assert.Equal(JsonValueKind.Null, file.GetProperty("first_error").ValueKind);
+ Assert.NotEqual(JsonValueKind.Null, file.GetProperty("ended_utc").ValueKind);
+ }
+ finally { Cleanup(folder); }
+ }
+
+ [Fact]
+ public void TheEndRewrite_OnFailure_CarriesTheExitCode_TheFirstError_AndTheStopCheck()
+ {
+ var folder = NewFolder();
+ try
+ {
+ Run(folder, "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run | Out-Null; Close-DarlingUpgradeRun $root $run $false 'blocked: postgres (pid 4)' '' 'the copy failed twice' | Out-Null");
+ var file = ReadFile(folder);
+ Assert.Equal("failed", file.GetProperty("state").GetString());
+ Assert.Equal(1, file.GetProperty("exit_code").GetInt32());
+ Assert.Equal("the copy failed twice", file.GetProperty("first_error").GetString());
+ Assert.Equal("blocked: postgres (pid 4)", file.GetProperty("stop_check").GetString());
+ Assert.Equal(JsonValueKind.Null, file.GetProperty("rollback_folder").ValueKind);
+ }
+ finally { Cleanup(folder); }
+ }
+
+ [Fact]
+ public void MarkVerified_RewritesASucceededRun_ButNotAFailedOrUnfinishedOne_AndHoldsNoSecret()
+ {
+ var folder = NewFolder();
+ try
+ {
+ var body = "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run | Out-Null; "
+ + "$early = Set-DarlingUpgradeRunVerified $root ([datetime]::UtcNow); 'early=' + $early.Ok; "
+ + "Close-DarlingUpgradeRun $root $run $false '' '' 'boom' | Out-Null; $bad = Set-DarlingUpgradeRunVerified $root ([datetime]::UtcNow); 'failed=' + $bad.Ok; "
+ + "Close-DarlingUpgradeRun $root $run $true 'clear' '' '' | Out-Null; $ok = Set-DarlingUpgradeRunVerified $root ([datetime]::UtcNow); 'ok=' + $ok.Ok; "
+ + "$again = Set-DarlingUpgradeRunVerified $root ([datetime]::UtcNow); 'again=' + $again.Ok";
+ var output = Run(folder, body);
+ Assert.Contains("early=False", output, StringComparison.Ordinal);
+ Assert.Contains("failed=False", output, StringComparison.Ordinal);
+ Assert.Contains("ok=True", output, StringComparison.Ordinal);
+ Assert.Contains("again=True", output, StringComparison.Ordinal);
+ var file = ReadFile(folder);
+ Assert.Equal("verified", file.GetProperty("state").GetString());
+ Assert.NotEqual(JsonValueKind.Null, file.GetProperty("verified_utc").ValueKind);
+ var names = file.EnumerateObject().Select(p => p.Name).ToHashSet();
+ Assert.DoesNotContain(names, n => n.Contains("password", StringComparison.OrdinalIgnoreCase)
+ || n.Contains("token", StringComparison.OrdinalIgnoreCase) || n.Contains("connection", StringComparison.OrdinalIgnoreCase));
+ }
+ finally { Cleanup(folder); }
+ }
+
+ [Fact]
+ public void MarkVerified_WithNoFile_ChangesNothing_AndSaysSo()
+ {
+ var folder = NewFolder();
+ try
+ {
+ var output = Run(folder, "$r = Set-DarlingUpgradeRunVerified $root ([datetime]::UtcNow); 'ok=' + $r.Ok");
+ Assert.Contains("ok=False", output, StringComparison.Ordinal);
+ Assert.False(File.Exists(Path.Combine(folder, "upgrade-run.json")));
+ }
+ finally { Cleanup(folder); }
+ }
+
+ [Fact]
+ public void AWriteThatFails_LeavesNoTempFile_AndTheOldFileUntouched()
+ {
+ var folder = NewFolder();
+ try
+ {
+ Run(folder, "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run | Out-Null");
+ var before = File.ReadAllText(Path.Combine(folder, "upgrade-run.json"));
+ /* A write that cannot finish: the run is not a record the JSON converter can write a file from, so the temp file never gets made; and a
+ held lock on the target makes the replace itself fail. Either way no partial file may remain and the old file must stay whole. */
+ using (new FileStream(Path.Combine(folder, "upgrade-run.json"), FileMode.Open, FileAccess.Read, FileShare.Read))
+ {
+ var output = Run(folder, "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); $run['state'] = 'succeeded'; $w = Write-DarlingUpgradeRunFile $root $run; 'ok=' + $w.Ok");
+ if (OperatingSystem.IsWindows()) { Assert.Contains("ok=False", output, StringComparison.Ordinal); }
+ }
+
+ Assert.Empty(Directory.GetFiles(folder, "*.tmp"));
+ if (OperatingSystem.IsWindows()) { Assert.Equal(before, File.ReadAllText(Path.Combine(folder, "upgrade-run.json"))); }
+ }
+ finally { Cleanup(folder); }
+ }
+}
diff --git a/Darling/Darling.Tests/RungRewindArtifacts.cs b/Darling/Darling.Tests/RungRewindArtifacts.cs
index 54dbe213dc..fae243a296 100644
--- a/Darling/Darling.Tests/RungRewindArtifacts.cs
+++ b/Darling/Darling.Tests/RungRewindArtifacts.cs
@@ -988,6 +988,8 @@ ALTER TABLE config.config_alert_settings
// V305 (#9419): the WAL columns on collect.store_metrics. wal_stats_reset is the probe's newest sentinel. The rewind drops the eleven columns, so a re-run of V305
// adds them again. Safe on a store that never had them.
new(305, "hasStoreWalFigures", @"ALTER TABLE collect.store_metrics DROP COLUMN IF EXISTS wal_records, DROP COLUMN IF EXISTS wal_fpi, DROP COLUMN IF EXISTS wal_bytes, DROP COLUMN IF EXISTS wal_buffers_full, DROP COLUMN IF EXISTS wal_write_count, DROP COLUMN IF EXISTS wal_sync_count, DROP COLUMN IF EXISTS wal_write_ms, DROP COLUMN IF EXISTS wal_sync_ms, DROP COLUMN IF EXISTS wal_stats_reset, DROP COLUMN IF EXISTS wal_dir_bytes, DROP COLUMN IF EXISTS wal_dir_files;"),
+ // V306 (#9432): the upgrade run table. The rewind drops it, so a re-run of V306 creates it again. Safe on a store that never had it.
+ new(306, "hasUpgradeRuns", @"DROP TABLE IF EXISTS collect.upgrade_runs;"),
];
///
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
new file mode 100644
index 0000000000..99fb6b66f0
--- /dev/null
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -0,0 +1,185 @@
+/*
+ * 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.Threading.Tasks;
+using Microsoft.Extensions.Logging;
+using Npgsql;
+using PerformanceMonitor.Darling.Storage;
+using Xunit;
+
+namespace Darling.Tests;
+
+///
+/// #9432: the service records upgrade-run.json into collect.upgrade_runs. A run that goes in_progress, then succeeded, then verified over
+/// three pickups ends as ONE row with each state seen, a run written while the store was down is recorded at the next pickup, the file
+/// is removed only once the run is verified, failed or a week old, and a file that does not parse warns once and stays.
+///
+/* #1776 own-store: each test mints its own scratch store database through ScratchPostgres. */
+public sealed class UpgradeRunPickupTests
+{
+ private static string? BaseConnectionString => Environment.GetEnvironmentVariable("DARLING_TEST_PG");
+
+ private const string SkipReason = "Set DARLING_TEST_PG to a Postgres connection string to run the live #9432 tests (each mints its own scratch database).";
+
+ private sealed class CountingLogger : ILogger
+ {
+ public int Warnings;
+
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
+ {
+ if (logLevel == LogLevel.Warning)
+ {
+ Warnings++;
+ }
+ }
+ }
+
+ private static string RunJson(Guid id, string state, string? error = null, DateTime? started = null) =>
+ "{\"run_id\":\"" + id + "\",\"state\":\"" + state + "\",\"tool_version\":\"3.14.0\",\"target_build\":\"3.14.0\",\"started_utc\":\""
+ + (started ?? DateTime.UtcNow.AddMinutes(-10)).ToUniversalTime().ToString("o") + "\",\"ended_utc\":"
+ + (state == "in_progress" ? "null" : "\"" + DateTime.UtcNow.ToString("o") + "\"") + ",\"exit_code\":"
+ + (state == "in_progress" ? "null" : state == "failed" ? "1" : "0") + ",\"stop_check\":\"clear\",\"rollback_folder\":\"C:\\\\x\\\\_rollback\","
+ + "\"first_error\":" + (error is null ? "null" : "\"" + error + "\"") + ",\"verified_utc\":" + (state == "verified" ? "\"" + DateTime.UtcNow.ToString("o") + "\"" : "null") + "}";
+
+ private static async Task<(long Rows, string State)> RowAsync(NpgsqlConnection connection, Guid id)
+ {
+ await using var command = new NpgsqlCommand("SELECT (SELECT count(*) FROM collect.upgrade_runs), (SELECT state FROM collect.upgrade_runs WHERE run_id = $1)", connection);
+ command.Parameters.AddWithValue(id);
+ await using var reader = await command.ExecuteReaderAsync(TestContext.Current.CancellationToken);
+ await reader.ReadAsync(TestContext.Current.CancellationToken);
+ return (reader.GetInt64(0), reader.IsDBNull(1) ? "" : reader.GetString(1));
+ }
+
+ [Fact]
+ public async Task ThreePickups_InProgressSucceededVerified_GiveOneRowWithEachStateSeen_AndTheFileGoesAtVerified()
+ {
+ Assert.SkipWhen(string.IsNullOrEmpty(BaseConnectionString), SkipReason);
+ var ct = TestContext.Current.CancellationToken;
+ await using var scratch = await ScratchPostgres.CreateAsync(BaseConnectionString!, ct);
+ var folder = Directory.CreateTempSubdirectory("darling-9432-").FullName;
+ var bodySucceeded = false;
+ try
+ {
+ await using var connection = new NpgsqlConnection(scratch.ConnectionString);
+ await connection.OpenAsync(ct);
+ await PgMigrations.MigrateAsync(connection, ct);
+ var pickup = new UpgradeRunPickup(new CountingLogger());
+ var file = Path.Combine(folder, UpgradeRunPickup.FileName);
+ var id = Guid.NewGuid();
+ var now = DateTime.UtcNow;
+
+ File.WriteAllText(file, RunJson(id, "in_progress"));
+ Assert.Equal(UpgradeRunPickupOutcome.Recorded, (await pickup.PickUpAsync(connection, folder, now, ct)).Outcome);
+ Assert.Equal((1L, "in_progress"), await RowAsync(connection, id));
+
+ File.WriteAllText(file, RunJson(id, "succeeded"));
+ Assert.Equal(UpgradeRunPickupOutcome.Recorded, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(5), ct)).Outcome);
+ Assert.Equal((1L, "succeeded"), await RowAsync(connection, id));
+ Assert.True(File.Exists(file), "a succeeded run is not verified yet, so its file stays");
+
+ File.WriteAllText(file, RunJson(id, "verified"));
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(10), ct)).Outcome);
+ Assert.Equal((1L, "verified"), await RowAsync(connection, id));
+ Assert.False(File.Exists(file), "a verified run's file is removed");
+ Assert.Equal(UpgradeRunPickupOutcome.NoFile, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(15), ct)).Outcome);
+ bodySucceeded = true;
+ }
+ finally
+ {
+ try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
+ await LiveStoreCleanup.RunAsync(scratch.ConnectionString, bodySucceeded, (_, _) => Task.CompletedTask);
+ }
+ }
+
+ [Fact]
+ public async Task ARunWrittenWhileTheStoreWasDown_IsRecordedAtTheNextPickup_AndAFailedRunsFileGoes()
+ {
+ Assert.SkipWhen(string.IsNullOrEmpty(BaseConnectionString), SkipReason);
+ var ct = TestContext.Current.CancellationToken;
+ await using var scratch = await ScratchPostgres.CreateAsync(BaseConnectionString!, ct);
+ var folder = Directory.CreateTempSubdirectory("darling-9432-").FullName;
+ var bodySucceeded = false;
+ try
+ {
+ var file = Path.Combine(folder, UpgradeRunPickup.FileName);
+ var id = Guid.NewGuid();
+ File.WriteAllText(file, RunJson(id, "failed", "the copy failed twice"));
+
+ /* The store is down: the pickup's connection is not open, so it throws and the file stays for the next pickup. */
+ await using (var down = new NpgsqlConnection(scratch.ConnectionString))
+ {
+ await Assert.ThrowsAnyAsync(() => new UpgradeRunPickup(new CountingLogger()).PickUpAsync(down, folder, DateTime.UtcNow, ct));
+ }
+
+ Assert.True(File.Exists(file), "a pickup that could not reach the store leaves the file");
+
+ await using var connection = new NpgsqlConnection(scratch.ConnectionString);
+ await connection.OpenAsync(ct);
+ await PgMigrations.MigrateAsync(connection, ct);
+ var result = await new UpgradeRunPickup(new CountingLogger()).PickUpAsync(connection, folder, DateTime.UtcNow, ct);
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, result.Outcome);
+ Assert.Equal((1L, "failed"), await RowAsync(connection, id));
+ Assert.False(File.Exists(file));
+ bodySucceeded = true;
+ }
+ finally
+ {
+ try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
+ await LiveStoreCleanup.RunAsync(scratch.ConnectionString, bodySucceeded, (_, _) => Task.CompletedTask);
+ }
+ }
+
+ [Fact]
+ public async Task AMalformedFile_WarnsOncePerContent_AndStaysInPlace_AndAnOldInProgressFileGoes()
+ {
+ Assert.SkipWhen(string.IsNullOrEmpty(BaseConnectionString), SkipReason);
+ var ct = TestContext.Current.CancellationToken;
+ await using var scratch = await ScratchPostgres.CreateAsync(BaseConnectionString!, ct);
+ var folder = Directory.CreateTempSubdirectory("darling-9432-").FullName;
+ var bodySucceeded = false;
+ try
+ {
+ await using var connection = new NpgsqlConnection(scratch.ConnectionString);
+ await connection.OpenAsync(ct);
+ await PgMigrations.MigrateAsync(connection, ct);
+ var logger = new CountingLogger();
+ var pickup = new UpgradeRunPickup(logger);
+ var file = Path.Combine(folder, UpgradeRunPickup.FileName);
+
+ File.WriteAllText(file, "{ not json");
+ for (var i = 0; i < 3; i++)
+ {
+ Assert.Equal(UpgradeRunPickupOutcome.Malformed, (await pickup.PickUpAsync(connection, folder, DateTime.UtcNow, ct)).Outcome);
+ }
+
+ Assert.Equal(1, logger.Warnings);
+ Assert.True(File.Exists(file), "a malformed file stays in place");
+
+ File.WriteAllText(file, "{\"run_id\":\"not-a-guid\"}");
+ await pickup.PickUpAsync(connection, folder, DateTime.UtcNow, ct);
+ Assert.Equal(2, logger.Warnings);
+
+ var oldId = Guid.NewGuid();
+ File.WriteAllText(file, RunJson(oldId, "in_progress", started: DateTime.UtcNow.AddDays(-8)));
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, (await pickup.PickUpAsync(connection, folder, DateTime.UtcNow, ct)).Outcome);
+ Assert.Equal((1L, "in_progress"), await RowAsync(connection, oldId));
+ bodySucceeded = true;
+ }
+ finally
+ {
+ try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
+ await LiveStoreCleanup.RunAsync(scratch.ConnectionString, bodySucceeded, (_, _) => Task.CompletedTask);
+ }
+ }
+}
diff --git a/Darling/Darling.Tests/ViewerDataServiceTests.cs b/Darling/Darling.Tests/ViewerDataServiceTests.cs
index 9f4e85a883..41d79b01cc 100644
--- a/Darling/Darling.Tests/ViewerDataServiceTests.cs
+++ b/Darling/Darling.Tests/ViewerDataServiceTests.cs
@@ -750,11 +750,19 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
that one and V290's is a V288 store and maps to 288, not 289. Each sentinel below shifts one place from the end. */
/* #9223: the V292 sentinel (the covering hash index on the corrected daily Query Store rollup) is the one before the last, so a store that has every
sentinel but that one and V293's, V294's and V295's is a V291 store and maps to 291, not 292. Each sentinel below shifts one place from the end. */
+ /* #9432: the V306 sentinel (the upgrade run table) is the last parameter, so a store that has every sentinel but that one is a V305 store
+ and maps to 305, not 306. Each sentinel below shifts one place from the end. */
+ var allButV306 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
+ allButV306[^1] = false;
+ Assert.Equal("hasUpgradeRuns", map.GetParameters()[^1].Name);
+ Assert.Equal(305, (int)map.Invoke(null, allButV306)!);
+
/* #9419: the V305 sentinel (the WAL columns on the store metrics table) is the last parameter, so a store that has every sentinel but that one is a V304
store and maps to 304, not 305. Each sentinel below shifts one place from the end. */
var allButV305 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
allButV305[^1] = false;
- Assert.Equal("hasStoreWalFigures", map.GetParameters()[^1].Name);
+ allButV305[^2] = false;
+ Assert.Equal("hasStoreWalFigures", map.GetParameters()[^2].Name);
Assert.Equal(304, (int)map.Invoke(null, allButV305)!);
/* #9410: the V304 sentinel (the statement history's write counters) is the last parameter, so a store that has every sentinel but that one is a V303 store
@@ -762,7 +770,8 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
var allButV304 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
allButV304[^1] = false;
allButV304[^2] = false;
- Assert.Equal("hasStatementHistoryWriteCounters", map.GetParameters()[^2].Name);
+ allButV304[^3] = false;
+ Assert.Equal("hasStatementHistoryWriteCounters", map.GetParameters()[^3].Name);
Assert.Equal(303, (int)map.Invoke(null, allButV304)!);
/* #9384: the V303 sentinel (the clutter-day stamp table) is the last parameter, so a store that has every sentinel but that one is a V302 store
@@ -771,18 +780,20 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV303[^1] = false;
allButV303[^2] = false;
allButV303[^3] = false;
- Assert.Equal("hasClutterDayBuilt", map.GetParameters()[^3].Name);
+ allButV303[^4] = false;
+ Assert.Equal("hasClutterDayBuilt", map.GetParameters()[^4].Name);
Assert.Equal(302, (int)map.Invoke(null, allButV303)!);
/* #8570: the V302 sentinel (the partial index of failed Agent job outcomes on job_history) is the last parameter, so a store that has every sentinel
but that one is a V301 store and maps to 301, not 302. Each sentinel below shifts one place from the end. */
var allButV302 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
allButV302[^1] = false;
-
allButV302[^2] = false;
+
allButV302[^3] = false;
allButV302[^4] = false;
- Assert.Equal("hasJobHistoryFailedIndex", map.GetParameters()[^4].Name);
+ allButV302[^5] = false;
+ Assert.Equal("hasJobHistoryFailedIndex", map.GetParameters()[^5].Name);
Assert.Equal(301, (int)map.Invoke(null, allButV302)!);
/* #9374: the V301 sentinel (the last measured relation sizes and their measured time) is the last parameter, so a store that has every sentinel but
@@ -790,10 +801,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
var allButV301 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
allButV301[^1] = false;
allButV301[^2] = false;
-
allButV301[^3] = false;
+
allButV301[^4] = false;
allButV301[^5] = false;
+ allButV301[^6] = false;
Assert.Equal(300, (int)map.Invoke(null, allButV301)!);
/* #9357: the V300 sentinel (the procedure_stats hour ledger's tables) is the one before the last, so a store that has every sentinel but that one
@@ -802,10 +814,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV300[^1] = false;
allButV300[^2] = false;
allButV300[^3] = false;
-
allButV300[^4] = false;
+
allButV300[^5] = false;
allButV300[^6] = false;
+ allButV300[^7] = false;
Assert.Equal(299, (int)map.Invoke(null, allButV300)!);
/* #9349: the V299 sentinel (the object usage chain's tables) is the last parameter, so a store that has every sentinel but that one
@@ -815,10 +828,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV299[^2] = false;
allButV299[^3] = false;
allButV299[^4] = false;
-
allButV299[^5] = false;
+
allButV299[^6] = false;
allButV299[^7] = false;
+ allButV299[^8] = false;
Assert.Equal(298, (int)map.Invoke(null, allButV299)!);
/* #9304: the V298 sentinel (the payload dimension tables' stamp tables) is the last parameter, so a store that has every sentinel but that one
@@ -829,10 +843,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV298[^3] = false;
allButV298[^4] = false;
allButV298[^5] = false;
-
allButV298[^6] = false;
+
allButV298[^7] = false;
allButV298[^8] = false;
+ allButV298[^9] = false;
Assert.Equal(297, (int)map.Invoke(null, allButV298)!);
/* #8784 part 2: the V297 sentinel (the dependency list and the per-day referenced-names summary) is the last parameter, so a store that has
@@ -844,10 +859,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV297[^4] = false;
allButV297[^5] = false;
allButV297[^6] = false;
-
allButV297[^7] = false;
+
allButV297[^8] = false;
allButV297[^9] = false;
+ allButV297[^10] = false;
Assert.Equal(296, (int)map.Invoke(null, allButV297)!);
/* #9280: the V296 sentinel (the hourly Query Store summary's index) is the one before the last, so a store that has every sentinel but that
@@ -860,10 +876,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV296[^5] = false;
allButV296[^6] = false;
allButV296[^7] = false;
-
allButV296[^8] = false;
+
allButV296[^9] = false;
allButV296[^10] = false;
+ allButV296[^11] = false;
Assert.Equal(295, (int)map.Invoke(null, allButV296)!);
/* #9225: the V295 sentinel (the plan regression block tables) is the one before the last, so a store that has every sentinel but that one and V296's
@@ -877,10 +894,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV295[^6] = false;
allButV295[^7] = false;
allButV295[^8] = false;
-
allButV295[^9] = false;
+
allButV295[^10] = false;
allButV295[^11] = false;
+ allButV295[^12] = false;
Assert.Equal(294, (int)map.Invoke(null, allButV295)!);
/* #9284: the V294 sentinel (the view-and-time index on the aggregate compression order history) is the one before V295's, so a store that has every
@@ -895,10 +913,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV294[^7] = false;
allButV294[^8] = false;
allButV294[^9] = false;
-
allButV294[^10] = false;
+
allButV294[^11] = false;
allButV294[^12] = false;
+ allButV294[^13] = false;
Assert.Equal(293, (int)map.Invoke(null, allButV294)!);
/* #9277: the V293 sentinel (the partial counter-row index on attention_events) is the one before the last, so a store that has every
@@ -914,10 +933,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV293[^8] = false;
allButV293[^9] = false;
allButV293[^10] = false;
-
allButV293[^11] = false;
+
allButV293[^12] = false;
allButV293[^13] = false;
+ allButV293[^14] = false;
Assert.Equal(292, (int)map.Invoke(null, allButV293)!);
var allButV292 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -932,10 +952,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV292[^9] = false;
allButV292[^10] = false;
allButV292[^11] = false;
-
allButV292[^12] = false;
+
allButV292[^13] = false;
allButV292[^14] = false;
+ allButV292[^15] = false;
Assert.Equal(291, (int)map.Invoke(null, allButV292)!);
/* #9215: the V291 sentinel (the covering server index on the corrected hourly Query Store rollup) is the one before the last, so a store that has every
@@ -953,10 +974,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV291[^10] = false;
allButV291[^11] = false;
allButV291[^12] = false;
-
allButV291[^13] = false;
+
allButV291[^14] = false;
allButV291[^15] = false;
+ allButV291[^16] = false;
Assert.Equal(290, (int)map.Invoke(null, allButV291)!);
/* #9193: the V290 sentinel (the query_stats summary floor table) is the third from the end, so a store that has every sentinel but that one
@@ -975,10 +997,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV290[^11] = false;
allButV290[^12] = false;
allButV290[^13] = false;
-
allButV290[^14] = false;
+
allButV290[^15] = false;
allButV290[^16] = false;
+ allButV290[^17] = false;
Assert.Equal(289, (int)map.Invoke(null, allButV290)!);
var allButV289 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -996,10 +1019,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV289[^12] = false;
allButV289[^13] = false;
allButV289[^14] = false;
-
allButV289[^15] = false;
+
allButV289[^16] = false;
allButV289[^17] = false;
+ allButV289[^18] = false;
Assert.Equal(288, (int)map.Invoke(null, allButV289)!);
var allButV288 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1018,10 +1042,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV288[^13] = false;
allButV288[^14] = false;
allButV288[^15] = false;
-
allButV288[^16] = false;
+
allButV288[^17] = false;
allButV288[^18] = false;
+ allButV288[^19] = false;
Assert.Equal(287, (int)map.Invoke(null, allButV288)!);
var allButV287 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1041,10 +1066,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV287[^14] = false;
allButV287[^15] = false;
allButV287[^16] = false;
-
allButV287[^17] = false;
+
allButV287[^18] = false;
allButV287[^19] = false;
+ allButV287[^20] = false;
Assert.Equal(286, (int)map.Invoke(null, allButV287)!);
var allButV286 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1065,10 +1091,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV286[^15] = false;
allButV286[^16] = false;
allButV286[^17] = false;
-
allButV286[^18] = false;
+
allButV286[^19] = false;
allButV286[^20] = false;
+ allButV286[^21] = false;
Assert.Equal(285, (int)map.Invoke(null, allButV286)!);
var allButV285 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1090,10 +1117,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV285[^16] = false;
allButV285[^17] = false;
allButV285[^18] = false;
-
allButV285[^19] = false;
+
allButV285[^20] = false;
allButV285[^21] = false;
+ allButV285[^22] = false;
Assert.Equal(284, (int)map.Invoke(null, allButV285)!);
var allButV284 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1116,10 +1144,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV284[^17] = false;
allButV284[^18] = false;
allButV284[^19] = false;
-
allButV284[^20] = false;
+
allButV284[^21] = false;
allButV284[^22] = false;
+ allButV284[^23] = false;
Assert.Equal(283, (int)map.Invoke(null, allButV284)!);
var allButV283 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1143,10 +1172,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV283[^18] = false;
allButV283[^19] = false;
allButV283[^20] = false;
-
allButV283[^21] = false;
+
allButV283[^22] = false;
allButV283[^23] = false;
+ allButV283[^24] = false;
Assert.Equal(282, (int)map.Invoke(null, allButV283)!);
var allButV282 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1171,10 +1201,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV282[^19] = false;
allButV282[^20] = false;
allButV282[^21] = false;
-
allButV282[^22] = false;
+
allButV282[^23] = false;
allButV282[^24] = false;
+ allButV282[^25] = false;
Assert.Equal(281, (int)map.Invoke(null, allButV282)!);
var allButV281 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1200,10 +1231,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV281[^20] = false;
allButV281[^21] = false;
allButV281[^22] = false;
-
allButV281[^23] = false;
+
allButV281[^24] = false;
allButV281[^25] = false;
+ allButV281[^26] = false;
Assert.Equal(280, (int)map.Invoke(null, allButV281)!);
var allButV280 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1230,10 +1262,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV280[^21] = false;
allButV280[^22] = false;
allButV280[^23] = false;
-
allButV280[^24] = false;
+
allButV280[^25] = false;
allButV280[^26] = false;
+ allButV280[^27] = false;
Assert.Equal(279, (int)map.Invoke(null, allButV280)!);
var allButV279 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1261,10 +1294,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV279[^22] = false;
allButV279[^23] = false;
allButV279[^24] = false;
-
allButV279[^25] = false;
+
allButV279[^26] = false;
allButV279[^27] = false;
+ allButV279[^28] = false;
Assert.Equal(278, (int)map.Invoke(null, allButV279)!);
var allButV278 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1293,10 +1327,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV278[^23] = false;
allButV278[^24] = false;
allButV278[^25] = false;
-
allButV278[^26] = false;
+
allButV278[^27] = false;
allButV278[^28] = false;
+ allButV278[^29] = false;
Assert.Equal(277, (int)map.Invoke(null, allButV278)!);
var allButV277 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1326,10 +1361,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV277[^24] = false;
allButV277[^25] = false;
allButV277[^26] = false;
-
allButV277[^27] = false;
+
allButV277[^28] = false;
allButV277[^29] = false;
+ allButV277[^30] = false;
Assert.Equal(276, (int)map.Invoke(null, allButV277)!);
var allButV276 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1360,10 +1396,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV276[^25] = false;
allButV276[^26] = false;
allButV276[^27] = false;
-
allButV276[^28] = false;
+
allButV276[^29] = false;
allButV276[^30] = false;
+ allButV276[^31] = false;
Assert.Equal(275, (int)map.Invoke(null, allButV276)!);
var allButV275 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1395,10 +1432,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV275[^26] = false;
allButV275[^27] = false;
allButV275[^28] = false;
-
allButV275[^29] = false;
+
allButV275[^30] = false;
allButV275[^31] = false;
+ allButV275[^32] = false;
Assert.Equal(274, (int)map.Invoke(null, allButV275)!);
var allButV274 = Enumerable.Repeat((object)true, map.GetParameters().Length).ToArray();
@@ -1431,10 +1469,11 @@ so a store without it (and without V286's) is a V284 store. #9149: the V284 sent
allButV274[^27] = false;
allButV274[^28] = false;
allButV274[^29] = false;
-
allButV274[^30] = false;
+
allButV274[^31] = false;
allButV274[^32] = false;
+ allButV274[^33] = false;
Assert.Equal(273, (int)map.Invoke(null, allButV274)!);
/* Probe row width vs mapper arity is not checked HERE, and the reason it was left to the live probes
diff --git a/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Collection.cs b/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Collection.cs
index bcf830c493..7bec9c534d 100644
--- a/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Collection.cs
+++ b/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Collection.cs
@@ -145,6 +145,9 @@ like a failed migration. The CLI and the Viewer only read the row. */
collector has written yet — so the gap the service was down for can be raised once the alert
engine exists. Best effort: a failed read loses one alert and must not fail or retry the start. */
collectionGapReport = await ReadCollectionGapAsync(migrateConnection, stoppingToken);
+ /* #9432: the upgrade run file beside the install, recorded now that the schema is current. A run written while the store was down
+ lands here at the next start. Failure-isolated inside: it never fails or retries the start. */
+ await TryRecordUpgradeRunAsync(migrateConnection, AppContext.BaseDirectory, stoppingToken);
break;
}
catch (Exception ex) when (ex is not OperationCanceledException
diff --git a/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Passes.cs b/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Passes.cs
index e9a0e061a4..d766776f76 100644
--- a/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Passes.cs
+++ b/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.Passes.cs
@@ -458,6 +458,10 @@ runs on every start and the state is re-derived after a restart. The rejected li
_nextStoreSettingsCheckUtc = DateTime.UtcNow.Add(s_storeSettingsCheckInterval);
await EvaluateStoreSettingsAsync(config, managedConfWriteResult, managedUsedLastGoodConf, managedConfVerification, stoppingToken);
}
+
+ /* #9432: the upgrade run file beside the install, recorded on the same five-minute store-side pass but on its own stamp, so it runs with
+ the alert engine off too. The upgrade restarts the service before its script ends, so the result and the verified state are read here. */
+ await RunUpgradeRunPassAsync(AppContext.BaseDirectory, stoppingToken);
}
///
diff --git a/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.UpgradeRun.cs b/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.UpgradeRun.cs
new file mode 100644
index 0000000000..c39296d83e
--- /dev/null
+++ b/Darling/PerformanceMonitor.Darling.Service/DarlingWorker.UpgradeRun.cs
@@ -0,0 +1,83 @@
+/*
+ * 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.Threading;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Logging;
+using Npgsql;
+using PerformanceMonitor.Darling.Storage;
+
+namespace PerformanceMonitor.Darling.Service;
+
+public sealed partial class DarlingWorker
+{
+ /* #9432: records upgrade-run.json beside the install into collect.upgrade_runs. One instance for the life of the process, because it
+ remembers which problems it already warned about. */
+ private UpgradeRunPickup? _upgradeRunPickup;
+
+ /* Next due time for the upgrade run pickup. It rides the store-side pass that runs every s_storeSettingsCheckInterval, on its own stamp
+ so it also runs when the alert engine is off. The upgrade restarts the service before its script ends, so the result and the
+ verified state arrive as a file change that only a pass sees. */
+ private DateTime _nextUpgradeRunCheckUtc = DateTime.MinValue;
+
+ ///
+ /// Records the upgrade run file on an open store connection (#9432). Failure-isolated: a store or file problem is logged and the file
+ /// stays for the next pass, and nothing here fails a start or the pass that called it.
+ ///
+ internal async Task TryRecordUpgradeRunAsync(
+ NpgsqlConnection connection, string installDirectory, CancellationToken cancellationToken)
+ {
+ try
+ {
+ _upgradeRunPickup ??= new UpgradeRunPickup(_logger);
+ var result = await _upgradeRunPickup.PickUpAsync(connection, installDirectory, DateTime.UtcNow, cancellationToken);
+ if (result.Outcome is UpgradeRunPickupOutcome.Recorded or UpgradeRunPickupOutcome.RecordedAndRemoved)
+ {
+ _logger.LogInformation("Upgrade run {RunId} recorded in the store, state {State}", result.RunId, result.State);
+ }
+
+ return result;
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogWarning(
+ "The upgrade run file could not be recorded in the store this time, so it stays for the next pass: {Message}", ex.Message);
+ return null;
+ }
+ }
+
+ ///
+ /// The store-side pass (#9432): when due, opens one connection and records the upgrade run file. The cheap case, no file, costs
+ /// one file check and opens no connection.
+ ///
+ internal async Task RunUpgradeRunPassAsync(string installDirectory, CancellationToken cancellationToken)
+ {
+ if (_postgres is null || !StampIsDue(_nextUpgradeRunCheckUtc, s_storeSettingsCheckInterval, DateTime.UtcNow))
+ {
+ return;
+ }
+
+ _nextUpgradeRunCheckUtc = DateTime.UtcNow.Add(s_storeSettingsCheckInterval);
+ if (!System.IO.File.Exists(System.IO.Path.Combine(installDirectory, UpgradeRunPickup.FileName)))
+ {
+ return;
+ }
+
+ try
+ {
+ await using var connection = await _postgres.OpenConnectionAsync(cancellationToken);
+ await TryRecordUpgradeRunAsync(connection, installDirectory, cancellationToken);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogWarning(
+ "The upgrade run file could not be recorded because the store could not be reached, so it stays for the next pass: {Message}", ex.Message);
+ }
+ }
+}
diff --git a/Darling/PerformanceMonitor.Darling.Storage/PgMigrations.cs b/Darling/PerformanceMonitor.Darling.Storage/PgMigrations.cs
index 98a5eeecbd..a0ab900e49 100644
--- a/Darling/PerformanceMonitor.Darling.Storage/PgMigrations.cs
+++ b/Darling/PerformanceMonitor.Darling.Storage/PgMigrations.cs
@@ -4073,6 +4073,8 @@ never reads it. */
/* V305 (#9419): the store's own WAL figures, eleven nullable columns on collect.store_metrics filled on the object_kind = 'wal' row only. No data moves
and existing rows keep NULL. An older build ignores the columns and the row: its store reads list only the kinds it knows. */
new Migration(StoreWalFigures.Version, "store-wal-figures", StoreWalFigures.AddColumnsSql),
+ /* V306 (#9432): the record of each upgrade run, one new table keyed on the run id. No existing table changes and no data moves. An older build never names it. */
+ new Migration(UpgradeRuns.Version, "upgrade-runs", UpgradeRuns.CreateSql),
};
///
diff --git a/Darling/PerformanceMonitor.Darling.Storage/StorageVersion.cs b/Darling/PerformanceMonitor.Darling.Storage/StorageVersion.cs
index d393b53922..6236ab6842 100644
--- a/Darling/PerformanceMonitor.Darling.Storage/StorageVersion.cs
+++ b/Darling/PerformanceMonitor.Darling.Storage/StorageVersion.cs
@@ -16,5 +16,5 @@ namespace PerformanceMonitor.Darling.Storage;
///
public static class StorageVersion
{
- public const int SchemaVersion = StoreWalFigures.Version;
+ public const int SchemaVersion = UpgradeRuns.Version;
}
diff --git a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
new file mode 100644
index 0000000000..d2e5c432a8
--- /dev/null
+++ b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
@@ -0,0 +1,395 @@
+/*
+ * 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.Globalization;
+using System.IO;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Logging;
+using Npgsql;
+using NpgsqlTypes;
+
+namespace PerformanceMonitor.Darling.Storage;
+
+///
+/// The store's record of each upgrade run (#9432): one row in collect.upgrade_runs per run id, so a service start that
+/// looks wrong can be read next to the upgrade that came before it.
+///
+/// The upgrade script never opens a connection. upgrade-darling.ps1 has no PostgreSQL driver and the store
+/// can be down in the middle of an upgrade. It writes beside the install instead: at the start of the run
+/// with state in_progress, again at the end with the result (succeeded or failed), and a later
+/// -MarkVerified run sets verified. Each write replaces the whole file through a temp file and a move. The file
+/// holds no secret.
+///
+/// The service records the file () at its start after the migrations and again on the
+/// five-minute store-side pass. The upgrade restarts the service before the script ends, so the end state and the verified state
+/// are only ever seen by a pass. One row per run id: in_progress, the result and verified land on the same row.
+///
+public static class UpgradeRuns
+{
+ /// The store migration that creates collect.upgrade_runs. One constant so a renumber is mechanical.
+ public const int Version = 306;
+
+ /// How long a row is kept: the same as the other store self-metrics series, .
+ public const int RetentionDays = StoreSelfMetrics.RetentionDays;
+
+ /// The run has started and not ended, as far as the file says.
+ public const string InProgress = "in_progress";
+
+ /// The script reached its end and the service is Running again.
+ public const string Succeeded = "succeeded";
+
+ /// The script stopped on an error. The first error is in the row.
+ public const string Failed = "failed";
+
+ /// The operator's checks passed and -MarkVerified said so.
+ public const string Verified = "verified";
+
+ /// The states a file may carry, in the order a run moves through them.
+ public static readonly IReadOnlyList States = new[] { InProgress, Succeeded, Failed, Verified };
+
+ /// The table, keyed on the run id. Timestamps are UTC timestamp columns like the other store tables.
+ public const string CreateSql = @"
+CREATE TABLE IF NOT EXISTS collect.upgrade_runs
+(
+ run_id uuid NOT NULL,
+ state text NOT NULL,
+ tool_version text NULL,
+ target_build text NULL,
+ started_at timestamp NOT NULL,
+ ended_at timestamp NULL,
+ exit_code integer NULL,
+ stop_check text NULL,
+ rollback_folder text NULL,
+ first_error text NULL,
+ verified_at timestamp NULL,
+ recorded_at timestamp NOT NULL,
+ updated_at timestamp NOT NULL,
+ CONSTRAINT pk_upgrade_runs PRIMARY KEY (run_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_upgrade_runs_started
+ ON collect.upgrade_runs(started_at);";
+
+ /// One row per run id: a second pickup of the same run updates the row, it never adds one. recorded_at keeps the
+ /// first time the service saw the run.
+ public const string UpsertSql = @"
+INSERT INTO collect.upgrade_runs
+ (run_id, state, tool_version, target_build, started_at, ended_at, exit_code, stop_check, rollback_folder, first_error, verified_at, recorded_at, updated_at)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $12)
+ON CONFLICT (run_id) DO UPDATE SET
+ state = EXCLUDED.state,
+ tool_version = EXCLUDED.tool_version,
+ target_build = EXCLUDED.target_build,
+ started_at = EXCLUDED.started_at,
+ ended_at = EXCLUDED.ended_at,
+ exit_code = EXCLUDED.exit_code,
+ stop_check = EXCLUDED.stop_check,
+ rollback_folder = EXCLUDED.rollback_folder,
+ first_error = EXCLUDED.first_error,
+ verified_at = EXCLUDED.verified_at,
+ updated_at = EXCLUDED.updated_at";
+
+ /// The bounded retention delete, run after each record.
+ public const string RetentionDeleteSql = @"
+DELETE FROM collect.upgrade_runs WHERE started_at < $1";
+}
+
+/// The run a file describes. Text fields are capped when the file is read.
+public sealed record UpgradeRunFile(
+ Guid RunId,
+ string State,
+ string? ToolVersion,
+ string? TargetBuild,
+ DateTime StartedUtc,
+ DateTime? EndedUtc,
+ int? ExitCode,
+ string? StopCheck,
+ string? RollbackFolder,
+ string? FirstError,
+ DateTime? VerifiedUtc);
+
+/// What one pickup did.
+public enum UpgradeRunPickupOutcome
+{
+ /// There was no file.
+ NoFile,
+
+ /// The file was recorded and left in place: the run is not finished or not yet verified.
+ Recorded,
+
+ /// The file was recorded and then removed: the run is verified, failed or older than a week.
+ RecordedAndRemoved,
+
+ /// The file was recorded but could not be removed. The next pass records it again and the row stays one row.
+ RecordedNotRemoved,
+
+ /// The file does not parse as a run. It stays where it is.
+ Malformed,
+}
+
+/// The outcome of one pickup, with the run it read when the file parsed.
+public readonly record struct UpgradeRunPickupResult(UpgradeRunPickupOutcome Outcome, Guid? RunId, string? State);
+
+///
+/// Reads the upgrade run file and records it (#9432). One instance per service, because it remembers which problems it has already
+/// warned about: a file that does not parse is warned about once per distinct content, not on every pass.
+///
+public sealed class UpgradeRunPickup
+{
+ /// The file the upgrade script writes beside the install.
+ public const string FileName = "upgrade-run.json";
+
+ /// A file this large is not a run file. It is not read.
+ public const int MaxFileBytes = 64 * 1024;
+
+ /// A file whose run started longer ago than this is recorded and removed whatever its state.
+ public static readonly TimeSpan MaxFileAge = TimeSpan.FromDays(7);
+
+ private const int MaxTextChars = 2000;
+ private const int MaxWarnedKeys = 100;
+
+ private readonly ILogger _logger;
+ private readonly HashSet _warned = new(StringComparer.Ordinal);
+
+ /// Makes a pickup that logs through .
+ public UpgradeRunPickup(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ ///
+ /// Records the file in into collect.upgrade_runs and removes it when the run is
+ /// done. A store failure propagates to the caller, which keeps the file for the next pass.
+ ///
+ public async Task PickUpAsync(
+ NpgsqlConnection connection, string installDirectory, DateTime nowUtc, CancellationToken cancellationToken)
+ {
+ var path = Path.Combine(installDirectory, UpgradeRunPickup.FileName);
+ string text;
+ try
+ {
+ var info = new FileInfo(path);
+ if (!info.Exists)
+ {
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.NoFile, null, null);
+ }
+
+ if (info.Length > MaxFileBytes)
+ {
+ WarnOnce("size:" + info.Length.ToString(CultureInfo.InvariantCulture) + ":" + info.LastWriteTimeUtc.Ticks.ToString(CultureInfo.InvariantCulture),
+ "The upgrade run file {Path} is {Bytes} bytes, more than the {Limit} a run file can be, so it was not read. It stays where it is.",
+ path, info.Length, MaxFileBytes);
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.Malformed, null, null);
+ }
+
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ using var reader = new StreamReader(stream, new UTF8Encoding(false), true);
+ text = await reader.ReadToEndAsync(cancellationToken);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ WarnOnce("read:" + ex.GetType().Name, "The upgrade run file {Path} could not be read: {Message}", path, ex.Message);
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.NoFile, null, null);
+ }
+
+ if (!TryParse(text, out var run, out var problem))
+ {
+ WarnOnce("parse:" + Hash(text),
+ "The upgrade run file {Path} was not recorded: {Problem}. It stays where it is, and this is logged once for this content.",
+ path, problem);
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.Malformed, null, null);
+ }
+
+ await RecordAsync(connection, run!, nowUtc, cancellationToken);
+
+ var finished = run!.State is UpgradeRuns.Verified or UpgradeRuns.Failed;
+ var stale = nowUtc - run.StartedUtc > MaxFileAge;
+ if (!finished && !stale)
+ {
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.Recorded, run.RunId, run.State);
+ }
+
+ try
+ {
+ File.Delete(path);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ WarnOnce("delete:" + run.RunId.ToString("N") + ":" + run.State,
+ "The upgrade run {RunId} ({State}) was recorded, but {Path} could not be removed: {Message}. The next pass records it again and the store keeps one row for it.",
+ run.RunId, run.State, path, ex.Message);
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.RecordedNotRemoved, run.RunId, run.State);
+ }
+
+ return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.RecordedAndRemoved, run.RunId, run.State);
+ }
+
+ /// Parses a run file. False, with the reason, when it is not valid JSON or lacks a usable run id, state or start time.
+ public static bool TryParse(string text, out UpgradeRunFile? run, out string problem)
+ {
+ run = null;
+ try
+ {
+ using var document = JsonDocument.Parse(text);
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object)
+ {
+ problem = "the file is not a JSON object";
+ return false;
+ }
+
+ if (!TryGuid(root, "run_id", out var runId))
+ {
+ problem = "run_id is missing or is not a GUID";
+ return false;
+ }
+
+ var state = Text(root, "state");
+ if (state is null || !UpgradeRuns.States.Contains(state))
+ {
+ problem = "state is missing or is not one of in_progress, succeeded, failed, verified";
+ return false;
+ }
+
+ if (!TryTime(root, "started_utc", out var started) || started is null)
+ {
+ problem = "started_utc is missing or is not a time";
+ return false;
+ }
+
+ DateTime? ended = null;
+ if (Has(root, "ended_utc"))
+ {
+ if (!TryTime(root, "ended_utc", out ended))
+ {
+ problem = "ended_utc is not a time";
+ return false;
+ }
+ }
+
+ DateTime? verified = null;
+ if (Has(root, "verified_utc"))
+ {
+ if (!TryTime(root, "verified_utc", out verified))
+ {
+ problem = "verified_utc is not a time";
+ return false;
+ }
+ }
+
+ int? exitCode = null;
+ if (Has(root, "exit_code"))
+ {
+ if (!root.GetProperty("exit_code").TryGetInt32(out var code))
+ {
+ problem = "exit_code is not a number";
+ return false;
+ }
+
+ exitCode = code;
+ }
+
+ run = new UpgradeRunFile(
+ runId, state, Text(root, "tool_version"), Text(root, "target_build"), started.Value, ended, exitCode,
+ Text(root, "stop_check"), Text(root, "rollback_folder"), Text(root, "first_error"), verified);
+ problem = "";
+ return true;
+ }
+ catch (JsonException ex)
+ {
+ problem = "the file is not valid JSON (" + ex.Message + ")";
+ return false;
+ }
+ }
+
+ private static async Task RecordAsync(NpgsqlConnection connection, UpgradeRunFile run, DateTime nowUtc, CancellationToken cancellationToken)
+ {
+ await using (var upsert = new NpgsqlCommand(UpgradeRuns.UpsertSql, connection) { CommandTimeout = 30 })
+ {
+ upsert.Parameters.Add(new NpgsqlParameter { Value = run.RunId, NpgsqlDbType = NpgsqlDbType.Uuid });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = run.State, NpgsqlDbType = NpgsqlDbType.Text });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.ToolVersion ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.TargetBuild ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = run.StartedUtc, NpgsqlDbType = NpgsqlDbType.Timestamp });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.EndedUtc ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Timestamp });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.ExitCode ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Integer });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.StopCheck ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.RollbackFolder ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.FirstError ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.VerifiedUtc ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Timestamp });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = nowUtc, NpgsqlDbType = NpgsqlDbType.Timestamp });
+ await upsert.ExecuteNonQueryAsync(cancellationToken);
+ }
+
+ await using var retention = new NpgsqlCommand(UpgradeRuns.RetentionDeleteSql, connection) { CommandTimeout = 30 };
+ retention.Parameters.Add(new NpgsqlParameter { Value = nowUtc.AddDays(-UpgradeRuns.RetentionDays), NpgsqlDbType = NpgsqlDbType.Timestamp });
+ await retention.ExecuteNonQueryAsync(cancellationToken);
+ }
+
+ private void WarnOnce(string key, string message, params object?[] args)
+ {
+ if (_warned.Count >= MaxWarnedKeys)
+ {
+ _warned.Clear();
+ }
+
+ if (_warned.Add(key))
+ {
+ _logger.LogWarning(message, args);
+ }
+ }
+
+ private static string Hash(string text) =>
+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
+
+ private static bool Has(JsonElement root, string name) =>
+ root.TryGetProperty(name, out var value) && value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined);
+
+ private static string? Text(JsonElement root, string name)
+ {
+ if (!root.TryGetProperty(name, out var value) || value.ValueKind != JsonValueKind.String)
+ {
+ return null;
+ }
+
+ var text = value.GetString();
+ if (string.IsNullOrEmpty(text))
+ {
+ return null;
+ }
+
+ return text.Length <= MaxTextChars ? text : text[..MaxTextChars];
+ }
+
+ private static bool TryGuid(JsonElement root, string name, out Guid value)
+ {
+ value = Guid.Empty;
+ var text = Text(root, name);
+ return text is not null && Guid.TryParse(text, out value) && value != Guid.Empty;
+ }
+
+ private static bool TryTime(JsonElement root, string name, out DateTime? value)
+ {
+ value = null;
+ var text = Text(root, name);
+ if (text is null
+ || !DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var parsed))
+ {
+ return false;
+ }
+
+ value = DateTime.SpecifyKind(parsed, DateTimeKind.Unspecified);
+ return true;
+ }
+}
diff --git a/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs b/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs
index ada98903f9..1513b7eab9 100644
--- a/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs
+++ b/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs
@@ -1661,7 +1661,9 @@ the answer does not depend on the connecting role's privileges. */
EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = to_regclass('collect.store_statement_history') AND attname = 'delta_shared_blks_dirtied' AND NOT attisdropped),
/* V305 (#9419) adds the WAL columns to collect.store_metrics, never dropped. The wal_stats_reset column is the mark that the rung ran. Found by catalog, as the
V156 line above is, so the answer does not depend on the connecting role's privileges. */
- EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = to_regclass('collect.store_metrics') AND attname = 'wal_stats_reset' AND NOT attisdropped)";
+ EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = to_regclass('collect.store_metrics') AND attname = 'wal_stats_reset' AND NOT attisdropped),
+ /* V306 (#9432) adds the upgrade run table, a plain table on every store and never dropped. Found by catalog, as the V303 line above is. */
+ to_regclass('collect.upgrade_runs') IS NOT NULL";
/// The store schema version this viewer build requires — the highest migration it knows
/// (). The connect-time gate blocks a store below this.
@@ -1683,7 +1685,7 @@ the answer does not depend on the connecting role's privileges. */
await using var reader = await command.ExecuteReaderAsync(ViewerReadScope.Effective(cancellationToken));
if (await reader.ReadAsync(cancellationToken))
{
- return MapProbedSchemaVersion(reader.GetBoolean(0), reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3), reader.GetBoolean(4), reader.GetBoolean(5), reader.GetBoolean(6), reader.GetBoolean(7), reader.GetBoolean(8), reader.GetBoolean(9), reader.GetBoolean(10), reader.GetBoolean(11), reader.GetBoolean(12), reader.GetBoolean(13), reader.GetBoolean(14), reader.GetBoolean(15), reader.GetBoolean(16), reader.GetBoolean(17), reader.GetBoolean(18), reader.GetBoolean(19), reader.GetBoolean(20), reader.GetBoolean(21), reader.GetBoolean(22), reader.GetBoolean(23), reader.GetBoolean(24), reader.GetBoolean(25), reader.GetBoolean(26), reader.GetBoolean(27), reader.GetBoolean(28), reader.GetBoolean(29), reader.GetBoolean(30), reader.GetBoolean(31), reader.GetBoolean(32), reader.GetBoolean(33), reader.GetBoolean(34), reader.GetBoolean(35), reader.GetBoolean(36), reader.GetBoolean(37), reader.GetBoolean(38), reader.GetBoolean(39), reader.GetBoolean(40), reader.GetBoolean(41), reader.GetBoolean(42), reader.GetBoolean(43), reader.GetBoolean(44), reader.GetBoolean(45), reader.GetBoolean(46), reader.GetBoolean(47), reader.GetBoolean(48), reader.GetBoolean(49), reader.GetBoolean(50), reader.GetBoolean(51), reader.GetBoolean(52), reader.GetBoolean(53), reader.GetBoolean(54), reader.GetBoolean(55), reader.GetBoolean(56), reader.GetBoolean(57), reader.GetBoolean(58), reader.GetBoolean(59), reader.GetBoolean(60), reader.GetBoolean(61), reader.GetBoolean(62), reader.GetBoolean(63), reader.GetBoolean(64), reader.GetBoolean(65), reader.GetBoolean(66), reader.GetBoolean(67), reader.GetBoolean(68), reader.GetBoolean(69), reader.GetBoolean(70), reader.GetBoolean(71), reader.GetBoolean(72), reader.GetBoolean(73), reader.GetBoolean(74), reader.GetBoolean(75), reader.GetBoolean(76), reader.GetBoolean(77), reader.GetBoolean(78), reader.GetBoolean(79), reader.GetBoolean(80), reader.GetBoolean(81), reader.GetBoolean(82), reader.GetBoolean(83), reader.GetBoolean(84), reader.GetBoolean(85), reader.GetBoolean(86), reader.GetBoolean(87), reader.GetBoolean(88), reader.GetBoolean(89), reader.GetBoolean(90), reader.GetBoolean(91), reader.GetBoolean(92), reader.GetBoolean(93), reader.GetBoolean(94), reader.GetBoolean(95), reader.GetBoolean(96), reader.GetBoolean(97), reader.GetBoolean(98), reader.GetBoolean(99), reader.GetBoolean(100), reader.GetBoolean(101), reader.GetBoolean(102), reader.GetBoolean(103), reader.GetBoolean(104), reader.GetBoolean(105), reader.GetBoolean(106), reader.GetBoolean(107), reader.GetBoolean(108), reader.GetBoolean(109), reader.GetBoolean(110), reader.GetBoolean(111), reader.GetBoolean(112), reader.GetBoolean(113), reader.GetBoolean(114), reader.GetBoolean(115), reader.GetBoolean(116), reader.GetBoolean(117), reader.GetBoolean(118), reader.GetBoolean(119), reader.GetBoolean(120), reader.GetBoolean(121), reader.GetBoolean(122), reader.GetBoolean(123), reader.GetBoolean(124), reader.GetBoolean(125), reader.GetBoolean(126), reader.GetBoolean(127), reader.GetBoolean(128), reader.GetBoolean(129), reader.GetBoolean(130), reader.GetBoolean(131), reader.GetBoolean(132), reader.GetBoolean(133), reader.GetBoolean(134), reader.GetBoolean(135), reader.GetBoolean(136), reader.GetBoolean(137), reader.GetBoolean(138), reader.GetBoolean(139), reader.GetBoolean(140), reader.GetBoolean(141), reader.GetBoolean(142), reader.GetBoolean(143), reader.GetBoolean(144), reader.GetBoolean(145), reader.GetBoolean(146), reader.GetBoolean(147), reader.GetBoolean(148), reader.GetBoolean(149), reader.GetBoolean(150), reader.GetBoolean(151), reader.GetBoolean(152), reader.GetBoolean(153), reader.GetBoolean(154), reader.GetBoolean(155), reader.GetBoolean(156), reader.GetBoolean(157), reader.GetBoolean(158), reader.GetBoolean(159), reader.GetBoolean(160), reader.GetBoolean(161), reader.GetBoolean(162), reader.GetBoolean(163), reader.GetBoolean(164), reader.GetBoolean(165), reader.GetBoolean(166), reader.GetBoolean(167), reader.GetBoolean(168), reader.GetBoolean(169), reader.GetBoolean(170), reader.GetBoolean(171), reader.GetBoolean(172), reader.GetBoolean(173), reader.GetBoolean(174), reader.GetBoolean(175), reader.GetBoolean(176), reader.GetBoolean(177), reader.GetBoolean(178), reader.GetBoolean(179), reader.GetBoolean(180), reader.GetBoolean(181), reader.GetBoolean(182), reader.GetBoolean(183), reader.GetBoolean(184), reader.GetBoolean(185), reader.GetBoolean(186), reader.GetBoolean(187), reader.GetBoolean(188), reader.GetBoolean(189), reader.GetBoolean(190), reader.GetBoolean(191), reader.GetBoolean(192), reader.GetBoolean(193), reader.GetBoolean(194), reader.GetBoolean(195), reader.GetBoolean(196), reader.GetBoolean(197), reader.GetBoolean(198), reader.GetBoolean(199), reader.GetBoolean(200), reader.GetBoolean(201), reader.GetBoolean(202), reader.GetBoolean(203), reader.GetBoolean(204), reader.GetBoolean(205), reader.GetBoolean(206), reader.GetBoolean(207), reader.GetBoolean(208), reader.GetBoolean(209), reader.GetBoolean(210), reader.GetBoolean(211), reader.GetBoolean(212), reader.GetBoolean(213), reader.GetBoolean(214), reader.GetBoolean(215), reader.GetBoolean(216), reader.GetBoolean(217), reader.GetBoolean(218), reader.GetBoolean(219), reader.GetBoolean(220), reader.GetBoolean(221), reader.GetBoolean(222), reader.GetBoolean(223), reader.GetBoolean(224), reader.GetBoolean(225), reader.GetBoolean(226), reader.GetBoolean(227), reader.GetBoolean(228), reader.GetBoolean(229), reader.GetBoolean(230), reader.GetBoolean(231), reader.GetBoolean(232), reader.GetBoolean(233), reader.GetBoolean(234), reader.GetBoolean(235), reader.GetBoolean(236), reader.GetBoolean(237), reader.GetBoolean(238), reader.GetBoolean(239), reader.GetBoolean(240), reader.GetBoolean(241), reader.GetBoolean(242), reader.GetBoolean(243), reader.GetBoolean(244), reader.GetBoolean(245), reader.GetBoolean(246), reader.GetBoolean(247), reader.GetBoolean(248), reader.GetBoolean(249), reader.GetBoolean(250), reader.GetBoolean(251), reader.GetBoolean(252), reader.GetBoolean(253), reader.GetBoolean(254), reader.GetBoolean(255), reader.GetBoolean(256), reader.GetBoolean(257), reader.GetBoolean(258), reader.GetBoolean(259), reader.GetBoolean(260), reader.GetBoolean(261), reader.GetBoolean(262), reader.GetBoolean(263), reader.GetBoolean(264), reader.GetBoolean(265), reader.GetBoolean(266), reader.GetBoolean(267), reader.GetBoolean(268), reader.GetBoolean(269), reader.GetBoolean(270), reader.GetBoolean(271), reader.GetBoolean(272), reader.GetBoolean(273), reader.GetBoolean(274), reader.GetBoolean(275), reader.GetBoolean(276), reader.GetBoolean(277), reader.GetBoolean(278), reader.GetBoolean(279), reader.GetBoolean(280));
+ return MapProbedSchemaVersion(reader.GetBoolean(0), reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3), reader.GetBoolean(4), reader.GetBoolean(5), reader.GetBoolean(6), reader.GetBoolean(7), reader.GetBoolean(8), reader.GetBoolean(9), reader.GetBoolean(10), reader.GetBoolean(11), reader.GetBoolean(12), reader.GetBoolean(13), reader.GetBoolean(14), reader.GetBoolean(15), reader.GetBoolean(16), reader.GetBoolean(17), reader.GetBoolean(18), reader.GetBoolean(19), reader.GetBoolean(20), reader.GetBoolean(21), reader.GetBoolean(22), reader.GetBoolean(23), reader.GetBoolean(24), reader.GetBoolean(25), reader.GetBoolean(26), reader.GetBoolean(27), reader.GetBoolean(28), reader.GetBoolean(29), reader.GetBoolean(30), reader.GetBoolean(31), reader.GetBoolean(32), reader.GetBoolean(33), reader.GetBoolean(34), reader.GetBoolean(35), reader.GetBoolean(36), reader.GetBoolean(37), reader.GetBoolean(38), reader.GetBoolean(39), reader.GetBoolean(40), reader.GetBoolean(41), reader.GetBoolean(42), reader.GetBoolean(43), reader.GetBoolean(44), reader.GetBoolean(45), reader.GetBoolean(46), reader.GetBoolean(47), reader.GetBoolean(48), reader.GetBoolean(49), reader.GetBoolean(50), reader.GetBoolean(51), reader.GetBoolean(52), reader.GetBoolean(53), reader.GetBoolean(54), reader.GetBoolean(55), reader.GetBoolean(56), reader.GetBoolean(57), reader.GetBoolean(58), reader.GetBoolean(59), reader.GetBoolean(60), reader.GetBoolean(61), reader.GetBoolean(62), reader.GetBoolean(63), reader.GetBoolean(64), reader.GetBoolean(65), reader.GetBoolean(66), reader.GetBoolean(67), reader.GetBoolean(68), reader.GetBoolean(69), reader.GetBoolean(70), reader.GetBoolean(71), reader.GetBoolean(72), reader.GetBoolean(73), reader.GetBoolean(74), reader.GetBoolean(75), reader.GetBoolean(76), reader.GetBoolean(77), reader.GetBoolean(78), reader.GetBoolean(79), reader.GetBoolean(80), reader.GetBoolean(81), reader.GetBoolean(82), reader.GetBoolean(83), reader.GetBoolean(84), reader.GetBoolean(85), reader.GetBoolean(86), reader.GetBoolean(87), reader.GetBoolean(88), reader.GetBoolean(89), reader.GetBoolean(90), reader.GetBoolean(91), reader.GetBoolean(92), reader.GetBoolean(93), reader.GetBoolean(94), reader.GetBoolean(95), reader.GetBoolean(96), reader.GetBoolean(97), reader.GetBoolean(98), reader.GetBoolean(99), reader.GetBoolean(100), reader.GetBoolean(101), reader.GetBoolean(102), reader.GetBoolean(103), reader.GetBoolean(104), reader.GetBoolean(105), reader.GetBoolean(106), reader.GetBoolean(107), reader.GetBoolean(108), reader.GetBoolean(109), reader.GetBoolean(110), reader.GetBoolean(111), reader.GetBoolean(112), reader.GetBoolean(113), reader.GetBoolean(114), reader.GetBoolean(115), reader.GetBoolean(116), reader.GetBoolean(117), reader.GetBoolean(118), reader.GetBoolean(119), reader.GetBoolean(120), reader.GetBoolean(121), reader.GetBoolean(122), reader.GetBoolean(123), reader.GetBoolean(124), reader.GetBoolean(125), reader.GetBoolean(126), reader.GetBoolean(127), reader.GetBoolean(128), reader.GetBoolean(129), reader.GetBoolean(130), reader.GetBoolean(131), reader.GetBoolean(132), reader.GetBoolean(133), reader.GetBoolean(134), reader.GetBoolean(135), reader.GetBoolean(136), reader.GetBoolean(137), reader.GetBoolean(138), reader.GetBoolean(139), reader.GetBoolean(140), reader.GetBoolean(141), reader.GetBoolean(142), reader.GetBoolean(143), reader.GetBoolean(144), reader.GetBoolean(145), reader.GetBoolean(146), reader.GetBoolean(147), reader.GetBoolean(148), reader.GetBoolean(149), reader.GetBoolean(150), reader.GetBoolean(151), reader.GetBoolean(152), reader.GetBoolean(153), reader.GetBoolean(154), reader.GetBoolean(155), reader.GetBoolean(156), reader.GetBoolean(157), reader.GetBoolean(158), reader.GetBoolean(159), reader.GetBoolean(160), reader.GetBoolean(161), reader.GetBoolean(162), reader.GetBoolean(163), reader.GetBoolean(164), reader.GetBoolean(165), reader.GetBoolean(166), reader.GetBoolean(167), reader.GetBoolean(168), reader.GetBoolean(169), reader.GetBoolean(170), reader.GetBoolean(171), reader.GetBoolean(172), reader.GetBoolean(173), reader.GetBoolean(174), reader.GetBoolean(175), reader.GetBoolean(176), reader.GetBoolean(177), reader.GetBoolean(178), reader.GetBoolean(179), reader.GetBoolean(180), reader.GetBoolean(181), reader.GetBoolean(182), reader.GetBoolean(183), reader.GetBoolean(184), reader.GetBoolean(185), reader.GetBoolean(186), reader.GetBoolean(187), reader.GetBoolean(188), reader.GetBoolean(189), reader.GetBoolean(190), reader.GetBoolean(191), reader.GetBoolean(192), reader.GetBoolean(193), reader.GetBoolean(194), reader.GetBoolean(195), reader.GetBoolean(196), reader.GetBoolean(197), reader.GetBoolean(198), reader.GetBoolean(199), reader.GetBoolean(200), reader.GetBoolean(201), reader.GetBoolean(202), reader.GetBoolean(203), reader.GetBoolean(204), reader.GetBoolean(205), reader.GetBoolean(206), reader.GetBoolean(207), reader.GetBoolean(208), reader.GetBoolean(209), reader.GetBoolean(210), reader.GetBoolean(211), reader.GetBoolean(212), reader.GetBoolean(213), reader.GetBoolean(214), reader.GetBoolean(215), reader.GetBoolean(216), reader.GetBoolean(217), reader.GetBoolean(218), reader.GetBoolean(219), reader.GetBoolean(220), reader.GetBoolean(221), reader.GetBoolean(222), reader.GetBoolean(223), reader.GetBoolean(224), reader.GetBoolean(225), reader.GetBoolean(226), reader.GetBoolean(227), reader.GetBoolean(228), reader.GetBoolean(229), reader.GetBoolean(230), reader.GetBoolean(231), reader.GetBoolean(232), reader.GetBoolean(233), reader.GetBoolean(234), reader.GetBoolean(235), reader.GetBoolean(236), reader.GetBoolean(237), reader.GetBoolean(238), reader.GetBoolean(239), reader.GetBoolean(240), reader.GetBoolean(241), reader.GetBoolean(242), reader.GetBoolean(243), reader.GetBoolean(244), reader.GetBoolean(245), reader.GetBoolean(246), reader.GetBoolean(247), reader.GetBoolean(248), reader.GetBoolean(249), reader.GetBoolean(250), reader.GetBoolean(251), reader.GetBoolean(252), reader.GetBoolean(253), reader.GetBoolean(254), reader.GetBoolean(255), reader.GetBoolean(256), reader.GetBoolean(257), reader.GetBoolean(258), reader.GetBoolean(259), reader.GetBoolean(260), reader.GetBoolean(261), reader.GetBoolean(262), reader.GetBoolean(263), reader.GetBoolean(264), reader.GetBoolean(265), reader.GetBoolean(266), reader.GetBoolean(267), reader.GetBoolean(268), reader.GetBoolean(269), reader.GetBoolean(270), reader.GetBoolean(271), reader.GetBoolean(272), reader.GetBoolean(273), reader.GetBoolean(274), reader.GetBoolean(275), reader.GetBoolean(276), reader.GetBoolean(277), reader.GetBoolean(278), reader.GetBoolean(279), reader.GetBoolean(280), reader.GetBoolean(281));
}
return null;
@@ -1708,7 +1710,7 @@ the answer does not depend on the connecting role's privileges. */
/// is unit-tested without a live store; any schema bump past the newest arm trips the pinning test that keeps
/// this in step with .
///
- internal static int MapProbedSchemaVersion(bool hasConfigControlPlane, bool hasAlertDeliveryOverride, bool hasAnalysisState, bool hasAlertTuningKnobs, bool hasDefaultTraceEvents, bool hasIndexObjectStatsLatestIndex, bool hasCollectionLogHypertableOrPlainPg, bool hasJobHistory, bool hasAgentStatus, bool hasGenericWebhook, bool hasDeadlocksDatabaseName, bool hasQueryStoreReplicaRole, bool hasLongQueryCompletions, bool hasWebDashboardConfig, bool hasCustomViews, bool hasServerTags, bool hasConnectionRefireKnobs = false, bool hasAgCollectors = false, bool hasAgAlertKnobs = false, bool hasAgLatencyColumns = false, bool hasAgDisconnectRefire = false, bool hasPayloadDimensions = false, bool hasDimFloorIndexes = false, bool hasBlockingWaitThreshold = false, bool hasQueryStoreIntervalIdentity = false, bool hasPagerDutyWebhook = false, bool hasPagerDutyProxy = false, bool hasCollectorState = false, bool hasPlanCorrection = false, bool hasPvsStats = false, bool hasPvsPressureKnobs = false, bool hasDatabaseStateAlert = false, bool hasServerTagColour = false, bool hasQueryStatsHostObject = false, bool hasFindingDrillDown = false, bool hasStoreMetrics = false, bool hasPlanDimGzip = false, bool hasSelfAlertKnobs = false, bool hasJobMetricsColumns = false, bool hasJobCadenceKnob = false, bool hasBackfillSwitch = false, bool hasCollectorMemoryKnobs = false, bool hasDatabaseStateEdgeMemory = false, bool hasIncidentOccurrences = false, bool hasPlanXmlCompressionKnob = false, bool hasMonitoredServerEngine = false, bool hasPgBlockingEdges = false, bool hasQueryStorePlanMap = false, bool hasPgStatementText = false, bool hasQueryStoreText = false, bool hasPlanContentRetentionKnob = false, bool hasQueryStoreHealth = false, bool hasQueryStoreTextHash = false, bool hasComposeTimeoutKnob = false, bool hasFileGrowthAlert = false, bool hasCollectionLogFanoutRollup = false, bool hasTempDbMaxSize = false, bool hasServerEngineKind = false, bool hasPgDatabaseStats = false, bool hasPgIndexUsageStats = false, bool hasPgTableBloatStats = false, bool hasPgSessionStates = false, bool hasPgPlanCaptureReadiness = false, bool hasPgWriteStats = false, bool hasPgExtensionAvailability = false, bool hasPgLockStats = false, bool hasPgColumnStats = false, bool hasPgReplicationStats = false, bool hasPgBufferUsage = false, bool hasPgIndexBloat = false, bool hasPgPerDatabaseAttribution = false, bool hasPgWaitSampling = false, bool hasPgKernelStats = false, bool hasPgPredicateStats = false, bool hasPgPlanCapture = false, bool hasPgMajorVersion = false, bool hasPg18IoBytes = false, bool hasPgServerConfig = false, bool hasPgDeadlocks = false, bool hasPgDeadlockIdentity = false, bool hasCollectorCost = false, bool hasPgCpuUtilization = false, bool hasPlanForceActions = false, bool hasCollectionLogPhaseSplit = false, bool hasCollectionLogDrainForensics = false, bool hasCollectionLogFetchPhaseSums = false, bool hasStoreLogSelfMonitoring = false, bool hasCollectorStallProbes = false, bool hasRemediationCredentialAndActor = false, bool hasPgIndexBloatEstimate = false, bool hasPgCpuCapacityHeadroom = false, bool hasCustomAlertCore = false, bool hasMuteRuleReloadBeacon = false, bool hasBuiltinAlertPersistence = false, bool hasRetentionHoldRatioKnobs = false, bool hasDeadlockRateBandKnobs = false, bool hasOversizedPlanBacklog = false, bool hasPgAlertCountKnobs = false, bool hasFleetSweepState = false, bool hasFleetSweepCadenceKnobs = false, bool hasCollectorScheduleDatabases = false, bool hasSelfDiskWarnGbFloor = false, bool hasDeltaFamilyIntervalColumns = false, bool hasDeltaFamilyIntervalCompletion = false, bool hasPgLogEvents = false, bool hasPgLogEventMetrics = false, bool hasNotificationRoutes = false, bool hasPerfmonCounterType = false, bool hasPgNumbackendsAndSampledMs = false, bool hasTimeHonesty = false, bool hasLrqExclusionKnob = false, bool hasPgDatabaseSizeStatsAndHostMemory = false, bool hasQsCaptureModeRouteKnobToast = false, bool hasPgServerConfigDatabaseRoleOverrides = false, bool hasPostmasterStartTime = false, bool hasCheckpointsTimed = false, bool hasCollectionCaveats = false, bool hasIndexObjectStatsServerTimeIndex = false, bool hasQueryStoreIntervalLatest = false, bool hasRawChunkIntervalRungHistory = false, bool hasQueryStoreIntervalWide = false, bool hasManagedConfVerdicts = false, bool hasComposeTimeoutSixty = false, bool hasReadLatency = false, bool hasHotLivenessTouch = false, bool hasCollectionLogWatermarkAndJobHistoryIndexes = false, bool hasAgGroupId = false, bool hasCaggGroupIndexDrop = false, bool hasIntervalFirstExecIndexes = false, bool hasIntervalWideFirstExecIndex = false, bool hasQueryStoreIntervalEnd = false, bool hasCheckpointLongestSync = false, bool hasMuteRuleServerId = false, bool hasInstallId = false, bool hasInstallIdTableOid = false, bool hasCollectorRunAt = false, bool hasQueryStoreTopDaily = false, bool hasSlowReads = false, bool hasStoreStatementHistory = false, bool hasQueryStatsHourLedger = false, bool hasPasswordKey = false, bool hasPagerDutyAutoResolve = false, bool hasLegacyPinCandidates = false, bool hasPlanRegressionDaily = false, bool hasAwsRole = false, bool hasPgIoStatsHourly = false, bool hasQueryStoreIntervalWidePartitioned = false, bool hasQueryStoreIntervalLatestPartitioned = false, bool hasQueryStoreComposeStamp = false, bool hasServiceVersion = false, bool hasPlanRegressionDailyRowcount = false, bool hasProcedureStatsTotals = false, bool hasRunnableQueueSettings = false, bool hasQueryStoreWatermarks = false, bool hasClientTimeoutSettings = false, bool hasExternalAlerts = false, bool hasNotificationRouteScope = false, bool hasReadLatencyCapacityFields = false, bool hasReadCaller = false, bool hasInvestigations = false, bool hasPlanRegressionPartialDays = false, bool hasCollectionLogHourly = false, bool hasAlertResolutionDelivery = false, bool hasInvestigationAlertFacts = false, bool hasComposeStampFailures = false, bool hasStoreMetricsSizeEstimated = false, bool hasAgentLevel2Store = false, bool hasQueryTagsStore = false, bool hasPhaseCStore = false, bool hasQueryTagSightingsDatabaseKey = false, bool hasQueryStoreForcedPlans = false, bool hasServerActionSwitches = false, bool hasForceChecks = false, bool hasPseudonymKey = false, bool hasBlockingHeadEvidence = false, bool hasExcludedVolumes = false, bool hasForcedPlanVariantsAndGuides = false, bool hasAgPrimaryReplica = false, bool hasHypotheticalIndexLogin = false, bool hasCustomViewFolders = false, bool hasCustomAlertRuleExpiry = false, bool hasInheritableCollectorEnabled = false, bool hasChangeWatches = false, bool hasMuteRuleStartsAt = false, bool hasQueryStoreFetchTopN = false, bool hasAgentRouteTagGuard = false, bool hasClientTimeoutsMultiples = false, bool hasServerMachineIdentity = false, bool hasQueryStoreReplica = false, bool hasKnownPatterns = false, bool hasAgentTableIndexes = false, bool hasClientTimeoutsOnByDefault = false, bool hasQueryStoreHints = false, bool hasServerActionRecompile = false, bool hasQueryStoreSelfKeys = false, bool hasJobHistorySuccessIndex = false, bool hasQueryStoreHashHourly = false, bool hasAgentAlerts = false, bool hasDatabaseProtection = false, bool hasIdentityCapacity = false, bool hasServerAwsRds = false, bool hasServerAwsRdsWebOrExpress = false, bool hasThresholdOverrideTagScope = false, bool hasBlockingBands = false, bool hasRouteSeverities = false, bool hasBlockingSnapshotBands = false, bool hasMuteRecurrence = false, bool hasDailyReportSettings = false, bool hasReportNotice = false, bool hasAlertLogKey = false, bool hasBlockingBarsOnWaitTime = false, bool hasMuteRuleAction = false, bool hasPeopleGrants = false, bool hasActionProposals = false, bool hasComposeFleet = false, bool hasQueryStoreTopDailyWsum = false, bool hasBlockingOpenTranCount = false, bool hasStatementTextOwnEntries = false, bool hasWaitingTasksProgramName = false, bool hasServerConnectDownState = false, bool hasProtectionThresholds = false, bool hasQueryStoreHashIndex = false, bool hasXeSessionDatabases = false, bool hasSelfKeysOldStatements = false, bool hasStatementStatsDatabaseName = false, bool hasMemoryPressureNode = false, bool hasComposeStampLateMarkOffsetZero = false, bool hasSlackBotThreads = false, bool hasSlackCards = false, bool hasChatRequests = false, bool hasWaitStatsCadenceBaseline = false, bool hasSchemaTracking = false, bool hasCollectionLogStatusTimeIndex = false, bool hasOversizedPlanBacklogDroppedIndex = false, bool hasWaitStatsDaily = false, bool hasOversizedPlanBacklogMedianIndexes = false, bool hasWebAccessGroups = false, bool hasAdvancedWebAccess = false, bool hasJobHistoryOldestDaily = false, bool hasOversizedPlanBacklogDropCounts = false, bool hasJobHistoryCategoryHourly = false, bool hasQueryTagSightingsFillfactor = false, bool hasPlanRegressionDailyServerDayIndex = false, bool hasObjectUsage = false, bool hasTempDbLogSpace = false, bool hasDatabaseSizeAutogrowAllFiles = false, bool hasInstanceEventAlertSwitches = false, bool hasColumnStats = false, bool hasWaitStatsHourly = false, bool hasTrigramIndexStoreOptions = false, bool hasPersonalTokens = false, bool hasStoreGrowthAlertSettings = false, bool hasAttentionLegacyCopy = false, bool hasDatabaseProtectionErrorLog = false, bool hasAggregateCompressionOrderHistory = false, bool hasPlanCorrectionServerDbQueryIndex = false, bool hasQueryStoreTextSeen = false, bool hasJobOutcomeDaily = false, bool hasQueryStoreClosedDayRollups = false, bool hasFleetSummaryCoveringIndexes = false, bool hasQueryStoreClutterDaily = false, bool hasQueryStatsCollectionSummary = false, bool hasQueryStatsHostHourly = false, bool hasCollectionLogWatermarkCovering = false, bool hasQueryStoreClutterHourly = false, bool hasQueryStatsCollectionFloor = false, bool hasQueryStoreServerCoveringIndex = false, bool hasQueryStoreCorrectedDailyHashIndex = false, bool hasAttentionCountIndex = false, bool hasAggregateCompressionOrderHistoryIndex = false, bool hasPlanRegressionBlock = false, bool hasQueryStoreTopHourly = false, bool hasObjectReferences = false, bool hasPayloadDimensionSeen = false, bool hasObjectUsageChain = false, bool hasProcedureStatsHourLedger = false, bool hasStoreRelationSizes = false, bool hasJobHistoryFailedIndex = false, bool hasClutterDayBuilt = false, bool hasStatementHistoryWriteCounters = false, bool hasStoreWalFigures = false)
+ internal static int MapProbedSchemaVersion(bool hasConfigControlPlane, bool hasAlertDeliveryOverride, bool hasAnalysisState, bool hasAlertTuningKnobs, bool hasDefaultTraceEvents, bool hasIndexObjectStatsLatestIndex, bool hasCollectionLogHypertableOrPlainPg, bool hasJobHistory, bool hasAgentStatus, bool hasGenericWebhook, bool hasDeadlocksDatabaseName, bool hasQueryStoreReplicaRole, bool hasLongQueryCompletions, bool hasWebDashboardConfig, bool hasCustomViews, bool hasServerTags, bool hasConnectionRefireKnobs = false, bool hasAgCollectors = false, bool hasAgAlertKnobs = false, bool hasAgLatencyColumns = false, bool hasAgDisconnectRefire = false, bool hasPayloadDimensions = false, bool hasDimFloorIndexes = false, bool hasBlockingWaitThreshold = false, bool hasQueryStoreIntervalIdentity = false, bool hasPagerDutyWebhook = false, bool hasPagerDutyProxy = false, bool hasCollectorState = false, bool hasPlanCorrection = false, bool hasPvsStats = false, bool hasPvsPressureKnobs = false, bool hasDatabaseStateAlert = false, bool hasServerTagColour = false, bool hasQueryStatsHostObject = false, bool hasFindingDrillDown = false, bool hasStoreMetrics = false, bool hasPlanDimGzip = false, bool hasSelfAlertKnobs = false, bool hasJobMetricsColumns = false, bool hasJobCadenceKnob = false, bool hasBackfillSwitch = false, bool hasCollectorMemoryKnobs = false, bool hasDatabaseStateEdgeMemory = false, bool hasIncidentOccurrences = false, bool hasPlanXmlCompressionKnob = false, bool hasMonitoredServerEngine = false, bool hasPgBlockingEdges = false, bool hasQueryStorePlanMap = false, bool hasPgStatementText = false, bool hasQueryStoreText = false, bool hasPlanContentRetentionKnob = false, bool hasQueryStoreHealth = false, bool hasQueryStoreTextHash = false, bool hasComposeTimeoutKnob = false, bool hasFileGrowthAlert = false, bool hasCollectionLogFanoutRollup = false, bool hasTempDbMaxSize = false, bool hasServerEngineKind = false, bool hasPgDatabaseStats = false, bool hasPgIndexUsageStats = false, bool hasPgTableBloatStats = false, bool hasPgSessionStates = false, bool hasPgPlanCaptureReadiness = false, bool hasPgWriteStats = false, bool hasPgExtensionAvailability = false, bool hasPgLockStats = false, bool hasPgColumnStats = false, bool hasPgReplicationStats = false, bool hasPgBufferUsage = false, bool hasPgIndexBloat = false, bool hasPgPerDatabaseAttribution = false, bool hasPgWaitSampling = false, bool hasPgKernelStats = false, bool hasPgPredicateStats = false, bool hasPgPlanCapture = false, bool hasPgMajorVersion = false, bool hasPg18IoBytes = false, bool hasPgServerConfig = false, bool hasPgDeadlocks = false, bool hasPgDeadlockIdentity = false, bool hasCollectorCost = false, bool hasPgCpuUtilization = false, bool hasPlanForceActions = false, bool hasCollectionLogPhaseSplit = false, bool hasCollectionLogDrainForensics = false, bool hasCollectionLogFetchPhaseSums = false, bool hasStoreLogSelfMonitoring = false, bool hasCollectorStallProbes = false, bool hasRemediationCredentialAndActor = false, bool hasPgIndexBloatEstimate = false, bool hasPgCpuCapacityHeadroom = false, bool hasCustomAlertCore = false, bool hasMuteRuleReloadBeacon = false, bool hasBuiltinAlertPersistence = false, bool hasRetentionHoldRatioKnobs = false, bool hasDeadlockRateBandKnobs = false, bool hasOversizedPlanBacklog = false, bool hasPgAlertCountKnobs = false, bool hasFleetSweepState = false, bool hasFleetSweepCadenceKnobs = false, bool hasCollectorScheduleDatabases = false, bool hasSelfDiskWarnGbFloor = false, bool hasDeltaFamilyIntervalColumns = false, bool hasDeltaFamilyIntervalCompletion = false, bool hasPgLogEvents = false, bool hasPgLogEventMetrics = false, bool hasNotificationRoutes = false, bool hasPerfmonCounterType = false, bool hasPgNumbackendsAndSampledMs = false, bool hasTimeHonesty = false, bool hasLrqExclusionKnob = false, bool hasPgDatabaseSizeStatsAndHostMemory = false, bool hasQsCaptureModeRouteKnobToast = false, bool hasPgServerConfigDatabaseRoleOverrides = false, bool hasPostmasterStartTime = false, bool hasCheckpointsTimed = false, bool hasCollectionCaveats = false, bool hasIndexObjectStatsServerTimeIndex = false, bool hasQueryStoreIntervalLatest = false, bool hasRawChunkIntervalRungHistory = false, bool hasQueryStoreIntervalWide = false, bool hasManagedConfVerdicts = false, bool hasComposeTimeoutSixty = false, bool hasReadLatency = false, bool hasHotLivenessTouch = false, bool hasCollectionLogWatermarkAndJobHistoryIndexes = false, bool hasAgGroupId = false, bool hasCaggGroupIndexDrop = false, bool hasIntervalFirstExecIndexes = false, bool hasIntervalWideFirstExecIndex = false, bool hasQueryStoreIntervalEnd = false, bool hasCheckpointLongestSync = false, bool hasMuteRuleServerId = false, bool hasInstallId = false, bool hasInstallIdTableOid = false, bool hasCollectorRunAt = false, bool hasQueryStoreTopDaily = false, bool hasSlowReads = false, bool hasStoreStatementHistory = false, bool hasQueryStatsHourLedger = false, bool hasPasswordKey = false, bool hasPagerDutyAutoResolve = false, bool hasLegacyPinCandidates = false, bool hasPlanRegressionDaily = false, bool hasAwsRole = false, bool hasPgIoStatsHourly = false, bool hasQueryStoreIntervalWidePartitioned = false, bool hasQueryStoreIntervalLatestPartitioned = false, bool hasQueryStoreComposeStamp = false, bool hasServiceVersion = false, bool hasPlanRegressionDailyRowcount = false, bool hasProcedureStatsTotals = false, bool hasRunnableQueueSettings = false, bool hasQueryStoreWatermarks = false, bool hasClientTimeoutSettings = false, bool hasExternalAlerts = false, bool hasNotificationRouteScope = false, bool hasReadLatencyCapacityFields = false, bool hasReadCaller = false, bool hasInvestigations = false, bool hasPlanRegressionPartialDays = false, bool hasCollectionLogHourly = false, bool hasAlertResolutionDelivery = false, bool hasInvestigationAlertFacts = false, bool hasComposeStampFailures = false, bool hasStoreMetricsSizeEstimated = false, bool hasAgentLevel2Store = false, bool hasQueryTagsStore = false, bool hasPhaseCStore = false, bool hasQueryTagSightingsDatabaseKey = false, bool hasQueryStoreForcedPlans = false, bool hasServerActionSwitches = false, bool hasForceChecks = false, bool hasPseudonymKey = false, bool hasBlockingHeadEvidence = false, bool hasExcludedVolumes = false, bool hasForcedPlanVariantsAndGuides = false, bool hasAgPrimaryReplica = false, bool hasHypotheticalIndexLogin = false, bool hasCustomViewFolders = false, bool hasCustomAlertRuleExpiry = false, bool hasInheritableCollectorEnabled = false, bool hasChangeWatches = false, bool hasMuteRuleStartsAt = false, bool hasQueryStoreFetchTopN = false, bool hasAgentRouteTagGuard = false, bool hasClientTimeoutsMultiples = false, bool hasServerMachineIdentity = false, bool hasQueryStoreReplica = false, bool hasKnownPatterns = false, bool hasAgentTableIndexes = false, bool hasClientTimeoutsOnByDefault = false, bool hasQueryStoreHints = false, bool hasServerActionRecompile = false, bool hasQueryStoreSelfKeys = false, bool hasJobHistorySuccessIndex = false, bool hasQueryStoreHashHourly = false, bool hasAgentAlerts = false, bool hasDatabaseProtection = false, bool hasIdentityCapacity = false, bool hasServerAwsRds = false, bool hasServerAwsRdsWebOrExpress = false, bool hasThresholdOverrideTagScope = false, bool hasBlockingBands = false, bool hasRouteSeverities = false, bool hasBlockingSnapshotBands = false, bool hasMuteRecurrence = false, bool hasDailyReportSettings = false, bool hasReportNotice = false, bool hasAlertLogKey = false, bool hasBlockingBarsOnWaitTime = false, bool hasMuteRuleAction = false, bool hasPeopleGrants = false, bool hasActionProposals = false, bool hasComposeFleet = false, bool hasQueryStoreTopDailyWsum = false, bool hasBlockingOpenTranCount = false, bool hasStatementTextOwnEntries = false, bool hasWaitingTasksProgramName = false, bool hasServerConnectDownState = false, bool hasProtectionThresholds = false, bool hasQueryStoreHashIndex = false, bool hasXeSessionDatabases = false, bool hasSelfKeysOldStatements = false, bool hasStatementStatsDatabaseName = false, bool hasMemoryPressureNode = false, bool hasComposeStampLateMarkOffsetZero = false, bool hasSlackBotThreads = false, bool hasSlackCards = false, bool hasChatRequests = false, bool hasWaitStatsCadenceBaseline = false, bool hasSchemaTracking = false, bool hasCollectionLogStatusTimeIndex = false, bool hasOversizedPlanBacklogDroppedIndex = false, bool hasWaitStatsDaily = false, bool hasOversizedPlanBacklogMedianIndexes = false, bool hasWebAccessGroups = false, bool hasAdvancedWebAccess = false, bool hasJobHistoryOldestDaily = false, bool hasOversizedPlanBacklogDropCounts = false, bool hasJobHistoryCategoryHourly = false, bool hasQueryTagSightingsFillfactor = false, bool hasPlanRegressionDailyServerDayIndex = false, bool hasObjectUsage = false, bool hasTempDbLogSpace = false, bool hasDatabaseSizeAutogrowAllFiles = false, bool hasInstanceEventAlertSwitches = false, bool hasColumnStats = false, bool hasWaitStatsHourly = false, bool hasTrigramIndexStoreOptions = false, bool hasPersonalTokens = false, bool hasStoreGrowthAlertSettings = false, bool hasAttentionLegacyCopy = false, bool hasDatabaseProtectionErrorLog = false, bool hasAggregateCompressionOrderHistory = false, bool hasPlanCorrectionServerDbQueryIndex = false, bool hasQueryStoreTextSeen = false, bool hasJobOutcomeDaily = false, bool hasQueryStoreClosedDayRollups = false, bool hasFleetSummaryCoveringIndexes = false, bool hasQueryStoreClutterDaily = false, bool hasQueryStatsCollectionSummary = false, bool hasQueryStatsHostHourly = false, bool hasCollectionLogWatermarkCovering = false, bool hasQueryStoreClutterHourly = false, bool hasQueryStatsCollectionFloor = false, bool hasQueryStoreServerCoveringIndex = false, bool hasQueryStoreCorrectedDailyHashIndex = false, bool hasAttentionCountIndex = false, bool hasAggregateCompressionOrderHistoryIndex = false, bool hasPlanRegressionBlock = false, bool hasQueryStoreTopHourly = false, bool hasObjectReferences = false, bool hasPayloadDimensionSeen = false, bool hasObjectUsageChain = false, bool hasProcedureStatsHourLedger = false, bool hasStoreRelationSizes = false, bool hasJobHistoryFailedIndex = false, bool hasClutterDayBuilt = false, bool hasStatementHistoryWriteCounters = false, bool hasStoreWalFigures = false, bool hasUpgradeRuns = false)
{
/* V71 (the PostgreSQL blocking-edges rung): a table-existence sentinel and now the newest-first arm.
A collector table would ordinarily get no arm at all — see the V63-V69 note below — but the TOP
@@ -1947,6 +1949,13 @@ spurious upgrade banner on a store that is current. */
/* V303 (#9384): the clutter-day stamp, created on every store and never dropped. Relation-existence sentinel, newest-first, and the TOP rung,
so a fully-migrated store maps to EXACTLY StorageVersion.SchemaVersion rather than falling through to 302 and showing a spurious upgrade
banner on a store that is current. */
+ /* V306 (#9432): the upgrade run table, created on every store and never dropped. Relation-existence sentinel, newest-first, and the TOP rung,
+ so a fully-migrated store maps to EXACTLY StorageVersion.SchemaVersion rather than falling through to 305 and showing a spurious upgrade
+ banner on a store that is current. */
+ if (hasUpgradeRuns)
+ {
+ return 306;
+ }
/* V305 (#9419): the WAL columns on collect.store_metrics, never dropped. Column-existence sentinel, newest-first, and the TOP rung, so a
fully-migrated store maps to EXACTLY StorageVersion.SchemaVersion rather than falling through to 304 and showing a spurious upgrade
banner on a store that is current. */
diff --git a/Darling/tools/upgrade-darling.ps1 b/Darling/tools/upgrade-darling.ps1
index f3cc8e1afe..b03398b344 100644
--- a/Darling/tools/upgrade-darling.ps1
+++ b/Darling/tools/upgrade-darling.ps1
@@ -110,6 +110,15 @@ failed, and exits 0 when the upgrade can run and 1 when it cannot. The pre-fligh
install root, restricts it to SYSTEM and Administrators exactly as the real backup folder is, and removes it. Nothing is
stopped, copied or left behind, and the service keeps running. It cannot be combined with -PruneOnly or -ListRollbacks.
+.PARAMETER MarkVerified
+Mark the newest upgrade run as verified, and exit. Run it once your own checks of the new build pass (the Viewer shows every
+server Online, the collectors report OK, the service log shows the store ready). It does no upgrade: nothing is stopped, copied or
+started. Every upgrade run writes upgrade-run.json in the install root (#9432), and the service records that file in the store's
+collect.upgrade_runs table, so the store can say how the upgrade before a service start went. The file has the run's state:
+in_progress while the script runs, then succeeded or failed, then verified after this switch. It holds no password, connection
+string or token. A run that failed, or has not finished, cannot be verified. It cannot be combined with -PruneOnly,
+-ListRollbacks or -Check.
+
.PARAMETER SkipHashCheck
Proceed with a source zip whose SHA256 could not be verified.
@@ -150,7 +159,8 @@ param(
[switch]$SkipHashCheck,
[switch]$SkipStopGuard,
[switch]$AcceptWritableExtraction,
- [switch]$Check
+ [switch]$Check,
+ [switch]$MarkVerified
)
$ErrorActionPreference = 'Stop'
@@ -181,7 +191,9 @@ $script:InstallTreeClearWaitSeconds = 120
$script:InstallTreeClearPollSeconds = 2
$manifestName = 'darling-install-manifest.txt'
-function Fail([string]$message) { Write-Host "ERROR: $message" -ForegroundColor Red; exit 1 }
+# The first message Fail was given is the first error the upgrade run record (#9432) keeps. Fail exits, and the finally at the end of
+# the script writes the record.
+function Fail([string]$message) { if (-not $script:UpgradeRunFirstError) { $script:UpgradeRunFirstError = $message }; Write-Host "ERROR: $message" -ForegroundColor Red; exit 1 }
function Note([string]$message) { Write-Host $message }
# Read-only counterpart to Lock-DarlingInstallTree, for #4043: is $path ALREADY writable by someone outside
@@ -3993,6 +4005,154 @@ function Remove-DarlingStaleFiles([string]$installRoot, $relativePaths, $shipped
}
}
+# ============================ the upgrade run record (#9432) ============================
+#
+# Each upgrade run leaves a small JSON file, upgrade-run.json, in the install root. This script never opens a PostgreSQL
+# connection: it has no driver, and the store can be down in the middle of an upgrade. The service reads the file at its start
+# and on its five-minute store-side pass, and records it in collect.upgrade_runs, one row per run id. The file holds no secret:
+# no connection string, no password, no token.
+#
+# - at the start of a real run (after the -Check exit, before the service is stopped): state in_progress, with the run id,
+# tool version, target build and start time.
+# - at the end: the end time, exit code, the stop check's result, the rollback folder, the first error if it failed, and
+# state succeeded or failed.
+# - -MarkVerified rewrites it to verified once the operator's checks pass. It does no upgrade.
+#
+# Every write goes to a temp file in the same folder and is moved over the old file, so a reader never sees half a file. The
+# service account gets Modify on the file itself (not on the install root), because the service removes the file once the run is
+# verified or failed and the install root gives it only Read and Execute.
+
+# The product version of an exe, or $null when it has none or cannot be read.
+function Get-DarlingBuildVersion([string]$exePath) {
+ try {
+ if (-not (Test-Path -LiteralPath $exePath -PathType Leaf)) { return $null }
+ $version = (Get-Item -LiteralPath $exePath -ErrorAction Stop).VersionInfo.ProductVersion
+ if ([string]::IsNullOrWhiteSpace($version)) { return $null }
+ return $version.Trim()
+ }
+ catch { return $null }
+}
+
+# A new run record: state in_progress, a new run id and the start time. An ordered hashtable, so the file reads the same every time.
+function New-DarlingUpgradeRun([string]$toolVersion, [string]$targetBuild, [datetime]$nowUtc) {
+ return [ordered]@{
+ run_id = [guid]::NewGuid().ToString()
+ state = 'in_progress'
+ tool_version = $toolVersion
+ target_build = $targetBuild
+ started_utc = $nowUtc.ToUniversalTime().ToString('o')
+ ended_utc = $null
+ exit_code = $null
+ stop_check = $null
+ rollback_folder = $null
+ first_error = $null
+ verified_utc = $null
+ }
+}
+
+# The run record at its end, as a copy. A failed run carries its first error, cut at 2000 characters, the most the service reads.
+function Complete-DarlingUpgradeRun($run, [bool]$succeeded, [int]$exitCode, [string]$stopCheck, [string]$rollbackFolder, [string]$firstError, [datetime]$nowUtc) {
+ $done = [ordered]@{}
+ foreach ($key in $run.Keys) { $done[$key] = $run[$key] }
+ $done['state'] = if ($succeeded) { 'succeeded' } else { 'failed' }
+ $done['ended_utc'] = $nowUtc.ToUniversalTime().ToString('o')
+ $done['exit_code'] = $exitCode
+ $done['stop_check'] = if ([string]::IsNullOrWhiteSpace($stopCheck)) { $null } else { $stopCheck }
+ $done['rollback_folder'] = if ([string]::IsNullOrWhiteSpace($rollbackFolder)) { $null } else { $rollbackFolder }
+ if ($succeeded -or [string]::IsNullOrWhiteSpace($firstError)) { $done['first_error'] = $null }
+ else { $done['first_error'] = if ($firstError.Length -gt 2000) { $firstError.Substring(0, 2000) } else { $firstError } }
+ return $done
+}
+
+# Writes the run record: a temp file in the install root, then a move over upgrade-run.json. Returns an object with Ok, Reason
+# (when not Ok) and Warning (the service could not be given Modify on the file, so it may not be able to remove it). It never
+# throws and never leaves the temp file behind: a run record that cannot be written is the caller's warning, not a failed upgrade.
+function Write-DarlingUpgradeRunFile([string]$installRoot, $run, [string]$serviceAccount = '') {
+ $path = Join-Path $installRoot 'upgrade-run.json'
+ $temp = Join-Path $installRoot ('upgrade-run.json.{0}.tmp' -f [guid]::NewGuid().ToString('N'))
+ $warning = ''
+ try {
+ $json = $run | ConvertTo-Json -Depth 3
+ [System.IO.File]::WriteAllText($temp, $json, (New-Object System.Text.UTF8Encoding($false)))
+ # LocalSystem already has full control through the root. Any other account gets Modify on this one file, so the service can
+ # delete it. The grant goes on the temp file because a move keeps a file's own DACL.
+ if (-not [string]::IsNullOrWhiteSpace($serviceAccount) -and $serviceAccount -notmatch '^(NT AUTHORITY\\SYSTEM|LocalSystem)$') {
+ $grantOutput = & icacls.exe $temp /grant:r "${serviceAccount}:(M)" 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ $warning = "the service account '$serviceAccount' could not be given Modify on $path (icacls exit $LASTEXITCODE), so the service may not be able to remove it. It records the file on every pass and keeps one row for the run."
+ }
+ }
+ if (Test-Path -LiteralPath $path -PathType Leaf) { [System.IO.File]::Replace($temp, $path, $null) }
+ else { [System.IO.File]::Move($temp, $path) }
+ return [pscustomobject]@{ Ok = $true; Reason = ''; Warning = $warning }
+ }
+ catch {
+ return [pscustomobject]@{ Ok = $false; Reason = $_.Exception.Message; Warning = $warning }
+ }
+ finally {
+ if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue }
+ }
+}
+
+# The run record on disk, as an ordered hashtable, or $null when there is no file or it is not a run record.
+function Read-DarlingUpgradeRunFile([string]$installRoot) {
+ $path = Join-Path $installRoot 'upgrade-run.json'
+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null }
+ try {
+ $parsed = Get-Content -LiteralPath $path -Raw -ErrorAction Stop | ConvertFrom-Json
+ if ($null -eq $parsed -or -not ($parsed.PSObject.Properties.Name -contains 'run_id')) { return $null }
+ $record = [ordered]@{}
+ foreach ($property in $parsed.PSObject.Properties) { $record[$property.Name] = $property.Value }
+ return $record
+ }
+ catch { return $null }
+}
+
+# -MarkVerified: the newest run's state becomes verified. Does nothing to the install. Returns Ok, a Message for the operator and a
+# Warning. A run that has not finished, or failed, is not verified: the operator's checks mean nothing for an upgrade that did not complete.
+function Set-DarlingUpgradeRunVerified([string]$installRoot, [datetime]$nowUtc, [string]$serviceAccount = '') {
+ $run = Read-DarlingUpgradeRunFile $installRoot
+ if ($null -eq $run) {
+ $missing = "There is no upgrade run to verify: $(Join-Path $installRoot 'upgrade-run.json') is missing or is not an upgrade run record. The service removes it once a run is verified or failed. Nothing was changed."
+ return [pscustomobject]@{ Ok = $false; Message = $missing; Warning = '' }
+ }
+ $state = "$($run['state'])"
+ if ($state -eq 'verified') {
+ return [pscustomobject]@{ Ok = $true; Message = "Upgrade run $($run['run_id']) is already verified. Nothing was changed."; Warning = '' }
+ }
+ if ($state -eq 'in_progress') {
+ return [pscustomobject]@{ Ok = $false; Message = "Upgrade run $($run['run_id']) has not finished, so it cannot be marked verified. Nothing was changed."; Warning = '' }
+ }
+ if ($state -ne 'succeeded') {
+ return [pscustomobject]@{ Ok = $false; Message = "Upgrade run $($run['run_id']) is in state '$state', not succeeded, so it cannot be marked verified. Run the upgrade again. Nothing was changed."; Warning = '' }
+ }
+ $run['state'] = 'verified'
+ $run['verified_utc'] = $nowUtc.ToUniversalTime().ToString('o')
+ $written = Write-DarlingUpgradeRunFile $installRoot $run $serviceAccount
+ if (-not $written.Ok) {
+ return [pscustomobject]@{ Ok = $false; Message = "Upgrade run $($run['run_id']) could not be marked verified: $($written.Reason)"; Warning = $written.Warning }
+ }
+ return [pscustomobject]@{ Ok = $true; Message = "Upgrade run $($run['run_id']) is marked verified. The service records it in the store at its next pass, within about five minutes."; Warning = $written.Warning }
+}
+
+# The end of a run, called from the script's finally: rewrites the record with the result. $succeeded is true only when the script
+# reached the point where the service is Running. Returns the write's result, or $null when no run was started.
+function Close-DarlingUpgradeRun([string]$installRoot, $run, [bool]$succeeded, [string]$stopCheck, [string]$rollbackFolder, [string]$firstError, [string]$serviceAccount = '') {
+ if ($null -eq $run) { return $null }
+ $exitCode = if ($succeeded) { 0 } else { 1 }
+ $done = Complete-DarlingUpgradeRun $run $succeeded $exitCode $stopCheck $rollbackFolder $firstError ([datetime]::UtcNow)
+ return Write-DarlingUpgradeRunFile $installRoot $done $serviceAccount
+}
+
+# The account the service logs on as, spelled the way icacls takes it (LocalSystem is NT AUTHORITY\SYSTEM, a leading .\ is this computer),
+# or $null when it cannot be read.
+function Get-DarlingUpgradeRunServiceAccount([string]$name) {
+ $account = Get-DarlingServiceLogonName $name
+ if ($account -eq 'LocalSystem') { return 'NT AUTHORITY\SYSTEM' }
+ if ($account) { return ($account -replace '^\.\\', "$env:COMPUTERNAME\") }
+ return $null
+}
+
# ============================ preamble ============================
$powerShellText = "PowerShell $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition) edition)"
@@ -4002,6 +4162,9 @@ if ($Check) {
Fail "-Check changes nothing, so it cannot be combined with -PruneOnly or -ListRollbacks. Nothing was stopped, copied or pruned."
}
}
+if ($MarkVerified -and ($Check -or $PruneOnly -or $ListRollbacks)) {
+ Fail "-MarkVerified only marks the newest upgrade run verified, so it cannot be combined with -Check, -PruneOnly or -ListRollbacks. Nothing was changed."
+}
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Fail "Run this from an ELEVATED PowerShell. Stopping the service, writing to the install directory, and starting it again all need it."
@@ -4058,6 +4221,17 @@ if (-not (Test-Path -LiteralPath (Join-Path $InstallRoot $serviceExeName))) {
Note "Install directory: $InstallRoot"
+# ============================ -MarkVerified (#9432) ============================
+#
+# The operator's checks passed: the newest upgrade run becomes verified. No upgrade, no stop, no copy.
+if ($MarkVerified) {
+ $verified = Set-DarlingUpgradeRunVerified $InstallRoot ([datetime]::UtcNow) (Get-DarlingUpgradeRunServiceAccount $serviceName)
+ if ($verified.Warning) { Warn $verified.Warning }
+ if (-not $verified.Ok) { Fail $verified.Message }
+ Good $verified.Message
+ exit 0
+}
+
# ============================ -ListRollbacks / -PruneOnly ============================
#
# Both run against a LIVE service on purpose. Neither touches a binary, and the backups are inert copies
@@ -4508,6 +4682,24 @@ if ($Check) {
exit 0
}
+# ============================ the upgrade run record (#9432) ============================
+#
+# A real run starts here: the service is still up and nothing has changed. The record says in_progress until the end of the script.
+# A record that cannot be written is a warning, not a refusal: it is bookkeeping for the store and the upgrade does not depend on it.
+$script:UpgradeRunAccount = Get-DarlingUpgradeRunServiceAccount $serviceName
+$upgradeToolVersion = Get-DarlingBuildVersion (Join-Path $PSScriptRoot $serviceExeName)
+if (-not $upgradeToolVersion) { $upgradeToolVersion = 'unknown' }
+$upgradeTargetBuild = if ($sourceIsZip) { [IO.Path]::GetFileName($Source) } else { Get-DarlingBuildVersion (Join-Path $Source $serviceExeName) }
+if (-not $upgradeTargetBuild) { $upgradeTargetBuild = 'unknown' }
+$script:UpgradeRun = New-DarlingUpgradeRun $upgradeToolVersion $upgradeTargetBuild ([datetime]::UtcNow)
+$script:UpgradeRunSucceeded = $false
+$script:UpgradeStopCheck = $null
+$script:UpgradeRollbackFolder = $null
+$upgradeRunWrite = Write-DarlingUpgradeRunFile $InstallRoot $script:UpgradeRun $script:UpgradeRunAccount
+if ($upgradeRunWrite.Ok) { Note "Upgrade run $($script:UpgradeRun['run_id']) started (in_progress), recorded in $(Join-Path $InstallRoot 'upgrade-run.json')." }
+else { Warn "The upgrade run record could not be written ($($upgradeRunWrite.Reason)). The upgrade goes on, and the store will not show this run." }
+if ($upgradeRunWrite.Warning) { Warn $upgradeRunWrite.Warning }
+
# ============================ stop, back up, prune, copy, start ============================
#
# From here on a failure leaves the service DOWN. Every step below is idempotent and the failure messages
@@ -4562,8 +4754,11 @@ $stillHolding = Get-DarlingProcessesUnderPath $InstallRoot
# Made a list before it is counted: Windows PowerShell 5.1 gives a lone record no Count, and nothing
# compared with zero would pass the check below with one process still holding the tree.
$stillHolding = @($stillHolding)
+# #9432: the stop check's result, for the upgrade run record.
+$script:UpgradeStopCheck = if ($SkipStopGuard) { 'skipped (-SkipStopGuard)' } else { 'clear' }
if ($stillHolding.Count -gt 0 -and -not $SkipStopGuard) {
$names = @($stillHolding | ForEach-Object { "$($_.ProcessName) (pid $($_.Id))" })
+ $script:UpgradeStopCheck = 'blocked: ' + ($names -join ', ')
Note "The service is stopped, but processes are STILL running out of the install tree:"
foreach ($name in $names) { Note " $name" }
Fail "Nothing has been copied, so the install is intact - but the service is now STOPPED. Either close these and re-run (safe, and it will reuse the backup it is about to take), or abandon the upgrade with: Start-Service '$serviceName'. Do NOT kill anything under $InstallRoot\pg-runtime - that is the bundled PostgreSQL and killing it takes the store down; give a postmaster that outlived the stop a few seconds and re-run."
@@ -4617,6 +4812,7 @@ $nowUtc = [datetime]::UtcNow
$backupDecision = Get-DarlingRollbackBackupDecision $backups $BackupWindowMinutes $nowUtc $manifestPath
if ($backupDecision -eq 'reuse') {
+ $script:UpgradeRollbackFolder = $backups[0].FullName
Note ("Reusing the rollback backup {0}, taken {1:N0} minute(s) ago - this looks like a re-run of an interrupted upgrade (no upgrade has finished since it was taken), and a second backup now would copy a half-upgraded tree over the good one." -f $backups[0].Name, ($nowUtc - $backups[0].LastWriteTimeUtc).TotalMinutes)
}
else {
@@ -4627,6 +4823,7 @@ else {
Note "Backing up the install root's files to $backupPath ..."
try {
New-Item -ItemType Directory -Path $backupPath -Force | Out-Null
+ $script:UpgradeRollbackFolder = $backupPath
# The folder is restricted to SYSTEM and Administrators BEFORE anything is copied into it (#5700), so every copy is born
# with only that DACL instead of the install root's inherited one, and no file in it is ever readable by another account.
# A folder that could not be restricted is never copied into: the upgrade stops here, with nothing copied or overwritten.
@@ -4782,6 +4979,13 @@ if (-not $sourceIsZip) {
Good "New build in place."
+# #9432: the build that is now installed is the true target. A folder source can also carry an upgrade-run.json of its own that the
+# copy just laid over this run's file, so the record is written again here.
+$installedBuild = Get-DarlingBuildVersion (Join-Path $InstallRoot $serviceExeName)
+if ($installedBuild) { $script:UpgradeRun['target_build'] = $installedBuild }
+$upgradeRunWrite = Write-DarlingUpgradeRunFile $InstallRoot $script:UpgradeRun $script:UpgradeRunAccount
+if (-not $upgradeRunWrite.Ok) { Warn "The upgrade run record could not be rewritten after the copy ($($upgradeRunWrite.Reason))." }
+
if ($configHashBefore) {
$configHashAfter = if (Test-Path -LiteralPath $configPath) { (Get-FileHash -LiteralPath $configPath -Algorithm SHA256).Hash } else { $null }
if ($configHashAfter -ne $configHashBefore) {
@@ -4969,6 +5173,7 @@ try { (Get-Service -Name $serviceName).WaitForStatus('Running', [TimeSpan]::From
catch { Fail "'$serviceName' did not reach Running within two minutes. The new build IS in place - read %ProgramData%\PerformanceMonitorDarling\logs before rolling back." }
Good "Service is Running."
+$script:UpgradeRunSucceeded = $true
Note ""
Note "The install is NOT verified yet. 'Running' means the process started, not that it collects."
Note "About 10-15 minutes after the start, check these:"
@@ -4976,9 +5181,18 @@ Note " 1. Open the Viewer. Every monitored server shows Online, and the status
Note " 2. On each server card, Collectors shows OK and 'Failing: 0'. The status bar shows 'Collectors: N OK'. The web page has a Collection Health tab for each server."
Note " 3. The service log (%ProgramData%\PerformanceMonitorDarling\logs) has a line 'Postgres store ready (schema v, ...)' from this start. N is the store version this build expects. If the line is missing, the store did not finish its update: read the log lines near the start."
Note " If you connect to the store, you can also run SELECT MAX(version) FROM darling_schema_version. It returns the same N."
+Note " 4. When the checks pass, run this script again with -MarkVerified. That marks this run verified in the store. It does no upgrade."
}
finally {
+ # #9432: the end of the run record. Runs on success, on Fail (which exits) and on an unhandled error. The first error is the first
+ # message Fail was given, or, for an error nothing caught, the last error PowerShell recorded.
+ if ($script:UpgradeRun) {
+ $upgradeFirstError = $script:UpgradeRunFirstError
+ if (-not $script:UpgradeRunSucceeded -and -not $upgradeFirstError -and $Error.Count -gt 0) { $upgradeFirstError = "$($Error[0].Exception.Message)" }
+ $upgradeRunEnd = Close-DarlingUpgradeRun $InstallRoot $script:UpgradeRun $script:UpgradeRunSucceeded $script:UpgradeStopCheck $script:UpgradeRollbackFolder $upgradeFirstError $script:UpgradeRunAccount
+ if ($upgradeRunEnd -and -not $upgradeRunEnd.Ok) { Warn "The upgrade run record could not be finished ($($upgradeRunEnd.Reason))." }
+ }
# H1's staging copy (#4043 round-1 review): best-effort, and expected to be a no-op on the folder
# -Source path, where $zipStagingFolder is never set. Administrators owns it and holds full control (see
# Protect-DarlingStagingFolder), and this script is already running elevated, so nothing here needs the
diff --git a/docs/darling/store-tables.csv b/docs/darling/store-tables.csv
index 69293cc08f..aba5691f99 100644
--- a/docs/darling/store-tables.csv
+++ b/docs/darling/store-tables.csv
@@ -220,6 +220,7 @@ store_statement_history,internal,no,store own statement history
system_health_events,collected,yes,
tempdb_stats,collected,yes,
trace_flags,collected,yes,
+upgrade_runs,internal,no,upgrade run record
v_blocked_process_reports,derived,derived,read view over blocked_process_reports
v_collection_log,derived,derived,read view over collection_log
v_cpu_scheduler_stats,derived,derived,read view over cpu_scheduler_stats
From edcdd648a9a1d97ded170382d8b5d2531763ecdd Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 04:28:12 -0500
Subject: [PATCH 02/14] Add the missing using for the upgrade run state check
(#9432)
---
Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
index d2e5c432a8..5cada87aa9 100644
--- a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
+++ b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
@@ -10,6 +10,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
From e707b8096169e8688513fa236a3887f3c593ad46 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 04:42:25 -0500
Subject: [PATCH 03/14] Replace the upgrade run file with a null backup name
that PowerShell passes through (#9432)
---
Darling/tools/upgrade-darling.ps1 | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Darling/tools/upgrade-darling.ps1 b/Darling/tools/upgrade-darling.ps1
index b03398b344..0d69401184 100644
--- a/Darling/tools/upgrade-darling.ps1
+++ b/Darling/tools/upgrade-darling.ps1
@@ -4082,7 +4082,7 @@ function Write-DarlingUpgradeRunFile([string]$installRoot, $run, [string]$servic
$warning = "the service account '$serviceAccount' could not be given Modify on $path (icacls exit $LASTEXITCODE), so the service may not be able to remove it. It records the file on every pass and keeps one row for the run."
}
}
- if (Test-Path -LiteralPath $path -PathType Leaf) { [System.IO.File]::Replace($temp, $path, $null) }
+ if (Test-Path -LiteralPath $path -PathType Leaf) { [System.IO.File]::Replace($temp, $path, [NullString]::Value) }
else { [System.IO.File]::Move($temp, $path) }
return [pscustomobject]@{ Ok = $true; Reason = ''; Warning = $warning }
}
From 0e88ee36ecf7f6cf5cf5161a24edb0168b649796 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 04:53:31 -0500
Subject: [PATCH 04/14] wip diag
---
Darling/Darling.Tests/UpgradeRunPickupTests.cs | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
index 99fb6b66f0..9cf9f0bda2 100644
--- a/Darling/Darling.Tests/UpgradeRunPickupTests.cs
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -95,6 +95,8 @@ public async Task ThreePickups_InProgressSucceededVerified_GiveOneRowWithEachSta
Assert.Equal(UpgradeRunPickupOutcome.NoFile, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(15), ct)).Outcome);
bodySucceeded = true;
}
+ catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + "
+"); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
@@ -133,6 +135,8 @@ public async Task ARunWrittenWhileTheStoreWasDown_IsRecordedAtTheNextPickup_AndA
Assert.False(File.Exists(file));
bodySucceeded = true;
}
+ catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + "
+"); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
@@ -176,6 +180,8 @@ public async Task AMalformedFile_WarnsOncePerContent_AndStaysInPlace_AndAnOldInP
Assert.Equal((1L, "in_progress"), await RowAsync(connection, oldId));
bodySucceeded = true;
}
+ catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + "
+"); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
From ba9643842f837a99d6c6477f8f50e3fbcf07ebec Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 04:55:43 -0500
Subject: [PATCH 05/14] wip diag
---
Darling/Darling.Tests/UpgradeRunPickupTests.cs | 9 +++------
1 file changed, 3 insertions(+), 6 deletions(-)
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
index 9cf9f0bda2..da4b12533f 100644
--- a/Darling/Darling.Tests/UpgradeRunPickupTests.cs
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -95,8 +95,7 @@ public async Task ThreePickups_InProgressSucceededVerified_GiveOneRowWithEachSta
Assert.Equal(UpgradeRunPickupOutcome.NoFile, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(15), ct)).Outcome);
bodySucceeded = true;
}
- catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + "
-"); throw; }
+ catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + Environment.NewLine); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
@@ -135,8 +134,7 @@ public async Task ARunWrittenWhileTheStoreWasDown_IsRecordedAtTheNextPickup_AndA
Assert.False(File.Exists(file));
bodySucceeded = true;
}
- catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + "
-"); throw; }
+ catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + Environment.NewLine); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
@@ -180,8 +178,7 @@ public async Task AMalformedFile_WarnsOncePerContent_AndStaysInPlace_AndAnOldInP
Assert.Equal((1L, "in_progress"), await RowAsync(connection, oldId));
bodySucceeded = true;
}
- catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + "
-"); throw; }
+ catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + Environment.NewLine); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
From 17e3637ab5687f897d410ca2a6ba11a3fb927b52 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 04:59:03 -0500
Subject: [PATCH 06/14] wip diag2
---
Darling/Darling.Tests/UpgradeRunPickupTests.cs | 3 +++
1 file changed, 3 insertions(+)
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
index da4b12533f..7356ee6265 100644
--- a/Darling/Darling.Tests/UpgradeRunPickupTests.cs
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -24,6 +24,9 @@ namespace Darling.Tests;
/* #1776 own-store: each test mints its own scratch store database through ScratchPostgres. */
public sealed class UpgradeRunPickupTests
{
+ static UpgradeRunPickupTests() { AppDomain.CurrentDomain.FirstChanceException += (_, e) => { try { File.AppendAllText("C:/runner/logs/p9432-fc.txt", e.Exception.GetType().Name + ": " + e.Exception.Message.Replace("
", " ").Replace("
+", " ") + Environment.NewLine); } catch (IOException) { } }; }
+
private static string? BaseConnectionString => Environment.GetEnvironmentVariable("DARLING_TEST_PG");
private const string SkipReason = "Set DARLING_TEST_PG to a Postgres connection string to run the live #9432 tests (each mints its own scratch database).";
From b5e50eb6558f6978c95694aee1da2b8018efbf31 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 05:00:44 -0500
Subject: [PATCH 07/14] wip diag3
---
Darling/Darling.Tests/UpgradeRunPickupTests.cs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
index 7356ee6265..ea0469db29 100644
--- a/Darling/Darling.Tests/UpgradeRunPickupTests.cs
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -24,8 +24,7 @@ namespace Darling.Tests;
/* #1776 own-store: each test mints its own scratch store database through ScratchPostgres. */
public sealed class UpgradeRunPickupTests
{
- static UpgradeRunPickupTests() { AppDomain.CurrentDomain.FirstChanceException += (_, e) => { try { File.AppendAllText("C:/runner/logs/p9432-fc.txt", e.Exception.GetType().Name + ": " + e.Exception.Message.Replace("
", " ").Replace("
-", " ") + Environment.NewLine); } catch (IOException) { } }; }
+ static UpgradeRunPickupTests() { AppDomain.CurrentDomain.FirstChanceException += (_, e) => { try { File.AppendAllText("C:/runner/logs/p9432-fc.txt", e.Exception.GetType().Name + ": " + e.Exception.Message.Replace(Environment.NewLine, " ") + Environment.NewLine); } catch (IOException) { } }; }
private static string? BaseConnectionString => Environment.GetEnvironmentVariable("DARLING_TEST_PG");
From 122eab6eee2dae28ec91db3e19492f309d36dc72 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 05:03:07 -0500
Subject: [PATCH 08/14] Remove the diagnostic lines from the upgrade run pickup
tests (#9432)
---
Darling/Darling.Tests/UpgradeRunPickupTests.cs | 5 -----
1 file changed, 5 deletions(-)
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
index ea0469db29..99fb6b66f0 100644
--- a/Darling/Darling.Tests/UpgradeRunPickupTests.cs
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -24,8 +24,6 @@ namespace Darling.Tests;
/* #1776 own-store: each test mints its own scratch store database through ScratchPostgres. */
public sealed class UpgradeRunPickupTests
{
- static UpgradeRunPickupTests() { AppDomain.CurrentDomain.FirstChanceException += (_, e) => { try { File.AppendAllText("C:/runner/logs/p9432-fc.txt", e.Exception.GetType().Name + ": " + e.Exception.Message.Replace(Environment.NewLine, " ") + Environment.NewLine); } catch (IOException) { } }; }
-
private static string? BaseConnectionString => Environment.GetEnvironmentVariable("DARLING_TEST_PG");
private const string SkipReason = "Set DARLING_TEST_PG to a Postgres connection string to run the live #9432 tests (each mints its own scratch database).";
@@ -97,7 +95,6 @@ public async Task ThreePickups_InProgressSucceededVerified_GiveOneRowWithEachSta
Assert.Equal(UpgradeRunPickupOutcome.NoFile, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(15), ct)).Outcome);
bodySucceeded = true;
}
- catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + Environment.NewLine); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
@@ -136,7 +133,6 @@ public async Task ARunWrittenWhileTheStoreWasDown_IsRecordedAtTheNextPickup_AndA
Assert.False(File.Exists(file));
bodySucceeded = true;
}
- catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + Environment.NewLine); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
@@ -180,7 +176,6 @@ public async Task AMalformedFile_WarnsOncePerContent_AndStaysInPlace_AndAnOldInP
Assert.Equal((1L, "in_progress"), await RowAsync(connection, oldId));
bodySucceeded = true;
}
- catch (Exception ex) { File.AppendAllText("C:/runner/logs/p9432-err.txt", ex.ToString() + Environment.NewLine); throw; }
finally
{
try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
From 4bd04e54f728c56f41e8fbcd3ec3a8ff9756ed7e Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 05:09:33 -0500
Subject: [PATCH 09/14] Bind the upgrade run pickup's own timestamps without a
UTC Kind so the store accepts them (#9432)
---
Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
index 5cada87aa9..e3ab0207f5 100644
--- a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
+++ b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
@@ -316,6 +316,9 @@ public static bool TryParse(string text, out UpgradeRunFile? run, out string pro
private static async Task RecordAsync(NpgsqlConnection connection, UpgradeRunFile run, DateTime nowUtc, CancellationToken cancellationToken)
{
+ /* The columns are timestamp without time zone, and Npgsql refuses a Kind=Utc value for one. The file's times are already Unspecified,
+ so the caller's UtcNow gets the same Kind here. Without this the first pickup throws and the file never reaches the store (#9432). */
+ var now = DateTime.SpecifyKind(nowUtc, DateTimeKind.Unspecified);
await using (var upsert = new NpgsqlCommand(UpgradeRuns.UpsertSql, connection) { CommandTimeout = 30 })
{
upsert.Parameters.Add(new NpgsqlParameter { Value = run.RunId, NpgsqlDbType = NpgsqlDbType.Uuid });
@@ -329,12 +332,12 @@ private static async Task RecordAsync(NpgsqlConnection connection, UpgradeRunFil
upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.RollbackFolder ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.FirstError ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.VerifiedUtc ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Timestamp });
- upsert.Parameters.Add(new NpgsqlParameter { Value = nowUtc, NpgsqlDbType = NpgsqlDbType.Timestamp });
+ upsert.Parameters.Add(new NpgsqlParameter { Value = now, NpgsqlDbType = NpgsqlDbType.Timestamp });
await upsert.ExecuteNonQueryAsync(cancellationToken);
}
await using var retention = new NpgsqlCommand(UpgradeRuns.RetentionDeleteSql, connection) { CommandTimeout = 30 };
- retention.Parameters.Add(new NpgsqlParameter { Value = nowUtc.AddDays(-UpgradeRuns.RetentionDays), NpgsqlDbType = NpgsqlDbType.Timestamp });
+ retention.Parameters.Add(new NpgsqlParameter { Value = now.AddDays(-UpgradeRuns.RetentionDays), NpgsqlDbType = NpgsqlDbType.Timestamp });
await retention.ExecuteNonQueryAsync(cancellationToken);
}
From b682ffa425b5818298f7c45ed7374c9ebdf51613 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 09:37:52 -0500
Subject: [PATCH 10/14] Fix the V311 probe line's closing quote after the stack
merge (#9432)
---
Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs b/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs
index 6e44d7d7bd..82b855c0f3 100644
--- a/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs
+++ b/Darling/PerformanceMonitor.Darling.Viewer/ViewerDataService.cs
@@ -1673,7 +1673,7 @@ the answer does not depend on the connecting role's privileges. */
/* V310 (#9452) adds the partial index of the oversized-plan backlog's pending rows, never dropped. Found by catalog, as the V309 line above is. */
to_regclass('collect.idx_oversized_plan_backlog_pending') IS NOT NULL,
/* V311 (#9438) adds what each migration rung changed, one plain table on every store and never dropped. Found by catalog, as the V310 line above is. */
- to_regclass('collect.service_start_rung_objects') IS NOT NULL",
+ to_regclass('collect.service_start_rung_objects') IS NOT NULL,
/* V312 (#9432) adds the upgrade run table, a plain table on every store and never dropped. Found by catalog, as the V311 line above is. */
to_regclass('collect.upgrade_runs') IS NOT NULL";
From e2773b7cd3368f5eadb6caf4af9dc9ad30a2b719 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 11:34:08 -0500
Subject: [PATCH 11/14] Keep upgrade-run.json on the service-written list and
never step a run row back (#9432)
---
.../DarlingUpgradeRunRecordTests.cs | 77 ++++++++++++++++++-
.../Darling.Tests/UpgradeRunPickupTests.cs | 52 +++++++++++++
.../UpgradeRuns.cs | 28 ++++---
Darling/tools/install-darling.ps1 | 7 +-
Darling/tools/upgrade-darling.ps1 | 13 +++-
5 files changed, 159 insertions(+), 18 deletions(-)
diff --git a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
index 70df549300..1ad5b8de40 100644
--- a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
+++ b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
@@ -54,14 +54,14 @@ private static string? PwshPath
}
/// Runs the extracted functions plus under PowerShell and returns what the body wrote to the output.
- private static string Run(string folder, string body)
+ private static string Run(string folder, string body, params string[] extraFunctions)
{
var pwsh = PwshPath;
Assert.SkipUnless(pwsh is not null, "neither Windows PowerShell 5.1 nor pwsh is installed on this machine.");
var script = ReadRepoFile(Path.Combine("Darling", "tools", "upgrade-darling.ps1"));
var text = new StringBuilder();
text.AppendLine("$ErrorActionPreference = 'Stop'");
- foreach (var name in FunctionNames) { text.AppendLine(Extract(script, name)); }
+ foreach (var name in FunctionNames.Concat(extraFunctions)) { text.AppendLine(Extract(script, name)); }
text.AppendLine("$root = '" + folder.Replace("'", "''") + "'");
text.AppendLine(body);
var driver = Path.Combine(folder, "driver.ps1");
@@ -224,4 +224,77 @@ public void AWriteThatFails_LeavesNoTempFile_AndTheOldFileUntouched()
}
finally { Cleanup(folder); }
}
+
+ private static readonly string[] ServiceWrittenListFunctions =
+ {
+ "Get-DarlingServiceWrittenNames", "Test-DarlingServiceWrittenFileName", "Test-PathIsAtOrUnder", "Get-DarlingFileNameCount",
+ "Initialize-DarlingNativeOwner", "Test-DarlingServiceWrittenPath", "Get-DarlingServiceWrittenRootFiles", "Get-DarlingCanonicalPath",
+ "Get-DarlingSegmentsBelowRoot",
+ };
+
+ ///
+ /// The review of #9493: the service account (NT SERVICE
+ame, never LocalSystem) holds an explicit Modify grant on upgrade-run.json,
+ /// and the pre-lock walk of a re-run named it as a stranger's write grant, so a run that failed before the lock blocked the documented
+ /// re-run. A real SID that is not this account (Network Service) stands for the service: granting on a file this account owns needs no
+ /// admin. The control run, with no service SID passed, shows the walk does see the grant.
+ ///
+ [Fact]
+ public void TheServicesGrantOnTheRunFile_IsNotAStrangersGrant_ToThePreLockWalk()
+ {
+ Assert.SkipUnless(OperatingSystem.IsWindows(), "the grant is an NTFS ACL.");
+ var folder = NewFolder();
+ try
+ {
+ var body = "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); $w = Write-DarlingUpgradeRunFile $root $run '*S-1-5-20'; 'warning=[' + $w.Warning + ']'; "
+ + "$wk = [System.Security.Principal.WellKnownSidType]; $service = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-20'); "
+ + "$trusted = @([System.Security.Principal.WindowsIdentity]::GetCurrent().User, (New-Object System.Security.Principal.SecurityIdentifier($wk::LocalSystemSid, $null)), (New-Object System.Security.Principal.SecurityIdentifier($wk::BuiltinAdministratorsSid, $null))); "
+ + "$rule = @((Get-Acl -LiteralPath (Join-Path $root 'upgrade-run.json')).GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) | Where-Object { $_.IdentityReference -eq $service }); 'granted=' + ($rule.Count -gt 0); "
+ + "$control = @(Get-UntrustedWriteGrantees $root $trusted -Recurse | Where-Object { $_ -like '*upgrade-run.json*' }); 'control=' + $control.Count; "
+ + "$walk = @(Get-UntrustedWriteGrantees $root $trusted -Recurse -ServiceSids @($service) | Where-Object { $_ -like '*upgrade-run.json*' }); 'walk=' + $walk.Count; "
+ + "'trustedPath=' + (Test-DarlingServiceWrittenPath $root (Join-Path $root 'upgrade-run.json') @() (Get-Item -LiteralPath (Join-Path $root 'upgrade-run.json')))";
+ var output = Run(folder, body, ServiceWrittenListFunctions.Append("Get-UntrustedWriteGrantees").ToArray());
+ Assert.Contains("granted=True", output, StringComparison.Ordinal);
+ Assert.Contains("control=1", output, StringComparison.Ordinal);
+ Assert.Contains("walk=0", output, StringComparison.Ordinal);
+ Assert.Contains("trustedPath=True", output, StringComparison.Ordinal);
+ }
+ finally { Cleanup(folder); }
+ }
+
+ ///
+ /// The review of #9493: the install-tree lock kept resetting the run file's explicit grant, and File.Replace keeps the DACL of the file it
+ /// replaces, so after the lock the service could never delete the file. With the file on the service-written list the lock keeps the
+ /// grant, and a rewrite after the lock (the run's end, or -MarkVerified) keeps it too. The lock needs an elevated token for its owner step:
+ /// without one it reports the file as not owned by the service, which this test ignores, and still sets the permissions it asserts on.
+ ///
+ [Fact]
+ public void AfterTheInstallTreeLock_AndARewrite_TheServiceStillHoldsModifyOnTheRunFile()
+ {
+ Assert.SkipUnless(OperatingSystem.IsWindows(), "the grant is an NTFS ACL.");
+ var folder = NewFolder();
+ try
+ {
+ var body = "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run 'NT AUTHORITY\NETWORK SERVICE' | Out-Null; "
+ + "$service = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-20'); $file = Join-Path $root 'upgrade-run.json'; "
+ + "function Get-ServiceModify { @((Get-Acl -LiteralPath $file).GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) | Where-Object { $_.IdentityReference -eq $service -and ([int]$_.FileSystemRights -band 0x10000) -ne 0 }).Count -gt 0 }; "
+ + "'before=' + (Get-ServiceModify); "
+ + "$open = @(Lock-DarlingInstallTree $root 'NT AUTHORITY\NETWORK SERVICE'); 'lockRan=' + ($open.Count -ge 0); "
+ + "'afterLock=' + (Get-ServiceModify); "
+ + "Close-DarlingUpgradeRun $root $run $true 'clear' '' '' 'NT AUTHORITY\NETWORK SERVICE' | Out-Null; "
+ + "'afterRewrite=' + (Get-ServiceModify); "
+ + "'state=' + (Read-DarlingUpgradeRunFile $root)['state']";
+ var output = Run(folder, body, ServiceWrittenListFunctions.Append("Lock-DarlingInstallTree").ToArray());
+ Assert.Contains("before=True", output, StringComparison.Ordinal);
+ Assert.Contains("afterLock=True", output, StringComparison.Ordinal);
+ Assert.Contains("afterRewrite=True", output, StringComparison.Ordinal);
+ Assert.Contains("state=succeeded", output, StringComparison.Ordinal);
+ }
+ finally
+ {
+ try { _ = System.Diagnostics.Process.Start(new ProcessStartInfo("icacls.exe", $"\"{folder}\" /reset /T /C /Q") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true })?.WaitForExit(30_000); }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) { }
+ Cleanup(folder);
+ }
+ }
}
diff --git a/Darling/Darling.Tests/UpgradeRunPickupTests.cs b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
index 99fb6b66f0..5252fd1d4b 100644
--- a/Darling/Darling.Tests/UpgradeRunPickupTests.cs
+++ b/Darling/Darling.Tests/UpgradeRunPickupTests.cs
@@ -182,4 +182,56 @@ public async Task AMalformedFile_WarnsOncePerContent_AndStaysInPlace_AndAnOldInP
await LiveStoreCleanup.RunAsync(scratch.ConnectionString, bodySucceeded, (_, _) => Task.CompletedTask);
}
}
+
+ ///
+ /// The review of #9493: an older copy of a run's file (the rollback backup copies the in_progress file, and a manual restore puts it back)
+ /// must not move a finished row back to in_progress. The row keeps its state, and the stale file is removed.
+ ///
+ [Fact]
+ public async Task AnOlderCopyOfTheRunFile_NeverMovesAFinishedRowBack_AndIsRemoved()
+ {
+ Assert.SkipWhen(string.IsNullOrEmpty(BaseConnectionString), SkipReason);
+ var ct = TestContext.Current.CancellationToken;
+ await using var scratch = await ScratchPostgres.CreateAsync(BaseConnectionString!, ct);
+ var folder = Directory.CreateTempSubdirectory("darling-9432-").FullName;
+ var bodySucceeded = false;
+ try
+ {
+ await using var connection = new NpgsqlConnection(scratch.ConnectionString);
+ await connection.OpenAsync(ct);
+ await PgMigrations.MigrateAsync(connection, ct);
+ var pickup = new UpgradeRunPickup(new CountingLogger());
+ var file = Path.Combine(folder, UpgradeRunPickup.FileName);
+ var now = DateTime.UtcNow;
+
+ var verified = Guid.NewGuid();
+ File.WriteAllText(file, RunJson(verified, "verified"));
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, (await pickup.PickUpAsync(connection, folder, now, ct)).Outcome);
+ File.WriteAllText(file, RunJson(verified, "in_progress"));
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(1), ct)).Outcome);
+ Assert.Equal((1L, "verified"), await RowAsync(connection, verified));
+ Assert.False(File.Exists(file), "a file behind the stored row is stale and goes");
+
+ var failed = Guid.NewGuid();
+ File.WriteAllText(file, RunJson(failed, "failed", "the copy failed twice"));
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(2), ct)).Outcome);
+ File.WriteAllText(file, RunJson(failed, "in_progress"));
+ Assert.Equal(UpgradeRunPickupOutcome.RecordedAndRemoved, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(3), ct)).Outcome);
+ Assert.Equal((2L, "failed"), await RowAsync(connection, failed));
+
+ /* A run that moves forward is still recorded: succeeded after in_progress, with the file kept until it is verified. */
+ var forward = Guid.NewGuid();
+ File.WriteAllText(file, RunJson(forward, "in_progress"));
+ Assert.Equal(UpgradeRunPickupOutcome.Recorded, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(4), ct)).Outcome);
+ File.WriteAllText(file, RunJson(forward, "succeeded"));
+ Assert.Equal(UpgradeRunPickupOutcome.Recorded, (await pickup.PickUpAsync(connection, folder, now.AddMinutes(5), ct)).Outcome);
+ Assert.Equal((3L, "succeeded"), await RowAsync(connection, forward));
+ bodySucceeded = true;
+ }
+ finally
+ {
+ try { Directory.Delete(folder, recursive: true); } catch (IOException) { }
+ await LiveStoreCleanup.RunAsync(scratch.ConnectionString, bodySucceeded, (_, _) => Task.CompletedTask);
+ }
+ }
}
diff --git a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
index e167732800..5276159aa2 100644
--- a/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
+++ b/Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs
@@ -83,9 +83,12 @@ CREATE INDEX IF NOT EXISTS idx_upgrade_runs_started
ON collect.upgrade_runs(started_at);";
/// One row per run id: a second pickup of the same run updates the row, it never adds one. recorded_at keeps the
- /// first time the service saw the run.
+ /// first time the service saw the run. A row never steps back: the update runs only when the file's state is at least as far along
+ /// as the stored one (in_progress, then succeeded or failed, then verified), so an older copy of the run's file, put back from a
+ /// rollback backup, cannot move a failed or verified row to in_progress. When the update is skipped the statement returns no row,
+ /// and the pickup treats the file as stale.
public const string UpsertSql = @"
-INSERT INTO collect.upgrade_runs
+INSERT INTO collect.upgrade_runs AS r
(run_id, state, tool_version, target_build, started_at, ended_at, exit_code, stop_check, rollback_folder, first_error, verified_at, recorded_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $12)
ON CONFLICT (run_id) DO UPDATE SET
@@ -99,7 +102,10 @@ ON CONFLICT (run_id) DO UPDATE SET
rollback_folder = EXCLUDED.rollback_folder,
first_error = EXCLUDED.first_error,
verified_at = EXCLUDED.verified_at,
- updated_at = EXCLUDED.updated_at";
+ updated_at = EXCLUDED.updated_at
+WHERE (CASE EXCLUDED.state WHEN 'verified' THEN 2 WHEN 'in_progress' THEN 0 ELSE 1 END)
+ >= (CASE r.state WHEN 'verified' THEN 2 WHEN 'in_progress' THEN 0 ELSE 1 END)
+RETURNING r.state";
/// The bounded retention delete, run after each record.
public const string RetentionDeleteSql = @"
@@ -129,7 +135,7 @@ public enum UpgradeRunPickupOutcome
/// The file was recorded and left in place: the run is not finished or not yet verified.
Recorded,
- /// The file was recorded and then removed: the run is verified, failed or older than a week.
+ /// The file was recorded and then removed: the run is verified, failed or older than a week, or the stored row is already further along than the file.
RecordedAndRemoved,
/// The file was recorded but could not be removed. The next pass records it again and the row stays one row.
@@ -212,10 +218,11 @@ public async Task PickUpAsync(
return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.Malformed, null, null);
}
- await RecordAsync(connection, run!, nowUtc, cancellationToken);
+ var recorded = await RecordAsync(connection, run!, nowUtc, cancellationToken);
- var finished = run!.State is UpgradeRuns.Verified or UpgradeRuns.Failed;
- var stale = nowUtc - run.StartedUtc > MaxFileAge;
+ /* A file behind the stored row (an older copy put back from a rollback backup) changed nothing and is stale: it is removed. */
+ var finished = !recorded || run!.State is UpgradeRuns.Verified or UpgradeRuns.Failed;
+ var stale = nowUtc - run!.StartedUtc > MaxFileAge;
if (!finished && !stale)
{
return new UpgradeRunPickupResult(UpgradeRunPickupOutcome.Recorded, run.RunId, run.State);
@@ -314,11 +321,13 @@ public static bool TryParse(string text, out UpgradeRunFile? run, out string pro
}
}
- private static async Task RecordAsync(NpgsqlConnection connection, UpgradeRunFile run, DateTime nowUtc, CancellationToken cancellationToken)
+ /// False when the stored row is further along than the file, so nothing was written.
+ private static async Task RecordAsync(NpgsqlConnection connection, UpgradeRunFile run, DateTime nowUtc, CancellationToken cancellationToken)
{
/* The columns are timestamp without time zone, and Npgsql refuses a Kind=Utc value for one. The file's times are already Unspecified,
so the caller's UtcNow gets the same Kind here. Without this the first pickup throws and the file never reaches the store (#9432). */
var now = DateTime.SpecifyKind(nowUtc, DateTimeKind.Unspecified);
+ bool written;
await using (var upsert = new NpgsqlCommand(UpgradeRuns.UpsertSql, connection) { CommandTimeout = 30 })
{
upsert.Parameters.Add(new NpgsqlParameter { Value = run.RunId, NpgsqlDbType = NpgsqlDbType.Uuid });
@@ -333,12 +342,13 @@ private static async Task RecordAsync(NpgsqlConnection connection, UpgradeRunFil
upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.FirstError ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Text });
upsert.Parameters.Add(new NpgsqlParameter { Value = (object?)run.VerifiedUtc ?? DBNull.Value, NpgsqlDbType = NpgsqlDbType.Timestamp });
upsert.Parameters.Add(new NpgsqlParameter { Value = now, NpgsqlDbType = NpgsqlDbType.Timestamp });
- await upsert.ExecuteNonQueryAsync(cancellationToken);
+ written = await upsert.ExecuteScalarAsync(cancellationToken) is not null;
}
await using var retention = new NpgsqlCommand(UpgradeRuns.RetentionDeleteSql, connection) { CommandTimeout = 30 };
retention.Parameters.Add(new NpgsqlParameter { Value = now.AddDays(-UpgradeRuns.RetentionDays), NpgsqlDbType = NpgsqlDbType.Timestamp });
await retention.ExecuteNonQueryAsync(cancellationToken);
+ return written;
}
private void WarnOnce(string key, string message, params object?[] args)
diff --git a/Darling/tools/install-darling.ps1 b/Darling/tools/install-darling.ps1
index 025032ed5c..095380754b 100644
--- a/Darling/tools/install-darling.ps1
+++ b/Darling/tools/install-darling.ps1
@@ -345,7 +345,8 @@ function Resolve-DarlingServiceAccountSid([string]$account) {
# account is trusted as owner and as a write grantee), so the two cannot drift apart. Directories are always
# created and granted; KeyDirectories only on a bring-your-own PostgreSQL install (Get-DarlingExtraServiceWriteDirectories
# returns them, and only then are they on the list). Files are matched in the install root only, and only files (a folder of the same name is not on the
-# list): darling.json, and every file whose name starts with darling.json.bak- (BackupPrefix, #5649). That is the prefix the hardening covers: the
+# list): darling.json, upgrade-run.json (the run record upgrade-darling.ps1 writes and the service removes, #9432), and every file whose
+# name starts with darling.json.bak- (BackupPrefix, #5649). That is the prefix the hardening covers: the
# install-time pass in install-darling.ps1, the service's TryHardenConfigBackups and the CLI's backup enumeration all
# take every darling.json.bak-* name, not only the darling.json.bak-yyyyMMdd-HHmmss(-N) names the config-editing verbs
# write, so a backup an operator named by hand (darling.json.bak-before-edit) becomes service-owned at the next start
@@ -361,7 +362,7 @@ function Get-DarlingServiceWrittenNames {
return [pscustomobject]@{
Directories = @('pg-runtime', 'pg-runtime-prev')
KeyDirectories = @('darling-keys')
- Files = @('darling.json')
+ Files = @('darling.json', 'upgrade-run.json')
BackupPrefix = 'darling.json.bak-'
}
}
@@ -1231,7 +1232,7 @@ function Get-DarlingBackupFileFindingNames([string]$root, [array]$findings) {
$segments = Get-DarlingSegmentsBelowRoot $root "$($finding.Path)"
if ($null -eq $segments -or $segments.Count -ne 1) { return @() }
$leaf = $segments[0]
- if (-not (Test-DarlingServiceWrittenFileName $leaf) -or [string]::Equals($leaf, 'darling.json', [StringComparison]::OrdinalIgnoreCase)) { return @() }
+ if (-not (Test-DarlingServiceWrittenFileName $leaf) -or -not $leaf.StartsWith((Get-DarlingServiceWrittenNames).BackupPrefix, [StringComparison]::OrdinalIgnoreCase)) { return @() }
if ($names -notcontains $leaf) { $names += $leaf }
}
return @($names)
diff --git a/Darling/tools/upgrade-darling.ps1 b/Darling/tools/upgrade-darling.ps1
index 0d69401184..4f1b969e74 100644
--- a/Darling/tools/upgrade-darling.ps1
+++ b/Darling/tools/upgrade-darling.ps1
@@ -385,7 +385,8 @@ function Resolve-DarlingServiceAccountSid([string]$account) {
# account is trusted as owner and as a write grantee), so the two cannot drift apart. Directories are always
# created and granted; KeyDirectories only on a bring-your-own PostgreSQL install (Get-DarlingExtraServiceWriteDirectories
# returns them, and only then are they on the list). Files are matched in the install root only, and only files (a folder of the same name is not on the
-# list): darling.json, and every file whose name starts with darling.json.bak- (BackupPrefix, #5649). That is the prefix the hardening covers: the
+# list): darling.json, upgrade-run.json (the run record upgrade-darling.ps1 writes and the service removes, #9432), and every file whose
+# name starts with darling.json.bak- (BackupPrefix, #5649). That is the prefix the hardening covers: the
# install-time pass in install-darling.ps1, the service's TryHardenConfigBackups and the CLI's backup enumeration all
# take every darling.json.bak-* name, not only the darling.json.bak-yyyyMMdd-HHmmss(-N) names the config-editing verbs
# write, so a backup an operator named by hand (darling.json.bak-before-edit) becomes service-owned at the next start
@@ -401,7 +402,7 @@ function Get-DarlingServiceWrittenNames {
return [pscustomobject]@{
Directories = @('pg-runtime', 'pg-runtime-prev')
KeyDirectories = @('darling-keys')
- Files = @('darling.json')
+ Files = @('darling.json', 'upgrade-run.json')
BackupPrefix = 'darling.json.bak-'
}
}
@@ -1380,7 +1381,7 @@ function Get-DarlingBackupFileFindingNames([string]$root, [array]$findings) {
$segments = Get-DarlingSegmentsBelowRoot $root "$($finding.Path)"
if ($null -eq $segments -or $segments.Count -ne 1) { return @() }
$leaf = $segments[0]
- if (-not (Test-DarlingServiceWrittenFileName $leaf) -or [string]::Equals($leaf, 'darling.json', [StringComparison]::OrdinalIgnoreCase)) { return @() }
+ if (-not (Test-DarlingServiceWrittenFileName $leaf) -or -not $leaf.StartsWith((Get-DarlingServiceWrittenNames).BackupPrefix, [StringComparison]::OrdinalIgnoreCase)) { return @() }
if ($names -notcontains $leaf) { $names += $leaf }
}
return @($names)
@@ -4075,7 +4076,11 @@ function Write-DarlingUpgradeRunFile([string]$installRoot, $run, [string]$servic
$json = $run | ConvertTo-Json -Depth 3
[System.IO.File]::WriteAllText($temp, $json, (New-Object System.Text.UTF8Encoding($false)))
# LocalSystem already has full control through the root. Any other account gets Modify on this one file, so the service can
- # delete it. The grant goes on the temp file because a move keeps a file's own DACL.
+ # delete it. The grant goes on the temp file, because the first write moves it into place and a moved file keeps its own DACL.
+ # Later writes use File.Replace, which keeps the DACL of the file it replaces, so the grant lasts for the whole run. upgrade-run.json
+ # is on Get-DarlingServiceWrittenNames, so the install-tree lock keeps this grant and makes the service the owner, and the pre-lock
+ # walk of a re-run trusts it. This grant is still needed for a run that stops before the lock runs, and for an install whose older
+ # install-darling.ps1 did not list the file, because nothing else gives the service Modify on it.
if (-not [string]::IsNullOrWhiteSpace($serviceAccount) -and $serviceAccount -notmatch '^(NT AUTHORITY\\SYSTEM|LocalSystem)$') {
$grantOutput = & icacls.exe $temp /grant:r "${serviceAccount}:(M)" 2>&1
if ($LASTEXITCODE -ne 0) {
From c725b87632d0a1f3c2b0a26b3f9e2dc5960ea74d Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 11:37:07 -0500
Subject: [PATCH 12/14] Fix a comment line in the run record tests (#9432)
---
Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
index 1ad5b8de40..8f8cdee594 100644
--- a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
+++ b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
@@ -233,8 +233,7 @@ public void AWriteThatFails_LeavesNoTempFile_AndTheOldFileUntouched()
};
///
- /// The review of #9493: the service account (NT SERVICE
-ame, never LocalSystem) holds an explicit Modify grant on upgrade-run.json,
+ /// The review of #9493: the service account (NT SERVICE account, never LocalSystem) holds an explicit Modify grant on upgrade-run.json,
/// and the pre-lock walk of a re-run named it as a stranger's write grant, so a run that failed before the lock blocked the documented
/// re-run. A real SID that is not this account (Network Service) stands for the service: granting on a file this account owns needs no
/// admin. The control run, with no service SID passed, shows the walk does see the grant.
From 4ffb3334ea1a7e720d06ab83db07202b64e967aa Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 11:39:33 -0500
Subject: [PATCH 13/14] Escape the service account name in the run record tests
(#9432)
---
Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
index 8f8cdee594..70c9687e01 100644
--- a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
+++ b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
@@ -274,13 +274,13 @@ public void AfterTheInstallTreeLock_AndARewrite_TheServiceStillHoldsModifyOnTheR
var folder = NewFolder();
try
{
- var body = "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run 'NT AUTHORITY\NETWORK SERVICE' | Out-Null; "
+ var body = "$run = New-DarlingUpgradeRun 'a' 'b' ([datetime]::UtcNow); Write-DarlingUpgradeRunFile $root $run 'NT AUTHORITY\\NETWORK SERVICE' | Out-Null; "
+ "$service = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-20'); $file = Join-Path $root 'upgrade-run.json'; "
+ "function Get-ServiceModify { @((Get-Acl -LiteralPath $file).GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) | Where-Object { $_.IdentityReference -eq $service -and ([int]$_.FileSystemRights -band 0x10000) -ne 0 }).Count -gt 0 }; "
+ "'before=' + (Get-ServiceModify); "
- + "$open = @(Lock-DarlingInstallTree $root 'NT AUTHORITY\NETWORK SERVICE'); 'lockRan=' + ($open.Count -ge 0); "
+ + "$open = @(Lock-DarlingInstallTree $root 'NT AUTHORITY\\NETWORK SERVICE'); 'lockRan=' + ($open.Count -ge 0); "
+ "'afterLock=' + (Get-ServiceModify); "
- + "Close-DarlingUpgradeRun $root $run $true 'clear' '' '' 'NT AUTHORITY\NETWORK SERVICE' | Out-Null; "
+ + "Close-DarlingUpgradeRun $root $run $true 'clear' '' '' 'NT AUTHORITY\\NETWORK SERVICE' | Out-Null; "
+ "'afterRewrite=' + (Get-ServiceModify); "
+ "'state=' + (Read-DarlingUpgradeRunFile $root)['state']";
var output = Run(folder, body, ServiceWrittenListFunctions.Append("Lock-DarlingInstallTree").ToArray());
From d5e3cf9876178c69338cc9e5238e71a01efd56f2 Mon Sep 17 00:00:00 2001
From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com>
Date: Tue, 24 Nov 2026 12:22:56 -0500
Subject: [PATCH 14/14] Start the run record tests' PowerShell through the
shared helper, so a PowerShell 7 parent's module path no longer stops Get-Acl
loading (#9432)
---
Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs | 10 +++-------
1 file changed, 3 insertions(+), 7 deletions(-)
diff --git a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
index 70c9687e01..f1322d305e 100644
--- a/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
+++ b/Darling/Darling.Tests/DarlingUpgradeRunRecordTests.cs
@@ -67,13 +67,9 @@ private static string Run(string folder, string body, params string[] extraFunct
var driver = Path.Combine(folder, "driver.ps1");
File.WriteAllText(driver, text.ToString(), new UTF8Encoding(true));
- using var process = Process.Start(new ProcessStartInfo(pwsh!, $"-NoProfile -ExecutionPolicy Bypass -File \"{driver}\"")
- {
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- CreateNoWindow = true,
- })!;
+ /* #9432: the shared helper drops the PSModulePath a PowerShell 7 parent (CI's step shell) hands down, which
+ otherwise stops Windows PowerShell 5.1 loading Microsoft.PowerShell.Security, so Get-Acl and Set-Acl fail. */
+ using var process = Process.Start(WindowsPowerShellStartInfo.Create(pwsh!, $"-NoProfile -ExecutionPolicy Bypass -File \"{driver}\""))!;
var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError.ReadToEnd();
Assert.True(process.WaitForExit(120_000), "PowerShell did not finish");