Repository navigation
Conversation
lfittl
force-pushed
the
instrument-usage-stack-v19-alt
branch
5 times, most recently
from
November 7, 2026 17:56
70d02a3 to
ee81ba4
Compare
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
branch
7 times, most recently
from
November 7, 2026 19:11
1df32e4 to
e156778
Compare
This adds regression tests that cover some of the expected behaviour around the buffer statistics reported in EXPLAIN ANALYZE and pg_stat_statements, specifically how they behave in parallel query, nested function calls 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
lfittl
force-pushed
the
instrument-usage-stack-v19-alt
branch
from
November 7, 2026 19:21
e156778 to
50e9db5
Compare
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) and get added to their parent entry when they are finalized, i.e. no more modifications can occur. 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). At ExecutorFinish, each node is added directly to the query-level entry rather than rolled up through its parents, which 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. 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. 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. 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, whose base entry is what consumers such as pg_stat_statements and auto_explain read from, instead of to a plain Instrumentation. 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
Utility statements share many things with regular queries, but thus far there was no utility-statement equivalent of QueryDesc to hold common fields that matter for execution. Instead this information was passed down via an ever-growing list of arguments to ProcessUtility / ProcessUtility_hook. To enable a future change that will introduce another field, and to reduce future breakage of the hook API, introduce a dedicated utility statement descriptor (UtilityStmtDesc), and make it the single argument passed to ProcessUtility. Author: Lukas Fittl <lukas@fittl.com> Reviewed-by: Discussion:
…ements pg_stat_statements measures the time and buffer/WAL usage of a utility statement by wrapping the whole ProcessUtility hook chain in an Instrumentation entry of its own. Give utility statements the counterpart of what optimizable statements have in QueryDesc's query_instr_options and query_instr instead: a consumer ORs the InstrumentOption flags it wants into UtilityStmtDesc->instr_options before calling standard_ProcessUtility, which brackets the command's processing with the QueryInstrumentation entry embedded in the descriptor, and reads the entry afterwards. Like query_instr, the entry only describes the command's own processing in standard_ProcessUtility. What a ProcessUtility hook does before or after calling it is not included, and a hook that handles a command itself without calling standard_ProcessUtility, or passes it a different descriptor, leaves the entry empty, just as query_instr stays NULL when standard_ExecutorStart is not reached. With the instrumentation stack, the entry has to be finalized even when the command fails, so that the stack is unwound and what was measured reaches the enclosing entry. Unlike the executor's query entry it cannot rely on a resource owner or on transaction-lifetime memory, since a command may end the transaction while running (transaction control statements, CALL with COMMIT). Introduce InstrQueryInitLocal, which sets up a query entry in caller-provided memory that the caller finalizes itself, and have standard_ProcessUtility bracket the command with it under PG_FINALLY. Convert pg_stat_statements accordingly. Having the entry set up by core is what allows later commits to account the activity of statements and parallel workers run by a utility command to that command. 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 wraps its planner and utility statement timing in PG_TRY/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 BufferUsageAccumDiff, and update comments that referred to it. Extensions that read pgBufferUsage directly should use InstrStart and InstrStop around the code section they want to measure instead. 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. When a query entry is finalized, its worker part is passed on to the enclosing query entry only, never to a plan node, trigger 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, every entry now carries a kind, and query entries are always on the instrumentation stack while started, whatever options were requested, so that the innermost query entry on the stack is always the entry of the innermost enclosing statement for which instrumentation was requested. 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 are finalized right then, innermost first, so that what a failed nested statement did, including what its workers did, stays attributed to the statement that ran it rather than to whatever entry the resource owner cleanup happens to release last. The totals a worker reports now cover everything it did: the worker rolls its plan nodes up into its query entry like any query, instead of keeping them out of the totals so that the leader could import the per-node stats it retrieves for EXPLAIN separately. Those per-node copies are for display only, and the leader imports nothing from them. 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. EXPLAIN adds the worker part to a node's own counters at display time. 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 rolls up its plan nodes like any query and is finalized into 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 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
This sets up a separate instrumentation stack 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 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. 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 top level stack that is maintained as a running total. There is currently no in-core user that utilizes the top-level values in this manner, and especially during abort situations this helps ensure we don't lose activity due to incorrect handling of unfinalized node stacks.
lfittl
force-pushed
the
instrument-usage-stack-v19-alt
branch
from
November 7, 2026 19:38
50e9db5 to
fe7bbb6
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.