From eafa50c04d47748f817aef190def2e1d49881a1d Mon Sep 17 00:00:00 2001 From: Sami Imseih Date: Thu, 3 Dec 2026 22:39:23 +0000 Subject: [PATCH 1/1] pgstat: Flush pending stats at statement boundaries within a transaction --- doc/src/sgml/config.sgml | 24 ++++++ doc/src/sgml/monitoring.sgml | 15 ++-- src/backend/tcop/postgres.c | 40 ++++++++++ src/backend/utils/activity/pgstat.c | 78 ++++++++++++++++++- src/backend/utils/misc/guc_parameters.dat | 6 ++ src/backend/utils/misc/postgresql.conf.sample | 1 + src/include/pgstat.h | 2 + 7 files changed, 157 insertions(+), 9 deletions(-) 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..40bb1c2f208 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,34 @@ 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) + { + 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 52a82c613ca..f6148c69d18 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" @@ -187,6 +188,7 @@ static void pgstat_init_snapshot_fixed(void); static void pgstat_reset_after_failure(void); +static long pgstat_report_stat_internal(bool force, bool nowait); static bool pgstat_flush_pending_entries(bool nowait); static void pgstat_prep_snapshot(void); @@ -203,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; /* ---------- @@ -249,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; @@ -727,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); @@ -763,12 +775,21 @@ pgstat_initialize(void) */ long pgstat_report_stat(bool force) +{ + return pgstat_report_stat_internal(force, false); +} + +/* + * Workhorse for pgstat_report_stat(). With nowait, don't wait for lock + * acquisition even when forced; entries that can't be locked stay pending. + */ +static long +pgstat_report_stat_internal(bool force, bool nowait) { static TimestampTz pending_since = 0; static TimestampTz last_flush = 0; bool partial_flush; TimestampTz now; - bool nowait; pgstat_assert_is_up(); @@ -839,7 +860,7 @@ pgstat_report_stat(bool force) pgstat_update_dbstats(now); /* don't wait for lock acquisition when !force */ - nowait = !force; + nowait = nowait || !force; partial_flush = false; @@ -875,7 +896,12 @@ pgstat_report_stat(bool force) } 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) @@ -884,7 +910,7 @@ pgstat_report_stat(bool force) 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; @@ -896,6 +922,50 @@ pgstat_report_stat(bool force) 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; /* -- 2.50.1