Repository navigation
Conversation
This replaces different repeated code blocks that read pgBufferUsage / pgWalUsage, and may have also been running a timer to measure activity, with the Instrumentation struct and associated helpers. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
…ith INSTR_* macros This encapsulates the ownership of these globals better, and will allow a subsequent refactoring. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Andres Freund <andres@anarazel.de> Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> Discussion: https://postgr.es/m/CAP53PkzZ3UotnRrrnXWAv%3DF4avRq9MQ8zU%2BbxoN9tpovEu6fGQ%40mail.gmail.com#fc7140e8af21e07a90a09d7e76b300c4
lfittl
force-pushed
the
instrument-usage-stack-v19-alt-alt-alt
branch
2 times, most recently
from
November 22, 2026 23:47
817d59f to
fbd604b
Compare
This adds regression tests that cover some of the expected behaviour around the buffer and WAL statistics reported in EXPLAIN ANALYZE, pg_stat_statements and the cumulative statistics, specifically how they behave in parallel query, nested function calls, cursors, procedures that commit, serialization and abort situations. Testing this is challenging because there can be different sources of buffer activity, so we rely on temporary tables where we can to prove that activity was captured and not lost. This supports a future commit that will rework some of the instrumentation logic that could cause areas covered by these tests to fail. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
So far the leader merged the per-node stats that parallel workers report through shared memory into its own plan node entries when retrieving them (InstrAggNode in ExecParallelRetrieveInstrumentation), so that EXPLAIN could print each node's entry as the combined picture, and only kept the per-worker copies around for the per-worker details. Instead, leave the leader's entries alone, so that they only ever describe the leader's own activity, and have EXPLAIN compute what it shows: one ExplainNodeUsage per plan node, with the leader's and the workers' stats combined, computed up front in ExplainPrintPlan since ExplainNode prints a node before recursing into its children. The per-worker details are taken from the per-worker copies as before. This prepares for a following commit that changes the executor to keep per-node buffer/WAL counters exclusive of child nodes, which will make EXPLAIN responsible for producing the inclusive numbers it shows, by propagating each node's usage to its parents here. This commit only changes how worker activity gets merged into the leader's stats; the per-node counters are still inclusive, and the numbers EXPLAIN prints do not change. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
Previously, in order to determine the buffer/WAL usage of a given code section, we utilized continuously incrementing global counters that get updated when the actual activity (e.g. shared block read) occurred, and then calculated a diff when the code section ended. This resulted in a bottleneck for executor node instrumentation specifically, with profiles showing BufferUsageAccumDiff in EXPLAIN (ANALYZE, BUFFERS) runs. Instead, introduce a stack-based mechanism, where the actual activity writes into the current stack entry. In the case of executor nodes, this means that each node gets its own stack entry that is pushed at InstrStartNode, and popped at InstrStopNode. Stack entries are zero initialized (avoiding the diff mechanism), so each one holds exactly the activity that happened while it was the current entry. How that activity reaches the enclosing entries depends on the kind of entry, see below. Per-node counters are thereby exclusive of child nodes: they only reflect activity that happened while the node itself was the current stack entry, which includes any statements the node ran (e.g. through a function). Node counters are never added to anything: the total of a statement is the query-level entry's own counters plus those of all its nodes, computed whenever the entry is stopped. This keeps the per-node counters identical for the leader and for parallel workers, whose per-node stats the preceding commit already keeps apart from the leader's own. Each time the query-level entry is stopped, e.g. after each fetch from a cursor, the difference between its total and what it passed on before goes to the stack entry that is current at that time, so that the activity of a fetch is attributed to the statement that ran it rather than to the one that closes the cursor. The abort cleanup does the same, so the normal and the abort path never count anything twice, whatever the order in which resource owners release their entries. EXPLAIN ANALYZE now also computes the inclusive per-node numbers it displays by summing each subtree at display time, on top of combining leader and workers there. Parallel workers measure their whole parallel section with a query-level entry, whose totals include their plan nodes, and the leader adds what its workers report to the query-level entry of the statement that launched them, or to the current stack entry if it has none. The per-node statistics the leader retrieves from its workers are for display only. Adding the workers' totals to the query-level entry rather than the current stack entry, which is the Gather node while workers are shut down, keeps them out of the Gather node's own counters, which EXPLAIN would otherwise show the workers' plan node activity in twice. Since subtrees are summed by plan structure rather than by what ran while a node was active, the buffer/WAL usage of an InitPlan, including the subplan of a CTE, is now included in the node it is shown under, i.e. the node it is attached to, and the nodes above it. It is no longer included in the node that ran it, i.e. the node that first needed the InitPlan's result or the CTE Scan reading from the CTE, nor in the nodes in between, even though their time still is. This keeps a single rule for what a node's numbers include, and keeps the usage of a CTE's subplan separate from that of the nodes reading from it, which tools could not tell apart before, e.g. to subtract the CTE's activity from the CTE Scans that read from it. The documentation of EXPLAIN's BUFFERS option now describes this. To correctly handle abort situations, any use of instrumentation stacks must involve either a top-level QueryInstrumentation struct, and its associated InstrQueryStart/InstrQueryStop helpers (which use resource owners to handle aborts), or the Instrumentation struct itself with dedicated PG_TRY/PG_FINALLY calls that ensure the stack is in a consistent state after an abort. Growing the stack is the only part of pushing an entry that can fail. As a query-level entry is registered with its resource owner before it is pushed, the abort handling must clean it up even if the push failed. An injection point in InstrStackGrow allows testing this, which a new test in the injection_points module does. In tests, the stack-based instrumentation mechanism reduces the overhead of EXPLAIN (ANALYZE, BUFFERS ON, TIMING OFF) for a large COUNT(*) query from about 35% to about 20% on top of the actual runtime. QueryDesc->query_instr now points to the statement's QueryInstrumentation instead of to a plain Instrumentation. Consumers such as pg_stat_statements read the statement's buffer/WAL totals through InstrTotalUsage, and its runtime from the base entry. Callers of the plain Instrumentation API (InstrAlloc/InstrInitOptions with InstrStart/InstrStop) keep measuring by snapshot-based diffing of the global pgBufferUsage/pgWalUsage counters for now. That handling lives only in InstrStart/InstrStop themselves: node instrumentation never measures that way, so InstrStartNode/InstrStopNode go through common helpers that handle just the timer and the stack, keeping the snapshot-based diffing out of the per-tuple ExecProcNodeInstr path, which would otherwise regress EXPLAIN (ANALYZE, TIMING OFF, BUFFERS OFF) slightly relative to master. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> (in an earlier version) Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi> (in an earlier version) Discussion: https://postgr.es/m/CAP53PkxrmpECzVFpeeEEHDGe6u625s%2BYkmVv5-gw3L_NDSfbiA%40mail.gmail.com#cb583a08e8e096aa1f093bb178906173
pg_stat_statements measures a utility statement by wrapping the rest of the ProcessUtility hook chain in a plain Instrumentation. Use a QueryInstrumentation entry instead, the counterpart of the query entry the executor sets up for optimizable statements. Later commits rely on such an entry being on the stack while the command runs, so that the activity of statements and parallel workers run by the command (e.g. a parallel CREATE INDEX) can be accounted to it. The entry for a utility statement cannot be managed like the executor's: the command may end the transaction while running (transaction control statements, CALL with COMMIT), and with it any resource owner and transaction-lifetime memory. Introduce InstrQueryInit, which sets up a query entry in caller-provided memory that is neither registered with a resource owner nor owns a memory context. The caller must finalize it with InstrQueryStopFinalize, including on error, so that the stack is unwound and what was measured reaches the enclosing entry. pg_stat_statements keeps the entry in its own stack frame and finalizes it under PG_FINALLY. Leaving the entry to the consumer, rather than having standard_ProcessUtility set it up, keeps the measurement covering the whole remainder of the hook chain: if another extension's hook executes a command itself instead of calling standard_ProcessUtility, that work is still accounted to the statement. It also leaves the ProcessUtility hook signature unchanged. Add a test that the activity of a cursor's query is attributed to the FETCH statements running it, as their utility entries are what is current when the cursor's query entry is stopped, rather than to the statement that closes the cursor. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
The stack-based instrumentation left the plain Instrumentation API (InstrAlloc/InstrInitOptions with InstrStart/InstrStop) measuring by snapshot-based diffing of the global pgBufferUsage/pgWalUsage counters, and kept pgBufferUsage updated alongside the stack for that purpose. Convert the remaining users of that API to the stack: VACUUM and ANALYZE logging as well as the planning-time measurement of EXPLAIN and EXECUTE use QueryInstrumentation, which handles aborts through the resource owner, while pg_stat_statements finalizes its planner timing entry in PG_FINALLY and the EXPLAIN (SERIALIZE) destination receiver registers its entry as a child of the query instrumentation. With that, Instrumentation entries always track WAL/buffer usage through the stack, so remove the snapshot-based diffing along with the global pgBufferUsage, and update comments that referred to it. Extensions that read pgBufferUsage directly should instead measure the code section with a QueryInstrumentation (InstrQueryAlloc, InstrQueryStart and InstrQueryStopFinalize, reading the totals with InstrTotalUsage), which the resource owner cleans up on abort, or with a plain Instrumentation that is started with InstrStart and finalized with InstrStopFinalize from a PG_FINALLY block, so that the instrumentation stack is unwound on error. The related global pgWalUsage is kept for now due to its use in pgstat to track aggregate WAL activity and heap_page_prune_and_freeze for measuring FPIs. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
…on totals Each parallel worker tracks its own buffer/WAL activity, reports it through shared memory when it finishes, and the leader then imported it into its own instrumentation stack. From there it propagated into the leader's session totals (instr_top) and, for WAL, into pgWalUsage. This double counts worker activity once the session totals are reported to the cumulative statistics system, since each worker reports its own activity there as well: parallel workers already double reported their WAL in pg_stat_wal for utility statements like parallel vacuum, and for queries that cause pruning or update hint bits in a parallel scan. To fix, never accumulate worker activity into the leader's own counters. Instead, QueryInstrumentation gets a separate worker part, which the leader imports worker usage into: the executor into the query entry of the statement that launched the workers, if it has one, and otherwise, like parallel index builds and parallel vacuum, into the innermost query entry on the stack (InstrQueryCurrent). That is the innermost enclosing statement for which instrumentation was requested, e.g. the top-level statement under pg_stat_statements with track = top when a nested parallel query or a CREATE INDEX run from a function launches the workers. The usage is added right away to the worker parts of all running query entries enclosing that one as well, never to a plan node or plain entry, which would carry it into instr_top, so the session totals only ever describe the process' own activity. Consumers that want the complete picture, such as pg_stat_statements, EXPLAIN, and VACUUM and ANALYZE's verbose output, add the two up with InstrTotalUsage(). To be able to find that entry from inside the executor or a utility command, query entries are now always on the instrumentation stack while running, whatever options were requested, and the running query entries form a chain: each one remembers the query entry that was innermost when it was started, and its own position on the stack, and the innermost one is tracked alongside the stack. That is always the entry of the innermost enclosing statement for which instrumentation was requested, found without having to tell the entries on the stack apart. Statements that nobody asked to instrument still get no entry: setting one up for every statement would cost a memory context and a resource owner registration per statement, which measurably slows down nested statements that pg_stat_statements does not track with track = top, and their activity reaches the enclosing statement's entry directly anyway. When an outer entry is finalized with inner query entries still on the stack (an error unwinding through nested statements), the inner entries, recognized through the chain, pass on what they have not passed on yet right then, innermost first, so that what a failed nested statement did stays attributed to the statement that ran it rather than to whatever entry the resource owner cleanup happens to release last. pg_stat_statements reads the totals of both the executor's query entry and the utility statement entry through InstrTotalUsage(), so that what the parallel workers of a query, a CREATE INDEX or a VACUUM did is included in its counters as before. Since the counters of plan node entries no longer receive worker usage, EXPLAIN would lose what the workers of a statement run by a function did from the plan: it used to show on the node that ran the function. To keep that, a plan node entry with buffer/WAL instrumentation gets a separate worker part of its own, for display only, which is never accumulated anywhere. When the usage of a statement without an entry of its own is imported, it is also added to the worker part of the plan node that is current on the stack, i.e. the node that ran the nested statement the workers belong to, which is the node that statement's own counters go to. Likewise, as worker usage is added to the running enclosing query entries, the entry right below each of them on the stack, i.e. what ran that statement, gets it in its worker part if it is such a plan node. EXPLAIN adds the worker part to a node's own counters at display time. As before, a query's own workers are not attributed to its Gather node: their activity shows on the nodes they ran, through the per-worker copies. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
For most queries, the bulk of the overhead of EXPLAIN ANALYZE happens in ExecProcNodeInstr when starting/stopping instrumentation for that node. Previously each ExecProcNodeInstr would check which instrumentation options are active in the InstrStartNode/InstrStopNode calls, and do the corresponding work (timers, instrumentation stack, etc.). These conditionals being checked for each tuple being emitted add up, and cause a non-optimal set of instructions to be generated by the compiler. Because we already have a mechanism to specify a function pointer when instrumentation is enabled, we can instead create specialized functions that are tailored to the instrumentation options enabled, and avoid conditionals on subsequent ExecProcNodeInstr calls. In a stress test with a large COUNT(*) that does many ExecProcNode calls, this roughly halves the overhead of EXPLAIN (ANALYZE, TIMING OFF, BUFFERS OFF), from ~13% on top of actual runtime to ~6%. When using BUFFERS ON the same query goes from ~20% to ~15% overhead. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
pg_stat_wal and the per-backend WAL statistics were computed from the backend-local counters in pgWalUsage, which the INSTR_WALUSAGE_* macros kept incrementing alongside the current instrumentation stack entry. With the stack-based instrumentation the session-level totals are available in instr_top, so derive them from there instead, and remove pgWalUsage, the last of the global usage counters. This also settles what these statistics describe. The session totals only ever contain the process' own activity: what a parallel query leader imports from its workers stays on the statement-level entries and never reaches instr_top, and each worker reports its own activity itself, which requires each worker's instr_top to be complete. It is: a worker's query entry includes its plan nodes in its total like any query, and passes that on to the worker's session totals, also in case of errors, through the abort handling. Deriving the WAL statistics from instr_top therefore guarantees that worker activity is counted exactly once, by construction rather than by every import site taking care not to touch pgWalUsage. instr_top is only updated when an instrumentation stack entry is stopped or finalized, but pgstat_report_stat() is only called between transactions, when a backend is idle or at process exit, and by auxiliary processes that have no stack entries. The stack is empty at the first two, but a FATAL error exits without unwinding the C stack and leaves entries behind, so finalize anything still on the stack before the final report (InstrStackFinalizeAll). Since the amounts are computed as a difference of the session totals since the previous report, these totals must never be reset. heap_page_prune_and_freeze() compared pgWalUsage.wal_fpi before and after pruning to tell whether an FPI was emitted; it now compares the counter of the current stack entry, which receives the same increments. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
pg_stat_database's blk_read_time and blk_write_time were accumulated in the backend-local counters pgStatBlockReadTime and pgStatBlockWriteTime, which pgstat_count_io_op_time() incremented alongside the equivalent fields of the current instrumentation stack entry. Like the WAL statistics in the preceding commit, derive them from the session totals in instr_top instead, so the separate counters are redundant. Remove the counters and the pgstat_count_buffer_read_time() and pgstat_count_buffer_write_time() macros, and instead have pgstat_update_dbstats() compute the increase of the shared and local block read/write times in instr_top since the previous report. This covers the same activity as before: relation and temp relation reads, writes and extends, but not temporary file I/O or WAL I/O. The same considerations as for the WAL statistics apply: instr_top is complete whenever pgstat_report_stat() runs, including at process exit after a FATAL error, parallel workers report their own activity themselves while the leader's totals never include what it imported from them, and since the amounts are computed as a difference of the session totals, these totals must never be reset. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
Trigger instrumentation so far only measured the time spent in a trigger and the number of times it fired. Buffer and WAL usage of a trigger was recorded in whichever instrumentation stack entry was current while the trigger ran, i.e. the ModifyTable node for BEFORE and INSTEAD OF triggers, and the query entry for AFTER triggers. Give triggers their own stack entry when buffer or WAL usage is requested, and show the usage of each trigger in EXPLAIN (ANALYZE), like the time spent in it. Like plan nodes, the trigger entries are registered with the query entry as its children, so their usage counts towards the totals of the statement, also if a firing is cut short by an error. Like plan nodes, they also keep a separate, display-only part for what parallel workers launched by statements the trigger ran did, which EXPLAIN adds to the trigger's numbers; that usage is only counted in the totals of the statement, through its worker part. The usage of BEFORE and INSTEAD OF triggers is thereby no longer included in the ModifyTable node that fired them, but only shown with the trigger, the same as for AFTER triggers. The time spent in BEFORE triggers is still included in the node, as before. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion:
This sets up a separate instrumentation stack entry that is used while an Index Scan fetches heap tuples, or an Index Only Scan checks the visibility map and fetches heap tuples for pages that are not all-visible. EXPLAIN ANALYZE will now show "Table Buffers" that represent such activity. The activity is also included in regular "Buffers" together with index activity and that of any child nodes. The EXPLAIN examples in perform.sgml that include index scans were regenerated to show the new "Table Buffers" line, so their other buffer counts changed as well. Author: Lukas Fittl <lukas@fittl.com> Suggested-by: Andres Freund <andres@anarazel.de> (in an earlier version) Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> (in an earlier version) Reviewed-by: Tomas Vondra <tomas@vondra.me> (in an earlier version) Discussion: https://postgr.es/m/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
This is intended for testing instrumentation related logic as it pertains to the session totals at the bottom of the instrumentation stack, which are maintained as a running total. The cumulative statistics system derives pg_stat_wal and the I/O timings in pg_stat_database from them, but only reports them in aggregate and with some delay. Exposing the totals directly allows checking that each statement's activity reaches them exactly once, especially in abort situations, where the activity of statements and their child entries that were cut short must not be lost.
lfittl
force-pushed
the
instrument-usage-stack-v19-alt-alt-alt
branch
from
November 23, 2026 05:39
fbd604b to
be85975
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.