diff --git a/Darling/Darling.Tests/DarlingAnalysisPipelineTests.cs b/Darling/Darling.Tests/DarlingAnalysisPipelineTests.cs
index 406bf01c55..5a8e8c02d4 100644
--- a/Darling/Darling.Tests/DarlingAnalysisPipelineTests.cs
+++ b/Darling/Darling.Tests/DarlingAnalysisPipelineTests.cs
@@ -285,6 +285,8 @@ so its right-hand operand parses as a relation name.
/* #5794: JOIN LATERAL (subquery) names no relation, and unnest() is a set-returning function, not a table. */
scanSql = Regex.Replace(scanSql, @"\bLATERAL\b", " ", RegexOptions.IgnoreCase);
scanSql = Regex.Replace(scanSql, @"\bFROM\s+unnest\s*\(", "FROM (", RegexOptions.IgnoreCase);
+ /* #9492: EXTRACT(epoch FROM col) is a function's argument syntax, so its FROM names a column, not a relation. */
+ scanSql = Regex.Replace(scanSql, @"\bEXTRACT\s*\(\s*\w+\s+FROM\b", "EXTRACT(", RegexOptions.IgnoreCase);
/* CTE names defined by this query are legal FROM targets too (WITH x AS ( / , y AS (). */
var ctes = Regex.Matches(scanSql, @"(?:WITH|,)\s*(\w+)\s+AS\s*(?:(?:NOT\s+)?MATERIALIZED\s*)?\(", RegexOptions.Singleline)
diff --git a/Darling/Darling.Tests/ParameterSensitivityNewestRowLiveTests.cs b/Darling/Darling.Tests/ParameterSensitivityNewestRowLiveTests.cs
new file mode 100644
index 0000000000..63cae003eb
--- /dev/null
+++ b/Darling/Darling.Tests/ParameterSensitivityNewestRowLiveTests.cs
@@ -0,0 +1,345 @@
+/*
+ * 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.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Npgsql;
+using PerformanceMonitor.Darling.Analysis;
+using PerformanceMonitor.Darling.Storage;
+using Xunit;
+
+namespace Darling.Tests;
+
+///
+/// #9492: the parameter-sensitivity fact and its drill-down take each plan's newest row by an aggregate (the largest
+/// array whose leading elements are the row's time and id), not by numbering every row of the window. Both reads are run
+/// on a live store over the same seeded rows, and each case below can only pass if the row the read keeps is the right
+/// ONE row: the newest by time, the larger collection_id when two share that time, with every figure from that same row.
+///
+/// The cases, by plan key: two rows at the newest time (the larger id wins, with its own worker, grant, spill,
+/// creation time to the microsecond, execution count, inline-text flag and digest) with an older row that has a larger id
+/// and larger figures; a newest row with NULL grant and spill fields over an older row that has values; an older row that
+/// passes the filter under a newest row that does not; and NULL key parts, which form one group.
+///
+[Collection("live-postgres")]
+public sealed class ParameterSensitivityNewestRowLiveTests
+{
+ /// Distinctive fake id: a real server_id is a storage-name hash, never this.
+ private const int TestServerId = -949201;
+ private const string TestServerName = "PspNewestSrv";
+ private const int LiveTimeoutSeconds = 60;
+
+ private const string TieDb = "Psp9492Db";
+ private const string TieQueryHash = "0xQH_9492_TIE";
+ private const string TiePlanHash = "0xPH_9492_TIE";
+ private const string NullNewestQueryHash = "0xQH_9492_NULLNEWEST";
+ private const string NewestQuietQueryHash = "0xQH_9492_NEWESTQUIET";
+ private const string OlderQueryHash = "0xQH_9492_OLDER";
+ private const string InlineTieQueryHash = "0xQH_9492_INLINETIE";
+
+ private static readonly byte[] DigestTieLoser = [0x94, 0x92, 0x01];
+ private static readonly byte[] DigestTieWinner = [0x94, 0x92, 0x02];
+ private static readonly byte[] DigestOlderRow = [0x94, 0x92, 0x03];
+
+ /// The compile time of the tied pair's winner, microseconds included, so the epoch round trip is tested to the last digit.
+ private static DateTime WinnerCreation => Window().Start.AddDays(-2).AddHours(-3).AddTicks(1_234_560);
+
+ private static DateTime OtherCreation => Window().Start.AddDays(-2).AddTicks(7_654_320);
+
+ /// One seeded query_stats row.
+ private sealed record Row(
+ string? Db,
+ string? QueryHash,
+ string? PlanHash,
+ DateTime Time,
+ long Id,
+ long ExecutionCount,
+ long MinWorker,
+ long MaxWorker,
+ long? MinGrant,
+ long? MaxGrant,
+ long? MinSpills,
+ long? MaxSpills,
+ string? InlineText,
+ byte[]? Digest,
+ DateTime Creation);
+
+ /// What a read handed back for one plan key.
+ private sealed record Seen(
+ double WorkerRatio,
+ double? GrantRatio,
+ int SpillDivergence,
+ DateTime? CreationLocal,
+ long? ExecutionCount,
+ bool? HasInlineText,
+ byte[]? Digest);
+
+ [Fact]
+ public async Task TheFact_KeepsEachPlansNewestRow_AndTheLargerIdOnATiedTime_AgainstDevPostgres()
+ {
+ var seen = await RunReadAsync(PgFactCollector.ParameterSensitivitySql, keyOrdinal: 8, isDrillDown: false);
+ AssertNewestRows(seen, isDrillDown: false);
+ }
+
+ [Fact]
+ public async Task TheDrillDown_KeepsEachPlansNewestRow_AndReadsItsTextFieldsFromThatRow_AgainstDevPostgres()
+ {
+ var seen = await RunReadAsync(PgDrillDownCollector.ParameterSensitiveSql, keyOrdinal: 0, isDrillDown: true);
+ AssertNewestRows(seen, isDrillDown: true);
+ }
+
+ [Fact]
+ public async Task TheDrillDownInlineText_OnATiedTime_ComesFromTheLargerCollectionId_AgainstDevPostgres()
+ {
+ /* Both rows of the key carry inline text and the texts differ. The key's ratio is 2, so the ranking does not report it:
+ the inline-text read takes its keys as arrays, so it is asked for this plan directly. */
+ var texts = await WithSeededStoreAsync(async (connection, windowStart, windowEnd, ct) =>
+ {
+ await using var cmd = new NpgsqlCommand(PgDrillDownCollector.ParameterSensitiveInlineTextSql, connection) { CommandTimeout = LiveTimeoutSeconds };
+ cmd.Parameters.AddWithValue(TestServerId);
+ cmd.Parameters.AddWithValue(DateTime.SpecifyKind(windowStart, DateTimeKind.Unspecified));
+ cmd.Parameters.AddWithValue(DateTime.SpecifyKind(windowEnd, DateTimeKind.Unspecified));
+ cmd.Parameters.AddWithValue(new[] { TieDb });
+ cmd.Parameters.AddWithValue(new[] { InlineTieQueryHash });
+ cmd.Parameters.AddWithValue(new[] { TiePlanHash });
+
+ var found = new List();
+ await using var reader = await cmd.ExecuteReaderAsync(ct);
+ while (await reader.ReadAsync(ct))
+ {
+ found.Add(reader.IsDBNull(3) ? null : reader.GetString(3));
+ }
+
+ return found;
+ });
+
+ Assert.Equal("inline text of the larger id", Assert.Single(texts));
+ }
+
+ private static void AssertNewestRows(Dictionary seen, bool isDrillDown)
+ {
+ /* Two rows at the newest time: the larger collection_id wins and every figure is its own. The older row (the
+ largest id of the three, and the largest figures) never wins on id: time decides first. */
+ var tie = seen[Key(TieDb, TieQueryHash, TiePlanHash)];
+ Assert.Equal(100.0, tie.WorkerRatio);
+ Assert.Equal(10.0, tie.GrantRatio);
+ Assert.Equal(1, tie.SpillDivergence);
+ Assert.Equal(WinnerCreation, tie.CreationLocal);
+ if (isDrillDown)
+ {
+ Assert.Equal(700L, tie.ExecutionCount);
+ Assert.False(tie.HasInlineText);
+ Assert.Equal(DigestTieWinner, tie.Digest);
+ }
+
+ /* A NULL grant and spill on the newest row come back NULL: the older row's values are not borrowed. */
+ var nullNewest = seen[Key(TieDb, NullNewestQueryHash, TiePlanHash)];
+ Assert.Equal(20.0, nullNewest.WorkerRatio);
+ Assert.Null(nullNewest.GrantRatio);
+ Assert.Equal(0, nullNewest.SpillDivergence);
+
+ /* An older row with larger values is not chosen. */
+ var older = seen[Key(TieDb, OlderQueryHash, TiePlanHash)];
+ Assert.Equal(20.0, older.WorkerRatio);
+ Assert.Equal(2.0, older.GrantRatio);
+
+ /* The older row passes the filter and the newest does not: the plan is not reported. */
+ Assert.False(seen.ContainsKey(Key(TieDb, NewestQuietQueryHash, TiePlanHash)));
+
+ /* NULL key parts form one group, with the newest row's figures. */
+ var nullKeys = seen.Where(pair => pair.Key == Key(null, null, null)).ToList();
+ var nullKey = Assert.Single(nullKeys).Value;
+ Assert.Equal(20.0, nullKey.WorkerRatio);
+
+ Assert.Equal(4, seen.Count);
+ }
+
+ private static string Key(string? db, string? queryHash, string? planHash) =>
+ string.Join('|', db ?? "", queryHash ?? "", planHash ?? "");
+
+ private static readonly DateTime WindowEnd = LiveClock.Now();
+
+ private static (DateTime Start, DateTime End) Window() => (WindowEnd.AddHours(-4), WindowEnd);
+
+ private static async Task> RunReadAsync(string sql, int keyOrdinal, bool isDrillDown) =>
+ await WithSeededStoreAsync(async (connection, windowStart, windowEnd, ct) =>
+ {
+ var seen = new Dictionary();
+ await using var cmd = new NpgsqlCommand(sql, connection) { CommandTimeout = LiveTimeoutSeconds };
+ cmd.Parameters.AddWithValue(TestServerId);
+ cmd.Parameters.AddWithValue(DateTime.SpecifyKind(windowStart, DateTimeKind.Unspecified));
+ cmd.Parameters.AddWithValue(DateTime.SpecifyKind(windowEnd, DateTimeKind.Unspecified));
+
+ await using var reader = await cmd.ExecuteReaderAsync(ct);
+ while (await reader.ReadAsync(ct))
+ {
+ var key = Key(
+ reader.IsDBNull(keyOrdinal) ? null : reader.GetString(keyOrdinal),
+ reader.IsDBNull(keyOrdinal + 1) ? null : reader.GetString(keyOrdinal + 1),
+ reader.IsDBNull(keyOrdinal + 2) ? null : reader.GetString(keyOrdinal + 2));
+
+ /* The fact's columns: worker ratio 2, grant ratio 3, spill 4, creation time 5. The drill-down's: execution
+ count 3, worker ratio 6, grant ratio 7, spill 8, has inline text 9, creation time 10, digest 13. */
+ var workerOrdinal = isDrillDown ? 6 : 2;
+ var creationOrdinal = isDrillDown ? 10 : 5;
+ seen.Add(key, new Seen(
+ reader.GetDouble(workerOrdinal),
+ reader.IsDBNull(workerOrdinal + 1) ? null : reader.GetDouble(workerOrdinal + 1),
+ Convert.ToInt32(reader.GetValue(workerOrdinal + 2), CultureInfo.InvariantCulture),
+ reader.IsDBNull(creationOrdinal) ? null : reader.GetDateTime(creationOrdinal),
+ isDrillDown ? reader.GetInt64(3) : null,
+ isDrillDown ? reader.GetBoolean(9) : null,
+ isDrillDown && !reader.IsDBNull(13) ? reader.GetFieldValue(13) : null));
+ }
+
+ return seen;
+ });
+
+ /// Migrates, seeds the window's rows, runs one read on its own connection, and cleans up.
+ private static async Task WithSeededStoreAsync(Func> read)
+ {
+ var connectionString = Environment.GetEnvironmentVariable("DARLING_TEST_PG");
+ Assert.SkipWhen(string.IsNullOrEmpty(connectionString),
+ "Set DARLING_TEST_PG to a Postgres connection string to run the live #9492 newest-row test.");
+
+ var ct = TestContext.Current.CancellationToken;
+ var bodySucceeded = false;
+
+ await using (var connection = new NpgsqlConnection(connectionString))
+ {
+ await connection.OpenAsync(ct);
+ await PgMigrations.MigrateAsync(connection, ct);
+ }
+
+ await using (var connection = await OpenWithSearchPathAsync(connectionString!, ct))
+ {
+ await DeleteTestRowsAsync(connection, ct);
+ }
+
+ try
+ {
+ var (windowStart, windowEnd) = Window();
+
+ await using (var connection = await OpenWithSearchPathAsync(connectionString!, ct))
+ {
+ foreach (var row in SeedRows(windowStart))
+ {
+ await InsertAsync(connection, row, windowStart, ct);
+ }
+ }
+
+ T result;
+ await using (var connection = await OpenWithSearchPathAsync(connectionString!, ct))
+ {
+ result = await read(connection, windowStart, windowEnd, ct);
+ }
+
+ bodySucceeded = true;
+ return result;
+ }
+ finally
+ {
+ await LiveStoreCleanup.RunAsync(connectionString!, bodySucceeded, DeleteTestRowsAsync);
+ }
+ }
+
+ ///
+ /// The window's rows, in the order they are inserted: the tied pair goes in smaller id first, so a read that kept the
+ /// first or the last of the tie by physical order could not pass both by luck.
+ ///
+ private static IEnumerable SeedRows(DateTime windowStart)
+ {
+ /* A fractional second, so the time the read hands back through epoch microseconds must round trip exactly. */
+ var newest = windowStart.AddHours(2).AddTicks(6_543_210);
+ var hourBefore = newest.AddHours(-1);
+ var twoHoursBefore = newest.AddHours(-2);
+
+ /* Two rows at the newest time. The winner (larger id) has ratio 100, grant ratio 10, a spill, no inline text and its own
+ digest; the loser has ratio 20, grant ratio 2, no spill, inline text. The older row has the largest id and the largest
+ figures: time, not id, is what picks the newest row. */
+ yield return new Row(TieDb, TieQueryHash, TiePlanHash, newest, -94_920_050, 500, 20_000, 400_000, 1_024, 2_048, 0, 0, "inline loser", DigestTieLoser, OtherCreation);
+ yield return new Row(TieDb, TieQueryHash, TiePlanHash, hourBefore, -94_920_030, 900, 20_000, 4_000_000, 1_024, 20_480, 0, 9, "inline older", DigestOlderRow, OtherCreation);
+ yield return new Row(TieDb, TieQueryHash, TiePlanHash, newest, -94_920_040, 700, 25_000, 2_500_000, 1_024, 10_240, 0, 5, null, DigestTieWinner, WinnerCreation);
+
+ /* A newest row with NULL grant and spill fields over an older row that has them. */
+ yield return new Row(TieDb, NullNewestQueryHash, TiePlanHash, hourBefore, -94_920_060, 500, 20_000, 2_000_000, 1_024, 8_192, 0, 7, null, null, OtherCreation);
+ yield return new Row(TieDb, NullNewestQueryHash, TiePlanHash, newest, -94_920_070, 500, 20_000, 400_000, null, null, null, null, null, null, OtherCreation);
+
+ /* An older row with larger values under a newest row with smaller ones. */
+ yield return new Row(TieDb, OlderQueryHash, TiePlanHash, twoHoursBefore, -94_920_080, 500, 20_000, 2_000_000, 1_024, 20_480, 0, 0, null, null, OtherCreation);
+ yield return new Row(TieDb, OlderQueryHash, TiePlanHash, newest, -94_920_090, 500, 20_000, 400_000, 1_024, 2_048, 0, 0, null, null, OtherCreation);
+
+ /* An older row that passes the filter under a newest row that does not (a ratio of 2). */
+ yield return new Row(TieDb, NewestQuietQueryHash, TiePlanHash, hourBefore, -94_920_100, 500, 20_000, 2_000_000, 1_024, 2_048, 0, 0, null, null, OtherCreation);
+ yield return new Row(TieDb, NewestQuietQueryHash, TiePlanHash, newest, -94_920_110, 500, 20_000, 40_000, 1_024, 2_048, 0, 0, null, null, OtherCreation);
+
+ /* Two rows at the newest time that both carry inline text, the larger id inserted last. A ratio of 2, so the ranking does not
+ report the key and the other reads are unchanged. */
+ yield return new Row(TieDb, InlineTieQueryHash, TiePlanHash, newest, -94_920_150, 500, 20_000, 40_000, 1_024, 2_048, 0, 0, "inline text of the smaller id", null, OtherCreation);
+ yield return new Row(TieDb, InlineTieQueryHash, TiePlanHash, newest, -94_920_140, 500, 20_000, 40_000, 1_024, 2_048, 0, 0, "inline text of the larger id", null, OtherCreation);
+
+ /* NULL database, query hash and plan hash: one group, two rows, the newest wins. */
+ yield return new Row(null, null, null, hourBefore, -94_920_120, 500, 20_000, 2_000_000, 1_024, 2_048, 0, 0, null, null, OtherCreation);
+ yield return new Row(null, null, null, newest, -94_920_130, 500, 20_000, 400_000, 1_024, 2_048, 0, 0, null, null, OtherCreation);
+ }
+
+ private static async Task InsertAsync(NpgsqlConnection connection, Row row, DateTime windowStart, CancellationToken ct)
+ {
+ await using var cmd = new NpgsqlCommand(@"
+INSERT INTO query_stats
+ (collection_id, collection_time, server_id, server_name, database_name, query_hash, query_plan_hash,
+ creation_time, execution_count, min_worker_time, max_worker_time, min_grant_kb, max_grant_kb,
+ min_spills, max_spills, query_text, query_text_digest, delta_execution_count)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, 25)", connection)
+ {
+ CommandTimeout = LiveTimeoutSeconds
+ };
+
+ cmd.Parameters.AddWithValue(row.Id);
+ cmd.Parameters.AddWithValue(DateTime.SpecifyKind(row.Time, DateTimeKind.Unspecified));
+ cmd.Parameters.AddWithValue(TestServerId);
+ cmd.Parameters.AddWithValue(TestServerName);
+ cmd.Parameters.AddWithValue((object?)row.Db ?? DBNull.Value);
+ cmd.Parameters.AddWithValue((object?)row.QueryHash ?? DBNull.Value);
+ cmd.Parameters.AddWithValue((object?)row.PlanHash ?? DBNull.Value);
+ cmd.Parameters.AddWithValue(DateTime.SpecifyKind(row.Creation, DateTimeKind.Unspecified));
+ cmd.Parameters.AddWithValue(row.ExecutionCount);
+ cmd.Parameters.AddWithValue(row.MinWorker);
+ cmd.Parameters.AddWithValue(row.MaxWorker);
+ cmd.Parameters.AddWithValue((object?)row.MinGrant ?? DBNull.Value);
+ cmd.Parameters.AddWithValue((object?)row.MaxGrant ?? DBNull.Value);
+ cmd.Parameters.AddWithValue((object?)row.MinSpills ?? DBNull.Value);
+ cmd.Parameters.AddWithValue((object?)row.MaxSpills ?? DBNull.Value);
+ cmd.Parameters.AddWithValue((object?)row.InlineText ?? DBNull.Value);
+ cmd.Parameters.Add(new NpgsqlParameter { NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Bytea, Value = (object?)row.Digest ?? DBNull.Value });
+ await cmd.ExecuteNonQueryAsync(ct);
+ }
+
+ private static async Task OpenWithSearchPathAsync(string connectionString, CancellationToken ct)
+ {
+ var connection = new NpgsqlConnection(connectionString);
+ await connection.OpenAsync(ct);
+ await using var setPath = new NpgsqlCommand("SET search_path = " + PgSchemaGenerator.SearchPath, connection);
+ await setPath.ExecuteNonQueryAsync(ct);
+ return connection;
+ }
+
+ private static async Task DeleteTestRowsAsync(NpgsqlConnection connection, CancellationToken ct)
+ {
+ await using var cmd = new NpgsqlCommand("DELETE FROM query_stats WHERE server_id = $1", connection)
+ {
+ CommandTimeout = LiveTimeoutSeconds
+ };
+ cmd.Parameters.AddWithValue(TestServerId);
+ await cmd.ExecuteNonQueryAsync(ct);
+ }
+}
diff --git a/Darling/Darling.Tests/PgFactCollectorTests.cs b/Darling/Darling.Tests/PgFactCollectorTests.cs
index 60a5991d37..defceeaa25 100644
--- a/Darling/Darling.Tests/PgFactCollectorTests.cs
+++ b/Darling/Darling.Tests/PgFactCollectorTests.cs
@@ -303,6 +303,8 @@ so its right-hand operand parses as a relation name.
/* JOIN LATERAL (subquery) names no relation; the subquery's own FROM is scanned in its place (as the
drill-down guard does, #5794). */
scanSql = Regex.Replace(scanSql, @"\bLATERAL\b", " ", RegexOptions.IgnoreCase);
+ /* #9492: EXTRACT(epoch FROM col) is a function's argument syntax, so its FROM names a column, not a relation. */
+ scanSql = Regex.Replace(scanSql, @"\bEXTRACT\s*\(\s*\w+\s+FROM\b", "EXTRACT(", RegexOptions.IgnoreCase);
/* CTE names defined by this query are legal FROM targets too (WITH x AS ( / , y AS (). */
var ctes = Regex.Matches(scanSql, @"(?:WITH|,)\s*(\w+)\s+AS\s*(?:(?:NOT\s+)?MATERIALIZED\s*)?\(", RegexOptions.Singleline)
diff --git a/Darling/Darling.Tests/StatementDrillDownTextFetchLiveTests.cs b/Darling/Darling.Tests/StatementDrillDownTextFetchLiveTests.cs
index b6318d85df..a241045e72 100644
--- a/Darling/Darling.Tests/StatementDrillDownTextFetchLiveTests.cs
+++ b/Darling/Darling.Tests/StatementDrillDownTextFetchLiveTests.cs
@@ -293,7 +293,7 @@ INSERT INTO query_stats
dimension read for the kept plans. */
var oracleSql = PgDrillDownCollector.ParameterSensitiveSql
.Replace("query_text IS NOT NULL AS has_inline_text,", "query_text,", StringComparison.Ordinal)
- .Replace(" has_inline_text,", " query_text,", StringComparison.Ordinal)
+ .Replace(" t.has_inline_text,", " t.query_text,", StringComparison.Ordinal)
.Replace(" o.has_inline_text,", " o.query_text,", StringComparison.Ordinal);
Assert.DoesNotContain("has_inline_text", oracleSql, StringComparison.Ordinal);
var kept = new List<(object?[] Row, string? Inline, byte[]? Digest)>();
diff --git a/Darling/PerformanceMonitor.Darling.Analysis/PgDrillDownCollector.Queries.cs b/Darling/PerformanceMonitor.Darling.Analysis/PgDrillDownCollector.Queries.cs
index 96ce928ae9..12536f02f6 100644
--- a/Darling/PerformanceMonitor.Darling.Analysis/PgDrillDownCollector.Queries.cs
+++ b/Darling/PerformanceMonitor.Darling.Analysis/PgDrillDownCollector.Queries.cs
@@ -306,61 +306,98 @@ svr AS
latest AS
(
-- #3902: the base table, not v_query_stats. The view resolves statement text for EVERY row it returns
- -- by joining query_text_dim -- the whole fleet's text dimension -- and the window sort below then
- -- carries each row's text, so this read paid for the window's worth of text to print five. The row
- -- keeps the two halves the view would have COALESCEd (the inline legacy text and the digest). This
- -- read resolves neither against the dimension: the reader keeps the first five plans that pass its
- -- exact test, and ParameterSensitiveInlineTextSql then reads the inline text of those plans only and
+ -- by joining query_text_dim -- the whole fleet's text dimension -- so this read paid for the window's
+ -- worth of text to print five. The two halves the view would have COALESCEd (the inline legacy text and
+ -- the digest) are read below for the plans that survive the rough filter only. This read resolves
+ -- neither against the dimension: the reader keeps the first five plans that pass its exact test, and
+ -- ParameterSensitiveInlineTextSql then reads the inline text of those plans only and
-- ParameterSensitiveTextSql resolves the digests of those plans only.
+ --
+ -- #9492: each plan's newest row by an aggregate, not by numbering every row of the window. ROW_NUMBER over
+ -- the window sorted each chunk's rows, held every chunk's sort until the merge ended, and so cost memory in
+ -- step with the window; max over an array whose leading elements are the row's time and id keeps one array
+ -- per plan. Arrays compare element by element, so the largest array is the newest row, and on two rows at
+ -- the newest time the larger collection_id (the pair is unique, so a NULL field after it never decides the
+ -- winner and comes back NULL). Every field here is a bigint or a timestamp, which rides as epoch
+ -- microseconds and is read back exactly: the column is timestamp without time zone, which holds
+ -- microseconds. The boolean and the bytea cannot ride in a bigint[], so offenders looks them up.
SELECT
database_name,
query_hash,
query_plan_hash,
- execution_count,
- creation_time,
- min_worker_time,
- max_worker_time,
- min_grant_kb,
- max_grant_kb,
- min_spills,
- max_spills,
- -- #5361: whether the row has inline text, never the text. The window sort below would carry every
- -- row's whole text (up to 64 KB each) to keep five plans, so the text is read afterwards for those plans.
- query_text IS NOT NULL AS has_inline_text,
- query_text_digest,
- ROW_NUMBER() OVER
- (
- PARTITION BY database_name, query_hash, query_plan_hash
- ORDER BY collection_time DESC
- ) AS rn
+ max(ARRAY[
+ (extract(epoch FROM collection_time) * 1000000)::bigint,
+ collection_id,
+ execution_count,
+ (extract(epoch FROM creation_time) * 1000000)::bigint,
+ min_worker_time,
+ max_worker_time,
+ min_grant_kb,
+ max_grant_kb,
+ min_spills,
+ max_spills
+ ]) AS w
FROM query_stats
WHERE server_id = $1
AND collection_time >= $2
AND collection_time <= $3
AND delta_execution_count > 0
+ GROUP BY database_name, query_hash, query_plan_hash
),
-offenders AS
+newest_rows AS
(
SELECT
database_name,
query_hash,
query_plan_hash,
- execution_count,
- min_worker_time,
- max_worker_time,
- max_worker_time::DOUBLE PRECISION / NULLIF(min_worker_time, 0) AS worker_ratio,
- max_grant_kb::DOUBLE PRECISION / NULLIF(min_grant_kb, 0) AS grant_ratio,
- CASE WHEN max_spills > 0 AND min_spills = 0 THEN 1 ELSE 0 END AS spill_divergence,
- creation_time,
- has_inline_text,
- query_text_digest,
+ timestamp 'epoch' + w[1] * interval '1 microsecond' AS newest_time,
+ w[2] AS newest_id,
+ w[3] AS execution_count,
+ timestamp 'epoch' + w[4] * interval '1 microsecond' AS creation_time,
+ w[5] AS min_worker_time,
+ w[6] AS max_worker_time,
+ w[7] AS min_grant_kb,
+ w[8] AS max_grant_kb,
+ w[9] AS min_spills,
+ w[10] AS max_spills
+ FROM latest
+),
+offenders AS
+(
+ SELECT
+ n.database_name,
+ n.query_hash,
+ n.query_plan_hash,
+ n.execution_count,
+ n.min_worker_time,
+ n.max_worker_time,
+ n.max_worker_time::DOUBLE PRECISION / NULLIF(n.min_worker_time, 0) AS worker_ratio,
+ n.max_grant_kb::DOUBLE PRECISION / NULLIF(n.min_grant_kb, 0) AS grant_ratio,
+ CASE WHEN n.max_spills > 0 AND n.min_spills = 0 THEN 1 ELSE 0 END AS spill_divergence,
+ n.creation_time,
+ -- #5361: whether the row has inline text, never the text: the text is read afterwards for the plans
+ -- that print. The winning row is looked up by time and id for the plans that pass the rough filter only.
+ t.has_inline_text,
+ t.query_text_digest,
svr.offset_minutes,
svr.time_zone_id
- FROM latest, svr
+ FROM newest_rows AS n
+ CROSS JOIN svr
+ LEFT JOIN LATERAL
+ (
+ SELECT
+ q.query_text IS NOT NULL AS has_inline_text,
+ q.query_text_digest
+ FROM query_stats AS q
+ WHERE q.server_id = $1
+ AND q.collection_time = n.newest_time
+ AND q.collection_id = n.newest_id
+ LIMIT 1
+ ) AS t ON TRUE
-- The creation_time predicate is a rough filter only (#4821): the newest offset, an hour wider than the bound.
-- The reader makes the exact compiled-before-the-window test on the converted time and keeps the first five,
-- so this read has no LIMIT.
- WHERE rn = 1
+ WHERE TRUE
" + ParameterSensitivitySignature.PredicateSql("creation_time - make_interval(mins => svr.offset_minutes) <= $2 + interval '1 hour'", " ") + @"
)
SELECT
@@ -394,8 +431,8 @@ FROM offenders AS o
/// The inline statement text of the parameter-sensitive plans the reader keeps (#5361), whole: the text
/// flags with has_inline_text but does not carry, because it runs
/// before the reader's cap. Each plan's row is the one that read ranked: the newest row of the window with
- /// delta_execution_count > 0 (its rn = 1), so a kept plan prints the text it printed when the ranking
- /// read carried it. $1 to $3 are the server and the window, $4 to $6 the kept plans'
+ /// delta_execution_count > 0, the newest by (collection_time, collection_id), the same row the ranking keeps,
+ /// so a kept plan prints the text of the row it was ranked on, also when two rows share the newest time. $1 to $3 are the server and the window, $4 to $6 the kept plans'
/// database, query hash and plan hash as three parallel arrays; a NULL part matches a NULL part, as the ranking's
/// PARTITION BY groups it. The hash comparison also states = ANY so the (server_id, query_hash,
/// collection_time) index serves the read. The text is the view's own COALESCE (#1767): the row's inline text, else
@@ -419,7 +456,7 @@ AND q.query_plan_hash IS NOT DISTINCT FROM k.query_plan_hash
AND q.collection_time <= $3
AND q.delta_execution_count > 0
AND (q.query_hash = ANY($5::text[]) OR q.query_hash IS NULL)
-ORDER BY q.database_name, q.query_hash, q.query_plan_hash, q.collection_time DESC";
+ORDER BY q.database_name, q.query_hash, q.query_plan_hash, q.collection_time DESC, q.collection_id DESC";
///
/// The statement text of the parameter-sensitive plans the reader keeps, by digest (#3902, #4821): one
diff --git a/Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs b/Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs
index 7d2d00cfca..8b7245f7c7 100644
--- a/Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs
+++ b/Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs
@@ -218,28 +218,51 @@ svr AS
),
latest AS
(
+ -- #9492: each plan's newest row by an aggregate, not by numbering every row of the window. ROW_NUMBER over
+ -- the window sorted each chunk's rows, held every chunk's sort until the merge ended, and so cost memory in
+ -- step with the window; max over an array whose leading elements are the row's time and id keeps one array
+ -- per plan. Arrays compare element by element, so the largest array is the newest row, and on two rows at
+ -- the newest time the larger collection_id (the pair is unique, so a NULL field after it never decides the
+ -- winner and comes back NULL). Every field is a bigint or a timestamp, which rides as epoch microseconds
+ -- and is read back exactly: the column is timestamp without time zone, which holds microseconds.
SELECT
+ database_name,
query_hash,
query_plan_hash,
- database_name,
- execution_count,
- creation_time,
- min_worker_time,
- max_worker_time,
- min_grant_kb,
- max_grant_kb,
- min_spills,
- max_spills,
- ROW_NUMBER() OVER
- (
- PARTITION BY database_name, query_hash, query_plan_hash
- ORDER BY collection_time DESC
- ) AS rn
+ max(ARRAY[
+ (extract(epoch FROM collection_time) * 1000000)::bigint,
+ collection_id,
+ execution_count,
+ (extract(epoch FROM creation_time) * 1000000)::bigint,
+ min_worker_time,
+ max_worker_time,
+ min_grant_kb,
+ max_grant_kb,
+ min_spills,
+ max_spills
+ ]) AS w
FROM v_query_stats
WHERE server_id = $1
AND collection_time >= $2
AND collection_time <= $3
AND delta_execution_count > 0
+ GROUP BY database_name, query_hash, query_plan_hash
+),
+newest_rows AS
+(
+ SELECT
+ database_name,
+ query_hash,
+ query_plan_hash,
+ w[3] AS execution_count,
+ timestamp 'epoch' + w[4] * interval '1 microsecond' AS creation_time,
+ w[5] AS min_worker_time,
+ w[6] AS max_worker_time,
+ w[7] AS min_grant_kb,
+ w[8] AS max_grant_kb,
+ w[9] AS min_spills,
+ w[10] AS max_spills
+ FROM latest
)
SELECT
min_worker_time,
@@ -253,8 +276,8 @@ AND delta_execution_count > 0
database_name,
query_hash,
query_plan_hash
-FROM latest, svr
-WHERE rn = 1
+FROM newest_rows, svr
+WHERE TRUE
" + ParameterSensitivitySignature.PredicateSql("creation_time - make_interval(mins => svr.offset_minutes) <= $2 + interval '1 hour'") + @"
ORDER BY worker_ratio DESC, database_name, query_hash, query_plan_hash";