Skip to content

Darling analysis: the plan advisory read groups each plan's rows before it ranks them, so a week of history no longer spills to disk (#9495) - #9496

Open
erikdarlingdata wants to merge 2 commits into
devfrom
fix/9495-plan-advisory-group
Open

erikdarlingdata wants to merge 2 commits into
devfrom
fix/9495-plan-advisory-group

Conversation

@erikdarlingdata

Copy link
Copy Markdown
Owner

Claude posting for Erik Darling.

The change

PgFactCollector.PlanAdvisorySql used to rank every query_stats row of the window with DENSE_RANK() and ROW_NUMBER() before it kept one row per plan. At seven days that is every snapshot row of the server, and the sort spilled to disk.

The statement now reads the window through a grp step first. It groups the rows by database, query hash, plan key (COALESCE(query_plan_hash, plan_handle)), query_plan_xml and query_plan_digest. cand ranks those groups instead of the rows. The FROM and WHERE of the old cand moved into grp unchanged, including the query_plan_xml IS NOT NULL OR query_plan_digest IS NOT NULL filter and its comments. hits, misses, demoted, the final select, the parameters and the reply are byte for byte the same.

The cost of a group is CASE WHEN bool_or(cost IS NULL) THEN NULL ELSE max(cost) END. A NULL cost sorts first under DESC, so a group with a NULL-cost row ranks first, as that row does today.

Type checks. Every later step reads only plan_id, plan_rank, query_plan_xml, query_plan_digest and the cost from cand, and all of those still come out of cand with the same meaning. query_plan_xml is text and query_plan_digest is bytea, so both have an equality operator and GROUP BY works. Neither is the xml type.

Tests

New class PlanAdvisoryGroupLiveTests (live, own scratch store):

  • a plan whose costliest row has a NULL cost still ranks that row first
  • a plan with two digests, where the costliest digest has no dimension row, is represented by its other digest (the demoted path)
  • rows with inline query_plan_xml group by their own text
  • ten distinct plans come back when one hot plan has 150 snapshots
  • the old statement text (kept as a private constant in the test file) and the new one return identical replies on one seed: 22 plans with several snapshots each, a NULL cost, two digests for one plan, inline text, and a digest with no dimension row

Revert proof. With the CASE replaced by a plain max(), APlan_WhoseCostliestRowHasNoCost_StillRanksFirst and the old-vs-new comparison both fail. With the CASE back, all five pass.

EXPLAIN

Seeded 268,800 rows (400 plans, 672 snapshots each) on a scratch store, seven day window. The scratch store runs without TimescaleDB, so query_stats is a plain table here and the three-chunk seed was not possible. The row counts and spill below are what the grouped form changes. The per-chunk sort shape from the issue is not reproduced here.

New statement, 105 ms, no temp files:

Nested Loop Left Join  (actual time=104.982..104.993 rows=10)  Buffers: shared hit=7970
  CTE cand
    WindowAgg (DENSE_RANK)  rows=400
      WindowAgg (ROW_NUMBER)  rows=400
        Sort  Sort Method: quicksort  Memory: 56kB   rows=400
          Subquery Scan on g
            HashAggregate  Batches: 1  Memory Usage: 601kB  rows=400
              Group Key: database_name, query_hash, COALESCE(query_plan_hash, plan_handle), query_plan_xml, query_plan_digest

Old statement, 827 ms:

Nested Loop Left Join  (actual time=821.796..821.827 rows=10)  Buffers: shared hit=14009, temp read=8552 written=5458
  CTE cand
    WindowAgg (DENSE_RANK)  rows=268800
      WindowAgg (ROW_NUMBER)  rows=268800
        Sort  Sort Method: external merge  Disk: 18816kB   rows=268800
          Seq Scan on query_stats  rows=268800

Runs

  • Release build, 0 errors.
  • ci-select.py local-classes --base origin/dev lists PlanAdvisoryGroupLiveTests only, which passes.
  • *PlanAdvisory* 13 passed, *PgFactCollector* 18 passed, *AnalysisPlanAdvisory* 2 passed.
  • pre-push.sh: both Guard lines green (Darling 5004, Lite 1248, 0 failed). Then GATE STOP because the selection is the whole suite. CI decides the rest.

Left as a draft until a field check of the seven day read.

Fixes #9495

Release note: the plan advisory check reads a week of history about two and a half times faster and no longer writes temporary files.

@erikdarlingdata
erikdarlingdata marked this pull request as ready for review November 24, 2026 17:01
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Non-blocking notes from the review of #9496:

  1. The release note's speed-up doesn't match the body's EXPLAIN. The body measures 827 ms before and 105 ms after, which is about 7.9x. The release note says "about two and a half times faster". If 2.5x comes from the field check that is still pending, say so in the note. Otherwise the two numbers don't agree.
  2. No test covers the spill claim for the new shape. PlanAdvisoryReadLiveTests.TheFetch_SortsThinRows_AndReturnsTheViewBasedStatementsRows adds up only Sort Space Used on Sort nodes. The new grp step may run as a HashAggregate, and that test would not see it if it spilled (Batches > 1, or disk usage). That matters most for legacy rows whose own query_plan_xml is set, because that text is now a group key. The 268,800-row EXPLAIN in the body is the only evidence for "no temp files", which is fine for a draft waiting on a field check.
  3. The equivalence argument holds. Every step after cand reads only the plan key (through plan_id), query_plan_xml, query_plan_digest and the cost. Rows that share the five group columns are interchangeable except for cost. Within a group, has_plan is the same for every row, so the costliest row (NULL first under DESC, which the bool_or CASE keeps) is the only one hits, misses or demoted could pick.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verdict: LGTM

Claims

  • VERIFIED — The old cand ranked every in-window row with DENSE_RANK/ROW_NUMBER — RowRankedSql in Darling/Darling.Tests/PlanAdvisoryGroupLiveTests.cs (the old statement) and the removed lines of the diff hunk at PgFactCollector.QueryPerf.cs:1699.
  • VERIFIED — A new grp step groups by database, query hash, COALESCE(query_plan_hash, plan_handle), query_plan_xml and query_plan_digest, and cand now ranks the groups — Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs:1699-1746.
  • VERIFIED — The FROM/WHERE moved into grp unchanged, including the query_plan_xml IS NOT NULL OR query_plan_digest IS NOT NULL filter and its comments — PgFactCollector.QueryPerf.cs:1716-1725; the diff touches nothing in those lines except the word "rank"→"group" and "sort"→"carry" in one comment.
  • VERIFIED — hits, misses, demoted, the final select and the parameters are byte for byte the same — the diff has only the two hunks, and both end before hits AS MATERIALIZED.
  • VERIFIED — The group's cost is CASE WHEN bool_or(cost IS NULL) THEN NULL ELSE max(cost) END, so a group holding a NULL-cost row sorts first under DESC as the row did — PgFactCollector.QueryPerf.cs:1711. PostgreSQL's DESC defaults to NULLS FIRST.
  • VERIFIED — Every later step reads only plan_id, plan_rank, query_plan_xml, query_plan_digest and cost from cand — PgFactCollector.QueryPerf.cs:1747-1820.
  • VERIFIED — The five new tests exist and assert what the body says: NULL cost ranks first, the demoted other-digest path, inline-text grouping, ten distinct plans with one hot plan, and old-vs-new equality on a 22-plan seed — PlanAdvisoryGroupLiveTests (APlan_WhoseCostliestRowHasNoCost_StillRanksFirst, APlan_WhoseCostliestDigestHasNoDimensionRow_IsRepresentedByItsOtherDigest, RowsWithInlinePlanText_GroupByTheirOwnText, TenDistinctPlansComeBack_WhenOneHotPlanHasManySnapshots, TheGroupedStatement_ReturnsTheRowRankedStatementsReply_OnOneSeed).
  • UNVERIFIED — Revert proof: with a plain max(), the NULL-cost test and the comparison test fail. Reading the seed agrees (plan 1 at 700 loses to eleven plans at 1,020 or more), but the run itself needs a live PostgreSQL.
  • UNVERIFIED — EXPLAIN: 105 ms with no temp files against 827 ms with an 18,816 kB external merge, on 268,800 rows — needs a live store.
  • UNVERIFIED — Release build has 0 errors; *PlanAdvisory* 13, *PgFactCollector* 18 and *AnalysisPlanAdvisory* 2 pass; the pre-push Guard lines are green — needs a build and a live run.
  • UNVERIFIED — Release note: "about two and a half times faster" — no measurement in the tree or the body gives 2.5x (see Divergence).

Riskiest lines

  1. Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs:1711 — the group's cost must keep the NULL-first ordering of the per-row rank — covered by PlanAdvisoryGroupLiveTests.APlan_WhoseCostliestRowHasNoCost_StillRanksFirst
  2. Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs:1726 — the GROUP BY must keep the digest and the inline text apart, or a digest with no dimension row would merge with one that has a plan and the demoted path would break — covered by PlanAdvisoryGroupLiveTests.APlan_WhoseCostliestDigestHasNoDimensionRow_IsRepresentedByItsOtherDigest
  3. Darling/PerformanceMonitor.Darling.Analysis/PgFactCollector.QueryPerf.cs:1743-1744 — plan_id and plan_rank now partition on the projected g.plan_key; a different key would change which plans count as distinct — covered by PlanAdvisoryGroupLiveTests.TenDistinctPlansComeBack_WhenOneHotPlanHasManySnapshots and TheGroupedStatement_ReturnsTheRowRankedStatementsReply_OnOneSeed

Traps near this diff

  • "Two copies of one definition pinned EQUAL to each other fail only after BOTH have drifted (#3684). Alias, do not copy." — does not apply — PgDrillDownCollector.PlanAdvisoryXmlSql is an alias (PgDrillDownCollector.Plans.cs:146, = PgFactCollector.PlanAdvisorySql). The test's RowRankedSql is a frozen reference to the old statement that the new one is compared with, not a second live definition.
  • "MAX(max_dop) grouped by query_hash is the highest DOP ANY plan for that statement text ever ran at ... An aggregate across plans needs provenance" — does not apply — the max() at PgFactCollector.QueryPerf.cs:1711 is taken within one plan key and one digest/text, so it cannot mix plans. It picks the one representative row that the old ROW_NUMBER would have ranked first.
  • "Ruling (#5833): tests are load-bearing ... Never add one [a census or pin] ... never answer a trap with a test that reads source text" — does not apply — every new test runs the statement against a seeded store and compares replies (PlanAdvisoryGroupLiveTests.RowsAsync). None reads source text.
  • "A test that reads the clock twice measures the CI scheduler ... One anchor owns both ends of an interval." — does not apply in effect. RowsAsync and InsertAsync each call LiveClock.Now(), but the window is 7 days back to 5 minutes ahead and the rows sit 30 minutes or more in the past, so the drift between calls cannot move a row across a window edge.
  • "Lite and Darling ship in parity (CONTRIBUTING's two-store rule): a fix to one SKU's reader ... without the counterpart's is a finding" — does not apply — this is a PostgreSQL-only plan-shape change with an unchanged reply. Lite's twin (Lite/Analysis/DuckDbFactCollector.QueryPerf.cs:687) is a different statement with no dimension probes, and its reply is not changed.

Divergence (blind read vs PR body)

  • The release note says "about two and a half times faster", but the body's own EXPLAIN shows 827 ms → 105 ms (~7.9x). Neither the body nor the tree has a 2.5x figure (non-blocking; see the PR comment).
  • The body says the new statement writes no temp files, and the only evidence is the one EXPLAIN in the body. The existing sort-space test (PlanAdvisoryReadLiveTests.TheFetch_SortsThinRows_AndReturnsTheViewBasedStatementsRows) adds up only Sort nodes' Sort Space Used, so it would not see a HashAggregate spill in grp. The body doesn't claim that test covers it, so this is a gap in coverage, not a contradiction.
    Otherwise the body's account matches the diff.

Reviewer checklist

  • Run the seven-day read on a TimescaleDB store with several chunks, with EXPLAIN (ANALYZE, BUFFERS). Confirm the grp HashAggregate stays at Batches: 1 with no temp read/write, including on a store with legacy rows whose own query_plan_xml is set.
  • Run PlanAdvisoryGroupLiveTests and the existing PlanAdvisoryReadLiveTests / PlanAdvisoryDigestProbeLiveTests against DARLING_TEST_PG (CI or local).
  • Fix the release note's speed-up figure, or say where it comes from.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant