Add Active Session History endpoints to Database Diagnostics
What does this MR do and why?
This is the first step of the Active Session History (ASH) web UI from work item 608101. Admins and Support want to look back at what the main database was doing: what it waited on, which queries caused it, and when.
This MR adds the data for that as three admin-only JSON endpoints on the Database Diagnostics page:
- Summary: load per wait event type and the top queries for a time range of 61 minutes up to 24 hours.
- Queries behind a wait event type: for a slice of up to 5 minutes.
- Session timeline: load per minute, for all wait event types or for one.
Each response says whether pg_ash is installed, whether its version is the one GitLab vendors, and which time range it covers, so the UI can show the right empty states and keep follow-up reads on the same range. The tab in MR 262713 uses the summary, and the database load chart in MR 262859 uses the timeline and the queries behind a wait event type.
Decisions
- Controller JSON, not GraphQL. The other sections on this page (the collation, schema and LFK checks, most recently MR 246223) use controller JSON with axios. This follows the page.
- No feature flag. The endpoints are admin-only. There is nothing to show unless pg_ash is installed and sampling is turned on, and sampling is off by default.
- Summary and timeline read pg_ash's minute rollups. An hour of raw samples took 3.3-3.8 s locally with about 38 active sessions. The same read from rollups takes about 6 ms, with the same totals and peaks. pg_ash only uses rollups for ranges longer than an hour that are already rolled up. So a range that ends after the last rolled-up minute ends there, and a shorter range starts earlier so that it is 61 minutes long. This lets the page ask for "the last 6 hours" without knowing where the rollups end. The data is a minute or two behind. Until the Sidekiq rollup job has run once, there are no rollups, so pg_ash reads raw samples instead, under the same time budget.
- Queries behind a wait event type use 5-minute slices. Rollups don't keep which query waited on what, so this always reads raw samples, and the cost grows with the range. 5 busy minutes took 0.23-0.67 s locally at 25-1,000 active sessions.
- Main database only, where pg_ash is installed. pg_ash samples the whole server, so every read filters to the current database.
- Reads run on the primary and share a 4.5 s budget, and all three actions have
urgency :low, as other admin database pages such as background migrations do. Each statement's timeout is what is left of the budget, so a request takes at most about 4.5 s plus the one-row watermark read. Full query text comes from the primary'spg_stat_statements, because pg_ash keeps only the first 100 characters. A failedpg_stat_statementsread only drops the text, and is tracked. Withpg_stat_statementsfull at its default 5,000 entries, the text read took 4-7 ms locally with 11 MB of query text, and 10-12 ms with 46 MB. - Query text shows for queries, transaction commands, and schema changes or maintenance that can hold heavy locks, such as
ALTER TABLE,CREATE INDEX,VACUUM, andCOPYto or from the client without options, with every value and comment replaced.pg_stat_statementskeeps many statements as typed, such asALTER ROLE ... PASSWORDandCOPY ... FROM PROGRAM, so every other statement type shows only its query ID.QueryTextRedactortakes the statement type from PostgreSQL's parser and replaces values and comments with its scanner, throughpg_query, so every quoting form is handled as PostgreSQL reads it. Text with a backslash shows only its query ID, because withstandard_conforming_stringsoff a backslash changes where a string ends. Names, such as tables and columns, show as written. Schema changes show because queries waiting for a table lock have no query ID yet, so in a lock pile-up the schema change is often the only named row. Its text appears once the same statement has finished, also for the minutes it spent waiting, because the page looks text up by query ID.
Database review
Each read runs on the primary with SET LOCAL statement_timeout set to what is left of a 4.5 s budget, and filters to the current database.
SQL
-- Newest rolled-up minute (every overview request)
SELECT ash.ts_to_timestamptz(last_rollup_1m_ts) AS watermark FROM ash.config WHERE singleton;
-- Summary: wait event types (n => 20) and top queries (n => 10)
SELECT key, source, period_start, period_end, avg_aas, peak_aas, p99_aas, pct
FROM ash.top('wait_event_type', since => $from::timestamptz, until => $to::timestamptz, database => current_database(), n => 20);
SELECT key, avg_aas, peak_aas, p99_aas, pct
FROM ash.top('query_id', since => $from::timestamptz, until => $to::timestamptz, database => current_database(), n => 10);
-- Timeline, one row per minute, optionally for one wait event type
SELECT bucket_start, source, avg_aas, peak_aas, p99_aas
FROM ash.timeline(since => $from::timestamptz, until => $to::timestamptz, bucket => interval '1 minute', wait_event_type => $type, database => current_database());
-- Queries behind a wait event type, 1 to 5 minutes of raw samples
SELECT key, avg_aas, peak_aas, p99_aas, pct
FROM ash.top('query_id', since => $from::timestamptz, until => $to::timestamptz, wait_event_type => $type, database => current_database(), n => 10);
-- Query text for the returned IDs
SELECT namespace.nspname AS schema FROM pg_extension extension
JOIN pg_namespace namespace ON namespace.oid = extension.extnamespace WHERE extension.extname = 'pg_stat_statements';
SELECT queryid::text AS query_id, query FROM "public".pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND queryid = ANY(ARRAY[$ids]::bigint[]);| Read, measured on GDK with production-sized data | Time |
|---|---|
| Wait event types, 24 h (300 active sessions every minute) | 26 ms |
| Top queries, 24 h (100 queries per minute) | 282 ms |
| Timeline for one wait event type, 24 h | 5-6 ms |
| Queries behind a wait event type, 5 min, 25-1,000 active sessions | 0.23-0.67 s (up to 1.9 s with a generic plan) |
GitLab.com's busiest main node peaked at 717 active sessions over the last 7 days.
Two reads take longer than the 100 ms guideline. Both run inside pg_ash's vendored functions, so there is no index or query on our side to change:
- Top queries for 24 hours aggregate 144,000 query-minute pairs from the minute rollups.
- The raw read is dominated by a filter that calls
ash._active_slots_for_at()once per sample row. That is the upstream fix in the follow-ups.
Both are admin-only, run on demand, and are capped by the 4.5 s budget.
pg_ash is not installed on GitLab.com: a thin clone of the gprd main database has no ash schema. So the plans can't come from a thin clone, and come from local production-sized data instead.
Plans: ash_report_plans.txt has EXPLAIN (ANALYZE, BUFFERS) for each statement above on the same production-sized data, and the auto_explain plans of the statements inside pg_ash's functions.
Follow-ups
- The Active session history tab, with a time range picker: MR 262713.
- The database load chart, and the queries behind a wait event type for a point in it: MR 262859.
- Queries behind a wait event type over the whole range instead of 5-minute slices. This needs a performance fix in pg_ash upstream: a helper runs once per sample row. When it runs once per call instead, the queries behind a wait event type for a busy hour take about 0.12 s instead of about 3.4 s.
- A breakdown by individual wait event within a type.
- An Experiment badge and the testing agreement on the Active session history settings.
- The rake report (MR 254959) and the JSON export from the same work item are tracked separately.
References
- Work item: #608101
- Epic: gitlab-org#23091
- Rake report MR: !254959 (closed)
- Page precedent for controller JSON: !246223 (merged)
- Paired HTTP Router snapshot update: gitlab-org/cells/http-router!1453 (merged)
Screenshots or screen recordings
Not applicable. This MR has no UI, and the endpoints aren't linked from the page yet.
How to set up and validate locally
-
Install pg_ash:
bundle exec rake gitlab:db:pg_ash:install -
Go to Admin > Settings > Metrics and profiling > Active session history, select Turn on session sampling, and select Save changes.
-
Optional. To see query IDs and text, load
pg_stat_statements:- In
gdk psql, runALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';. - Run
gdk restart postgresql. - In
gdk psql, runCREATE EXTENSION IF NOT EXISTS pg_stat_statements;.
- In
-
Make the database busy for a minute. For example, run
SELECT pg_sleep(60);in two or threegdk psqlsessions. Then wait two minutes so the minute rollups catch up. -
Sign in as an administrator and open:
http://127.0.0.1:3000/admin/database_diagnostics/active_session_history.json. Thepg_sleepload shows as theTimeoutwait event type.http://127.0.0.1:3000/admin/database_diagnostics/active_session_history_queries.json?wait_event_type=Timeouthttp://127.0.0.1:3000/admin/database_diagnostics/active_session_history_timeline.json
-
Optional. Add
fromandto(ISO 8601) to pick a range. A range outside the limits returns400.
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.