From a6ea35a0558f6c233921accd5652e51a328d149d Mon Sep 17 00:00:00 2001 From: Sami Imseih Date: Thu, 3 Dec 2026 22:39:23 +0000 Subject: [PATCH v25 6/6] pgstat: Flush pending stats at statement boundaries within a transaction Pending stats are flushed only when a backend goes idle outside a transaction, so the activity of a long-running transaction is not visible until it ends. With this change, the stats that don't depend on the outcome of the transaction are also flushed while it is in progress, when a statement completes or while the session is idle in the transaction. This uses the same timing as the flush at transaction boundaries. A flush at a statement boundary happens at most once per PGSTAT_MIN_INTERVAL (1s). When one is skipped, the same idle stats update timeout used outside of transactions is armed with PGSTAT_IDLE_INTERVAL (10s), if not already active, so the stats are flushed even if the session stays idle, without starting and canceling a timer at every statement. The 1s throttle at statement boundaries only needs the elapsed time, so it uses instr_time, which since 294520c4448 reads the TSC where available and is cheap enough to check at every statement boundary. The automatic flush doesn't wait for locks, so it can't delay the response to a statement. The idle timeout is handled for an open transaction in ProcessClientReadInterrupt(), outside catchup and notify processing; aborted transactions are skipped. A new GUC, stats_flush_in_transaction, on by default, turns this off for users who don't want stats flushed within transactions. This only covers regular backends. Logical replication apply workers are unchanged and, as before, report stats from their own loop outside of transactions. Add a test that uses an injection point to shorten the idle wait, and checks that stats are flushed while a session is idle in a transaction. Author: Sami Imseih --- doc/src/sgml/config.sgml | 24 +++++++ doc/src/sgml/monitoring.sgml | 15 +++-- src/backend/tcop/postgres.c | 45 +++++++++++++ src/backend/utils/activity/pgstat.c | 64 ++++++++++++++++++- src/backend/utils/misc/guc_parameters.dat | 6 ++ src/backend/utils/misc/postgresql.conf.sample | 1 + src/include/pgstat.h | 2 + src/test/modules/test_misc/meson.build | 1 + .../test_misc/t/018_in_transaction_stats.pl | 51 +++++++++++++++ 9 files changed, 202 insertions(+), 7 deletions(-) create mode 100644 src/test/modules/test_misc/t/018_in_transaction_stats.pl diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index a4b38a2876a..a642701e51a 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -9362,6 +9362,30 @@ COPY postgres_log FROM '/full/path/to/logfile.csv' WITH csv; + + stats_flush_in_transaction (boolean) + + stats_flush_in_transaction configuration parameter + + + + + Enables flushing pending statistics within a transaction. When on, + statistics that do not depend on the outcome of the transaction, such + as scan counts, are flushed when a statement completes, but not more + frequently than once per second, and within about 10 seconds while the + session is idle in the transaction. The other statistics are flushed + when the transaction ends. These flushes do not wait for locks held by + other processes; anything they cannot flush is flushed later. + This applies to regular backends only; logical replication apply + workers flush their statistics only outside of transactions. + This parameter is on by default. + Only superusers and users with the appropriate SET + privilege can change this setting. + + + + diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 79fa8147d66..986a059e521 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -237,10 +237,14 @@ postgres 27093 0.0 0.0 30096 2752 ? Ss 11:34 0:00 postgres: ser update instantaneously. Each individual server process flushes out accumulated statistics to shared memory just before going idle, but not more frequently than once per PGSTAT_MIN_INTERVAL - milliseconds (1 second unless altered while building the server); so a - query or transaction still in progress does not affect the displayed totals - and the displayed information lags behind actual activity, unless the process - is asked to flush its pending statistics by calling + milliseconds (1 second unless altered while building the server). Unless + is off, statistics that do + not depend on the outcome of a transaction, such as scan counts, are also + flushed while the transaction is in progress, when a statement completes or + while the session is idle in it. So a query still in progress does not + affect the displayed totals, a transaction still in progress affects them + only partially, and the displayed information lags behind actual activity, + unless the process is asked to flush its pending statistics by calling pg_stat_force_next_flush. However, current-query information collected by track_activities is always up-to-date. @@ -5979,7 +5983,8 @@ description | Waiting for a newly initialized WAL file to reach durable storage deletes, are flushed when the top-level transaction ends, or right away for rolled-back subtransactions. This is useful in tests, and to make the statistics of a long-running transaction visible before - it ends. + it ends, without waiting for the next automatic flush (see + ). diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index 1361dfa5526..1a2ef01d3ff 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -529,6 +529,18 @@ ProcessClientReadInterrupt(bool blocked) if (notifyInterruptPending) ProcessNotifyInterrupt(true); + /* + * ProcessInterrupts() only reports stats when completely out of a + * transaction. Within an open, non-aborted one, handle the idle + * stats update timeout here, outside catchup and notify processing. + */ + if (pgstat_flush_in_transaction && + IdleStatsUpdateTimeoutPending && IsTransactionState()) + { + IdleStatsUpdateTimeoutPending = false; + (void) pgstat_report_stat_in_xact(true); + } + /* * Processing a catchup or notify interrupt can run a transaction. If * the idle stats update timeout fired while we were in it, @@ -4775,6 +4787,39 @@ PostgresMain(const char *dbname, const char *username) } else if (IsTransactionOrTransactionBlock()) { + if (pgstat_flush_in_transaction) + { + long stats_timeout; + bool stats_force = IdleStatsUpdateTimeoutPending; + + /* + * Flush stats that needn't wait for the transaction to + * end, right away if the idle stats update timeout + * already fired. As below, arm the timeout if it's too + * soon, so that they're flushed if we stay idle, and + * disarm it after a flush. + */ + IdleStatsUpdateTimeoutPending = false; + stats_timeout = pgstat_report_stat_in_xact(stats_force); + if (stats_timeout > 0) + { +#ifdef USE_INJECTION_POINTS + /* allow tests to shorten the wait */ + if (IS_INJECTION_POINT_ATTACHED("in-transaction-stats-short-interval")) + stats_timeout = 1000; +#endif + if (!get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT)) + enable_timeout_after(IDLE_STATS_UPDATE_TIMEOUT, + stats_timeout); + } + else + { + /* flushed, no need for the timeout */ + if (get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT)) + disable_timeout(IDLE_STATS_UPDATE_TIMEOUT, false); + } + } + set_ps_display("idle in transaction"); pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL); diff --git a/src/backend/utils/activity/pgstat.c b/src/backend/utils/activity/pgstat.c index 602c2877e34..908032ac8ca 100644 --- a/src/backend/utils/activity/pgstat.c +++ b/src/backend/utils/activity/pgstat.c @@ -105,6 +105,7 @@ #include "access/xact.h" #include "lib/dshash.h" +#include "miscadmin.h" #include "pgstat.h" #include "storage/fd.h" #include "storage/ipc.h" @@ -204,6 +205,7 @@ static inline bool pgstat_is_kind_valid(PgStat_Kind kind); bool pgstat_track_counts = false; int pgstat_fetch_consistency = PGSTAT_FETCH_CONSISTENCY_CACHE; +bool pgstat_flush_in_transaction = true; /* ---------- @@ -250,6 +252,12 @@ static dlist_head pgStatPending = DLIST_STATIC_INIT(pgStatPending); */ static bool pgStatForceNextFlush = false; +/* + * Time of the last flush within a transaction, or of backend start, for + * pgstat_report_stat_in_xact(). + */ +static instr_time pgStatLastInXactFlush; + /* Set while pgstat_report_stat() flushes pending entries. */ static bool pgStatFlushInProgress = false; @@ -728,6 +736,9 @@ pgstat_initialize(void) kind_info->init_backend_cb(); } + /* Start the interval for flushes within a transaction */ + INSTR_TIME_SET_CURRENT_FAST(pgStatLastInXactFlush); + /* Set up a process-exit hook to clean up */ before_shmem_exit(pgstat_shutdown_hook, 0); @@ -889,7 +900,12 @@ pgstat_report_stat_internal(bool force, bool nowait) } PG_END_TRY(); - last_flush = now; + /* + * In-transaction flushes don't advance last_flush or pending_since, so + * that they don't delay the flush at transaction end. + */ + if (IsCompletelyOutOfTransaction()) + last_flush = now; /* Let the caller know when to retry after a partial flush. */ if (partial_flush) @@ -898,7 +914,7 @@ pgstat_report_stat_internal(bool force, bool nowait) Assert(!force || !IsCompletelyOutOfTransaction()); /* remember since when stats have been pending */ - if (pending_since == 0) + if (pending_since == 0 && IsCompletelyOutOfTransaction()) pending_since = now; return PGSTAT_IDLE_INTERVAL; @@ -910,6 +926,50 @@ pgstat_report_stat_internal(bool force, bool nowait) return 0; } +/* + * Flush the pending stats that needn't wait for the current transaction to + * end, at most once per PGSTAT_MIN_INTERVAL unless forced. Called at + * statement boundaries within a transaction, and forced when the idle stats + * update timeout fires while idle in one. Like pgstat_report_stat(), returns + * PGSTAT_IDLE_INTERVAL if it's too soon, so the caller can arm that timeout. + * + * Only elapsed time is needed, so use instr_time rather than + * GetCurrentTimestamp(). The flush doesn't wait for locks, so it can't delay + * the response to the statement, and holds off cancel interrupts, so a cancel + * can't abort the idle transaction. + */ +long +pgstat_report_stat_in_xact(bool force) +{ + instr_time now; + instr_time elapsed; + + if (!pgstat_flush_in_transaction) + return 0; + + INSTR_TIME_SET_CURRENT_FAST(now); + elapsed = now; + INSTR_TIME_SUBTRACT(elapsed, pgStatLastInXactFlush); + + /* a negative interval means timing_clock_source changed; restart */ + if (INSTR_TIME_GET_NANOSEC(elapsed) < 0) + { + pgStatLastInXactFlush = now; + return PGSTAT_IDLE_INTERVAL; + } + + if (!force && INSTR_TIME_GET_MILLISEC(elapsed) < PGSTAT_MIN_INTERVAL) + return PGSTAT_IDLE_INTERVAL; + + pgStatLastInXactFlush = now; + + HOLD_CANCEL_INTERRUPTS(); + (void) pgstat_report_stat_internal(true, true); + RESUME_CANCEL_INTERRUPTS(); + + return 0; +} + /* * Force locally pending stats to be flushed. During a transaction this * flushes immediately, and the next pgstat_report_stat() call is forced too. diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat index 8a8f1cca097..90da6950a92 100644 --- a/src/backend/utils/misc/guc_parameters.dat +++ b/src/backend/utils/misc/guc_parameters.dat @@ -2932,6 +2932,12 @@ assign_hook => 'assign_stats_fetch_consistency', }, +{ name => 'stats_flush_in_transaction', type => 'bool', context => 'PGC_SUSET', group => 'STATS_CUMULATIVE', + short_desc => 'Flushes pending statistics within a transaction.', + variable => 'pgstat_flush_in_transaction', + boot_val => 'true', +}, + { name => 'subtransaction_buffers', type => 'int', context => 'PGC_POSTMASTER', group => 'RESOURCES_MEM', short_desc => 'Sets the size of the dedicated buffer pool used for the subtransaction cache.', long_desc => '0 means use a fraction of "shared_buffers".', diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample index b492b3af06c..3fd6df2c386 100644 --- a/src/backend/utils/misc/postgresql.conf.sample +++ b/src/backend/utils/misc/postgresql.conf.sample @@ -710,6 +710,7 @@ #track_wal_io_timing = off #track_functions = none # none, pl, all #stats_fetch_consistency = cache # cache, none, snapshot +#stats_flush_in_transaction = on # - Monitoring - diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 4f6f095e911..b10c7df9071 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -680,6 +680,7 @@ extern void pgstat_initialize(void); /* Functions called from backends */ extern long pgstat_report_stat(bool force); +extern long pgstat_report_stat_in_xact(bool force); extern void pgstat_force_next_flush(void); extern void pgstat_reset_counters(void); @@ -1007,6 +1008,7 @@ extern PgStat_WalStats *pgstat_fetch_stat_wal(void); extern PGDLLIMPORT bool pgstat_track_counts; extern PGDLLIMPORT int pgstat_track_functions; extern PGDLLIMPORT int pgstat_fetch_consistency; +extern PGDLLIMPORT bool pgstat_flush_in_transaction; /* diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index ba6f17b7ca8..6af3b81ad07 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -26,6 +26,7 @@ tests += { 't/015_temp_schema_exit_deferrable.pl', 't/016_heap_scan_stream.pl', 't/017_toast_oid_reuse.pl', + 't/018_in_transaction_stats.pl', ], # The injection points are cluster-wide, so disable installcheck 'runningcheck': false, diff --git a/src/test/modules/test_misc/t/018_in_transaction_stats.pl b/src/test/modules/test_misc/t/018_in_transaction_stats.pl new file mode 100644 index 00000000000..98008d494f8 --- /dev/null +++ b/src/test/modules/test_misc/t/018_in_transaction_stats.pl @@ -0,0 +1,51 @@ + +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Test that stats are flushed automatically while a session is idle in a +# transaction. An injection point shortens the wait from +# PGSTAT_IDLE_INTERVAL (10s) to 1s. + +use strict; +use warnings FATAL => 'all'; + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +plan skip_all => 'Injection points not supported by this build' + unless $ENV{enable_injection_points} eq 'yes'; + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', 'stats_fetch_consistency = none'); +$node->start; + +if (!$node->check_extension('injection_points')) +{ + plan skip_all => 'Extension injection_points not installed'; +} + +$node->safe_psql('postgres', 'CREATE EXTENSION injection_points;'); +$node->safe_psql('postgres', + "SELECT injection_points_attach('in-transaction-stats-short-interval', 'error');" +); +$node->safe_psql('postgres', + 'CREATE TABLE test_intxn(a int) WITH (autovacuum_enabled = off);'); +$node->safe_psql('postgres', + 'INSERT INTO test_intxn SELECT generate_series(1, 100);'); +$node->safe_psql('postgres', 'SELECT pg_stat_force_next_flush();'); + +my $seq_scan = q{SELECT seq_scan FROM pg_stat_user_tables + WHERE relname = 'test_intxn'}; +my $before = $node->safe_psql('postgres', $seq_scan); + +# Scan the table, then leave the session idle in the transaction. The scan +# must become visible to other sessions before the transaction ends. +my $session = $node->background_psql('postgres'); +$session->query_safe('BEGIN;'); +$session->query_safe('SELECT count(*) FROM test_intxn;'); +ok($node->poll_query_until('postgres', $seq_scan, $before + 1), + 'stats flushed while idle in transaction'); +$session->quit; + +done_testing(); -- 2.50.1