From b11c9b9d61c8eee62c3c0bc54744cee58f6b2fe7 Mon Sep 17 00:00:00 2001 From: Sami Imseih Date: Tue, 1 Dec 2026 16:49:43 +0000 Subject: [PATCH v23 4/6] pgstat: Allow pg_stat_force_next_flush() to work in transaction Previously pg_stat_force_next_flush() only guaranteed that the next flush would happen after the transaction ended. Make it flush immediately when called during a transaction. Nontransactional counters flush right away because they describe completed work. Transactional counters flush once the top-level transaction ends, except counts from rolled-back subtransactions, which are final and flush right away. To support repeated flushes in one transaction, keep flushed baselines for relation, index, and function stats. Pending entries are now kept until the transaction ends, so the custom stats test module clears its pending counts after a flush to avoid counting them twice. Since a flush can now run inside a transaction, assert that a flush callback neither makes the entry being flushed pending again nor calls pgstat_force_next_flush(), and don't let pgstat_force_next_flush() reenter a flush that is already in progress. Clear this flush state with PG_FINALLY, so an error raised during a flush leaves it reset and entries not yet flushed stay pending. Document pg_stat_force_next_flush() and add regression tests for repeated flushes, subtransactions, truncation, procedures that commit, and recursive calls from a function. XXX catversion bump needed. Author: Sami Imseih Reviewed-by: Bertrand Drouvot Reviewed-by: Zsolt Parragi Reviewed-by: Michael Paquier Discussion: https://postgr.es/m/CAA5RZ0uA-4qcD3+2hjcE_-zQUBhvWf5foPM2vzYneFKrJLsBDQ@mail.gmail.com --- doc/src/sgml/monitoring.sgml | 26 +- src/backend/utils/activity/pgstat.c | 144 ++++- src/backend/utils/activity/pgstat_function.c | 21 +- src/backend/utils/activity/pgstat_index.c | 45 +- src/backend/utils/activity/pgstat_relation.c | 112 +++- .../utils/activity/pgstat_subscription.c | 5 +- src/backend/utils/adt/pgstatfuncs.c | 5 +- src/include/catalog/pg_proc.dat | 4 +- src/include/pgstat.h | 37 ++ src/include/utils/pgstat_internal.h | 30 +- .../test_custom_stats/t/001_custom_stats.pl | 20 + .../test_custom_stats/test_custom_var_stats.c | 8 + src/test/regress/expected/stats.out | 540 +++++++++++++++++- src/test/regress/sql/stats.sql | 348 ++++++++++- 14 files changed, 1244 insertions(+), 101 deletions(-) diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 68803c58d1c..79fa8147d66 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -239,7 +239,9 @@ postgres 27093 0.0 0.0 30096 2752 ? Ss 11:34 0:00 postgres: ser 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. However, + 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. @@ -4557,7 +4559,8 @@ description | Waiting for a newly initialized WAL file to reach durable storage The time of the last sequential scan on this table, based on the - most recent transaction stop time + most recent transaction stop time, or the statement start time + when flushed during a transaction @@ -4585,7 +4588,8 @@ description | Waiting for a newly initialized WAL file to reach durable storage The time of the last index scan on this table, based on the - most recent transaction stop time + most recent transaction stop time, or the statement start time + when flushed during a transaction @@ -5086,7 +5090,8 @@ description | Waiting for a newly initialized WAL file to reach durable storage The time of the last scan on this index, based on the - most recent transaction stop time + most recent transaction stop time, or the statement start time + when flushed during a transaction @@ -5967,11 +5972,14 @@ description | Waiting for a newly initialized WAL file to reach durable storage Forces the statistics accumulated by the current session to be - flushed to shared memory when the current transaction ends, - without waiting for the - PGSTAT_MIN_INTERVAL delay between flushes. This - is mainly useful in tests that need this flush to happen without - that delay. + flushed without waiting for the PGSTAT_MIN_INTERVAL + delay between flushes. When called within a transaction, + nontransactional counters are flushed right away, while + transactional counters, such as tuple inserts, updates, and + 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. diff --git a/src/backend/utils/activity/pgstat.c b/src/backend/utils/activity/pgstat.c index 7c2b03a916c..48071e17cd2 100644 --- a/src/backend/utils/activity/pgstat.c +++ b/src/backend/utils/activity/pgstat.c @@ -249,6 +249,15 @@ static dlist_head pgStatPending = DLIST_STATIC_INIT(pgStatPending); */ static bool pgStatForceNextFlush = false; +/* Set while pgstat_report_stat() flushes pending entries. */ +static bool pgStatFlushInProgress = false; + +/* Current pending entry callback executing, or NULL when none is active. */ +static PgStat_EntryRef *pgStatCurrentFlushEntry = NULL; + +/* Generation number of the current pgstat_flush_pending_entries() pass. */ +static uint64 pgStatFlushGeneration = 0; + /* * Force-clear existing snapshot before next use when stats_fetch_consistency * is changed. @@ -731,8 +740,9 @@ pgstat_initialize(void) * a timeout after which to call pgstat_report_stat(true), but are not * required to do so. * - * Note that this is called only when not within a transaction, so it is fair - * to use transaction stop time as an approximation of current time. + * A nonforced flush only happens outside a transaction, so transaction stop + * time is close enough for the flush interval checks. A forced flush can + * happen during a transaction and uses the current time instead. */ long pgstat_report_stat(bool force) @@ -744,7 +754,16 @@ pgstat_report_stat(bool force) bool nowait; pgstat_assert_is_up(); - Assert(IsCompletelyOutOfTransaction()); + + /* + * A forced flush may run inside a live transaction, but never while a + * transaction is being started or ended. + */ + Assert(IsCompletelyOutOfTransaction() || (force && IsTransactionState())); + + /* a prior flush must have cleared this, even if it errored out */ + Assert(!pgStatFlushInProgress); + Assert(pgStatCurrentFlushEntry == NULL); /* "absorb" the forced flush even if there's nothing to flush */ if (pgStatForceNextFlush) @@ -807,36 +826,45 @@ pgstat_report_stat(bool force) partial_flush = false; - /* flush of variable-numbered stats tracked in pending entries list */ - partial_flush |= pgstat_flush_pending_entries(nowait); + pgStatFlushInProgress = true; - /* flush of other stats kinds */ - if (pgstat_report_fixed) + /* Clear flush-pass state before leaving this flush. */ + PG_TRY(); { - for (PgStat_Kind kind = PGSTAT_KIND_MIN; kind <= PGSTAT_KIND_MAX; kind++) + /* flush of variable-numbered stats tracked in pending entries list */ + partial_flush |= pgstat_flush_pending_entries(nowait); + + /* flush of other stats kinds */ + if (pgstat_report_fixed) { - const PgStat_KindInfo *kind_info = pgstat_get_kind_info(kind); + for (PgStat_Kind kind = PGSTAT_KIND_MIN; kind <= PGSTAT_KIND_MAX; kind++) + { + const PgStat_KindInfo *kind_info = pgstat_get_kind_info(kind); - if (!kind_info) - continue; - if (!kind_info->flush_static_cb) - continue; + if (!kind_info) + continue; + if (!kind_info->flush_static_cb) + continue; - partial_flush |= kind_info->flush_static_cb(nowait, - IsCompletelyOutOfTransaction()); + partial_flush |= kind_info->flush_static_cb(nowait, + IsCompletelyOutOfTransaction()); + } } } + PG_FINALLY(); + { + pgStatCurrentFlushEntry = NULL; + pgStatFlushInProgress = false; + } + PG_END_TRY(); last_flush = now; - /* - * If some of the pending stats could not be flushed due to lock - * contention, let the caller know when to retry. - */ + /* Let the caller know when to retry after a partial flush. */ if (partial_flush) { - /* force should have prevented us from getting here */ - Assert(!force); + /* with force, only active transaction state can cause a partial flush */ + Assert(!force || !IsCompletelyOutOfTransaction()); /* remember since when stats have been pending */ if (pending_since == 0) @@ -852,12 +880,24 @@ pgstat_report_stat(bool force) } /* - * Force locally pending stats to be flushed during the next - * pgstat_report_stat() call. This is useful for writing tests. + * Force locally pending stats to be flushed. During a transaction this + * flushes immediately, and the next pgstat_report_stat() call is forced too. + * This is useful in tests, and for callers such as extensions that need + * statistics of a running transaction visible before it ends. */ void pgstat_force_next_flush(void) { + /* + * A flush callback must not call this; doing so would recursively enter + * pgstat_report_stat() while a flush is already in progress. + */ + Assert(!pgStatFlushInProgress); + + /* During a transaction flush now unless a flush is already running. */ + if (!pgStatFlushInProgress && IsTransactionState()) + pgstat_report_stat(true); + pgStatForceNextFlush = true; } @@ -1375,6 +1415,7 @@ pgstat_delete_pending_entry(PgStat_EntryRef *entry_ref) pfree(pending_data); entry_ref->pending = NULL; + entry_ref->flushed_generation = 0; dlist_delete(&entry_ref->pending_node); } @@ -1388,6 +1429,8 @@ pgstat_prep_pending_from_entry_ref(PgStat_EntryRef *entry_ref) PgStat_Kind kind; Assert(entry_ref != NULL); + /* The entry currently being flushed must not be made pending again. */ + Assert(entry_ref != pgStatCurrentFlushEntry); kind = entry_ref->shared_entry->key.kind; @@ -1409,8 +1452,19 @@ pgstat_prep_pending_from_entry_ref(PgStat_EntryRef *entry_ref) } entry_ref->pending = MemoryContextAllocZero(pgStatPendingContext, entrysize); + entry_ref->flushed_generation = 0; dlist_push_tail(&pgStatPending, &entry_ref->pending_node); } + else if (pgStatFlushInProgress && + entry_ref->flushed_generation == pgStatFlushGeneration) + { + /* + * The entry is already pending and was already visited in the current + * flush pass. Move it to the tail so the data just accumulated into + * it is flushed again before the pass ends. + */ + dlist_move_tail(&pgStatPending, &entry_ref->pending_node); + } } /* @@ -1427,12 +1481,18 @@ pgstat_flush_pending_entries(bool nowait) * Processing a pending entry may queue further pending entries to the end * of the list that we want to process, so a simple iteration won't do. * Further complicating matters is that we want to delete the current - * entry in each iteration from the list if we flushed successfully. + * entry in each iteration from the list if we flushed successfully, + * though during a transaction a fully flushed entry is retained and only + * deleted at a transaction boundary. * - * So we just keep track of the next pointer in each loop iteration. + * So we just keep track of the next pointer in each loop iteration, and + * start a new flush-pass generation only when there are pending entries. */ if (!dlist_is_empty(&pgStatPending)) + { cur = dlist_head_node(&pgStatPending); + pgStatFlushGeneration++; + } while (cur) { @@ -1451,18 +1511,44 @@ pgstat_flush_pending_entries(bool nowait) Assert(kind_info->flush_pending_cb != NULL); /* flush the stats, if possible */ + pgStatCurrentFlushEntry = entry_ref; result = kind_info->flush_pending_cb(entry_ref, nowait, xact_boundary); + pgStatCurrentFlushEntry = NULL; - Assert(result == PGSTAT_FLUSH_DONE || nowait); + /* + * A lock conflict can only happen when we allowed the callback to + * give up without waiting for a lock, and a partial flush can only + * happen inside a transaction. + */ + Assert(result == PGSTAT_FLUSH_DONE || + (result == PGSTAT_FLUSH_LOCK_CONFLICT && nowait) || + (result == PGSTAT_FLUSH_PARTIAL && !xact_boundary)); + + /* + * Mark the entry visited, unless we could not flush it at all. If a + * later callback adds more data to this entry in the same pass, + * pgstat_prep_pending_from_entry_ref() then re-queues it to the tail + * so the new data is flushed again before the pass ends. + */ + if (result != PGSTAT_FLUSH_LOCK_CONFLICT) + entry_ref->flushed_generation = pgStatFlushGeneration; - /* determine next entry, before deleting the pending entry */ + /* + * Determine the next entry after the callback ran (it may have + * re-queued an entry) and before possibly deleting the current one. + */ if (dlist_has_next(&pgStatPending, cur)) next = dlist_next_node(&pgStatPending, cur); else next = NULL; - /* if successfully flushed, remove entry */ - if (result == PGSTAT_FLUSH_DONE) + /* + * Only delete a fully flushed entry at a transaction boundary. + * Earlier in the transaction it may still be reused as more stats + * accumulate, and code holding a pointer into it relies on the entry + * staying put. + */ + if (result == PGSTAT_FLUSH_DONE && xact_boundary) pgstat_delete_pending_entry(entry_ref); else have_pending = true; diff --git a/src/backend/utils/activity/pgstat_function.c b/src/backend/utils/activity/pgstat_function.c index 7e76fc8ecd2..4187bf05e23 100644 --- a/src/backend/utils/activity/pgstat_function.c +++ b/src/backend/utils/activity/pgstat_function.c @@ -188,6 +188,9 @@ pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize) * * If nowait is true and the lock could not be immediately acquired, returns * PGSTAT_FLUSH_LOCK_CONFLICT without flushing the entry. + * + * Function stats are not transactional, so this never returns + * PGSTAT_FLUSH_PARTIAL. The entry can flush more than once per transaction. */ PgStat_FlushResult pgstat_function_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, @@ -199,19 +202,29 @@ pgstat_function_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, localent = (PgStat_FunctionStatus *) entry_ref->pending; shfuncent = (PgStatShared_Function *) entry_ref->shared_stats; - /* localent always has non-zero content */ + /* Nothing changed since the last flush. */ + if (memcmp(&localent->counts, &localent->flushed, + sizeof(PgStat_FunctionCounts)) == 0) + return PGSTAT_FLUSH_DONE; if (!pgstat_lock_entry(entry_ref, nowait)) return PGSTAT_FLUSH_LOCK_CONFLICT; - shfuncent->stats.numcalls += localent->counts.numcalls; + shfuncent->stats.numcalls += + localent->counts.numcalls - localent->flushed.numcalls; shfuncent->stats.total_time += - INSTR_TIME_GET_MICROSEC(localent->counts.total_time); + INSTR_TIME_GET_MICROSEC(localent->counts.total_time) - + INSTR_TIME_GET_MICROSEC(localent->flushed.total_time); shfuncent->stats.self_time += - INSTR_TIME_GET_MICROSEC(localent->counts.self_time); + INSTR_TIME_GET_MICROSEC(localent->counts.self_time) - + INSTR_TIME_GET_MICROSEC(localent->flushed.self_time); pgstat_unlock_entry(entry_ref); + /* Record the new baseline while counts keep accumulating. */ + if (!xact_boundary) + localent->flushed = localent->counts; + return PGSTAT_FLUSH_DONE; } diff --git a/src/backend/utils/activity/pgstat_index.c b/src/backend/utils/activity/pgstat_index.c index f18480efd9f..7dcb3740269 100644 --- a/src/backend/utils/activity/pgstat_index.c +++ b/src/backend/utils/activity/pgstat_index.c @@ -47,11 +47,11 @@ pgstat_index_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, shidxstats = (PgStatShared_Index *) entry_ref->shared_stats; /* - * Ignore entries that didn't accumulate any actual counts, such as - * indexes that were opened by the planner but not used. + * Ignore entries that didn't accumulate any new counts since the last + * flush, such as indexes that were opened by the planner but not used. */ - if (pg_memory_is_all_zeros(&lstats->idx.counts, - sizeof(struct PgStat_IndexCounts))) + if (memcmp(&lstats->idx.counts, &lstats->idx.flushed, + sizeof(struct PgStat_IndexCounts)) == 0) return PGSTAT_FLUSH_DONE; if (!pgstat_lock_entry(entry_ref, nowait)) @@ -60,27 +60,42 @@ pgstat_index_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, /* Add the values to the shared entry. */ idxentry = &shidxstats->stats; - idxentry->numscans += lstats->idx.counts.numscans; - if (lstats->idx.counts.numscans) + idxentry->numscans += lstats->idx.counts.numscans - + lstats->idx.flushed.numscans; + if (lstats->idx.counts.numscans > lstats->idx.flushed.numscans) { - TimestampTz t = GetCurrentTransactionStopTimestamp(); + TimestampTz t = xact_boundary ? + GetCurrentTransactionStopTimestamp() : + GetCurrentStatementStartTimestamp(); if (t > idxentry->lastscan) idxentry->lastscan = t; } - idxentry->tuples_returned += lstats->idx.counts.tuples_returned; - idxentry->tuples_fetched += lstats->idx.counts.tuples_fetched; - idxentry->blocks_fetched += lstats->idx.counts.blocks_fetched; - idxentry->blocks_hit += lstats->idx.counts.blocks_hit; + idxentry->tuples_returned += lstats->idx.counts.tuples_returned - + lstats->idx.flushed.tuples_returned; + idxentry->tuples_fetched += lstats->idx.counts.tuples_fetched - + lstats->idx.flushed.tuples_fetched; + idxentry->blocks_fetched += lstats->idx.counts.blocks_fetched - + lstats->idx.flushed.blocks_fetched; + idxentry->blocks_hit += lstats->idx.counts.blocks_hit - + lstats->idx.flushed.blocks_hit; pgstat_unlock_entry(entry_ref); /* The entry was successfully flushed, add the same to database stats */ dbentry = pgstat_prep_database_pending(dboid); - dbentry->tuples_returned += lstats->idx.counts.tuples_returned; - dbentry->tuples_fetched += lstats->idx.counts.tuples_fetched; - dbentry->blocks_fetched += lstats->idx.counts.blocks_fetched; - dbentry->blocks_hit += lstats->idx.counts.blocks_hit; + dbentry->tuples_returned += lstats->idx.counts.tuples_returned - + lstats->idx.flushed.tuples_returned; + dbentry->tuples_fetched += lstats->idx.counts.tuples_fetched - + lstats->idx.flushed.tuples_fetched; + dbentry->blocks_fetched += lstats->idx.counts.blocks_fetched - + lstats->idx.flushed.blocks_fetched; + dbentry->blocks_hit += lstats->idx.counts.blocks_hit - + lstats->idx.flushed.blocks_hit; + + /* Record the new baseline while counts keep accumulating. */ + if (!xact_boundary) + lstats->idx.flushed = lstats->idx.counts; return PGSTAT_FLUSH_DONE; } diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 93280411eb5..087e2770722 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -372,8 +372,13 @@ pgstat_report_analyze(Relation rel, livetuples -= trans->tuples_inserted - trans->tuples_deleted; deadtuples -= trans->tuples_updated + trans->tuples_deleted; } - /* count stuff inserted by already-aborted subxacts, too */ - deadtuples -= rel->pgstat_info->tab.counts_xact.delta_dead_tuples; + + /* + * Count stuff inserted by already-aborted subxacts, too, but only the + * part not yet flushed to shared stats. + */ + deadtuples -= rel->pgstat_info->tab.counts_xact.delta_dead_tuples - + rel->pgstat_info->tab.flushed_xact.delta_dead_tuples; /* Since ANALYZE's counts are estimates, we could have underflowed */ livetuples = Max(livetuples, 0); deadtuples = Max(deadtuples, 0); @@ -661,6 +666,8 @@ AtEOXact_PgStat_Relations(PgStat_SubXactStatus *xact_state, bool isCommit) /* forget live/dead stats seen by backend thus far */ relstat->tab.counts_xact.delta_live_tuples = 0; relstat->tab.counts_xact.delta_dead_tuples = 0; + relstat->tab.flushed_xact.delta_live_tuples = 0; + relstat->tab.flushed_xact.delta_dead_tuples = 0; } /* insert adds a live tuple, delete removes one */ relstat->tab.counts_xact.delta_live_tuples += @@ -865,6 +872,8 @@ pgstat_twophase_postcommit(FullTransactionId fxid, uint16 info, /* forget live/dead stats seen by backend thus far */ pgstat_info->tab.counts_xact.delta_live_tuples = 0; pgstat_info->tab.counts_xact.delta_dead_tuples = 0; + pgstat_info->tab.flushed_xact.delta_live_tuples = 0; + pgstat_info->tab.flushed_xact.delta_dead_tuples = 0; } pgstat_info->tab.counts_xact.delta_live_tuples += rec->tuples_inserted - rec->tuples_deleted; @@ -911,6 +920,9 @@ pgstat_twophase_postabort(FullTransactionId fxid, uint16 info, * If nowait is true and the lock could not be immediately acquired, returns * PGSTAT_FLUSH_LOCK_CONFLICT without flushing the entry. * + * Nontransactional and transactional counters hold only final values (see + * PgStat_TableCountsXact), so everything pending is flushed. + * * Some of the stats are copied to the corresponding pending database stats * entry when successfully flushing. */ @@ -932,13 +944,13 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, * Ignore entries that didn't accumulate any actual counts. If the table * was truncated, we still need to flush the entry to reset the live/dead * counters and ins_since_vacuum even when no other counts were - * accumulated. + * accumulated. Only counts since the last flush are considered. */ if (!lstats->tab.truncdropped && - pg_memory_is_all_zeros(&lstats->tab.counts, - sizeof(struct PgStat_TableCounts)) && - pg_memory_is_all_zeros(&lstats->tab.counts_xact, - sizeof(struct PgStat_TableCountsXact))) + memcmp(&lstats->tab.counts, &lstats->tab.flushed, + sizeof(PgStat_TableCounts)) == 0 && + memcmp(&lstats->tab.counts_xact, &lstats->tab.flushed_xact, + sizeof(PgStat_TableCountsXact)) == 0) return PGSTAT_FLUSH_DONE; if (!pgstat_lock_entry(entry_ref, nowait)) @@ -947,21 +959,33 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, /* add the values to the shared entry. */ tabentry = &shtabstats->stats; - tabentry->numscans += lstats->tab.counts.numscans; - if (lstats->tab.counts.numscans) + tabentry->numscans += lstats->tab.counts.numscans - + lstats->tab.flushed.numscans; + if (lstats->tab.counts.numscans > lstats->tab.flushed.numscans) { - TimestampTz t = GetCurrentTransactionStopTimestamp(); + TimestampTz t = xact_boundary ? + GetCurrentTransactionStopTimestamp() : + GetCurrentStatementStartTimestamp(); if (t > tabentry->lastscan) tabentry->lastscan = t; } - tabentry->tuples_returned += lstats->tab.counts.tuples_returned; - tabentry->tuples_fetched += lstats->tab.counts.tuples_fetched; - tabentry->tuples_inserted += lstats->tab.counts_xact.tuples_inserted; - tabentry->tuples_updated += lstats->tab.counts_xact.tuples_updated; - tabentry->tuples_deleted += lstats->tab.counts_xact.tuples_deleted; - tabentry->tuples_hot_updated += lstats->tab.counts_xact.tuples_hot_updated; - tabentry->tuples_newpage_updated += lstats->tab.counts_xact.tuples_newpage_updated; + tabentry->tuples_returned += lstats->tab.counts.tuples_returned - + lstats->tab.flushed.tuples_returned; + tabentry->tuples_fetched += lstats->tab.counts.tuples_fetched - + lstats->tab.flushed.tuples_fetched; + tabentry->tuples_inserted += lstats->tab.counts_xact.tuples_inserted - + lstats->tab.flushed_xact.tuples_inserted; + tabentry->tuples_updated += lstats->tab.counts_xact.tuples_updated - + lstats->tab.flushed_xact.tuples_updated; + tabentry->tuples_deleted += lstats->tab.counts_xact.tuples_deleted - + lstats->tab.flushed_xact.tuples_deleted; + tabentry->tuples_hot_updated += + lstats->tab.counts_xact.tuples_hot_updated - + lstats->tab.flushed_xact.tuples_hot_updated; + tabentry->tuples_newpage_updated += + lstats->tab.counts_xact.tuples_newpage_updated - + lstats->tab.flushed_xact.tuples_newpage_updated; /* * If table was truncated/dropped, first reset the live/dead counters. @@ -970,12 +994,15 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, { tabentry->live_tuples = 0; tabentry->dead_tuples = 0; - tabentry->ins_since_vacuum = 0; + tabentry->ins_since_vacuum = lstats->tab.flushed_xact.tuples_inserted; } - tabentry->live_tuples += lstats->tab.counts_xact.delta_live_tuples; - tabentry->dead_tuples += lstats->tab.counts_xact.delta_dead_tuples; - tabentry->mod_since_analyze += lstats->tab.counts_xact.changed_tuples; + tabentry->live_tuples += lstats->tab.counts_xact.delta_live_tuples - + lstats->tab.flushed_xact.delta_live_tuples; + tabentry->dead_tuples += lstats->tab.counts_xact.delta_dead_tuples - + lstats->tab.flushed_xact.delta_dead_tuples; + tabentry->mod_since_analyze += lstats->tab.counts_xact.changed_tuples - + lstats->tab.flushed_xact.changed_tuples; /* * Using tuples_inserted to update ins_since_vacuum does mean that we'll @@ -984,10 +1011,14 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, * triggering for inserts more often than they maybe should, which is * probably not going to be common enough to be too concerned about here. */ - tabentry->ins_since_vacuum += lstats->tab.counts_xact.tuples_inserted; + tabentry->ins_since_vacuum += + lstats->tab.counts_xact.tuples_inserted - + lstats->tab.flushed_xact.tuples_inserted; - tabentry->blocks_fetched += lstats->tab.counts.blocks_fetched; - tabentry->blocks_hit += lstats->tab.counts.blocks_hit; + tabentry->blocks_fetched += lstats->tab.counts.blocks_fetched - + lstats->tab.flushed.blocks_fetched; + tabentry->blocks_hit += lstats->tab.counts.blocks_hit - + lstats->tab.flushed.blocks_hit; /* Clamp live_tuples in case of negative delta_live_tuples */ tabentry->live_tuples = Max(tabentry->live_tuples, 0); @@ -998,13 +1029,32 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, /* The entry was successfully flushed, add the same to database stats */ dbentry = pgstat_prep_database_pending(dboid); - dbentry->tuples_returned += lstats->tab.counts.tuples_returned; - dbentry->tuples_fetched += lstats->tab.counts.tuples_fetched; - dbentry->tuples_inserted += lstats->tab.counts_xact.tuples_inserted; - dbentry->tuples_updated += lstats->tab.counts_xact.tuples_updated; - dbentry->tuples_deleted += lstats->tab.counts_xact.tuples_deleted; - dbentry->blocks_fetched += lstats->tab.counts.blocks_fetched; - dbentry->blocks_hit += lstats->tab.counts.blocks_hit; + dbentry->tuples_returned += lstats->tab.counts.tuples_returned - + lstats->tab.flushed.tuples_returned; + dbentry->tuples_fetched += lstats->tab.counts.tuples_fetched - + lstats->tab.flushed.tuples_fetched; + dbentry->tuples_inserted += lstats->tab.counts_xact.tuples_inserted - + lstats->tab.flushed_xact.tuples_inserted; + dbentry->tuples_updated += lstats->tab.counts_xact.tuples_updated - + lstats->tab.flushed_xact.tuples_updated; + dbentry->tuples_deleted += lstats->tab.counts_xact.tuples_deleted - + lstats->tab.flushed_xact.tuples_deleted; + dbentry->blocks_fetched += lstats->tab.counts.blocks_fetched - + lstats->tab.flushed.blocks_fetched; + dbentry->blocks_hit += lstats->tab.counts.blocks_hit - + lstats->tab.flushed.blocks_hit; + + /* + * Record everything as flushed while the entry stays around to gather + * more counts. Clear truncdropped so the next truncate is seen as new. + * At a transaction boundary the entry is deleted. + */ + if (!xact_boundary) + { + lstats->tab.flushed = lstats->tab.counts; + lstats->tab.flushed_xact = lstats->tab.counts_xact; + lstats->tab.truncdropped = false; + } return PGSTAT_FLUSH_DONE; } diff --git a/src/backend/utils/activity/pgstat_subscription.c b/src/backend/utils/activity/pgstat_subscription.c index a2fc2236c6b..3c61293eb5f 100644 --- a/src/backend/utils/activity/pgstat_subscription.c +++ b/src/backend/utils/activity/pgstat_subscription.c @@ -128,8 +128,6 @@ pgstat_subscription_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, localent = (PgStat_BackendSubEntry *) entry_ref->pending; shsubent = (PgStatShared_Subscription *) entry_ref->shared_stats; - /* localent always has non-zero content */ - if (!pgstat_lock_entry(entry_ref, nowait)) return PGSTAT_FLUSH_LOCK_CONFLICT; @@ -142,6 +140,9 @@ pgstat_subscription_flush_cb(PgStat_EntryRef *entry_ref, bool nowait, #undef SUB_ACC pgstat_unlock_entry(entry_ref); + + memset(localent, 0, sizeof(*localent)); + return PGSTAT_FLUSH_DONE; } diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index 1c69940146c..fb5ad101ac4 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -2058,7 +2058,10 @@ pg_stat_clear_snapshot(PG_FUNCTION_ARGS) } -/* Force statistics to be reported at the next occasion */ +/* + * Force statistics to be reported. When called in a transaction this flushes + * immediately; otherwise the flush happens at the next occasion. + */ Datum pg_stat_force_next_flush(PG_FUNCTION_ARGS) { diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 18b4be838a4..54376296ec9 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -6216,9 +6216,9 @@ proparallel => 'r', prorettype => 'void', proargtypes => '', prosrc => 'pg_stat_clear_snapshot' }, { oid => '2137', - descr => 'statistics: force stats to be flushed after the next commit', + descr => 'statistics: force stats to be flushed, immediately if within a transaction', proname => 'pg_stat_force_next_flush', proisstrict => 'f', provolatile => 'v', - proparallel => 'r', prorettype => 'void', proargtypes => '', + proparallel => 'u', prorettype => 'void', proargtypes => '', prosrc => 'pg_stat_force_next_flush' }, { oid => '2274', descr => 'statistics: reset collected statistics for current database', diff --git a/src/include/pgstat.h b/src/include/pgstat.h index c80556be3ff..4f6f095e911 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -90,12 +90,31 @@ typedef struct PgStat_FunctionCounts instr_time self_time; } PgStat_FunctionCounts; +/* Keep these counts in sync with the fields above. */ +#define PGSTAT_FUNCTIONCOUNTS_NUM_COUNTERS 1 +#define PGSTAT_FUNCTIONCOUNTS_NUM_INSTR_TIMES 2 + +StaticAssertDecl(sizeof(instr_time) == sizeof(int64), + "instr_time has padding"); +StaticAssertDecl(sizeof(PgStat_FunctionCounts) == + PGSTAT_FUNCTIONCOUNTS_NUM_COUNTERS * sizeof(PgStat_Counter) + + PGSTAT_FUNCTIONCOUNTS_NUM_INSTR_TIMES * sizeof(instr_time), + "PgStat_FunctionCounts has padding"); + /* * Pending function stats stored in PgStat_EntryRef->pending. + * + * counts accumulates for the whole transaction (it is what + * pg_stat_xact_user_functions reports); flushed is the portion already written + * to shared memory. A flush writes counts minus flushed and then sets flushed + * to counts, so counts survives an in-transaction flush intact and the shared + * totals are never double-counted. The same counts/flushed scheme is used for + * relation stats; see PgStat_RelationStatus. */ typedef struct PgStat_FunctionStatus { PgStat_FunctionCounts counts; + PgStat_FunctionCounts flushed; } PgStat_FunctionStatus; /* @@ -172,6 +191,12 @@ StaticAssertDecl(sizeof(PgStat_TableCounts) == 5 * sizeof(PgStat_Counter), * actions, regardless of whether the transaction committed. delta_live_tuples, * delta_dead_tuples, and changed_tuples are set depending on commit or abort. * Note that delta_live_tuples and delta_dead_tuples can be negative! + * + * Counts are added here only when the top-level transaction ends or a + * subtransaction aborts. Until then they stay in PgStat_TableXactStatus. + * The exception is the nontransactional recovery of dead tuples, which + * updates delta_dead_tuples directly (see pgstat_update_heap_dead_tuples()). + * So this group can be flushed at any time. * ---------- */ typedef struct PgStat_TableCountsXact @@ -211,6 +236,13 @@ typedef struct PgStat_IndexCounts PgStat_Counter blocks_hit; } PgStat_IndexCounts; +/* Keep this count in sync with the fields above. */ +#define PGSTAT_INDEXCOUNTS_NUM_COUNTERS 5 + +StaticAssertDecl(sizeof(PgStat_IndexCounts) == + PGSTAT_INDEXCOUNTS_NUM_COUNTERS * sizeof(PgStat_Counter), + "PgStat_IndexCounts has padding"); + /* ---------- * PgStat_RelationStatus Per-relation pending status within a backend * @@ -244,12 +276,17 @@ typedef struct PgStat_RelationStatus struct PgStat_TableXactStatus *trans; /* lowest subxact's counts */ PgStat_TableCounts counts; /* event counts to be sent */ PgStat_TableCountsXact counts_xact; /* transactional counts */ + PgStat_TableCounts flushed; /* portion of counts already written + * to shared memory */ + PgStat_TableCountsXact flushed_xact; /* portion of counts_xact + * already written */ } tab; /* index counters */ struct { PgStat_IndexCounts counts; + PgStat_IndexCounts flushed; } idx; }; } PgStat_RelationStatus; diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h index 35a6442d28d..373acecbbc3 100644 --- a/src/include/utils/pgstat_internal.h +++ b/src/include/utils/pgstat_internal.h @@ -42,7 +42,9 @@ * * Once there are pending stats updates for a table PgStat_EntryRef->pending * is allocated to contain a working space for as-of-yet-unapplied stats - * updates. Once the stats are flushed, PgStat_EntryRef->pending is freed. + * updates. Once the stats are fully flushed, PgStat_EntryRef->pending is + * freed. During a transaction a flushed entry is instead retained until the + * transaction boundary. * * Each variable-numbered shared stats struct has PgStatShared_Common as the * first element. @@ -190,6 +192,14 @@ typedef struct PgStat_EntryRef */ void *pending; dlist_node pending_node; /* membership in pgStatPending list */ + + /* + * Flush-pass generation in which this entry was last flushed. Used by + * pgstat_prep_pending_from_entry_ref() to decide whether an entry being + * accumulated into needs re-queuing during the current flush pass. Zero + * means the entry has not been flushed since it became pending. + */ + uint64 flushed_generation; } PgStat_EntryRef; @@ -239,6 +249,13 @@ typedef enum PgStat_FlushResult /* Fully flushed; the entry can be removed. */ PGSTAT_FLUSH_DONE, + + /* + * Only the non-transactional counters were flushed; transactional state + * was retained (e.g. flushing during a transaction) and must be flushed + * again at a transaction boundary. + */ + PGSTAT_FLUSH_PARTIAL, } PgStat_FlushResult; /* @@ -327,6 +344,17 @@ typedef struct PgStat_KindInfo * If nowait is true and the lock cannot be acquired, give up without * flushing. When xact_boundary is false, a callback must not flush the * transactional counters of the running transaction. + * + * When xact_boundary is false the pending entry is retained, so the + * callback may run again for it before the transaction ends and must not + * merge the same pending data twice. Clear the flushed fields, or track + * a flushed baseline and merge only the delta. A callback must not call + * pgstat_force_next_flush(). + * + * A callback may accumulate into another kind's pending entry (e.g. + * relation stats feed database stats), but it must not accumulate into + * the entry currently being flushed, and such dependencies must be + * acyclic (see pgstat_flush_pending_entries()). */ PgStat_FlushResult (*flush_pending_cb) (PgStat_EntryRef *sr, bool nowait, bool xact_boundary); diff --git a/src/test/modules/test_custom_stats/t/001_custom_stats.pl b/src/test/modules/test_custom_stats/t/001_custom_stats.pl index 484a2d73ff7..a9e06971baf 100644 --- a/src/test/modules/test_custom_stats/t/001_custom_stats.pl +++ b/src/test/modules/test_custom_stats/t/001_custom_stats.pl @@ -114,6 +114,26 @@ foreach my $stats_kind (@var_stats_kinds) "entry4|3|Test entry 4", "variable-sized stats of entry4 for $kind_name"); + # Repeated flushes in one transaction must not double count. + $node->safe_psql('postgres', + q(select test_custom_stats_var_create('xact_entry', 'Test xact entry'))); + $node->safe_psql( + 'postgres', q( + BEGIN; + select test_custom_stats_var_update('xact_entry'); + select pg_stat_force_next_flush(); + select test_custom_stats_var_update('xact_entry'); + select pg_stat_force_next_flush(); + select test_custom_stats_var_update('xact_entry'); + COMMIT;)); + $result = $node->safe_psql('postgres', + q(select * from test_custom_stats_var_report('xact_entry'))); + is( $result, + "xact_entry|3|Test xact entry", + "in-transaction flush does not double-count pending stats for $kind_name"); + $node->safe_psql('postgres', + q(select * from test_custom_stats_var_drop('xact_entry'))); + # Test drop of variable-sized stats via pgstat_drop_entry(). $node->safe_psql('postgres', q(select * from test_custom_stats_var_drop('entry3'))); diff --git a/src/test/modules/test_custom_stats/test_custom_var_stats.c b/src/test/modules/test_custom_stats/test_custom_var_stats.c index 8df22ce4a68..dcc94b6697c 100644 --- a/src/test/modules/test_custom_stats/test_custom_var_stats.c +++ b/src/test/modules/test_custom_stats/test_custom_var_stats.c @@ -213,6 +213,14 @@ test_custom_stats_var_flush_pending_cb(PgStat_EntryRef *entry_ref, bool nowait, pgstat_unlock_entry(entry_ref); + /* + * The pending entry is retained across in-transaction flushes (see + * pgstat_flush_pending_entries()), so clear what was just flushed to + * avoid counting it again on a later flush. Nothing reads these stats + * within the current transaction, so zeroing is correct. + */ + memset(pending_entry, 0, sizeof(*pending_entry)); + return PGSTAT_FLUSH_DONE; } diff --git a/src/test/regress/expected/stats.out b/src/test/regress/expected/stats.out index 0e54cf0d394..5b4d53527b5 100644 --- a/src/test/regress/expected/stats.out +++ b/src/test/regress/expected/stats.out @@ -778,12 +778,6 @@ SELECT pg_stat_force_next_flush(); (1 row) -SELECT last_seq_scan, last_idx_scan FROM pg_stat_all_tables WHERE relid = 'test_last_scan'::regclass; - last_seq_scan | last_idx_scan ----------------+--------------- - | -(1 row) - COMMIT; SELECT stats_reset IS NOT NULL AS has_stats_reset FROM pg_stat_all_tables WHERE relid = 'test_last_scan'::regclass; @@ -2184,4 +2178,538 @@ SELECT fastpath_exceeded > :backend_fastpath_exceeded_before (1 row) DROP TABLE part_test; +-- +-- Test in-transaction flushes +-- +CREATE TABLE xact_flush(id int) WITH (autovacuum_enabled = off); +INSERT INTO xact_flush VALUES (1), (2), (3); +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +-- Record counters before the explicit transaction +SELECT seq_scan AS seq_scan_before, + seq_tup_read AS seq_tup_read_before, + n_tup_ins AS n_tup_ins_before, + n_tup_upd AS n_tup_upd_before, + n_tup_hot_upd + n_tup_newpage_upd AS upd_detail_before + FROM pg_stat_user_tables WHERE relname = 'xact_flush' \gset +BEGIN; +SET LOCAL stats_fetch_consistency = none; +-- Generate both transaction-safe and transaction-unsafe counters. +SELECT count(*) FROM xact_flush; + count +------- + 3 +(1 row) + +INSERT INTO xact_flush VALUES (4), (5); +UPDATE xact_flush SET id = id WHERE id = 1; +-- Flush in-transaction +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +-- Scans are visible in-transaction; ins and upd stay deferred. +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + seq_tup_read - :seq_tup_read_before AS seq_tup_read_delta, + n_tup_ins - :n_tup_ins_before AS n_tup_ins_delta, + n_tup_upd - :n_tup_upd_before AS n_tup_upd_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush'; + seq_scan_delta | seq_tup_read_delta | n_tup_ins_delta | n_tup_upd_delta +----------------+--------------------+-----------------+----------------- + 2 | 8 | 0 | 0 +(1 row) + +-- The pg_stat_xact_user_tables view still reports this transaction's own +-- inserts and updates, which the flush leaves in the pending counts. +SELECT n_tup_ins, n_tup_upd + FROM pg_stat_xact_user_tables WHERE relname = 'xact_flush'; + n_tup_ins | n_tup_upd +-----------+----------- + 2 | 1 +(1 row) + +-- Generate more transaction-safe activity to verify no double counting. +SELECT count(*) FROM xact_flush; + count +------- + 5 +(1 row) + +-- Flush again in-transaction +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +-- Should show cumulative totals, not double-counted. +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + seq_tup_read - :seq_tup_read_before AS seq_tup_read_delta, + n_tup_ins - :n_tup_ins_before AS n_tup_ins_delta, + n_tup_upd - :n_tup_upd_before AS n_tup_upd_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush'; + seq_scan_delta | seq_tup_read_delta | n_tup_ins_delta | n_tup_upd_delta +----------------+--------------------+-----------------+----------------- + 3 | 13 | 0 | 0 +(1 row) + +COMMIT; +-- After commit, all counters should be flushed. +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + seq_tup_read - :seq_tup_read_before AS seq_tup_read_delta, + n_tup_ins - :n_tup_ins_before AS n_tup_ins_delta, + n_tup_upd - :n_tup_upd_before AS n_tup_upd_delta, + n_tup_hot_upd + n_tup_newpage_upd - :upd_detail_before AS upd_detail_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush'; + seq_scan_delta | seq_tup_read_delta | n_tup_ins_delta | n_tup_upd_delta | upd_detail_delta +----------------+--------------------+-----------------+-----------------+------------------ + 3 | 13 | 2 | 1 | 1 +(1 row) + +DROP TABLE xact_flush; +-- +-- Test in-transaction flushes of index statistics. An index scan reaches +-- shared stats during a transaction and must not be double-counted by a later flush. +-- +CREATE TABLE xact_flush_idx(id int primary key) WITH (autovacuum_enabled = off); +INSERT INTO xact_flush_idx SELECT generate_series(1, 100); +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT idx_scan AS idx_scan_before + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass \gset +BEGIN; +SET LOCAL stats_fetch_consistency = none; +SET LOCAL enable_seqscan = off; +SET LOCAL enable_bitmapscan = off; +-- Two index scans. +SELECT id FROM xact_flush_idx WHERE id = 1; + id +---- + 1 +(1 row) + +SELECT id FROM xact_flush_idx WHERE id = 2; + id +---- + 2 +(1 row) + +-- Flush in-transaction; index stats are non-transactional and reach shared +-- stats now. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT idx_scan - :idx_scan_before AS idx_scan_delta + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass; + idx_scan_delta +---------------- + 2 +(1 row) + +-- Another index scan, then flush again to verify no double counting. +SELECT id FROM xact_flush_idx WHERE id = 3; + id +---- + 3 +(1 row) + +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT idx_scan - :idx_scan_before AS idx_scan_delta + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass; + idx_scan_delta +---------------- + 3 +(1 row) + +COMMIT; +-- After commit the count is unchanged from the last in-transaction flush. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT idx_scan - :idx_scan_before AS idx_scan_delta + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass; + idx_scan_delta +---------------- + 3 +(1 row) + +DROP TABLE xact_flush_idx; +-- +-- Roll back a savepoint after an in-transaction flush. The flush must not +-- write the subxact's inserts to shared stats. After commit the inserts made +-- outside the subxact count as live tuples while those rolled back count as +-- dead. +-- +CREATE TABLE subxact_flush(id int) WITH (autovacuum_enabled = off); +INSERT INTO subxact_flush SELECT generate_series(1, 50); +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT n_live_tup AS n_live_tup_before, + n_dead_tup AS n_dead_tup_before, + seq_scan AS seq_scan_before + FROM pg_stat_user_tables WHERE relname = 'subxact_flush' \gset +BEGIN; +SET LOCAL stats_fetch_consistency = none; +SELECT count(*) FROM subxact_flush; + count +------- + 50 +(1 row) + +SAVEPOINT sp; +INSERT INTO subxact_flush SELECT generate_series(51, 80); +-- Flush during a transaction. The scan reaches shared stats; the insert is deferred. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + n_live_tup = :n_live_tup_before AS live_tup_unchanged + FROM pg_stat_user_tables WHERE relname = 'subxact_flush'; + seq_scan_delta | live_tup_unchanged +----------------+-------------------- + 1 | t +(1 row) + +ROLLBACK TO SAVEPOINT sp; +INSERT INTO subxact_flush SELECT generate_series(81, 90); +COMMIT; +-- After commit the inserts made outside the subxact count as live tuples, +-- those rolled back count as dead, and the in-transaction scan is still there. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT n_live_tup - :n_live_tup_before AS n_live_tup_delta, + n_dead_tup - :n_dead_tup_before AS n_dead_tup_delta, + seq_scan - :seq_scan_before AS seq_scan_delta + FROM pg_stat_user_tables WHERE relname = 'subxact_flush'; + n_live_tup_delta | n_dead_tup_delta | seq_scan_delta +------------------+------------------+---------------- + 10 | 30 | 1 +(1 row) + +DROP TABLE subxact_flush; +-- +-- Test that an in-transaction flush keeps the database aggregate in step with +-- the relation counters that feed it, rather than a flush behind. +-- +-- The relation flush accumulates into the database pending entry. If that +-- database entry was already visited earlier in the same flush pass, it must +-- be re-queued so the relation's contribution reaches shared stats in this +-- pass, not the next one. To force that ordering, prime the database pending +-- ahead of the table. Scan a catalog and flush (which leaves the database +-- entry pending), then scan the table and flush again. +-- +CREATE TABLE flush_db_lag(id int) WITH (autovacuum_enabled = off); +INSERT INTO flush_db_lag SELECT generate_series(1, 100); +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +BEGIN; +SET LOCAL stats_fetch_consistency = none; +-- Prime the database pending entry (and flush it) before touching the table. +SELECT 1 FROM pg_class LIMIT 1; + ?column? +---------- + 1 +(1 row) + +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT pg_stat_get_db_tuples_returned(:dboid) AS db_before \gset +-- Now scan the table; its 100 tuples feed the already-visited database entry. +SELECT count(*) FROM flush_db_lag; + count +------- + 100 +(1 row) + +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +-- The database aggregate must have advanced by at least the relation's own +-- 100 tuples in this same flush. It also counts catalog scans, so the +-- increase can only be larger, never smaller. Without re-queue the relation's +-- contribution would be deferred and the increase would fall short of 100. +SELECT pg_stat_get_db_tuples_returned(:dboid) - :db_before >= 100 AS db_kept_up; + db_kept_up +------------ + t +(1 row) + +COMMIT; +DROP TABLE flush_db_lag; +-- +-- Test an in-transaction flush with TRUNCATE. The truncate's reset of +-- live/dead counters is transactional and must not reach shared stats until +-- commit. +-- +CREATE TABLE xact_flush_truncate(id int) WITH (autovacuum_enabled = off); +INSERT INTO xact_flush_truncate SELECT generate_series(1, 100); +DELETE FROM xact_flush_truncate WHERE id <= 20; +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT n_live_tup AS n_live_tup_before, + n_dead_tup AS n_dead_tup_before, + seq_scan AS seq_scan_before + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate' \gset +-- Case 1 runs DML, TRUNCATE, more DML, then ROLLBACK. The truncate's zeroing +-- and all transactional counters must not leak to shared stats. +BEGIN; +SET LOCAL stats_fetch_consistency = none; +-- DML before truncate. +SELECT count(*) FROM xact_flush_truncate; + count +------- + 80 +(1 row) + +INSERT INTO xact_flush_truncate SELECT generate_series(101, 110); +UPDATE xact_flush_truncate SET id = id WHERE id = 1; +TRUNCATE xact_flush_truncate; +-- DML after truncate. +INSERT INTO xact_flush_truncate SELECT generate_series(1, 10); +-- Flush during a transaction. The scan reaches shared stats; the rest is deferred. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + n_live_tup = :n_live_tup_before AS live_tup_unchanged, + n_dead_tup = :n_dead_tup_before AS dead_tup_unchanged + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + seq_scan_delta | live_tup_unchanged | dead_tup_unchanged +----------------+--------------------+-------------------- + 2 | t | t +(1 row) + +ROLLBACK; +-- After rollback live_tup is unchanged, but dead_tup increases since the +-- aborted inserts leave dead tuples behind. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT n_live_tup = :n_live_tup_before AS live_tup_unchanged, + n_dead_tup - :n_dead_tup_before AS dead_tup_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + live_tup_unchanged | dead_tup_delta +--------------------+---------------- + t | 10 +(1 row) + +-- Case 2 runs DML, TRUNCATE, INSERT, DELETE, an aborted INSERT, then COMMIT. +-- Update the baseline to account for changes from case 1. +SELECT seq_scan AS seq_scan_before, + n_live_tup AS n_live_tup_before, + n_dead_tup AS n_dead_tup_before + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate' \gset +BEGIN; +SET LOCAL stats_fetch_consistency = none; +-- DML before truncate. +SELECT count(*) FROM xact_flush_truncate; + count +------- + 80 +(1 row) + +INSERT INTO xact_flush_truncate SELECT generate_series(101, 110); +UPDATE xact_flush_truncate SET id = id WHERE id = 1; +TRUNCATE xact_flush_truncate; +-- DML after truncate. +INSERT INTO xact_flush_truncate SELECT generate_series(1, 10); +DELETE FROM xact_flush_truncate WHERE id <= 3; +SAVEPOINT sp; +INSERT INTO xact_flush_truncate SELECT generate_series(1, 5); +ROLLBACK TO SAVEPOINT sp; +-- Flush during a transaction. The scan and the aborted inserts reach shared +-- stats; the rest is deferred. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + n_live_tup = :n_live_tup_before AS live_tup_unchanged, + n_dead_tup - :n_dead_tup_before AS dead_tup_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + seq_scan_delta | live_tup_unchanged | dead_tup_delta +----------------+--------------------+---------------- + 3 | t | 5 +(1 row) + +COMMIT; +-- After commit, TRUNCATE has zeroed live/dead, so the counts reflect only the +-- post-truncate inserts and deletes. n_ins_since_vacuum keeps the aborted +-- inserts already flushed. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT n_live_tup, n_dead_tup, n_ins_since_vacuum + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + n_live_tup | n_dead_tup | n_ins_since_vacuum +------------+------------+-------------------- + 7 | 3 | 15 +(1 row) + +DROP TABLE xact_flush_truncate; +-- +-- Test that pg_stat_force_next_flush() called inside a function does not +-- lose function call statistics. An in-transaction flush must not clear the +-- pending counts that the pg_stat_xact_user_functions view reports, and must +-- not lose or double-count the cumulative shared counts. +-- +SET track_functions TO 'all'; +CREATE FUNCTION flush_func_test() RETURNS VOID LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_stat_force_next_flush(); +END; +$$; +SELECT 'flush_func_test()'::regprocedure::oid AS flush_func_test_oid \gset +BEGIN; +SET LOCAL stats_fetch_consistency = none; +SELECT flush_func_test(); + flush_func_test +----------------- + +(1 row) + +SELECT flush_func_test(); + flush_func_test +----------------- + +(1 row) + +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +-- Function calls are not transactional, so the calls are visible in both +-- pg_stat_user_functions and pg_stat_xact_user_functions after the flush. The +-- flush must not clear the pending counts. +SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :flush_func_test_oid; + funcname | calls +-----------------+------- + flush_func_test | 2 +(1 row) + +SELECT pg_stat_get_xact_function_calls(:flush_func_test_oid) AS xact_calls; + xact_calls +------------ + 2 +(1 row) + +SELECT flush_func_test(); + flush_func_test +----------------- + +(1 row) + +COMMIT; +-- After commit the third call is visible too, with no call double-counted. +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :flush_func_test_oid; + funcname | calls +-----------------+------- + flush_func_test | 3 +(1 row) + +DROP FUNCTION flush_func_test; +-- +-- Test that a forced flush in a procedure publishes counters of a +-- transaction that already ended, but not those of the running one. +-- This includes HOT and new-page update counts. +-- +CREATE TABLE proc_flush(id int, v text); +ALTER TABLE proc_flush ALTER COLUMN v SET STORAGE PLAIN; +CREATE PROCEDURE proc_flush_probe(INOUT ins bigint DEFAULT NULL, + INOUT upd bigint DEFAULT NULL, + INOUT hot_upd bigint DEFAULT NULL, + INOUT newpage_upd bigint DEFAULT NULL) +LANGUAGE plpgsql AS $$ +DECLARE + big int := current_setting('block_size')::int * 6 / 10; +BEGIN + -- Two versions of this row do not fit on one page. + INSERT INTO proc_flush VALUES (1, repeat('x', big)); + UPDATE proc_flush SET v = repeat('y', big) WHERE id = 1; -- new page + UPDATE proc_flush SET v = 'z' WHERE id = 1; -- HOT + COMMIT; + INSERT INTO proc_flush VALUES (2, 'a'); + UPDATE proc_flush SET v = 'b' WHERE id = 2; -- HOT + PERFORM pg_stat_force_next_flush(); + SELECT n_tup_ins, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd + INTO ins, upd, hot_upd, newpage_upd + FROM pg_stat_user_tables WHERE relname = 'proc_flush'; +END; +$$; +SET stats_fetch_consistency = none; +CALL proc_flush_probe(); + ins | upd | hot_upd | newpage_upd +-----+-----+---------+------------- + 1 | 2 | 1 | 1 +(1 row) + +RESET stats_fetch_consistency; +DROP PROCEDURE proc_flush_probe; +DROP TABLE proc_flush; -- End of Stats Test diff --git a/src/test/regress/sql/stats.sql b/src/test/regress/sql/stats.sql index f4931fd84de..8c2f7e2246a 100644 --- a/src/test/regress/sql/stats.sql +++ b/src/test/regress/sql/stats.sql @@ -362,7 +362,6 @@ BEGIN; CREATE TEMPORARY TABLE test_last_scan(idx_col int primary key, noidx_col int); INSERT INTO test_last_scan(idx_col, noidx_col) VALUES(1, 1); SELECT pg_stat_force_next_flush(); -SELECT last_seq_scan, last_idx_scan FROM pg_stat_all_tables WHERE relid = 'test_last_scan'::regclass; COMMIT; SELECT stats_reset IS NOT NULL AS has_stats_reset @@ -1080,4 +1079,351 @@ SELECT fastpath_exceeded > :backend_fastpath_exceeded_before DROP TABLE part_test; +-- +-- Test in-transaction flushes +-- +CREATE TABLE xact_flush(id int) WITH (autovacuum_enabled = off); +INSERT INTO xact_flush VALUES (1), (2), (3); +SELECT pg_stat_force_next_flush(); + +-- Record counters before the explicit transaction +SELECT seq_scan AS seq_scan_before, + seq_tup_read AS seq_tup_read_before, + n_tup_ins AS n_tup_ins_before, + n_tup_upd AS n_tup_upd_before, + n_tup_hot_upd + n_tup_newpage_upd AS upd_detail_before + FROM pg_stat_user_tables WHERE relname = 'xact_flush' \gset + +BEGIN; +SET LOCAL stats_fetch_consistency = none; + +-- Generate both transaction-safe and transaction-unsafe counters. +SELECT count(*) FROM xact_flush; +INSERT INTO xact_flush VALUES (4), (5); +UPDATE xact_flush SET id = id WHERE id = 1; + +-- Flush in-transaction +SELECT pg_stat_force_next_flush(); + +-- Scans are visible in-transaction; ins and upd stay deferred. +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + seq_tup_read - :seq_tup_read_before AS seq_tup_read_delta, + n_tup_ins - :n_tup_ins_before AS n_tup_ins_delta, + n_tup_upd - :n_tup_upd_before AS n_tup_upd_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush'; + +-- The pg_stat_xact_user_tables view still reports this transaction's own +-- inserts and updates, which the flush leaves in the pending counts. +SELECT n_tup_ins, n_tup_upd + FROM pg_stat_xact_user_tables WHERE relname = 'xact_flush'; + +-- Generate more transaction-safe activity to verify no double counting. +SELECT count(*) FROM xact_flush; + +-- Flush again in-transaction +SELECT pg_stat_force_next_flush(); + +-- Should show cumulative totals, not double-counted. +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + seq_tup_read - :seq_tup_read_before AS seq_tup_read_delta, + n_tup_ins - :n_tup_ins_before AS n_tup_ins_delta, + n_tup_upd - :n_tup_upd_before AS n_tup_upd_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush'; + +COMMIT; + +-- After commit, all counters should be flushed. + +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + seq_tup_read - :seq_tup_read_before AS seq_tup_read_delta, + n_tup_ins - :n_tup_ins_before AS n_tup_ins_delta, + n_tup_upd - :n_tup_upd_before AS n_tup_upd_delta, + n_tup_hot_upd + n_tup_newpage_upd - :upd_detail_before AS upd_detail_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush'; + +DROP TABLE xact_flush; + +-- +-- Test in-transaction flushes of index statistics. An index scan reaches +-- shared stats during a transaction and must not be double-counted by a later flush. +-- +CREATE TABLE xact_flush_idx(id int primary key) WITH (autovacuum_enabled = off); +INSERT INTO xact_flush_idx SELECT generate_series(1, 100); +SELECT pg_stat_force_next_flush(); + +SELECT idx_scan AS idx_scan_before + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass \gset + +BEGIN; +SET LOCAL stats_fetch_consistency = none; +SET LOCAL enable_seqscan = off; +SET LOCAL enable_bitmapscan = off; + +-- Two index scans. +SELECT id FROM xact_flush_idx WHERE id = 1; +SELECT id FROM xact_flush_idx WHERE id = 2; + +-- Flush in-transaction; index stats are non-transactional and reach shared +-- stats now. +SELECT pg_stat_force_next_flush(); +SELECT idx_scan - :idx_scan_before AS idx_scan_delta + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass; + +-- Another index scan, then flush again to verify no double counting. +SELECT id FROM xact_flush_idx WHERE id = 3; +SELECT pg_stat_force_next_flush(); +SELECT idx_scan - :idx_scan_before AS idx_scan_delta + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass; + +COMMIT; + +-- After commit the count is unchanged from the last in-transaction flush. +SELECT pg_stat_force_next_flush(); +SELECT idx_scan - :idx_scan_before AS idx_scan_delta + FROM pg_stat_user_indexes WHERE indexrelid = 'xact_flush_idx_pkey'::regclass; + +DROP TABLE xact_flush_idx; + +-- +-- Roll back a savepoint after an in-transaction flush. The flush must not +-- write the subxact's inserts to shared stats. After commit the inserts made +-- outside the subxact count as live tuples while those rolled back count as +-- dead. +-- +CREATE TABLE subxact_flush(id int) WITH (autovacuum_enabled = off); +INSERT INTO subxact_flush SELECT generate_series(1, 50); +SELECT pg_stat_force_next_flush(); + +SELECT n_live_tup AS n_live_tup_before, + n_dead_tup AS n_dead_tup_before, + seq_scan AS seq_scan_before + FROM pg_stat_user_tables WHERE relname = 'subxact_flush' \gset + +BEGIN; +SET LOCAL stats_fetch_consistency = none; + +SELECT count(*) FROM subxact_flush; + +SAVEPOINT sp; +INSERT INTO subxact_flush SELECT generate_series(51, 80); + +-- Flush during a transaction. The scan reaches shared stats; the insert is deferred. +SELECT pg_stat_force_next_flush(); +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + n_live_tup = :n_live_tup_before AS live_tup_unchanged + FROM pg_stat_user_tables WHERE relname = 'subxact_flush'; + +ROLLBACK TO SAVEPOINT sp; +INSERT INTO subxact_flush SELECT generate_series(81, 90); + +COMMIT; + +-- After commit the inserts made outside the subxact count as live tuples, +-- those rolled back count as dead, and the in-transaction scan is still there. +SELECT pg_stat_force_next_flush(); +SELECT n_live_tup - :n_live_tup_before AS n_live_tup_delta, + n_dead_tup - :n_dead_tup_before AS n_dead_tup_delta, + seq_scan - :seq_scan_before AS seq_scan_delta + FROM pg_stat_user_tables WHERE relname = 'subxact_flush'; + +DROP TABLE subxact_flush; + +-- +-- Test that an in-transaction flush keeps the database aggregate in step with +-- the relation counters that feed it, rather than a flush behind. +-- +-- The relation flush accumulates into the database pending entry. If that +-- database entry was already visited earlier in the same flush pass, it must +-- be re-queued so the relation's contribution reaches shared stats in this +-- pass, not the next one. To force that ordering, prime the database pending +-- ahead of the table. Scan a catalog and flush (which leaves the database +-- entry pending), then scan the table and flush again. +-- +CREATE TABLE flush_db_lag(id int) WITH (autovacuum_enabled = off); +INSERT INTO flush_db_lag SELECT generate_series(1, 100); +SELECT pg_stat_force_next_flush(); + +BEGIN; +SET LOCAL stats_fetch_consistency = none; + +-- Prime the database pending entry (and flush it) before touching the table. +SELECT 1 FROM pg_class LIMIT 1; +SELECT pg_stat_force_next_flush(); + +SELECT pg_stat_get_db_tuples_returned(:dboid) AS db_before \gset + +-- Now scan the table; its 100 tuples feed the already-visited database entry. +SELECT count(*) FROM flush_db_lag; +SELECT pg_stat_force_next_flush(); + +-- The database aggregate must have advanced by at least the relation's own +-- 100 tuples in this same flush. It also counts catalog scans, so the +-- increase can only be larger, never smaller. Without re-queue the relation's +-- contribution would be deferred and the increase would fall short of 100. +SELECT pg_stat_get_db_tuples_returned(:dboid) - :db_before >= 100 AS db_kept_up; + +COMMIT; + +DROP TABLE flush_db_lag; + +-- +-- Test an in-transaction flush with TRUNCATE. The truncate's reset of +-- live/dead counters is transactional and must not reach shared stats until +-- commit. +-- +CREATE TABLE xact_flush_truncate(id int) WITH (autovacuum_enabled = off); +INSERT INTO xact_flush_truncate SELECT generate_series(1, 100); +DELETE FROM xact_flush_truncate WHERE id <= 20; +SELECT pg_stat_force_next_flush(); + +SELECT n_live_tup AS n_live_tup_before, + n_dead_tup AS n_dead_tup_before, + seq_scan AS seq_scan_before + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate' \gset + +-- Case 1 runs DML, TRUNCATE, more DML, then ROLLBACK. The truncate's zeroing +-- and all transactional counters must not leak to shared stats. +BEGIN; +SET LOCAL stats_fetch_consistency = none; + +-- DML before truncate. +SELECT count(*) FROM xact_flush_truncate; +INSERT INTO xact_flush_truncate SELECT generate_series(101, 110); +UPDATE xact_flush_truncate SET id = id WHERE id = 1; + +TRUNCATE xact_flush_truncate; + +-- DML after truncate. +INSERT INTO xact_flush_truncate SELECT generate_series(1, 10); + +-- Flush during a transaction. The scan reaches shared stats; the rest is deferred. +SELECT pg_stat_force_next_flush(); + +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + n_live_tup = :n_live_tup_before AS live_tup_unchanged, + n_dead_tup = :n_dead_tup_before AS dead_tup_unchanged + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + +ROLLBACK; + +-- After rollback live_tup is unchanged, but dead_tup increases since the +-- aborted inserts leave dead tuples behind. +SELECT pg_stat_force_next_flush(); +SELECT n_live_tup = :n_live_tup_before AS live_tup_unchanged, + n_dead_tup - :n_dead_tup_before AS dead_tup_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + +-- Case 2 runs DML, TRUNCATE, INSERT, DELETE, an aborted INSERT, then COMMIT. +-- Update the baseline to account for changes from case 1. +SELECT seq_scan AS seq_scan_before, + n_live_tup AS n_live_tup_before, + n_dead_tup AS n_dead_tup_before + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate' \gset + +BEGIN; +SET LOCAL stats_fetch_consistency = none; + +-- DML before truncate. +SELECT count(*) FROM xact_flush_truncate; +INSERT INTO xact_flush_truncate SELECT generate_series(101, 110); +UPDATE xact_flush_truncate SET id = id WHERE id = 1; + +TRUNCATE xact_flush_truncate; + +-- DML after truncate. +INSERT INTO xact_flush_truncate SELECT generate_series(1, 10); +DELETE FROM xact_flush_truncate WHERE id <= 3; +SAVEPOINT sp; +INSERT INTO xact_flush_truncate SELECT generate_series(1, 5); +ROLLBACK TO SAVEPOINT sp; + +-- Flush during a transaction. The scan and the aborted inserts reach shared +-- stats; the rest is deferred. +SELECT pg_stat_force_next_flush(); + +SELECT seq_scan - :seq_scan_before AS seq_scan_delta, + n_live_tup = :n_live_tup_before AS live_tup_unchanged, + n_dead_tup - :n_dead_tup_before AS dead_tup_delta + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + +COMMIT; + +-- After commit, TRUNCATE has zeroed live/dead, so the counts reflect only the +-- post-truncate inserts and deletes. n_ins_since_vacuum keeps the aborted +-- inserts already flushed. +SELECT pg_stat_force_next_flush(); +SELECT n_live_tup, n_dead_tup, n_ins_since_vacuum + FROM pg_stat_user_tables WHERE relname = 'xact_flush_truncate'; + +DROP TABLE xact_flush_truncate; + +-- +-- Test that pg_stat_force_next_flush() called inside a function does not +-- lose function call statistics. An in-transaction flush must not clear the +-- pending counts that the pg_stat_xact_user_functions view reports, and must +-- not lose or double-count the cumulative shared counts. +-- +SET track_functions TO 'all'; +CREATE FUNCTION flush_func_test() RETURNS VOID LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_stat_force_next_flush(); +END; +$$; +SELECT 'flush_func_test()'::regprocedure::oid AS flush_func_test_oid \gset + +BEGIN; +SET LOCAL stats_fetch_consistency = none; +SELECT flush_func_test(); +SELECT flush_func_test(); +SELECT pg_stat_force_next_flush(); + +-- Function calls are not transactional, so the calls are visible in both +-- pg_stat_user_functions and pg_stat_xact_user_functions after the flush. The +-- flush must not clear the pending counts. +SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :flush_func_test_oid; +SELECT pg_stat_get_xact_function_calls(:flush_func_test_oid) AS xact_calls; + +SELECT flush_func_test(); +COMMIT; + +-- After commit the third call is visible too, with no call double-counted. +SELECT pg_stat_force_next_flush(); +SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :flush_func_test_oid; + +DROP FUNCTION flush_func_test; + +-- +-- Test that a forced flush in a procedure publishes counters of a +-- transaction that already ended, but not those of the running one. +-- This includes HOT and new-page update counts. +-- +CREATE TABLE proc_flush(id int, v text); +ALTER TABLE proc_flush ALTER COLUMN v SET STORAGE PLAIN; +CREATE PROCEDURE proc_flush_probe(INOUT ins bigint DEFAULT NULL, + INOUT upd bigint DEFAULT NULL, + INOUT hot_upd bigint DEFAULT NULL, + INOUT newpage_upd bigint DEFAULT NULL) +LANGUAGE plpgsql AS $$ +DECLARE + big int := current_setting('block_size')::int * 6 / 10; +BEGIN + -- Two versions of this row do not fit on one page. + INSERT INTO proc_flush VALUES (1, repeat('x', big)); + UPDATE proc_flush SET v = repeat('y', big) WHERE id = 1; -- new page + UPDATE proc_flush SET v = 'z' WHERE id = 1; -- HOT + COMMIT; + INSERT INTO proc_flush VALUES (2, 'a'); + UPDATE proc_flush SET v = 'b' WHERE id = 2; -- HOT + PERFORM pg_stat_force_next_flush(); + SELECT n_tup_ins, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd + INTO ins, upd, hot_upd, newpage_upd + FROM pg_stat_user_tables WHERE relname = 'proc_flush'; +END; +$$; +SET stats_fetch_consistency = none; +CALL proc_flush_probe(); +RESET stats_fetch_consistency; +DROP PROCEDURE proc_flush_probe; +DROP TABLE proc_flush; + -- End of Stats Test -- 2.50.1