Skip to content

Viewer: store the Overview CPU and I/O baselines once a day and read them first - #10441

Merged
erikdarlingdata merged 5 commits into
devfrom
fix/10435-stored-overview-baseline
Dec 4, 2026
Merged

erikdarlingdata merged 5 commits into
devfrom
fix/10435-stored-overview-baseline

Conversation

@erikdarlingdata

Copy link
Copy Markdown
Owner

Claude posting for Erik Darling.

Fixes #10435

A server tab's first open in the Viewer took 5.36 s and 5.49 s in the field, and its longest read was the Overview I/O baseline at 2.91 s and 3.29 s. That band and the CPU band are 30-day aggregates whose window ends at the UTC midnight, so each is the same all day. The service now stores both once a day and the Viewer reads the stored entry first.

What changes

  • V334, collect.overview_baseline_entries. One row per server, lane and UTC key day (primary key server_id, metric_name, key_day). The row holds the 193 tier rows as parallel arrays, the window start, the server's clock (utc_offset_minutes, time_zone_id) and a compute_version. An older build ignores the table: it neither reads nor writes it and nothing it reads changes, so there is no rollback line.
  • Writer. OverviewBaselineWriter is a new tenant of the hourly store-maintenance tick, after the pg_io_stats hourly rollup. From the first tick at or after 00:15 UTC it writes the missing entries for the I/O lane and then the CPU lane, for each server with rows in the last day. It is one serial pass that skips entries already written, so the first tick after a restart catches up and a compute that failed or timed out is tried again on the next tick. The compute goes through the provider's existing single flight and shared tier.
  • Reader. The Viewer's CPU and I/O lanes read the entry for the request's key first, a primary-key read, and compute exactly as before when there is no entry, when the store is older than V334 (the schema version gate, not a caught error), or when the entry's window or compute_version is not the one a compute at that key would use.
  • Retention. The existing retention sweep keeps two key days and drops older ones in one statement.
  • Schema gate. The store probe gains the V334 sentinel and its arm, and the schema version tests move up one rung.
  • The wait and blocking lanes stay computed: they are keyed by the hour, so a daily entry would change their answer, and they are not among the slow reads.
  • The web Overview's read is unchanged.

Numbers

  • Lab rig of 28.3M rows: a stored entry reads in 3.3 ms cold and 0.1 ms warm, against 736.2 ms cold and 160.6 ms warm for dev's compute. The rows are equal to dev's (worst difference 7.37e-15) and the band is the same (0 of 193 tiers differ at 2 or 3 dp).
  • Lab writer: 791.7 ms per server cold (median, max 1,272.3 ms) and 58 KB of WAL per entry. Steady state at 300 servers is 2,400 entries in 17 MB, and deleting a key day takes 25 ms.
  • Field: 42 servers have rows in the last day. The cold compute is 2.95 s for the largest server's I/O lane, 1.55 s for the median server and 0.37 s for CPU. That prices the daily writes at about 86 s a day (upper bound about 144 s with every server at the largest), 0.17 h a week.

The six conditions

  1. Fallback. The Viewer computes as before whenever it cannot use an entry: no entry, a store older than V334, or a key, window or compute version that does not match.
  2. Budget. A tick stops starting entries after 60 s and leaves the rest to the next hourly tick. A tick is held for the budget plus the compute under way, about 63 s with the field's worst compute of 2.95 s and at most 150 s (the compute's own 90 s limit). At 300 servers the day's writes are about 612 s of compute at the field's median cost, so they finish over about 11 hourly ticks, and a server not yet written computes as today. At 42 servers they finish in 2 ticks.
  3. Connection. The pass holds one store connection. An entry whose compute or write fails is counted and logged, the connection is reopened if it closed (the A refused Query Store corrected daily copy no longer closes the retention pass's connection, and the copy finishes past the decompression limit (#10429) #10431 pattern), and the entries after it still run. The tenant has its own catch-all, so nothing in it fails the steps behind it on the tick.
  4. compute_version. An entry of a version this build does not know is skipped and the band is computed.
  5. Retention. Key days older than two days drop in the existing retention sweep.
  6. Lite. Lite draws the same bands from its local DuckDB through its own BaselineProvider, a single-pass aggregate over the local file, and no walk note times that read near the 5 s bar. Lite is unchanged.

Tests

  • OverviewBaselineEntriesLiveTests, 8 live PostgreSQL facts on fixed clocks with no waits. The writer writes each missing entry once from 00:15 UTC, skips the written ones, gives a server with no rows in the last day no entry, and writes a later day after a gap. A tick on a clock the test moves stops at the budget and the next tick carries on. An entry whose compute ends the writer's store session fails alone, the three after it are written, and the next tick writes it. The Viewer draws the compute's band from the entry, and still does once the raw rows are deleted. The Viewer computes with no entry, on a V333 store (the gate reads 333 and the table is never read), and for an entry of another key day, another window or an unknown compute version. The retention sweep keeps two key days.
  • ViewerSchemaVersionGateTests pin the V334 rung and move the V333 pins down one.
  • Gate on Linux at e9318a6 (the head after it changes one doc comment): every test class in the 294 test files a git grep of the touched symbols names, built in a Linux harness and run once. 3,343 tests ran, 18 skipped (environment or DPAPI gated). 273 of the 294 files ran tests. The other 21 do not build on Linux: 12 use helpers or fixtures outside the harness and the rest need those. OverviewBaselineEntriesLiveTests 8 of 8, ViewerSchemaVersionGateTests 34, MigrationProbeLadderTests 196, DarlingRetentionTests 56, StoreSelfMetricsTests 44 and StoreSessionNamesTests 4 are green.
  • 55 failed, none of them head only. 45 are WPF tests that cannot load WindowsBase, PresentationCore or PresentationFramework on Linux, so those Viewer tests need Windows. 3 classes pass alone at the head (cluster roles left by parallel role tests). The other 7 tests in 4 classes fail the same way at dev 35b9118 on the same box.
  • Red proof: with the window check taken out of the stored read (|| reader.GetDateTime(1) != AsNaive(windowStart), 1 match), OverviewBaselineEntriesLiveTests ran 8 with 1 failed, AnEntryWhoseKeyWindowOrVersionDoesNotMatch_IsNotRead_AndTheViewerComputes: Expected 24, Actual 9999. Reverted to 0 changed files.

…st in the Viewer (#10435)

V334 adds collect.overview_baseline_entries. The hourly store-maintenance tick writes the day's missing entries from 00:15 UTC within a 60 s budget, reopening its connection after a failed entry. The Viewer reads the entry for today's key first and computes as before when there is none, when the store is older than V334, or when the entry's window or compute version does not match. Retention keeps two key days.
claude[bot]
claude Bot previously requested changes Dec 4, 2026

@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: CHANGES REQUESTED

Claims

  • VERIFIED — V334 adds collect.overview_baseline_entries, PK (server_id, metric_name, key_day), 193 tier rows as parallel arrays, window start, clock and compute_version — OverviewBaselineEntries.cs CreateSql; 193 asserted by TheWriter_WritesEachMissingEntryOnce_FromTheMargin_AndSkipsWhatIsWritten
  • VERIFIED — the writer is a new hourly-tick tenant after the pg_io_stats hourly rollup — DarlingWorker.Passes.cs:1224-1226
  • VERIFIED — from 00:15 UTC it writes the missing entries, I/O lane then CPU, for servers with rows in the last day, and skips written ones — OverviewBaselineWriter.cs:66, Lanes, :79-90
  • VERIFIED — the compute goes through the provider's existing single flight and shared tier — PgBaselineProvider.ComputeEntryToStoreAsync → GetSharedEntryAsync
  • VERIFIED — the reader falls back to the compute when there is no entry, the store is below V334 (schema gate, not a caught error), or the window or version does not match — PgBaselineProvider.cs:621, ViewerDataService.OverviewLanes.cs:255-257
  • VERIFIED — retention keeps two key days in one statement — DarlingRetention.cs:1343-1348, OverviewBaselineEntries.PruneSql
  • VERIFIED — the store probe gains the V334 sentinel and arm — ViewerDataService.cs probe line and arm at :2016-2020; 310 GetBoolean reads for 310 parameters
  • VERIFIED — the wait and blocking lanes stay computed — StoredOverviewMetrics = [IoLatencyChart, Cpu] gate in ReadStoredEntryAsync
  • VERIFIED — the web Overview's read is unchanged — GetBaselineStepsSharedAsync body untouched; the only other provider change is the TierFor extraction
  • VERIFIED — the 60 s budget and the compute's 90 s limit — OverviewBaselineWriter.TickBudget; SharedComputeTimeout = AnalysisCommandTimeoutSeconds (60) + 30
  • VERIFIED — a failed entry reopens the connection and the later entries still run — OverviewBaselineWriter.cs:116-126; AnEntryThatBreaksTheConnection_FailsAlone_AndTheNextTickWritesIt
  • VERIFIED — Lite is unchanged — no Lite file in gh pr diff --name-only
  • VERIFIED — OverviewBaselineEntriesLiveTests has 8 live facts — 8 [Fact] in the file
  • VERIFIED — the window-check red proof targets a test that asserts it — AnEntryWhoseKeyWindowOrVersionDoesNotMatch_IsNotRead_AndTheViewerComputes shifts window_start and expects the computed band, not 9999
  • UNVERIFIED — lab rig timings (3.3 ms / 736.2 ms, 7.37e-15 worst difference, 58 KB WAL per entry, 17 MB at 300 servers) — need the 28.3M-row rig
  • UNVERIFIED — field timings (42 servers, 2.95 s / 1.55 s / 0.37 s, ~86 s a day) — need the field store
  • UNVERIFIED — the Linux gate run (3,343 ran, 55 failures none head-only) — needs a build and test run
  • REFUTED — "8 live PostgreSQL facts on fixed clocks" — TheRetentionSweep_DropsKeyDaysPastTwoDays_AndKeepsTheRecentOnes seeds from DateTime.UtcNow.Date (OverviewBaselineEntriesLiveTests.cs:288), and its own summary says "It runs on the real clock"

Riskiest lines

  1. Darling/PerformanceMonitor.Darling.Analysis/PgBaselineProvider.cs:621 — the gate that decides whether a stored row stands in for the compute — covered by AnEntryWhoseKeyWindowOrVersionDoesNotMatch_IsNotRead_AndTheViewerComputes and TheViewer_DrawsTheComputesBand_FromTheEntry
  2. Darling/PerformanceMonitor.Darling.Service/OverviewBaselineWriter.cs:107 — a null or faulted compute must not be stored — UNCOVERED (no test hands the writer a null or Faulted entry; the reopen path at :122 is covered by AnEntryThatBreaksTheConnection_FailsAlone_AndTheNextTickWritesIt)
  3. Darling/PerformanceMonitor.Darling.Service/DarlingRetention.cs:1346 — the prune cutoff — covered by TheRetentionSweep_DropsKeyDaysPastTwoDays_AndKeepsTheRecentOnes, which can flake across UTC midnight (see traps)

Traps near this diff

  • "A live test that seeds at the wall clock (DateTime.UtcNow, SQL now()) and asserts an hour or day bucket splits its seed across two buckets when a run starts near the boundary, and fails only on the pull request that happens to run then (#10403)." — applies — OverviewBaselineEntriesLiveTests.cs:288 seeds from DateTime.UtcNow.Date; the sweep reads its own clock at DarlingRetention.cs:516. If midnight falls between those two reads, the cutoff (:1346) deletes the today-1 row and the test sees 1 row, not 2. Inline comment posted.
  • "A test that reads the clock twice measures the CI scheduler" (#3676) — applies — the same test: the seed and the sweep each read the wall clock, so no single anchor owns both ends of the interval.
  • "Lite and Darling ship in parity (CONTRIBUTING's two-store rule)" — does not apply — this is a Darling store and Viewer read-path optimization over a service-written table. Lite has no service/Viewer store split; it computes bands in-process from DuckDB. No reader, tool, alert or description changes (PgBaselineProvider.cs web path unchanged).
  • "A retention-tiered store answers a 7-day question from a 4-day raw tier…" (#3590) — does not apply — the reader uses only today's key day, and rows outside it are rejected by key and window (PgBaselineProvider.cs:607-621).
  • "Two copies of one definition pinned EQUAL to each other fail only after BOTH have drifted (#3684). Alias, do not copy." — does not apply — the tier rule moved into one TierFor (PgBaselineProvider.cs:682-685) used by both the compute and the stored read, and OverviewBaselineEntries.Version is the single number the migration, StorageVersion and the probe arm read.

Divergence (blind read vs PR body)

  • The body says all 8 live facts run "on fixed clocks with no waits". One of them, the retention sweep, runs on the wall clock and carries a midnight race (trap #10403).
  • The body doesn't mention that the writer stores the service's shared-cache entry. If the web Overview or the analysis pass computed today's key before 00:15, that earlier entry is what gets stored, so WriteMargin's stated purpose (the collection lag has passed) is not guaranteed (OverviewBaselineWriter.cs:66, DarlingWorker.Passes.cs:1351). This is non-blocking because it is the same answer the service already serves.
  • The window check is described as rejecting an entry whose window "is not the one a compute at that key would use". The writer always writes keyDay - 30 whatever the compute read (OverviewBaselineWriter.cs UpsertAsync). That is correct for Cpu/IoLatencyChart because ClampToPlainViewPurgeHorizonAsync clamps only event metrics, but in practice the check guards a BaselineWindowDays change or a hand-edited row, not the compute's actual window.

Reviewer checklist

  • Run OverviewBaselineEntriesLiveTests and the WPF Viewer tests on Windows; the gate run excluded 45 WPF tests.
  • On a live service, confirm the 00:15+ tick writes entries for all candidate servers within the expected number of ticks, and that the hourly tick's later tenants are not delayed beyond about 150 s.
  • Open a server tab in the Viewer on a migrated store and confirm the CPU/I/O band timings drop to the PK read.

@erikdarlingdata

Copy link
Copy Markdown
Owner Author

One small follow-up in OverviewBaselineWriter.cs (in addition to the bot review's midnight-race item): RunTickAsync ignores the false return value of TimescaleSupport.ReopenBrokenConnectionAsync, so a failed reopen keeps looping through the rest of pending instead of stopping the tick.

Verified in code

  • Darling/PerformanceMonitor.Darling.Storage/TimescaleSupport.cs:2461-2492: ReopenBrokenConnectionAsync returns Task<bool> (false when the connection stays broken and cannot be reopened) so the caller can stop the pass rather than repeating the same failure on every later item.
  • Darling/PerformanceMonitor.Darling.Service/OverviewBaselineWriter.cs:96-127: the catch block awaits TimescaleSupport.ReopenBrokenConnectionAsync(...) at line 122 and discards its return value.

Concrete trigger and result

  1. The store restarts, drops connections, or hits max_connections during the daily 00:15+ tick after OverviewBaselineWriter opens its pass connection.
  2. An upsert fails on the broken connection and ReopenBrokenConnectionAsync logs "the store connection is closed and could not be reopened..." and returns false.
  3. Because the loop continues until TickBudget (60 s) expires, each later (serverId, metric) in pending still calls compute(...) (which hits _baselineCache or opens its own pool connection for a 30-day aggregate up to 90 s). Any entry that returns from _baselineCache or after a brief blip then fails in UpsertAsync with "Connection is not open", logging two more warnings per entry and counting every remaining entry under Failed instead of Deferred.

Fix (4 lines)

Stop the loop when reopen returns false, advancing next first so the failed entry is not counted in both Failed and Deferred:

if (!await TimescaleSupport.ReopenBrokenConnectionAsync(
        connection, logger, cancellationToken,
        "Overview baselines: the store connection is closed and could not be reopened, so the rest of this tick is deferred; the next tick tries again: {Message}"))
{
    next++;
    break;
}

@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 new commits list collect.overview_baseline_entries in the store table inventory — the one-line hunk in docs/darling/store-tables.csv:74 matches the CSV header and column format (relation,kind,export,note). The table name matches Darling/PerformanceMonitor.Darling.Storage/OverviewBaselineEntries.cs and PgMigrations.cs.

Riskiest lines

  1. docs/darling/store-tables.csv:74 — the kind and export values (derived,derived) were chosen by hand. They match the neighbouring derived tables. — UNCOVERED (docs-only change, no behaviour)
  2. docs/darling/store-tables.csv:74 — sort order, placed between oversized_plan_backlog_drops and perfmon_interval_baseline. It is alphabetical. — UNCOVERED (docs-only change)
  3. docs/darling/store-tables.csv:74 — the note text has no commas, so the CSV stays valid. — UNCOVERED (docs-only change)

Traps near this diff

  • No trap applies: the range changes only a documentation CSV and no code, SQL or behaviour. I did not open .github/REVIEW-TRAPS.md for this range.

Divergence (blind read vs PR body)

None — the range is a single CSV row and I did not compare it against the PR body.

Reviewer checklist

  • Confirm that no test parses store-tables.csv and expects a different export value for this table.

@github-actions
github-actions Bot dismissed claude[bot]’s stale review December 4, 2026 11:16

Superseded by claude[bot]'s LGTM on 6d41ba7: #10441 (review)

…nd say the stored entry is the shared cached answer (#10435)
…analysis command deadline, not Npgsql's 30 s default (#10435)
@erikdarlingdata
erikdarlingdata merged commit 7ca4981 into dev Dec 4, 2026
34 checks passed
@erikdarlingdata
erikdarlingdata deleted the fix/10435-stored-overview-baseline branch December 4, 2026 12:06
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