Flush some statistics within running transactions
Flush some statistics within running transactions
Hi hackers,
Long running transactions can accumulate significant statistics (WAL, IO, ...)
that remain unflushed until the transaction ends. This delays visibility of
resource usage in monitoring views like pg_stat_io and pg_stat_wal.
This patch series introduce the ability to $SUBJECT (suggested in [1]) to:
- improve monitoring of long running transactions
- avoid missing places where we should flush statistics (like the one fixed in
039549d70f6)
The patch series is made of 3 sub-patches:
0001: Add pgstat_report_anytime_stat() for periodic stats flushing
It introduces pgstat_report_anytime_stat(), which flushes non transactional
statistics even inside active transactions. A new timeout handler fires every
second to call this function, ensuring timely stats visibility without waiting
for transaction completion.
Implementation details:
- Add PgStat_FlushBehavior enum to classify stats kinds:
* FLUSH_ANYTIME: Stats that can always be flushed (WAL, IO, ...)
* FLUSH_AT_TXN_BOUNDARY: Stats requiring transaction boundaries
- Modify pgstat_flush_pending_entries() and pgstat_flush_fixed_stats() to accept
a boolean anytime_only parameter:
* When false: flushes all stats (existing behavior)
* When true: flushes only FLUSH_ANYTIME stats and skips FLUSH_AT_TXN_BOUNDARY
stats
- Register ANYTIME_STATS_UPDATE_TIMEOUT that fires every 1 second, calling
pgstat_report_anytime_stat(false)
Remarks:
- The force parameter in pgstat_report_anytime_stat() is currently unused (always
called with force=false) but reserved for future use cases requiring immediate flushing.
The 1 second flush interval is currently hardcoded but we could imagine increase
it or make it configurable. I ran some benchmarks and did not notice any noticeable
performance regression even with a large number of pending entries.
0002: Remove useless calls to flush some stats
Now that some stats can be flushed outside of transaction boundaries, remove
useless calls to flush some stats. Those calls were in place because
before 0001 stats were flushed only at transaction boundaries.
Remarks:
- it reverts 039549d70f6 (it just keeps its tests)
- it can't be done for checkpointer and bgworker for example because they don't
have a flush callback to call
- it can't be done for auxiliary process (walsummarizer for example) because they
currently do not register the new timeout handler
- we may want to improve the current behavior to "fix" the 2 above
0003: Add FLUSH_MIXED support and implement it for RELATION stats
This patch extends the non transactional stats infrastructure to support statistics
kinds with mixed transaction behavior: some fields are transactional (e.g., tuple
inserts/updates/deletes) while others are non transactional (e.g., sequential scans
blocks read, ...).
It introduces FLUSH_MIXED as a third flush behavior type, alongside FLUSH_ANYTIME
and FLUSH_AT_TXN_BOUNDARY. For FLUSH_MIXED kinds, a new flush_anytime_cb callback
enables partial flushing of only the non transactional fields during running
transactions.
Some tests are also added.
Implementation details:
- Add FLUSH_MIXED to PgStat_FlushBehavior enum
- Add flush_anytime_cb to PgStat_KindInfo for partial flushing callback
- Update pgstat_flush_pending_entries() to call flush_anytime_cb for
FLUSH_MIXED entries when in anytime_only mode
- Keep FLUSH_MIXED entries in the pending list after partial flush, as
transactional fields still need to be flushed at transaction boundary
RELATION stats are making use of FLUSH_MIXED:
- Change RELATION from TXN_ALL to FLUSH_MIXED
- Implement pgstat_relation_flush_anytime_cb() to flush only read related
stats: numscans, tuples_returned, tuples_fetched, blocks_fetched,
blocks_hit
- Clear these fields after flushing to prevent double counting when
pgstat_relation_flush_cb() runs at transaction commit
- Transactional stats (tuples_inserted, tuples_updated, tuples_deleted,
live_tuples, dead_tuples) remain pending until transaction boundary
Remark:
We could also imagine adding a new flush_anytime_static_cb() callback for
future FLUSH_MIXED fixed amount stats.
[1]: https://postgr.es/m/erpzwxoptqhuptdrtehqydzjapvroumkhh7lc6poclbhe7jk7l%40l3yfsq5q4pw7
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
Hi, Thanks for these patches! I took a quick look at the patches and I have some general comments. > Long running transactions can accumulate significant statistics (WAL, IO, ...) > that remain unflushed until the transaction ends. This delays visibility of > resource usage in monitoring views like pg_stat_io and pg_stat_wal. +1. I do think this is a good idea. Long-running transactions cause accumulated stats to appear as spikes in monitoring tools rather than as gradual activity. This would help level out, though not eliminate, those artificial spikes. > The 1 second flush interval is currently hardcoded but we could imagine increase > it or make it configurable. Someone may want to turn this off as well. I think a GUC will be needed. > RELATION stats are making use of FLUSH_MIXED: > stats: numscans, tuples_returned, tuples_fetched, blocks_fetched, > blocks_hit I’m concerned that fields being temporarily out of sync might impact monitoring calculations, if the formula is dealing with fields that have different flush strategies. That said, minor discrepancies are usually tolerable for monitoring data analysis. For the numscans, should we not also update the scan timestamp? -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Wed, Jan 14, 2026 at 09:54:17PM -0600, Sami Imseih wrote: > I took a quick look at the patches and I have some general comments. Thanks! > > > Long running transactions can accumulate significant statistics (WAL, IO, ...) > > that remain unflushed until the transaction ends. This delays visibility of > > resource usage in monitoring views like pg_stat_io and pg_stat_wal. > > +1. I do think this is a good idea. Long-running transactions cause accumulated > stats to appear as spikes in monitoring tools rather than as gradual activity. > This would help level out, though not eliminate, those artificial spikes. Yeah. > > The 1 second flush interval is currently hardcoded but we could imagine increase > > it or make it configurable. > > Someone may want to turn this off as well. I think a GUC will be needed. I gave this more thoughts and I wonder if this should be configurable at all. I mean, we don't do it for PGSTAT_MIN_INTERVAL, PGSTAT_MAX_INTERVAL and PGSTAT_IDLE_INTERVAL. We could imagine make it configurable if it produces noticeable performance impact but that's not what I observed. > > RELATION stats are making use of FLUSH_MIXED: > > > stats: numscans, tuples_returned, tuples_fetched, blocks_fetched, > > blocks_hit > > I’m concerned that fields being temporarily out of sync might impact monitoring > calculations, if the formula is dealing with fields that have > different flush strategies. That's a good point. Maybe we should document the fields flush strategy? > That said, minor discrepancies are usually tolerable for monitoring > data analysis. > > For the numscans, should we not also update the scan timestamp? The problem is that we could not call GetCurrentTransactionStopTimestamp(), so we would need to call GetCurrentTimestamp() instead. I'm not sure that calling GetCurrentTimestamp() every second would be a real issue though, and if it is maybe we could increase this 1s value. That said I agree that having seq_scan being updated and not last_seq_scan is not that great. Maybe we should keep this in mind and see what to do depending where this thread is going (I mean if the current proposed design has to be changed). Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > > The 1 second flush interval is currently hardcoded but we could imagine increase
> > > it or make it configurable.
> >
> > Someone may want to turn this off as well. I think a GUC will be needed.
>
> I gave this more thoughts and I wonder if this should be configurable at all.
> I mean, we don't do it for PGSTAT_MIN_INTERVAL, PGSTAT_MAX_INTERVAL and
> PGSTAT_IDLE_INTERVAL. We could imagine make it configurable if it produces
> noticeable performance impact but that's not what I observed.
Is there a reason we need a new constant (PGSTAT_ANYTIME_FLUSH_INTERVAL)
for anytime flushes and can't rely on the existing PGSTAT_MIN_INTERVAL?
Also, How did you benchmark? I am less concerned about long running
transactions,
background processes and more about short/high concurrency transactions seeing
additional overhead due to additional flushing. Is that latter a concern?
> > > stats: numscans, tuples_returned, tuples_fetched, blocks_fetched,
> > > blocks_hit
> >
> > I’m concerned that fields being temporarily out of sync might impact monitoring
> > calculations, if the formula is dealing with fields that have
> > different flush strategies.
>
> That's a good point. Maybe we should document the fields flush strategy?
Yeah, we will need to document this.
> > That said, minor discrepancies are usually tolerable for monitoring
> > data analysis.
> >
> > For the numscans, should we not also update the scan timestamp?
>
> The problem is that we could not call GetCurrentTransactionStopTimestamp(), so
> we would need to call GetCurrentTimestamp() instead. I'm not sure that calling
> GetCurrentTimestamp() every second would be a real issue though, and if it is
> maybe we could increase this 1s value.
> That said I agree that having seq_scan being updated and not last_seq_scan is not
> that great.
with v3 , I checked by running seq scans in a long running transaction,
and I observed both for these values being updated at the same time. I think
this is OK.
# pgstat_relation_flush_anytime_cb
```
tabentry->numscans += lstats->counts.numscans;
if (lstats->counts.numscans)
{
TimestampTz t = GetCurrentTimestamp();
if (t > tabentry->lastscan)
tabentry->lastscan = t;
}
```
and
# pgstat_relation_flush_cb
```
if (lstats->counts.numscans)
{
TimestampTz t = GetCurrentTransactionStopTimestamp();
if (t > tabentry->lastscan)
tabentry->lastscan = t;
}
```
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> with v3 , I checked by running seq scans in a long running transaction, Sorry I mean 0003 -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,
On Thu, Jan 15, 2026 at 11:25:18AM -0600, Sami Imseih wrote:
> > > > The 1 second flush interval is currently hardcoded but we could imagine increase
> > > > it or make it configurable.
> > >
> > > Someone may want to turn this off as well. I think a GUC will be needed.
> >
> > I gave this more thoughts and I wonder if this should be configurable at all.
> > I mean, we don't do it for PGSTAT_MIN_INTERVAL, PGSTAT_MAX_INTERVAL and
> > PGSTAT_IDLE_INTERVAL. We could imagine make it configurable if it produces
> > noticeable performance impact but that's not what I observed.
>
> Is there a reason we need a new constant (PGSTAT_ANYTIME_FLUSH_INTERVAL)
> for anytime flushes and can't rely on the existing PGSTAT_MIN_INTERVAL?
It currently gives flexibility for testing. If we agree that 1s is the right value
to set and that it should not be configurable then yeah we could replace it with
PGSTAT_MIN_INTERVAL then.
> Also, How did you benchmark? I am less concerned about long running
> transactions,
> background processes and more about short/high concurrency transactions seeing
> additional overhead due to additional flushing. Is that latter a concern?
I ran 3 kinds of tests:
1/
pgbench -c 32 -j 4 -T 60 -f short.sql -n -r $DB
with short.sql:
\set t1 random(1, 100)
\set t2 random(1, 100)
\set t3 random(1, 100)
\set t4 random(1, 100)
\set t5 random(1, 100)
\set t6 random(1, 100)
\set t7 random(1, 100)
\set t8 random(1, 100)
\set t9 random(1, 100)
\set t10 random(1, 100)
\set row random(1, 1000)
BEGIN;
UPDATE t:t1 SET val = val + 1 WHERE id = :row;
UPDATE t:t2 SET val = val + 1 WHERE id = :row;
UPDATE t:t3 SET val = val + 1 WHERE id = :row;
UPDATE t:t4 SET val = val + 1 WHERE id = :row;
UPDATE t:t5 SET val = val + 1 WHERE id = :row;
UPDATE t:t6 SET val = val + 1 WHERE id = :row;
UPDATE t:t7 SET val = val + 1 WHERE id = :row;
UPDATE t:t8 SET val = val + 1 WHERE id = :row;
UPDATE t:t9 SET val = val + 1 WHERE id = :row;
UPDATE t:t10 SET val = val + 1 WHERE id = :row;
COMMIT;
2/
psql $DB -f long.sql
with long.sql:
DO $$
BEGIN
FOR i IN 1..100 LOOP
EXECUTE format('TRUNCATE TABLE t%s', i);
EXECUTE format('INSERT INTO t%s SELECT generate_series(1, 1000000)', i);
EXECUTE format('UPDATE t%s SET val = val + 1', i);
EXECUTE format('SELECT COUNT(1) FROM t%s', i);
END LOOP;
END $$;
3/
pgbench -i -s 50 $DB
pgbench -c 32 -j 4 -T 60 -N -n -r $DB
I don't think this feature could add a noticeable performance impact, so the tests
have been that simple. Do you think we should worry more?
> > > I’m concerned that fields being temporarily out of sync might impact monitoring
> > > calculations, if the formula is dealing with fields that have
> > > different flush strategies.
> >
> > That's a good point. Maybe we should document the fields flush strategy?
>
> Yeah, we will need to document this.
Will do in the next version.
> I checked by running seq scans in a long running transaction,
> and I observed both for these values being updated at the same time. I think
> this is OK.
>
I do think the same.
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
I took a look at 0001 in depth.
> I don't think this feature could add a noticeable performance impact, so the tests
> have been that simple. Do you think we should worry more?
One observation is there's no coordination between ANYTIME and
TXN_BOUNDARY flushes. While PGSTAT_MIN_INTERVAL
prevents a backend from flushing more than once per second, a backend can
still perform both an ANYTIME flush and a TXN_BOUNDARY flush within
the same 1-second window. Not saying this will be a real problem in
the real-world,
but we definitely took measures in the current implementation to avoid
this scenario.
A few other comments on 0001
+ /* Skip if completely idle */
+ if (!DoingCommandRead || IsTransactionOrTransactionBlock())
+ pgstat_report_anytime_stat(false);
Does this need to be conditional? worst case, we return right away with an empty
list. Best case, is we are consistently flushing.
+ /*
+ * When in anytime_only mode, the list may not be empty because
+ * FLUSH_AT_TXN_BOUNDARY entries were skipped.
+ */
+ Assert(!anytime_only || dlist_is_empty(&pgStatPending) ==
!have_pending);
Checking for !anytime_only is unnecessary here.
"list_is_empty(&pgStatPending) == !have_pending"
should be true regardless of ANYTIME or TXN_BOUNDARY, right?
Below are a couple of edits for comments I felt would improve
readability of the code.
1/
/*
- * Flush non-transactional stats
- *
- * This is safe to call even inside a transaction. It only flushes stats
- * kinds marked as FLUSH_ANYTIME.
- *
- * This allows long running transactions to report activity without waiting
- * for transaction to finish.
+ * Flushes only FLUSH_ANYTIME stats using non-blocking locks. Transactional
+ * stats (FLUSH_AT_TXN_BOUNDARY) remain pending until transaction boundary.
+ * Safe to call inside transactions.
*/
2/
typedef enum PgStat_FlushBehavior
{
- FLUSH_ANYTIME, /* All fields can
flush anytime */
- FLUSH_AT_TXN_BOUNDARY, /* All fields need transaction
boundary */
+ FLUSH_ANYTIME, /* All fields can be
flushed anytime,
+ *
including within transactions */
+ FLUSH_AT_TXN_BOUNDARY, /* All fields can only be flushed at
+ *
transaction boundary */
} PgStat_FlushBehavior;
I will start looking at the remaining patches next.
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
Hi, On Fri, Jan 16, 2026 at 10:44:48AM -0600, Sami Imseih wrote: > I took a look at 0001 in depth. Thanks! > > I don't think this feature could add a noticeable performance impact, so the tests > > have been that simple. Do you think we should worry more? > > One observation is there's no coordination between ANYTIME and > TXN_BOUNDARY flushes. While PGSTAT_MIN_INTERVAL > prevents a backend from flushing more than once per second, a backend can > still perform both an ANYTIME flush and a TXN_BOUNDARY flush within > the same 1-second window. Not saying this will be a real problem in > the real-world, > but we definitely took measures in the current implementation to avoid > this scenario. Right. I think that the PGSTAT_MIN_INTERVAL throttling was put in place to prevent flushing too frequently when the backend has a high commit rate. But here, while it's true that we don't follow that rule (means a backend could flush more than one time per second), that would be a maximum of 2 times (given that ANYTIME is flushing every second). So, I'm not sure that this single extra flush is worth worrying about. Plus we'd certainly need an extra GetCurrentTimestamp() call, so I'm not sure it's worth it. > A few other comments on 0001 > > + /* Skip if completely idle */ > + if (!DoingCommandRead || IsTransactionOrTransactionBlock()) > + pgstat_report_anytime_stat(false); > > Does this need to be conditional? worst case, we return right away with an empty > list. Best case, is we are consistently flushing. Yeah, I think we could remove this check and just rely on the ones in pgstat_report_anytime_stat(). Done in the attached. > + Assert(!anytime_only || dlist_is_empty(&pgStatPending) == > !have_pending); > > Checking for !anytime_only is unnecessary here. > "list_is_empty(&pgStatPending) == !have_pending" > should be true regardless of ANYTIME or TXN_BOUNDARY, right? Right, thanks for catching it, it was remaining garbage from my dev iterations. > Below are a couple of edits for comments I felt would improve > readability of the code. Done as suggested. > I will start looking at the remaining patches next. Thanks! Note that I also updated the doc in 0003 for the stats that have mixed fields. BTW, I think that we could also make the Function stat kind as flush any time, thoughts? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
Thanks for the updates!
> > > I don't think this feature could add a noticeable performance impact, so the tests
> > > have been that simple. Do you think we should worry more?
> >
> > One observation is there's no coordination between ANYTIME and
> > TXN_BOUNDARY flushes. While PGSTAT_MIN_INTERVAL
> > prevents a backend from flushing more than once per second, a backend can
> > still perform both an ANYTIME flush and a TXN_BOUNDARY flush within
> > the same 1-second window. Not saying this will be a real problem in
> > the real-world,
> > but we definitely took measures in the current implementation to avoid
> > this scenario.
>
> Right. I think that the PGSTAT_MIN_INTERVAL throttling was put in place to prevent
> flushing too frequently when the backend has a high commit rate. But here, while
> it's true that we don't follow that rule (means a backend could flush more than one
> time per second), that would be a maximum of 2 times (given that ANYTIME is
> flushing every second). So, I'm not sure that this single extra flush is worth
> worrying about. Plus we'd certainly need an extra GetCurrentTimestamp() call, so
> I'm not sure it's worth it.
Yeah, all PGSTAT_MIN_INTERVAL does is throttle pgstat_flush_pending_entries.
Even in the current state, it does not limit how many kinds are flushed, etc.
I consider the ANYTIME flushes the same as just adding another stats kind.
So, I am not really worried about either.
I have some more comments:
-- v2-0001
#1.
+/* When to call pgstat_report_anytime_stat() again */
+#define PGSTAT_ANYTIME_FLUSH_INTERVAL 1000
+
We should just use PGSTAT_MIN_INTERVAL.
#2.
instead of ".flush_behavior", maybe ".flush_mode"? "mode" in the name is better
for configuration fields.
#3.
+/*
+ * Flush behavior for statistics kinds.
+ */
+typedef enum PgStat_FlushBehavior
+{
+ FLUSH_ANYTIME, /* All fields can be
flushed anytime,
+ *
including within transactions */
+ FLUSH_AT_TXN_BOUNDARY, /* All fields can only be flushed at
+ *
transaction boundary */
+} PgStat_FlushBehavior;
FLUSH_AT_TXN_BOUNDARY should be the first value in PgStat_FlushBehavior.
Otherwise kinds ( built-in or custom ) that do not specify a flush_behavior
will default to FLUSH_ANYTIME. I don't think this is what we want.
FLUSH_AT_TXN_BOUNDARY should be the default.
#4. Can we add a test here? Maybe generate some wal inside a long
running transaction and
make sure the stats are updated after > 1 second
-- v2-0002
No comments for this one. With ANYTIME, indeed those flushes are not needed.
-- v2-0003
#1. Should we maybe make this a bit longer? maybe 2 or 3 seconds?
May make the tests slightly longer, but maybe better for test stability.
```
+step s1_sleep: SELECT pg_sleep(1.5);
+pg_sleep
+--------
```
#2.
+ /*
+ * Check if there are any non-transactional stats to flush. Avoid
+ * unnecessarily locking the entry if nothing accumulated.
+ */
+ if (lstats->counts.numscans > 0 ||
+ lstats->counts.tuples_returned > 0 ||
+ lstats->counts.tuples_fetched > 0 ||
+ lstats->counts.blocks_fetched > 0 ||
+ lstats->counts.blocks_hit > 0)
+ has_nontxn_stats = true;
+
+ if (!has_nontxn_stats)
+ return true;
Can we just do this without a has_nontxn_stats?
This is also the same patter as a regular flush, although
in the case `pg_memory_is_all_zeros` is used.
```
if (lstats->counts.numscans == 0 &&
lstats->counts.tuples_returned == 0 &&
lstats->counts.tuples_fetched == 0 &&
lstats->counts.blocks_fetched == 0 &&
lstats->counts.blocks_hit == 0)
return true;
```
#3.
+ are updated while the transactions are in progress. This means
that we can see
+ those statistics being updated without having to wait until the transaction
+ finishes.
+
The "This means ...... " line used several times does not add value, IMO.
"are updated while the transactions are in progress." is sufficient.
#4.
+
+
+ All the statistics are updated while the transactions are in
progress, except
+ for xact_commit,
xact_rollback,
+ tup_inserted,
tup_updated and
+ tup_deleted that are updated only when
the transactions
+ finish.
+
+
Only these 5 fields from pgstat_relation_flush_anytime_cb, so only the below are
"All the statistics are updated while the transactions are in progress", right?
numscans
tuples_returned
tuples_fetched
blocks_fetched
blocks_hit
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello @@ -264,6 +266,12 @@ typedef struct PgStat_KindInfo /* Flush behavior */ PgStat_FlushBehavior flush_behavior; + /* + * For PGSTAT_FLUSH_MIXED kinds: callback to flush only some fields. If + * NULL for a MIXED kind, treated as PGSTAT_FLUSH_AT_TXN_BOUNDARY. + */ + bool (*flush_anytime_cb) (PgStat_EntryRef *entry_ref, bool nowait); + The comment seems to use incorrect names, shouldn't be FLUSH_MIXED and FLUSH_AT_TXN_BOUNDARY without PGSTAT_?
Re: Flush some statistics within running transactions
Hi, On Tue, Jan 20, 2026 at 01:27:55PM -0600, Sami Imseih wrote: > I have some more comments: Thanks! > -- v2-0001 > > #1. > > +/* When to call pgstat_report_anytime_stat() again */ > +#define PGSTAT_ANYTIME_FLUSH_INTERVAL 1000 > + > > We should just use PGSTAT_MIN_INTERVAL. Okay, done. We can still switch to a dedicated one if we feel the need later on. > #2. > > instead of ".flush_behavior", maybe ".flush_mode"? "mode" in the name is better > for configuration fields. Sounds good. > #3. > > FLUSH_AT_TXN_BOUNDARY should be the first value in PgStat_FlushBehavior. > Otherwise kinds ( built-in or custom ) that do not specify a flush_behavior > will default to FLUSH_ANYTIME. I don't think this is what we want. > FLUSH_AT_TXN_BOUNDARY should be the default. Good point, agreed and done. > #4. Can we add a test here? Maybe generate some wal inside a long > running transaction and > make sure the stats are updated after > 1 second I'm not sure, that's also somehow the purpose of 0002 (with 039549d70f6 being reverted). 0001 and 0002 could be merged and pushed as one commit. That said I'm not opposed if you feel strongly about it. > -- v2-0003 > > #1. Should we maybe make this a bit longer? maybe 2 or 3 seconds? > May make the tests slightly longer, but maybe better for test stability. > > ``` > +step s1_sleep: SELECT pg_sleep(1.5); > +pg_sleep > +-------- > ``` Not sure, we could increase if we see the test failing. > #2. > + /* > + * Check if there are any non-transactional stats to flush. Avoid > + * unnecessarily locking the entry if nothing accumulated. > + */ > + if (lstats->counts.numscans > 0 || > + lstats->counts.tuples_returned > 0 || > + lstats->counts.tuples_fetched > 0 || > + lstats->counts.blocks_fetched > 0 || > + lstats->counts.blocks_hit > 0) > + has_nontxn_stats = true; > + > + if (!has_nontxn_stats) > + return true; > Can we just do this without a has_nontxn_stats? Yeah. > #3. > + are updated while the transactions are in progress. This means > that we can see > + those statistics being updated without having to wait until the transaction > + finishes. > + > > The "This means ...... " line used several times does not add value, IMO. > "are updated while the transactions are in progress." is sufficient. Removed. > > #4. > + > + > + All the statistics are updated while the transactions are in > progress, except > + for xact_commit, > xact_rollback, > + tup_inserted, > tup_updated and > + tup_deleted that are updated only when > the transactions > + finish. > + > + > > Only these 5 fields from pgstat_relation_flush_anytime_cb, so only the below are > "All the statistics are updated while the transactions are in progress", right? > > numscans > tuples_returned > tuples_fetched > blocks_fetched > blocks_hit No, 0003 also changes the flush mode for the database KIND. All the fields that I mentioned are inherited from relations stats and are flushed only at transaction boundaries (so they don't appear in pg_stat_database until the transaction finishes). Does that make sense? (if the database kind is not switched to flush any time then none would appear while the transaction is in progress, even the ones inherited from relations stats). PFA v3, also taking care of Zsolt's comment (thanks!) done up-thread. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
Thanks for the updated patches! > No, 0003 also changes the flush mode for the database KIND. All the fields that > I mentioned are inherited from relations stats and are flushed only at transaction > boundaries (so they don't appear in pg_stat_database until the transaction > finishes). Does that make sense? yes, I understand it clearly now. But, the Note under pg_stat_database reads like this: "All the statistics are updated while the transactions are in progress, except for xact_commit, xact_rollback, tup_inserted, tup_updated and tup_deleted that are updated only when the transactions finish." But that is not true for all pg_stat_database fields, such as session_time, active_time, idle_in_transaction_time, etc. From what I can tell some of their fields are updated when the connection is closed. For example in one session run "select pg_sleep(10)" and in another session monitor pg_stat_database.active_time. That will not be updated until the session is closed. This is because these are not relation stats, which makes sense. The Note section should elaborate more on this, right? -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
On Wed, Jan 21, 2026 at 10:34:09AM +0000, Bertrand Drouvot wrote: > No, 0003 also changes the flush mode for the database KIND. All the fields that > I mentioned are inherited from relations stats and are flushed only at transaction > boundaries (so they don't appear in pg_stat_database until the transaction > finishes). Does that make sense? (if the database kind is not switched to > flush any time then none would appear while the transaction is in progress, even > the ones inherited from relations stats). > > PFA v3, also taking care of Zsolt's comment (thanks!) done up-thread. While reading through 0001, I got to question on which properties and/or assumptions of a stats kind one has to rely on to decide to what flush_mode should be set. To put is simpler, why don't we just do a periodic pgstat_report_stat(false) call that would flush all the stats for all stats kinds based on the new timeout registered, expanding a bit the flush we currently do when idle in ProcessInterrupts()? It seems that one point of contention should be that we should be careful with entries in the shmem hash table that have been created in a transactional way, but we may already flush them while we are in a transaction state, no? Are there any fields in a stats kind that we do may not want to flush? If yes, it sounds to me that it would be better to document these in the structures to explain the reason why a flush mode is chosen over the other. I am also not convinced that we have to be that aggressive with these extra flushes. The target is long-running analytical queries, that could take minutes or even hours. Using the same value as PGSTAT_IDLE_INTERVAL (10s), perhaps renaming the value while on it, would be a more natural fit. A 1s vs 10s report interval does not really matter for long analytical queries, where I'd imagine data being picked up on at least a 30s interval, at the shortest. Of course, one may want to get a more "live" representation of the data with more aggressive flushes, but is that really helpful for long-running queries to have more granularity, stressing more the shmem state? -- Michael
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > No, 0003 also changes the flush mode for the database KIND. All the fields that > > I mentioned are inherited from relations stats and are flushed only at transaction > > boundaries (so they don't appear in pg_stat_database until the transaction > > finishes). Does that make sense? (if the database kind is not switched to > > flush any time then none would appear while the transaction is in progress, even > > the ones inherited from relations stats). > > > > PFA v3, also taking care of Zsolt's comment (thanks!) done up-thread. > > While reading through 0001, I got to question on which properties > and/or assumptions of a stats kind one has to rely on to decide to > what flush_mode should be set. To put is simpler, why don't we just > do a periodic pgstat_report_stat(false) call that would flush all the > stats for all stats kinds based on the new timeout registered, > expanding a bit the flush we currently do when idle in > ProcessInterrupts()? There are some important cases in which we would want to distinguish between a "transaction boundary" flush vs an "anytime" flush. For example, xact_commit/rollback. I would want those fields to be in sync with tuples_inserted/updated/deleted to allow for accurate calculations like number of inserts per commit, etc. Another one would be n_mod_since_analyze, That should only be updated after commit (or not after rollback). Otherwise, it may throw autovanalyze threshold calculations way off. Same for n_dead_tup and autovacuum. > I am also not convinced that we have to be that aggressive with these > extra flushes. The target is long-running analytical queries, that > could take minutes or even hours. Using the same value as > PGSTAT_IDLE_INTERVAL (10s), PGSTAT_IDLE_INTERVAL is flushing an idle backend every 10 seconds IIUC. So this value only applies when outside of a transaction. > A 1s vs 10s report interval does not really matter for long analytical queries. Sure, Bertrand mentioned early in the thread that the anytime flushes could be made configurable. Perhaps that is a good idea where we can default with something large like 10s intervals for anytime flushes, but allow the user to configure a more frequent flushes ( although I would think that 1 sec is the minimum we should allow ). -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Thu, Jan 22, 2026 at 10:41 AM Sami Imseih wrote: > > > > No, 0003 also changes the flush mode for the database KIND. All the fields that > > > I mentioned are inherited from relations stats and are flushed only at transaction > > > boundaries (so they don't appear in pg_stat_database until the transaction > > > finishes). Does that make sense? (if the database kind is not switched to > > > flush any time then none would appear while the transaction is in progress, even > > > the ones inherited from relations stats). > > > > > > PFA v3, also taking care of Zsolt's comment (thanks!) done up-thread. > > > > While reading through 0001, I got to question on which properties > > and/or assumptions of a stats kind one has to rely on to decide to > > what flush_mode should be set. To put is simpler, why don't we just > > do a periodic pgstat_report_stat(false) call that would flush all the > > stats for all stats kinds based on the new timeout registered, > > expanding a bit the flush we currently do when idle in > > ProcessInterrupts()? > > There are some important cases in which we would want to > distinguish between a "transaction boundary" flush vs an > "anytime" flush. > > For example, xact_commit/rollback. I would want those > fields to be in sync with tuples_inserted/updated/deleted > to allow for accurate calculations like number of inserts > per commit, etc. > > Another one would be n_mod_since_analyze, That should > only be updated after commit (or not after rollback). Otherwise, > it may throw autovanalyze threshold calculations way off. Same > for n_dead_tup and autovacuum. > > > I am also not convinced that we have to be that aggressive with these > > extra flushes. The target is long-running analytical queries, that > > could take minutes or even hours. Using the same value as > > PGSTAT_IDLE_INTERVAL (10s), > > PGSTAT_IDLE_INTERVAL is flushing an idle backend every 10 seconds > IIUC. So this value only applies when outside of a transaction. > > > A 1s vs 10s report interval does not really matter for long analytical queries. > > Sure, Bertrand mentioned early in the thread that the anytime flushes > could be made configurable. Perhaps that is a good idea where we can > default with something large like 10s intervals for anytime flushes, but allow > the user to configure a more frequent flushes ( although I would think > that 1 sec is the minimum we should allow ). +1 on adding an option to control the interval. With a fixed interval (for example, 1s), log_lock_waits messages could be emitted that frequently, which may be annoying for some users. Of course, it would be even better if these periodic wakeups did not trigger log_lock_waits messages at all, though. Regards, -- Fujii Masao
Re: Flush some statistics within running transactions
On Wed, Jan 21, 2026 at 07:41:30PM -0600, Sami Imseih wrote: > Another one would be n_mod_since_analyze, That should > only be updated after commit (or not after rollback). Otherwise, > it may throw autovanalyze threshold calculations way off. Same > for n_dead_tup and autovacuum. Point taken. It sounds like it is going to be super important to document in the patch these kind of current expectations, so as one does not flip the flush mode one way or another incorrectly, or assigns an incorrect flush mode when adding a new stats kind. It's probably worth documenting that the end-of-transaction flush should be the default norm, while the out-of-transaction case should be an exception one needs to be careful of. > Sure, Bertrand mentioned early in the thread that the anytime flushes > could be made configurable. Perhaps that is a good idea where we can > default with something large like 10s intervals for anytime flushes, but allow > the user to configure a more frequent flushes ( although I would think > that 1 sec is the minimum we should allow ). Sure, I am just mentioning that we should not be that aggressive for everybody. If this can be made configurable on a call-basis, even if it means a new GUC, that may be better in the long run. -- Michael
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Thu, Jan 22, 2026 at 10:56:48AM +0900, Fujii Masao wrote: > On Thu, Jan 22, 2026 at 10:41 AM Sami Imseih wrote: > > > > Sure, Bertrand mentioned early in the thread that the anytime flushes > > could be made configurable. Perhaps that is a good idea where we can > > default with something large like 10s intervals for anytime flushes, but allow > > the user to configure a more frequent flushes ( although I would think > > that 1 sec is the minimum we should allow ). > > +1 on adding an option to control the interval. With a fixed interval > (for example, 1s), log_lock_waits messages could be emitted that frequently, > which may be annoying for some users. > > Of course, it would be even better if these periodic wakeups did not trigger > log_lock_waits messages at all, though. pgstat_report_anytime_stat() is called with the force parameter set to false, means that the flushes are done with nowait = true means that LWLockConditionalAcquire() is used. In that case, do you still see cases where log_lock_waits messages could be triggered due to the new flush? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Thu, Jan 22, 2026 at 11:28:06AM +0900, Michael Paquier wrote: > On Wed, Jan 21, 2026 at 07:41:30PM -0600, Sami Imseih wrote: > > Another one would be n_mod_since_analyze, That should > > only be updated after commit (or not after rollback). Otherwise, > > it may throw autovanalyze threshold calculations way off. Same > > for n_dead_tup and autovacuum. > > Point taken. It sounds like it is going to be super important to > document in the patch these kind of current expectations, so as one > does not flip the flush mode one way or another incorrectly, or > assigns an incorrect flush mode when adding a new stats kind. It's > probably worth documenting that the end-of-transaction flush should be > the default norm, while the out-of-transaction case should be an > exception one needs to be careful of. Agreed, I'll add more explanations around that. > > Sure, Bertrand mentioned early in the thread that the anytime flushes > > could be made configurable. Perhaps that is a good idea where we can > > default with something large like 10s intervals for anytime flushes, but allow > > the user to configure a more frequent flushes ( although I would think > > that 1 sec is the minimum we should allow ). > > Sure, I am just mentioning that we should not be that aggressive for > everybody. I'm not opposed to increase the flush frequency but I suppose most of the monitoring tools are sampling at a 1s frequency. So, if we set the flush frequency to say 10s, that would result in "spikes" every 10s. That's misleading, because it's not a spike in activity, it's a delay in reporting. I think that would make sense if we expect the 1s interval to have a negative impact, but that's not what I expect and observed. > If this can be made configurable on a call-basis, even if > it means a new GUC, that may be better in the long run. If we think that the 1s interval is a problem, we could go in that direction. Though it might be better to hardcode a larger value instead of letting the users set values that could be problematic. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Wed, Jan 21, 2026 at 05:41:13PM -0600, Sami Imseih wrote: > Thanks for the updated patches! > > > No, 0003 also changes the flush mode for the database KIND. All the fields that > > I mentioned are inherited from relations stats and are flushed only at transaction > > boundaries (so they don't appear in pg_stat_database until the transaction > > finishes). Does that make sense? > > yes, I understand it clearly now. > > But, the Note under pg_stat_database reads like this: > > "All the statistics are updated while the transactions are in progress, > except for xact_commit, xact_rollback, tup_inserted, tup_updated > and tup_deleted that are updated only when the transactions finish." > > But that is not true for all pg_stat_database fields, such as session_time, > active_time, idle_in_transaction_time, etc. From what I can tell some of their > fields are updated when the connection is closed. For example > in one session run "select pg_sleep(10)" and in another session monitor > pg_stat_database.active_time. That will not be updated until the session > is closed. > > This is because these are not relation stats, which makes sense. The > Note section should elaborate more on this, right? Yeah, so, while pgstat_database_flush_cb() is now called every second (if there are pending stats), not all the stats would have their pending entries updated. For example, pgstat_update_dbstats() updates some of them: xact_commit, xact_rollback, blk_read_time, blk_write_time, session_time, active_time and idle_in_transaction_time but only at transaction boundaries. Indeed, pgstat_update_dbstats() is only called during pgstat_report_stat() and not during pgstat_report_anytime_stat(). I think that we could: 1. Update the doc as you suggest or 2. Call a modified version of pgstat_update_dbstats() in pgstat_report_anytime_stat() that would update blk_read_time, blk_write_time, session_time, active_time and idle_in_transaction_time but that would require an extra GetCurrentTimestamp() call. or 3. Call a modified version of pgstat_update_dbstats() in pgstat_report_anytime_stat() that would update the same as in 2. except session_time then avoiding the need of a GetCurrentTimestamp() extra call. I'm tempted to vote for 1. as I'm not sure of the added value of 2. and 3., thoughts? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Thu, Jan 22, 2026 at 4:43 PM Bertrand Drouvot
wrote:
>
> Hi,
>
> On Thu, Jan 22, 2026 at 10:56:48AM +0900, Fujii Masao wrote:
> > On Thu, Jan 22, 2026 at 10:41 AM Sami Imseih wrote:
> > >
> > > Sure, Bertrand mentioned early in the thread that the anytime flushes
> > > could be made configurable. Perhaps that is a good idea where we can
> > > default with something large like 10s intervals for anytime flushes, but allow
> > > the user to configure a more frequent flushes ( although I would think
> > > that 1 sec is the minimum we should allow ).
> >
> > +1 on adding an option to control the interval. With a fixed interval
> > (for example, 1s), log_lock_waits messages could be emitted that frequently,
> > which may be annoying for some users.
> >
> > Of course, it would be even better if these periodic wakeups did not trigger
> > log_lock_waits messages at all, though.
>
> pgstat_report_anytime_stat() is called with the force parameter set to false,
> means that the flushes are done with nowait = true means that LWLockConditionalAcquire()
> is used. In that case, do you still see cases where log_lock_waits messages could
> be triggered due to the new flush?
I haven't read the patch in detail yet, but after applying patch 0001 and
causing a lock wait (for example, using the steps below), I observed that
log_lock_waits messages are emitted every second.
[session 1]
create table tbl as select id from generate_series(1, 10) id;
begin;
select * from tbl where id = 1 for update;
[session 2]
begin;
select * from tbl where id = 1 for update;
With this setup, the following messages were logged once per second:
LOG: process 72199 still waiting for ShareLock on transaction 771
after 63034.119 ms
DETAIL: Process holding the lock: 72190. Wait queue: 72199.
Regards,
--
Fujii Masao
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Thu, Jan 22, 2026 at 09:12:18PM +0900, Fujii Masao wrote: > On Thu, Jan 22, 2026 at 4:43 PM Bertrand Drouvot > wrote: > > > > pgstat_report_anytime_stat() is called with the force parameter set to false, > > means that the flushes are done with nowait = true means that LWLockConditionalAcquire() > > is used. In that case, do you still see cases where log_lock_waits messages could > > be triggered due to the new flush? > > I haven't read the patch in detail yet, but after applying patch 0001 and > causing a lock wait (for example, using the steps below), I observed that > log_lock_waits messages are emitted every second. > > [session 1] > create table tbl as select id from generate_series(1, 10) id; > begin; > select * from tbl where id = 1 for update; > > [session 2] > begin; > select * from tbl where id = 1 for update; > > With this setup, the following messages were logged once per second: > > LOG: process 72199 still waiting for ShareLock on transaction 771 > after 63034.119 ms > DETAIL: Process holding the lock: 72190. Wait queue: 72199. > Thanks! I see, the WaitLatch() in ProcSleep() is "woken up" every 1s due to the enable_timeout_after(ANYTIME_STATS_UPDATE_TIMEOUT,...) being set unconditionally in ProcessInterrupts(). We need to be more restrictive as to when to enable the timeout, I'll fix in the next version. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> For example, pgstat_update_dbstats() updates some of them: xact_commit, xact_rollback, > blk_read_time, blk_write_time, session_time, active_time and idle_in_transaction_time > but only at transaction boundaries. Indeed, pgstat_update_dbstats() is only called > during pgstat_report_stat() and not during pgstat_report_anytime_stat(). > > I think that we could: > > 1. Update the doc as you suggest I am thinking the _time related fields are OK to be non-anytime fields, since they have overhead and also they can be actively monitored from pg_stat_activity if someone really needs real time information. The other session related counters don't need need special consideration. parallel counters are anytime. So, the documentation can mention the _time related fields that are flushed only at their appropriate times. Maybe something general like this: "Some statistics are updated while a transaction is in progress. Statistics that either do not depend on transactions or require transactional consistency are updated only when the transaction ends. Statistics that require transactional consistency include xact_commit, xact_rollback, tup_inserted, tup_updated, and tup_deleted." What do you think? -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
Hi, On Thu, Jan 22, 2026 at 04:45:31PM +0000, Bertrand Drouvot wrote: > On Thu, Jan 22, 2026 at 09:12:18PM +0900, Fujii Masao wrote: > > > > With this setup, the following messages were logged once per second: > > > > LOG: process 72199 still waiting for ShareLock on transaction 771 > > after 63034.119 ms > > DETAIL: Process holding the lock: 72190. Wait queue: 72199. > > > > Thanks! > > I see, the WaitLatch() in ProcSleep() is "woken up" every 1s due to the > enable_timeout_after(ANYTIME_STATS_UPDATE_TIMEOUT,...) being set unconditionally > in ProcessInterrupts(). We need to be more restrictive as to when to enable the > timeout, I'll fix in the next version. The attached, to apply on top of 0001, fix the issue. However it handles only the WaitLatch in ProcSleep() case and I start to have concern about the others WaitLatch() that would/could be "woken up" every 1s. Using disable_timeout() and enable_timeout_after() in WaitEventSetWait() does not look like a great answer to this concern, so I wonder if we should use a larger flush frequency instead (as proposed up-thread), thoughts? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Thu, Jan 22, 2026 at 11:23:29AM -0600, Sami Imseih wrote: > > For example, pgstat_update_dbstats() updates some of them: xact_commit, xact_rollback, > > blk_read_time, blk_write_time, session_time, active_time and idle_in_transaction_time > > but only at transaction boundaries. Indeed, pgstat_update_dbstats() is only called > > during pgstat_report_stat() and not during pgstat_report_anytime_stat(). > > > > I think that we could: > > > > 1. Update the doc as you suggest > > I am thinking the _time related fields are OK to be non-anytime > fields, since they > have overhead and also they can be actively monitored from pg_stat_activity > if someone really needs real time information. > > The other session related counters don't need need special consideration. > > parallel counters are anytime. > > So, the documentation can mention the _time related fields that are flushed > only at their appropriate times. > > Maybe something general like this: > > "Some statistics are updated while a transaction is in progress. > Statistics that either do > not depend on transactions or require transactional consistency are > updated only > when the transaction ends. Statistics that require transactional consistency > include xact_commit, xact_rollback, tup_inserted, tup_updated, and tup_deleted." > > What do you think? Thanks! That sounds good, maybe just change the first sentence to something like: " Some statistics are updated while a transaction is in progress (this includes blks_read, blks_hit, tup_returned and tup_fetched). " Thoughts? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> Some statistics are updated while a transaction is in progress (this includes > blks_read, blks_hit, tup_returned and tup_fetched). I am ok with this. Just a slight change. """ Some statistics are updated while a transaction is in progress (for example, blks_read, blks_hit, tup_returned, and tup_fetched). """ The difference is "for example" makes it clear this is not a comprehensive list. -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
On Mon, Jan 26, 2026 at 06:59:28AM +0000, Bertrand Drouvot wrote: > The attached, to apply on top of 0001, fix the issue. However it handles only the > WaitLatch in ProcSleep() case and I start to have concern about the others WaitLatch() > that would/could be "woken up" every 1s. Hmm, I indeed suspect that is may not be the only one.. This is much bigger. > Using disable_timeout() and enable_timeout_after() in WaitEventSetWait() does not > look like a great answer to this concern, so I wonder if we should use a larger > flush frequency instead (as proposed up-thread), thoughts? Only a larger frequency is not the correct answer here. It would just reduce the frequency of the extra lock wait messages for one: these should never appear more than necessary. And how about for example extension code? -- Michael
Re: Flush some statistics within running transactions
Hi, On Wed, Jan 28, 2026 at 03:35:21PM +0900, Michael Paquier wrote: > On Mon, Jan 26, 2026 at 06:59:28AM +0000, Bertrand Drouvot wrote: > > The attached, to apply on top of 0001, fix the issue. However it handles only the > > WaitLatch in ProcSleep() case and I start to have concern about the others WaitLatch() > > that would/could be "woken up" every 1s. > > > Using disable_timeout() and enable_timeout_after() in WaitEventSetWait() does not > > look like a great answer to this concern, so I wonder if we should use a larger > > flush frequency instead (as proposed up-thread), thoughts? > > Only a larger frequency is not the correct answer here. It would just > reduce the frequency of the extra lock wait messages for one: these > should never appear more than necessary. Right. The fix in fix_ProcSleep.txt shared up-thread solves that and has been added in 0001 attached. Also the attached is now split in 4 sub-patches with 0002 introducing a new GUC to control the flush interval (default is 10s). Note that 0001 to 0003 could be merged as one patch but I did it that way to ease the review. The new version also adds more documentation and takes care of Sami's comments shared up-thread. > And how about for example extension code? I think that depending on how they write their code around WaitLatch (if any) they could see messages being reported (if they do) in the logs at stats_flush_interval frequency. That said the default value is 10s and that looks pretty long for a latch to wait on. In any case, they should already take care of a latch being woken by WL_LATCH_SET. What do you think? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-22, Fujii Masao wrote: > I haven't read the patch in detail yet, but after applying patch 0001 and > causing a lock wait (for example, using the steps below), I observed that > log_lock_waits messages are emitted every second. Interesting. Bertrand asked me about this. He says[1] he diagnosed this down to SetLatch being called immediately after the handler runs, and I wonder if it's correct that other timeout handler functions used for RegisterTimeout are doing SetLatch(). The SIGALRM handler handle_sig_alarm() that calls the specific handler function already has a SetLatch call, so why do we need another one here? I tested this theory quickly by removing the SetLatch from IdleStatsUpdateTimeoutHandler() and rerunning the tests. (This one chosen because it has highest coverage per [2]). Everything passed, though of course this is probably not proof enough. Maybe we're just cargo-culting these SetLatch() calls? [1] https://postgr.es/m/aXJUK90lKXw3wrZn@ip-10-97-1-34.eu-west-3.compute.internal [2] https://coverage.postgresql.org/src/backend/utils/init/postinit.c.gcov.html -- Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/ "Right now the sectors on the hard disk run clockwise, but I heard a rumor that you can squeeze 0.2% more throughput by running them counterclockwise. It's worth the effort. Recommended." (Gerry Pourwelle)
Re: Flush some statistics within running transactions
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-30, Álvaro Herrera wrote:
> Interesting. Bertrand asked me about this. He says[1] he diagnosed this
> down to SetLatch being called immediately after the handler runs, and I
> wonder if it's correct that other timeout handler functions used for
> RegisterTimeout are doing SetLatch(). The SIGALRM handler
> handle_sig_alarm() that calls the specific handler function already has
> a SetLatch call, so why do we need another one here?
So apparently the first function to do this in postinit.c was added by
commit c6dda1f48e57 -- and apparently it was mimicking
CheckDeadLockAlert(), which at this time looked like this:
void
CheckDeadLockAlert(void)
{
int save_errno = errno;
got_deadlock_timeout = true;
/*
* Have to set the latch again, even if handle_sig_alarm already did. Back
* then got_deadlock_timeout wasn't yet set... It's unlikely that this
* ever would be a problem, but setting a set latch again is cheap.
*/
SetLatch(MyLatch);
errno = save_errno;
}
I wonder if it would work to move the SetLatch() that's currently at the
top of handle_sig_alarm() to the bottom, after we have called all the
specific handlers, and remove the ones that are there.
--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
Re: Flush some statistics within running transactions
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-30, Álvaro Herrera wrote: > So apparently the first function to do this in postinit.c was added by > commit c6dda1f48e57 -- and apparently it was mimicking > CheckDeadLockAlert(), which at this time looked like this: I'm now wondering if CheckDeadLockAlert() really needed to have this in the first place, or it was just an exercise in paranoia ... it was added by commit 6753333f55e1, with the discussion in [1], and it's not clear to me that there was any theoretical or experimental evidence that it was necessary; the thread didn't discuss it, and the commit message doesn't either. Added Andres to CC as committer to this thread, maybe he remembers. [1] https://www.postgresql.org/message-id/flat/20150115020335.GZ5245%40awork2.anarazel.de Just for laughs I moved the SetLatch call in handle_sig_alarm() to the bottom, and remove the ones in handlers, on the theory that by the time the SetLatch call is reached, all the handlers have already run and thus the flag variables are set. Everything seems to continue to work: https://cirrus-ci.com/build/5758839359799296 (Though to be honest, it's not clear to me why it would matter at which point in handle_sig_alarm we call SetLatch relative to the variables being set, given that these variables are only going to matter once the signal handler returns to the original code and the next CHECK_FOR_INTERRUPTS is hit.) -- Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/ "Pensar que el espectro que vemos es ilusorio no lo despoja de espanto, sólo le suma el nuevo terror de la locura" (Perelandra, C.S. Lewis)
Re: Flush some statistics within running transactions
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-01-30 15:37:57 +0100, Álvaro Herrera wrote: > I'm now wondering if CheckDeadLockAlert() really needed to have this in > the first place, or it was just an exercise in paranoia ... it was added > by commit 6753333f55e1, with the discussion in [1], and it's not clear > to me that there was any theoretical or experimental evidence that it > was necessary; the thread didn't discuss it, and the commit message > doesn't either. Added Andres to CC as committer to this thread, maybe > he remembers. I don't remember. But back then way more complicated things were still running in signal handlers, and some signal handlers were capable of interrupting other signal handlers. Including doing crazy things like starting transactions in signal handlers (e.g. to process notify interrupts), which in turn could clear latches. So there was a lot more potential to stomp on each others work. WRT the subject of this thread: I hope we aren't just enabling a timer to fire once a second forever but only when there actually is outstanding work? Greetings, Andres Freund
Re: Flush some statistics within running transactions
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-30, Andres Freund wrote: > I don't remember. But back then way more complicated things were still running > in signal handlers, and some signal handlers were capable of interrupting > other signal handlers. Including doing crazy things like starting transactions > in signal handlers (e.g. to process notify interrupts), which in turn could > clear latches. So there was a lot more potential to stomp on each others work. OK, thanks for clarifying. I think my proposal of moving the SetLatch() needs more research, but it's likely the best way to address this wrinkle. > WRT the subject of this thread: I hope we aren't just enabling a timer > to fire once a second forever but only when there actually is > outstanding work? I hope so too. (Just to be clear, I'm not claiming $SUBJECT as its potential committer, and haven't actually reviewed it.) -- Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/ "People get annoyed when you try to debug them." (Larry Wall)
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> Also the attached is now split in 4 sub-patches with 0002 introducing a new
> GUC to control the flush interval (default is 10s). Note that 0001 to 0003 could
> be merged as one patch but I did it that way to ease the review.
Thanks for the patches!
I do like the GUC introduced in 0002 to control the ANYTIME stats
flush interval.
But, as I was looking at this a bit more today and testing it, I am
not quite sure
I like what is happening here:
+void
+pgstat_report_anytime_stat(bool force)
+{
+ bool nowait = !force;
+
+ pgstat_assert_is_up();
+
+ /*
+ * Exit if no pending stats at all. This avoids unnecessary work when
+ * backends are idle or in sessions without stats accumulation.
+ *
+ * Note: This check isn't precise as there might be only transactional
+ * stats pending, which we'll skip during the flush. However,
maintaining
+ * precise tracking would add complexity that does not seem
worth it from
+ * a performance point of view (no noticeable performance regression has
+ * been observed with the current implementation).
+ */
+ if (dlist_is_empty(&pgStatPending) && !pgstat_report_fixed)
+ return;
+
+ /* Flush stats outside of transaction boundary */
+ pgstat_flush_pending_entries(nowait, true);
+ pgstat_flush_fixed_stats(nowait, true);
+}
There is a check if pgStatPending is empty so we can return early.
However, with FLUSH_MIXED, the scenario is we will more than likely always
have TXN_BOUNDARY stats that can only be flushed at the end of a transaction.
This means that most of the time we will call pgstat_flush_pending_entries
and then leave it up to the anytime_cb to check for pending ANYTIME stats to
flush (before taking the lock ).
+bool
+pgstat_relation_flush_anytime_cb(PgStat_EntryRef *entry_ref, bool nowait)
+{
+ Oid dboid;
+ PgStat_TableStatus *lstats; /* pending stats entry */
+ PgStatShared_Relation *shtabstats;
+ PgStat_StatTabEntry *tabentry; /* table entry of shared stats */
+ PgStat_StatDBEntry *dbentry; /* pending database entry */
+
+ dboid = entry_ref->shared_entry->key.dboid;
+ lstats = (PgStat_TableStatus *) entry_ref->pending;
+ shtabstats = (PgStatShared_Relation *) entry_ref->shared_stats;
+
+ /*
+ * Check if there are any non-transactional stats to flush. Avoid
+ * unnecessarily locking the entry if nothing accumulated.
+ */
+ if (!(lstats->counts.numscans > 0 ||
+ lstats->counts.tuples_returned > 0 ||
+ lstats->counts.tuples_fetched > 0 ||
+ lstats->counts.blocks_fetched > 0 ||
+ lstats->counts.blocks_hit > 0))
+ return true;
This makes things confusing because instead of just relying on
dlist_is_empty(&pgStatPending) to check if we need to flush anything,
the responsibility now moves to the callback, which now also has to
account for all the ANYTIME fields.
The way I can think about making this better is to somehow track if
we have ANYTIME data that needs to be flushed a different way
( maybe a second pgStatPending list for anytime stats ?? )
What do you think?
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> This makes things confusing because instead of just relying on
> dlist_is_empty(&pgStatPending) to check if we need to flush anything,
> the responsibility now moves to the callback, which now also has to
> account for all the ANYTIME fields.
>
> The way I can think about making this better is to somehow track if
> we have ANYTIME data that needs to be flushed a different way
> ( maybe a second pgStatPending list for anytime stats ?? )
Thinking about this a bit more, it seems the FLUSH_MIXED may
not be needed. Instead can we just introduce a new global variable
called pgstat_report_variable_anytime which acts like
pgstat_report_fixed, except it's set to true whenever we update
anytime variable-numbered stats
```
#define pgstat_count_heap_scan(rel)
\
do {
\
pgstat_report_variable_anytime = true;
\
if (pgstat_should_count_relation(rel))
\
(rel)->pgstat_info->counts.numscans++;
\
} while (0)
````
and reset whenever we call pgstat_report_anytime_stat, like this:
```
void
pgstat_report_anytime_stat(bool force)
{
.....
.........
if (!pgstat_report_variable_anytime && !pgstat_report_fixed)
return;
/* Flush stats outside of transaction boundary */
if (pgstat_report_variable_anytime)
pgstat_flush_pending_entries(nowait, true);
....
........
pgstat_report_variable_anytime = false;
}
```
and then inside pgstat_flush_pending_entries, we just look
for kind_info->flush_mode == FLUSH_ANYTIME to flush.
```
/* flush the stats (with the appropriate callback), if possible */
if (anytime_only &&
kind_info->flush_mode == FLUSH_ANYTIME &&
kind_info->flush_anytime_cb != NULL)
{
/* Partial flush of non-transactional fields only */
did_flush = kind_info->flush_anytime_cb(entry_ref, nowait);
is_partial_flush = true;
}
````
With this approach, we will not enter pgstat_flush_pending_entries
inside pgstat_report_anytime_stat unless we have anytime
variable stats to report.
Also, the anytime flush callback does not need to check if there are
any variable-numbered stats to flush. This will not be needed as
it is in v4-0004
```
+ /*
+ * Check if there are any non-transactional stats to flush. Avoid
+ * unnecessarily locking the entry if nothing accumulated.
+ */
+ if (!(lstats->counts.numscans > 0 ||
+ lstats->counts.tuples_returned > 0 ||
+ lstats->counts.tuples_fetched > 0 ||
+ lstats->counts.blocks_fetched > 0 ||
+ lstats->counts.blocks_hit > 0))
+ return true;
```
This feels like an easier approach to reason about and we don't
need to add a third flush mode.
Thoughts?
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
On Sat, Jan 31, 2026 at 11:16:03AM -0600, Sami Imseih wrote: > Also, the anytime flush callback does not need to check if there are > any variable-numbered stats to flush. This will not be needed as > it is in v4-0004 > > ``` > + /* > + * Check if there are any non-transactional stats to flush. Avoid > + * unnecessarily locking the entry if nothing accumulated. > + */ > + if (!(lstats->counts.numscans > 0 || > + lstats->counts.tuples_returned > 0 || > + lstats->counts.tuples_fetched > 0 || > + lstats->counts.blocks_fetched > 0 || > + lstats->counts.blocks_hit > 0)) > + return true; > ``` I think that this kind of check may finish by being expensive. Reducing the number of fields to check for a non-flushing state, if required, would be preferrable. -- Michael
Re: Flush some statistics within running transactions
Hi, On Sat, Jan 31, 2026 at 11:16:03AM -0600, Sami Imseih wrote: > > This makes things confusing because instead of just relying on > > dlist_is_empty(&pgStatPending) to check if we need to flush anything, > > the responsibility now moves to the callback, which now also has to > > account for all the ANYTIME fields. > > > > Thinking about this a bit more, it seems the FLUSH_MIXED may > not be needed. Instead can we just introduce a new global variable > called pgstat_report_variable_anytime which acts like > pgstat_report_fixed, except it's set to true whenever we update > anytime variable-numbered stats > > With this approach, we will not enter pgstat_flush_pending_entries > inside pgstat_report_anytime_stat unless we have anytime > variable stats to report. Thanks for looking at it! In v5 attached I changed the design so that we don't re-enable the timeout after each stats flush in ProcessInterrupts(). Instead the timeout is enabled when we set pgstat_report_fixed to true or in pgstat_prep_pending_entry() when appropriate. So that we know that when we enter pgstat_report_anytime_stat() that's for good reasons and we don't need extra checks in it. > ``` > + /* > + * Check if there are any non-transactional stats to flush. Avoid > + * unnecessarily locking the entry if nothing accumulated. > + */ > + if (!(lstats->counts.numscans > 0 || > + lstats->counts.tuples_returned > 0 || > + lstats->counts.tuples_fetched > 0 || > + lstats->counts.blocks_fetched > 0 || > + lstats->counts.blocks_hit > 0)) > + return true; > ``` Yeah, with the new design in place then those are not needed anymore. > This feels like an easier approach to reason about and we don't > need to add a third flush mode. I do think we still need it. Indeed in 0004 that helps distinguish between anytime flush or mixed flush (with the help of the new pgstat_report_mixed_anytime global variable) in pgstat_prep_pending_entry(). Thoughts? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Mon, Feb 02, 2026 at 04:31:48PM +0900, Michael Paquier wrote: > On Sat, Jan 31, 2026 at 11:16:03AM -0600, Sami Imseih wrote: > > Also, the anytime flush callback does not need to check if there are > > any variable-numbered stats to flush. This will not be needed as > > it is in v4-0004 > > > > ``` > > + /* > > + * Check if there are any non-transactional stats to flush. Avoid > > + * unnecessarily locking the entry if nothing accumulated. > > + */ > > + if (!(lstats->counts.numscans > 0 || > > + lstats->counts.tuples_returned > 0 || > > + lstats->counts.tuples_fetched > 0 || > > + lstats->counts.blocks_fetched > 0 || > > + lstats->counts.blocks_hit > 0)) > > + return true; > > ``` > > I think that this kind of check may finish by being expensive. > Reducing the number of fields to check for a non-flushing state, if > required, would be preferrable. Done, in v5 just shared up-thread. Oh and I forgot to mention that with the new design in v5, then the fix for the issue discovered by Masao-san is not needed anymore (and so has been removed from 0001). Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Fri, Jan 30, 2026 at 03:37:57PM +0100, Álvaro Herrera wrote: > On 2026-Jan-30, Álvaro Herrera wrote: > > > So apparently the first function to do this in postinit.c was added by > > commit c6dda1f48e57 -- and apparently it was mimicking > > CheckDeadLockAlert(), which at this time looked like this: > > I'm now wondering if CheckDeadLockAlert() really needed to have this in > the first place, or it was just an exercise in paranoia ... it was added > by commit 6753333f55e1, with the discussion in [1], and it's not clear > to me that there was any theoretical or experimental evidence that it > was necessary; the thread didn't discuss it, and the commit message > doesn't either. Added Andres to CC as committer to this thread, maybe > he remembers. > > [1] https://www.postgresql.org/message-id/flat/20150115020335.GZ5245%40awork2.anarazel.de > > Just for laughs I moved the SetLatch call in handle_sig_alarm() to the > bottom, and remove the ones in handlers, on the theory that by the time > the SetLatch call is reached, all the handlers have already run and thus > the flag variables are set. Everything seems to continue to work: > https://cirrus-ci.com/build/5758839359799296 Thanks for having looked at this! > (Though to be honest, it's not clear to me why it would matter at which > point in handle_sig_alarm we call SetLatch relative to the variables > being set, given that these variables are only going to matter once the > signal handler returns to the original code and the next > CHECK_FOR_INTERRUPTS is hit.) Yeah, I think that we could keep the SetLatch() at the top of handle_sig_alarm(). My understanding is that the signal handler runs to completion without being interrupted by the code it interrupted. So, by the time the interrupted code (like epoll_wait()) resumes and can check the latch, the entire handler has finished. So, if my understanding is correct, having SetLatch() at the top or the bottom should not change anything ( as long as we don't have nested signal handlers). Out of curiosity, I also remove the ones in handlers (and keep the one in handle_sig_alarm() at the top), and everything seems to work fine: https://cirrus-ci.com/build/6277169619402752 Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-02-03 06:19:13 +0000, Bertrand Drouvot wrote: > On Fri, Jan 30, 2026 at 03:37:57PM +0100, Álvaro Herrera wrote: > > (Though to be honest, it's not clear to me why it would matter at which > > point in handle_sig_alarm we call SetLatch relative to the variables > > being set, given that these variables are only going to matter once the > > signal handler returns to the original code and the next > > CHECK_FOR_INTERRUPTS is hit.) > > Yeah, I think that we could keep the SetLatch() at the top of handle_sig_alarm(). Why at the top, rather than at the bottom? I don't think / I hope today's signal handlers rely on it, but in the past we had cases where some signal handlers ran code that could lead to a ResetLatch() being done. Why does it matter for your patch whether SetLatch() is done multiple times as part of various timeout handlers? I don't see how repeated SetLatch() calls could trigger more interference with ProcSleep()? Once the latch is set it is set (and indeed SetLatch() just returns immediately if it already is set). > My understanding is that the signal handler runs to completion without being interrupted > by the code it interrupted. Right. But they can, on some platforms at least, be interrupted by *other* signal handlers. I don't see any reason to believe that is not happening at the moment. > Out of curiosity, I also remove the ones in handlers (and keep the one in handle_sig_alarm() > at the top), and everything seems to work fine: > > https://cirrus-ci.com/build/6277169619402752 That doesn't tell you very much, I think. Our coverage of the relevant edge cases isn't that good, I think. Greetings, Andres Freund
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Tue, Feb 03, 2026 at 12:09:31PM -0500, Andres Freund wrote: > Hi, > > On 2026-02-03 06:19:13 +0000, Bertrand Drouvot wrote: > > On Fri, Jan 30, 2026 at 03:37:57PM +0100, Álvaro Herrera wrote: > > > (Though to be honest, it's not clear to me why it would matter at which > > > point in handle_sig_alarm we call SetLatch relative to the variables > > > being set, given that these variables are only going to matter once the > > > signal handler returns to the original code and the next > > > CHECK_FOR_INTERRUPTS is hit.) > > > Why does it matter for your patch whether SetLatch() is done multiple times as > part of various timeout handlers? I don't see how repeated SetLatch() calls > could trigger more interference with ProcSleep()? Once the latch is set it is > set (and indeed SetLatch() just returns immediately if it already is set). > Yeah, this was just a finding while diagnosing the ProcSleep() "issue". This discussion is not relevant in this thread anymore (specially since v5 where the design changed in such a way that the ProcSleep() "issue" does not appear anymore). We could open a dedicated thread if we think that's worth continuing the discussion about removing the SetLatch() in those handlers (but they are probably harmless to keep afterall). Thanks to you and Álvaro for having shared your thoughts on it. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello
do { \
+ pgstat_report_mixed_anytime = true; \
if (pgstat_should_count_relation(rel)) \
(rel)->pgstat_info->counts.numscans++; \
Shouldn't these pgstat_report_mixed_anytime changes go inside the if
statement in all macros?
+/* Track if mixed anytime stats need to be flushed */
+
/* Backend-local stats state */
extern PGDLLIMPORT PgStat_LocalState pgStatLocal;
This seems to be a leftover comment
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> In v5 attached I changed the design so that we don't re-enable the timeout
Thanks!
> I do think we still need it. Indeed in 0004 that helps distinguish between
> anytime flush or mixed flush (with the help of the new pgstat_report_mixed_anytime
> global variable) in pgstat_prep_pending_entry().
Will address below in the comments.
v5-0001:
1/
```
.write_to_file = true,
+ .flush_mode = FLUSH_ANYTIME,
.snapshot_ctl_off = offsetof(PgStat_Snapshot, archiver),
```
FLUSH_ANYTIME does not have any impact on Archiver. It does not have
a .flush_static_cb registered and entries are flushed directly to
shared memory via `pgstat_report_archiver` inside the `pgarch_ArchiverCopyLoop`
loop.
FLUSH_ANYTIME needs to be described a bit more that it only applies to
kinds that have flush callbacks.
2/
I suggest simplifying the code comment to this:
```
/*
- * Some stats have to be updated only at transaction boundaries (such as
- * tuples_inserted updated, deleted), so it's very important to set the
- * right flush mode (FLUSH_AT_TXN_BOUNDARY being the default).
+ * The mode of when to flush stats. See PgStat_FlushMode for
more details.
*/
PgStat_FlushMode flush_mode;
```
PgStat_FlushMode has sufficient description.
3/
we have this pattern:
```
/* Schedule next anytime stats update timeout */
if (IsUnderPostmaster &&
!get_timeout_active(ANYTIME_STATS_UPDATE_TIMEOUT))
enable_timeout_after(ANYTIME_STATS_UPDATE_TIMEOUT,
pgstat_flush_interval);
/* Required for the flush of pending stats WAL data */
pgstat_report_fixed = true;
```
to report fixed stats. I think it will be good to turn this into a public
routine, i.e. pgstat_report_fixed_entry, that can also be used by extensions
that register custom kinds with ANYTIME flush.
extensions using variable-numbered will get the timeout enabled
via pgstat_prep_pending_entry, per v5-0004.
We may want to add a test in test_custom_stats to ensure
this ANYTIME mechanism can work with custom kinds. What do you think?
v5-0002:
Overall, this GUC seems like a good idea. 10 second default and 1
second minimum are fine.
The patch overall looks solid, and I could not find any issues.
I do have a suggestion about the documentation:
```
- Sets the interval at which non-transactional statistics are
made visible
- during running transactions. Non-transactional statistics include, for
- example, WAL activity and I/O operations.
- They become visible at that interval in monitoring views such as
-
pg_stat_io
- and
pg_stat_wal
- during running transactions.
- If this value is specified without units, it is taken as milliseconds.
- The default is 10 seconds (10s), which is probably
- about the smallest value you would want in practice for long running
- transactions.
+ Sets the interval at which statistics that can be updated
while a transaction is still running
+ are made visible. These include, for example, WAL activity
and I/O operations.
+ Such statistics are refreshed at the specified interval and
can be observed during active
+ transactions in monitoring views such as
+ pg_stat_io
and
+ pg_stat_wal.
+ Other statistics are only made visible at transaction end and
are not affected by this setting.
+ If the value is specified without a unit, milliseconds are assumed.
+ The default is 10 seconds (10s), which is
generally the smallest practical
+ value for long-running transactions.
-
- This parameter does not affect transactional statistics such as
- pg_stat_all_tables columns (like
- n_tup_ins,
n_tup_upd,
- n_tup_del), which are always
flushed at transaction
- boundaries to maintain consistency.
-
+ This parameter does not affect statistics that are
only reported at transaction end,
+ such as the columns of pg_stat_all_tables
+ (for example, n_tup_ins,
n_tup_upd,
+ and n_tup_del). These statistics
are always flushed at the end of
+ a transaction.
```
specifically, I want to avoid using "non-transactional", "transaction
boundary" terms, as
they may be confusing.
v5-0003: looks straightforward. I have no comments.
v5-0004:
/1
+ FLUSH_MIXED, /* Mix of fields that
can be flushed anytime
+ * or
only at transaction boundary */
I still don't think this is needed. I fail to see what value it adds.
When we set pgstat_report_mixed_anytime inside the pgstat_count functions,
which make it clear which of the fields are anytime fields.
2/
This is an oversight comment, it seems.
```
extern PGDLLIMPORT bool pgstat_report_fixed;
+/* Track if mixed anytime stats need to be flushed */
+
/* Backend-local stats state */
extern PGDLLIMPORT PgStat_LocalState pgStatLocal;
```
3/
```
+ tabentry->numscans += lstats->counts.numscans;
+ if (lstats->counts.numscans)
+ {
+ TimestampTz t = GetCurrentTimestamp();
```
Considering the 10 second default, GetCurrentTimestamp() should not be
an issue here.
The doc does need to be updated. From:
"The time of the last sequential scan on this table, based on the most
recent transaction stop time"
To this?
"The approximate time of the last sequential scan on this table,
updated at least every STATS_FLUSH_INTERVAL"
same for `last_index_scan`
4/
nit: /non partial flush/non-partial flush/
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> Will address below in the comments. Sorry there was one more comment I forgot about. in v5-0004, instead of `flush_anytime_cb`, can't we just pass the anytime flag to the `flush_pending_cb` and take care of what needs to be flushed there? It will be up to the author of the kind if they want to further split work in multiple functions, but we could just have a single callback that is ANYTIME aware. -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> do { \
> + pgstat_report_mixed_anytime = true; \
> if (pgstat_should_count_relation(rel)) \
> (rel)->pgstat_info->counts.numscans++; \
>
> Shouldn't these pgstat_report_mixed_anytime changes go inside the if
> statement in all macros?
I think you are correct here, and there is an even more fundamental issue.
since
``
#define pgstat_should_count_relation(rel) \
(likely((rel)->pgstat_info != NULL) ? true : \
```
could return if there is already a pgstat_info, we may never actually
enable the timeout.
so, I think we should:
1/
remove the scheduling of the timeout from pgstat_prep_pending_entry
@@ -1308,11 +1308,6 @@ pgstat_prep_pending_entry(PgStat_Kind kind, Oid
dboid, uint64 objid, bool *creat
entry_ref->pending =
MemoryContextAllocZero(pgStatPendingContext, entrysize);
dlist_push_tail(&pgStatPending, &entry_ref->pending_node);
-
- /* Schedule next anytime stats update timeout */
- if ((kind_info->flush_mode == FLUSH_ANYTIME ||
pgstat_report_mixed_anytime) &&
- IsUnderPostmaster &&
!get_timeout_active(ANYTIME_STATS_UPDATE_TIMEOUT))
-
enable_timeout_after(ANYTIME_STATS_UPDATE_TIMEOUT,
pgstat_flush_interval);
}
2/
Create a routine to schedule the timeout:
+void
+ScheduleAnyTimeUpdate(void)
+{
+ /* Schedule next anytime stats update timeout */
+ if (IsUnderPostmaster &&
!get_timeout_active(ANYTIME_STATS_UPDATE_TIMEOUT))
+ enable_timeout_after(ANYTIME_STATS_UPDATE_TIMEOUT,
pgstat_flush_interval);
+
+ pgstat_report_mixed_anytime = true;
+}
This will also set pgstat_report_mixed_anytime to true. In my earlier
comments, I mentioned
having this as a public routine will be needed for extensions that
register a custom kind as well.
3/
All the count routines that wish to schedule any ANYTIME update because
their kind allows it can do so with ScheduleAnyTimeUpdate(). In the relation
stats, this can happen after it is checked that the relation should
track counts.
+#define pgstat_count_heap_scan(rel) \
+ do { \
+ if (pgstat_should_count_relation(rel)) \
+ { \
+ (rel)->pgstat_info->counts.numscans++; \
+ ScheduleAnyTimeUpdate(); \
+ } \
+ } while (0)
Also, it would be good to check if we have anytime flushes of either a mixed or
a fixed kind. Not strictly necessary, but I think it's better to avoid
needlessly entering
the flush routines.
@@ -2220,11 +2215,27 @@ pgstat_report_anytime_stat(bool force)
pgstat_assert_is_up();
/* Flush stats outside of transaction boundary */
- pgstat_flush_pending_entries(nowait, true);
- pgstat_flush_fixed_stats(nowait, true);
+ if (pgstat_report_mixed_anytime)
+ pgstat_flush_pending_entries(nowait, true);
+
+ if (pgstat_report_mixed_anytime)
+ pgstat_flush_fixed_stats(nowait, true);
pgstat_report_mixed_anytime = false;
+ pgstat_report_fixed = false;
}
I think we could benefit from a test that st track_counts to OFF inside
a transaction and re-enables it, to make sure the pgstat_should_count_relation
work is done correctly.
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi, On Wed, Feb 04, 2026 at 10:26:35AM -0600, Sami Imseih wrote: > > Will address below in the comments. > > Sorry there was one more comment I forgot about. > > in v5-0004, instead of `flush_anytime_cb`, can't we > just pass the anytime flag to the `flush_pending_cb` and > take care of what needs to be flushed there? > > It will be up to the author of the kind if they want to further > split work in multiple functions, but we could just have a > single callback that is ANYTIME aware. Thank you Sami and Zsolt for the reviews! PFA attached v6, addressing the reviews comments. Main changes are: 0001: - Adds a pgstat_schedule_anytime_update() macro to schedule the next anytime flush - The flush_pending_cb and flush_static_cb callbacks now receive an anytime_only boolean parameter. Most of the time it's not used (except for assertions), but it's preparatory work for moving the relations stats to anytime (without introducing a new callback) in 0005. 0002: Add some tests for anytime flush on custom stats. It adds a few functions: we could/may want to avoid some duplicate code and update the version to 1.1 though. For the former, I don't have a strong opinion and for the later I'm not sure (for example 07ff701dbd53 did not bump the version). 0005: Get rid of the FLUSH_MIXED mode, the new anytime callback and the pgstat_report_mixed_anytime variable introduced in v5. Instead v6: - change RELATION and DATABASE kinds from FLUSH_AT_TXN_BOUNDARY to FLUSH_ANYTIME - Modify pgstat_relation_flush_cb() to handle anytime_only parameter: when true, then flush only non-transactional stats and when false, then flush all the stats Remark: I did not add any additional checks in pgstat_report_anytime_stat(), since we enter it for good reason: at least one the flush has to be triggered. I'm not sure it's worth to add more check to try to discard one of them. The flush functions return early if they don't have anything to flush anyway. So the gain would be to try to avoid one function call at pgstat_flush_interval interval, but we would need to maitain the variable(s) and avoid possible race conditions with pgstat_report_stat(). Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> PFA attached v6, addressing the reviews comments.
Thanks for the patches!
v6 is getting closer IMO. Here are some comments I have.
v6-0001 looks solid, but some minor comments:
1/
+ pgstat_flush_backend(nowait, PGSTAT_BACKEND_FLUSH_WAL, true);
let's also use explicit (void) cast here
2/
+ * Timeout handler for flushing non-transactional stats.
I also noticed in v6-0005, we refer to "anytime" stats as
"non-transactional". It's better to just refer to them as "anytime"
anywhere instead of "non-transactional:.
v6-0002:
+ if (nowait && !LWLockConditionalAcquire(&stats_shmem->lock, LW_EXCLUSIVE))
+ return true; /* failed to flush */
+
+ LWLockAcquire(&stats_shmem->lock, LW_EXCLUSIVE);
Here the LWLock acquisition will deadlock if we are nowait, successfully
acquire the lock conditionally, and then we try to acquire it again. The
logic here should not try to acquire the lock twice.
+ -- Force anytime flush (inside transaction!)
+ select pg_stat_force_anytime_flush();
Not sure why we need pg_stat_force_anytime_flush.
A pg_sleep is sufficient, like below. right?
```
select test_custom_stats_fixed_anytime_update() from generate_series(1, 2);
select pg_sleep(1.5);
select 'anytime:'||numcalls from test_custom_stats_fixed_report();
```
v6-0003:
1/
Suggested doc changes:
- Sets the interval at which statistics that can be updated while a
- transaction is still running are made visible. These include,
for example,
- WAL activity and I/O operations.
+ Sets the interval at which certain statistics, which can be
updated while a
+ transaction is in progress, are made visible. These include
WAL activity
+ and I/O operations.
Such statistics are refreshed at the specified interval and
can be observed
during active transactions in monitoring views such as
- pg_stat_io
+ pg_stat_wal
and
- pg_stat_wal.
- Other statistics are only made visible at transaction end and are not
- affected by this setting.
+ pg_stat_io.
If the value is specified without a unit, milliseconds are assumed.
The default is 10 seconds (10s), which is generally
the smallest practical value for long-running transactions.
- Other statistics are only made visible at transaction end and are not
- affected by this setting.
I removed this, because it's mentioned in the notes section later on.
2/
I don't see we have tests for other timeout based GUCs, but it would nice
to ensure that this woks correctly. Maybe as a custom_stats test where we
SET stats_flush_interval inside the transaction and make sure the stats flush
only after the new timeout has passed. Maybe?
v6-0004:
1/
NIT:
+$node_primary->append_conf('postgresql.conf', "stats_flush_interval= '1s'");
+$node_publisher->append_conf('postgresql.conf', "stats_flush_interval= '1s'");
missing space before the equal sign.
v6-0005:
1/
/* Partial flush only happens in anytime mode for FLUSH_ANYTIME stats */
is_partial_flush = (anytime_only && kind_info->flush_mode ==
FLUSH_ANYTIME);
Will this be tue at all time? Let's imagine a Kind that flushes all the fields
ANYTIME, would we not want to delete the pending entry?
+ /* if successfull non-partial flush, remove entry */
+ if (did_flush && !is_partial_flush)
pgstat_delete_pending_entry(entry_ref);
2/ indentation:
Some statistics are updated while a transaction is in progress
(for example,
blks_read, blks_hit,
tup_returned and
tup_fetched).
- Statistics that either do not depend on transactions or require
transactional
- consistency are updated only when the transaction ends.
Statistics that require
- transactional consistency include xact_commit,
- xact_rollback,
tup_inserted,
- tup_updated and
tup_deleted.
+ Statistics that either do not depend on transactions or require
transactional
+ consistency are updated only when the transaction ends.
Statistics that require
+ transactional consistency include xact_commit,
+ xact_rollback,
tup_inserted,
+ tup_updated and
tup_deleted.
--
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi,
On Fri, Feb 13, 2026 at 08:23:01PM -0600, Sami Imseih wrote:
> > PFA attached v6, addressing the reviews comments.
>
> v6 is getting closer IMO. Here are some comments I have.
Thanks!
> v6-0001 looks solid, but some minor comments:
> 1/
>
> + pgstat_flush_backend(nowait, PGSTAT_BACKEND_FLUSH_WAL, true);
>
> let's also use explicit (void) cast here
Yeah. The patch did not introduce this inconsistency but let's fix it in passing.
> 2/
>
> + * Timeout handler for flushing non-transactional stats.
>
> I also noticed in v6-0005, we refer to "anytime" stats as
> "non-transactional". It's better to just refer to them as "anytime"
> anywhere instead of "non-transactional:.
Done.
> v6-0002:
>
> The logic here should not try to acquire the lock twice.
Yeah, changed to match the pgstat_wal_flush_cb() logic.
> + -- Force anytime flush (inside transaction!)
> + select pg_stat_force_anytime_flush();
>
> Not sure why we need pg_stat_force_anytime_flush.
> A pg_sleep is sufficient, like below. right?
Right, done.
>
> v6-0003:
>
> 1/
> Suggested doc changes:
Done.
> 2/
> I don't see we have tests for other timeout based GUCs, but it would nice
> to ensure that this woks correctly. Maybe as a custom_stats test where we
> SET stats_flush_interval inside the transaction and make sure the stats flush
> only after the new timeout has passed. Maybe?
Not sure I follow, that's what 0002 is doing.
> v6-0004:
>
> 1/
>
> NIT:
>
> +$node_primary->append_conf('postgresql.conf', "stats_flush_interval= '1s'");
>
> +$node_publisher->append_conf('postgresql.conf', "stats_flush_interval= '1s'");
>
> missing space before the equal sign.
Done.
>
> v6-0005:
>
> 1/
>
> /* Partial flush only happens in anytime mode for FLUSH_ANYTIME stats */
> is_partial_flush = (anytime_only && kind_info->flush_mode ==
> FLUSH_ANYTIME);
>
> Will this be tue at all time? Let's imagine a Kind that flushes all the fields
> ANYTIME, would we not want to delete the pending entry?
>
> + /* if successfull non-partial flush, remove entry */
> + if (did_flush && !is_partial_flush)
> pgstat_delete_pending_entry(entry_ref);
>
Right, and that's why the MIXED flush mode was useful, i.e to be able to distinguish
here. So, in the attached, instead of re-introducing the MIXED flush mode, I added
a "is_partial" bool paramater to the flush_pending_cb().
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
Thanks! > > 2/ > > I don't see we have tests for other timeout based GUCs, but it would nice > > to ensure that this woks correctly. Maybe as a custom_stats test where we > > SET stats_flush_interval inside the transaction and make sure the stats flush > > only after the new timeout has passed. Maybe? > > Not sure I follow, that's what 0002 is doing. I was referring to "SET stats_flush_interval", which you are doing in 0005, so disregard this comment. I wrote this comment when I read 0003 only. > > Will this be tue at all time? Let's imagine a Kind that flushes all the fields > > ANYTIME, would we not want to delete the pending entry? > > > > + /* if successfull non-partial flush, remove entry */ > > + if (did_flush && !is_partial_flush) > > pgstat_delete_pending_entry(entry_ref); > > > > Right, and that's why the MIXED flush mode was useful, i.e to be able to distinguish > here. So, in the attached, instead of re-introducing the MIXED flush mode, I added > a "is_partial" bool paramater to the flush_pending_cb(). > Yeah, MIXED flush mode to deal with this is still not the right idea, IMO. I do agree with what you did here by passing "is_partial" to the callbacks. Now it will be up to the callbacks to determine if they performed a partial or a complete flush ( even in the case of any anytime flush, if they so happened to flush stats for all the fields ). I do not have any further comments on this patchset. -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Mon, Feb 16, 2026 at 04:42:50PM -0600, Sami Imseih wrote: > I do agree with what you did here by passing "is_partial" to the callbacks. > Now it will be up to the callbacks to determine if they performed a partial > or a complete flush ( even in the case of any anytime flush, if they so > happened to flush stats for all the fields ). Right. > I do not have any further comments on this patchset. Thanks for the review! Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > > I do not have any further comments on this patchset. > > Thanks for the review! I flipped this CF entry to Ready-for-committer -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi, On Tue, Feb 17, 2026 at 01:18:35PM -0600, Sami Imseih wrote: > > > > > I do not have any further comments on this patchset. > > > > Thanks for the review! > > I flipped this CF entry to Ready-for-committer Thanks! PFA a mandatory rebase (nothing that needs review) due to a92b809f9da1. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Wed, Feb 18, 2026 at 6:41 AM Bertrand Drouvot
wrote:
>
> Hi,
>
> On Tue, Feb 17, 2026 at 01:18:35PM -0600, Sami Imseih wrote:
> > >
> > > > I do not have any further comments on this patchset.
> > >
> > > Thanks for the review!
> >
> > I flipped this CF entry to Ready-for-committer
>
> Thanks!
>
> PFA a mandatory rebase (nothing that needs review) due to a92b809f9da1.
Hi Bertrand!
Thanks for working on this. I've took a quick look on this patchset:
v8-0005: you start using pgstat_schedule_anytime_update() from really
hot macros like pgstat_count_buffer_hit() / pgstat_count_buffer_read()
or pgstat_count_heap_getnext(), e.g.:
#define pgstat_count_buffer_hit(rel)
do {
if (pgstat_should_count_relation(rel))
+ {
(rel)->pgstat_info->counts.blocks_hit++;
+ pgstat_schedule_anytime_update();
+ }
} while (0)
where #define pgstat_schedule_anytime_update() is
do {
if (IsUnderPostmaster &&
!get_timeout_active(ANYTIME_STATS_UPDATE_TIMEOUT))
enable_timeout_after(ANYTIME_STATS_UPDATE_TIMEOUT,
pgstat_flush_interval);
} while (0)
however that function (get_timeout_active()) is not static inlined so I'm
wondering wouldn't there some major performance impact? Those buffer
macros seem to be pretty heavy hitters, e.g. quite often even per single
buffer in PinBufferForBlock():
pgstat_count_buffer_read(rel);
if (*foundPtr)
pgstat_count_buffer_hit(rel);
so it seems to be:
- often unnecessary double work (and probably as this is a function call to
get_timeout_active it won't be optimized by compiler?)
- but the main question is: why do we need that often to recheck and re-enable
timers so often from such hot places?
v8-0001: this patch modifies ProcessInterrupts() which checks for
AnytimeStatsUpdateTimeoutPending and it may happen that it takes LWLocks
(pgstat_report_anytime_stat()->pgstat_flush_pending_entries()->e.g.
pgstat_*_flush_cb()-> pgstat_lock_entry() -> LWLock)
(It's more a question than finding): isn't it too risky to take that
LWLock from potentially random spots as the CHECK_FOR_INTERRUPTS() is
literally everywhere (~318 places). Wouldn't it be safer to flush
from a couple of desired places?
-J.
Re: Flush some statistics within running transactions
On Wed, Feb 18, 2026 at 05:40:46AM +0000, Bertrand Drouvot wrote: > PFA a mandatory rebase (nothing that needs review) due to a92b809f9da1. I don't find the design of this patch appealing, and my mind points towards two pieces of it: 1) The new requirement related to pgstat_schedule_anytime_update() that a stats kind needs to call to enable a timeout. This partially doubles with pgstat_report_fixed. And I suspect that this extra set of requirements, introducing a new level of complexity for in-core stats kinds as well as extension developers, would be the source of more bugs. 2) The timeout requirement itself, relying on a timeout threshold controlled by a backend-side configuration. With that in mind, wouldn't it be simpler if we introduced an API that could be used from client applications instead, in a model similar what we do for procsignal.c/h? One such example is LOG_MEMORY_CONTEXT, where we have a SQL function that is able to tell to a backend that it needs to do something. I could see various benefits to this approach, because it gives more flexibility with the timing of the stats flushes, which may not be a backend-side only policy: - Use a cron bgworker in the backend, that scans pg_stat_activity, for example for long-running transactions based on a threshold. - Do the same periodic scan of pg_stat_activity, but from a client application. The PROCSIG would need to set a flag in a new SIGUSR1 handler that would trigger the flush for the stats kinds that have the out-of-transaction property set once we go through in ProcessInterrupts(). We already have a pgstats report call there, hence it is a matter of removing the timeout requirements as presented in the patch, and let client applications when this should happen. The property of tracking which stats kind is surely important, Sami has reminded that a couple of hours ago that there are some stats that we should not flush even if we get an async request. Another thing that I am doubting about is if using the same async flush threshold makes sense for everything. Long-running transactions, for example, mostly would not care much even if we use an interval less aggressive than what a WAL sender sees. Not a fan of the hardcoded sleeps in the tests, either. On fast machines, these tend to waste in runtime because a process stands idle doing nothing. On slow machines, tests could be unstable if a sleep takes longer than it takes for the environment to react to a condition of the test. -- Michael
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi Jakub! On Wed, Feb 18, 2026 at 12:37:01PM +0100, Jakub Wartak wrote: > On Wed, Feb 18, 2026 at 6:41 AM Bertrand Drouvot > wrote: > > > > Thanks for working on this. I've took a quick look on this patchset: Thanks! > however that function (get_timeout_active()) is not static inlined so I'm > wondering wouldn't there some major performance impact? The get_timeout_active() function is very simple but you are right to be concerned by the extra function call in hot paths. So, with a simple pgbench test as: pgbench -i -s 1 pgbench -n -c1 -j1 -f <(echo "SELECT count(*) FROM pgbench_accounts;") -T 60 1/ with the patch tps average over 5 runs is about 123.8 and a perf report reports: 0.44% postgres postgres [.] get_timeout_active 0.43% ;ExecAgg;fetch_input_tuple;IndexOnlyNext;get_timeout_active To compare with other solutions that will not make use of a get_timeout_active() function call, let's also check the IndexOnlyNext profile (see above as to why): 12.05% postgres postgres [.] IndexOnlyNext 2/ without the patch tps average over 5 runs is about 124.9 and a perf report reports: 11.59% postgres postgres [.] IndexOnlyNext 3/ with the patch and get_timeout_active() inlined: tps average over 5 runs is about 124 and a perf report reports: 10.89% postgres postgres [.] IndexOnlyNext 4/ with the patch and using a boolean instead of get_timeout_active() tps average over 5 runs is about 129 and a perf report reports: 11.88% postgres postgres [.] IndexOnlyNext I'm not 100% sure what to conclude here. What I can see is that get_timeout_active() was about 0.45%, that's not a lot but that is simple enough to remove that I think that we just should. > - but the main question is: why do we need that often to recheck and re-enable > timers so often from such hot places? We need to ensure that anytime stats are flushed each time we update an anytime stats. Kind of the same idea as with the existing "pgstat_report_fixed". > v8-0001: this patch modifies ProcessInterrupts() which checks for > AnytimeStatsUpdateTimeoutPending and it may happen that it takes LWLocks > (pgstat_report_anytime_stat()->pgstat_flush_pending_entries()->e.g. > pgstat_*_flush_cb()-> pgstat_lock_entry() -> LWLock) > > (It's more a question than finding): isn't it too risky to take that > LWLock from potentially random spots as the CHECK_FOR_INTERRUPTS() is > literally everywhere (~318 places). Wouldn't it be safer to flush > from a couple of desired places? That's a good question. pgstat_report_stat() is already called in ProcessInterrupts() and pgstat_report_anytime_stat() does not do more than it, so I'm tempted to say that we are fine here. PFA, a new version that: - Implements the boolean (i.e "pgstat_pending_anytime") usage instead of the get_timeout_active() call. - Fix a race in assign_stats_flush_interval() reported by Sami off thread. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,
On Thu, Feb 19, 2026 at 12:58:12PM +0900, Michael Paquier wrote:
> On Wed, Feb 18, 2026 at 05:40:46AM +0000, Bertrand Drouvot wrote:
> > PFA a mandatory rebase (nothing that needs review) due to a92b809f9da1.
>
> I don't find the design of this patch appealing, and my mind points
> towards two pieces of it:
> 1) The new requirement related to pgstat_schedule_anytime_update()
> that a stats kind needs to call to enable a timeout. This partially
> doubles with pgstat_report_fixed. And I suspect that this extra set
> of requirements, introducing a new level of complexity for in-core
> stats kinds as well as extension developers, would be the source of
> more bugs.
Yeah, maybe we should re-think the way we report that we have something to flush,
but I think that's more a general discussion that should also take care of
pgstat_report_fixed.
> 2) The timeout requirement itself, relying on a timeout threshold
> controlled by a backend-side configuration.
What are you concerns with this?
> With that in mind, wouldn't it be simpler if we introduced an API that
> could be used from client applications instead, in a model similar
> what we do for procsignal.c/h?
That's another angle to look at it but I think that giving this responsability to
the clients would not solve the concerns we had in [1] (that led to 039549d70f6
and to this thread). It seems to me that a solution/design that does not allow
us to "revert" 039549d70f6 does not suit our needs. Thoughts?
> Not a fan of the hardcoded sleeps in the tests, either.
Yeah, after our off-list discussion yesterday, I tried to implement the same
trick that f1e251be80a has done with injection points (nice trick by the way!),
but that led to:
TRAP: failed Assert("CritSectionCount == 0 || (context)->allowInCritSection"), File: "mcxt.c", Line: 1237
postgres: main: walwriter (ExceptionalCondition+0x9e)[0xc4ce4d]
postgres: main: walwriter (MemoryContextAlloc+0x8c)[0xc8f0ec]
postgres: main: walwriter (MemoryContextStrdup+0x37)[0xc8fea1]
postgres: main: walwriter (pstrdup+0x22)[0xc8fee4]
postgres: main: walwriter (substitute_path_macro+0x65)[0xc56068]
postgres: main: walwriter [0xc55e90]
postgres: main: walwriter (load_external_function+0x59)[0xc553db]
postgres: main: walwriter [0xc7b858]
postgres: main: walwriter [0xc7c125]
postgres: main: walwriter (IsInjectionPointAttached+0x18)[0xc7c20c]
postgres: main: walwriter (pgstat_count_backend_io_op+0x12f)[0xa9a116]
postgres: main: walwriter (pgstat_count_io_op+0x169)[0xa9cb57]
postgres: main: walwriter (pgstat_count_io_op_time+0x1cc)[0xa9cda7]
So, I did not spend that much time on it. I could if we strongly think that those
sleeps have to be discarded though.
[1]: https://postgr.es/m/erpzwxoptqhuptdrtehqydzjapvroumkhh7lc6poclbhe7jk7l%40l3yfsq5q4pw7
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > Not a fan of the hardcoded sleeps in the tests, either.
>
> Yeah, after our off-list discussion yesterday, I tried to implement the same
> trick that f1e251be80a has done with injection points (nice trick by the way!),
> but that led to:
>
> TRAP: failed Assert("CritSectionCount == 0 || (context)->allowInCritSection"), File: "mcxt.c", Line: 1237
> postgres: main: walwriter (ExceptionalCondition+0x9e)[0xc4ce4d]
> postgres: main: walwriter (MemoryContextAlloc+0x8c)[0xc8f0ec]
> postgres: main: walwriter (MemoryContextStrdup+0x37)[0xc8fea1]
> postgres: main: walwriter (pstrdup+0x22)[0xc8fee4]
> postgres: main: walwriter (substitute_path_macro+0x65)[0xc56068]
> postgres: main: walwriter [0xc55e90]
> postgres: main: walwriter (load_external_function+0x59)[0xc553db]
> postgres: main: walwriter [0xc7b858]
> postgres: main: walwriter [0xc7c125]
> postgres: main: walwriter (IsInjectionPointAttached+0x18)[0xc7c20c]
> postgres: main: walwriter (pgstat_count_backend_io_op+0x12f)[0xa9a116]
> postgres: main: walwriter (pgstat_count_io_op+0x169)[0xa9cb57]
> postgres: main: walwriter (pgstat_count_io_op_time+0x1cc)[0xa9cda7]
>
> So, I did not spend that much time on it. I could if we strongly think that those
> sleeps have to be discarded though.
I took a look at this today out of interest, based on what you mentioned to me
offline.
There is this in injection_points.c
```
/*
* Load an injection point into the local cache.
*
* This is useful to be able to load an injection point before running it,
* especially if the injection point is called in a code path where memory
* allocations cannot happen, like critical sections.
*/
void
InjectionPointLoad(const char *name)
{
#ifdef USE_INJECTION_POINTS
InjectionPointCacheRefresh(name);
#else
elog(ERROR, "Injection points are not supported by this build");
#endif
}
```
so, instead of calling IS_INJECTION_POINT_ATTACHED macro which is
called on-demand and in the case of I/O stats, during the critical section,
you can just call INJECTION_POINT_LOAD during pgstat_initialize(),
like this:
```
INJECTION_POINT_LOAD("anytime-update-reduce-timeout");
```
Sami Imseih
Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi,
On Thu, Feb 19, 2026 at 04:08:59PM -0600, Sami Imseih wrote:
> > > Not a fan of the hardcoded sleeps in the tests, either.
> >
> > Yeah, after our off-list discussion yesterday, I tried to implement the same
> > trick that f1e251be80a has done with injection points (nice trick by the way!),
PFA, a tiny ("include") rebase due to 9842e8aca09 (the v9 patch series was applying
but not compiling).
> I took a look at this today out of interest,
Thanks!
> so, instead of calling IS_INJECTION_POINT_ATTACHED macro which is
I think that not calling IS_INJECTION_POINT_ATTACHED() but only relying on
"ifdef USE_INJECTION_POINTS" would set the tiny timeout value to the entire test
suit.
I'm waiting for Michael's feedback about the current design ([1]) to see if it's
still worth spending time improving the tests.
[1]: https://postgr.es/m/aZbDYMrOkeCyIubO%40ip-10-97-1-34.eu-west-3.compute.internal
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > I took a look at this today out of interest, > > Thanks! > > > so, instead of calling IS_INJECTION_POINT_ATTACHED macro which is > > I think that not calling IS_INJECTION_POINT_ATTACHED() but only relying on > "ifdef USE_INJECTION_POINTS" would set the tiny timeout value to the entire test > suit. Yes, you are right about that. To Michael's earlier comments: > I don't find the design of this patch appealing, and my mind points > towards two pieces of it: > 1) The new requirement related to pgstat_schedule_anytime_update() > that a stats kind needs to call to enable a timeout. This partially > doubles with pgstat_report_fixed. And I suspect that this extra set > of requirements, introducing a new level of complexity for in-core > stats kinds as well as extension developers, would be the source of > more bugs. I don't see how for fixed stats, adding a pgstat_schedule_anytime_update() call for such kinds will be too complex or more error prone. it looks quite straightforward as this is done before pgstat_report_fixed is set to true. Also, because processes like wal-sender can loop forever, as mentioned here [1], a timeout at stats_flush_interval seems like a straightforward way to deal with this problem. For variable-length statistics, perhaps we can do things a bit differently than what is currently proposed. 0005 requires a relation anytime stat update to call pgstat_schedule_anytime_update(). This is done this way because it allows long-running queries to update their stats every stats_flush_interval using a timeout. But maybe what we should be doing for variable-numbered stats is to schedule an anytime update whenever a "transaction goes idle". This way, unlike the current state of things where we are only updating relation stats at the end of a transaction, we are now updating relation stats at the end of SQL execution, and within a transaction. Basically, we will continue scheduling anytime updates every stats_flush_interval for fixed stats (xlog, bgwriter, etc.), but for variable stats, we only update anytime stats after SQL execution. This is better than what we have now, where stats are only updated at the end of the transaction. The timeout will only be needed to schedule an update for fixed stats. For variable stats, we can use GetCurrentStatementStartTimestamp, which is the timestamp of the last query executed, to throttle pgstat_flush_pending_entries(). We can also flush variable number stats whenever we flush fixed number stats, in case we enter a long idle-in-transaction state after a few quick back-to-back queries. > 2) The timeout requirement itself, relying on a timeout threshold > controlled by a backend-side configuration. Perhaps we may not need the stats_flush_inteval and just force a 10 second timeout for fixed stats. > With that in mind, wouldn't it be simpler if we introduced an API that > could be used from client applications instead, in a model similar > what we do for procsignal.c/h? One such example is > LOG_MEMORY_CONTEXT, where we have a SQL function that is able to tell > to a backend that it needs to do something. I could see various > benefits to this approach, because it gives more flexibility with the > timing of the stats flushes, which may not be a backend-side only > policy: > - Use a cron bgworker in the backend, that scans pg_stat_activity, for > example for long-running transactions based on a threshold. > - Do the same periodic scan of pg_stat_activity, but from a client > application. I find it odd to ask applications/clients to trigger a flush. I am not saying that we should not offer such an API, especially if someone want to flush stats more frequently than stats_flush_interval, but there should be the ability for core to handle this automatically outside of the transaction boundaries. One comment about the current test. I think there is a bug that was missed in the earlier review. For the var_anytime_update, we need to have an escape before the pipe. Also, we should set stats_fetch_consistency=none in that test. -like($result, qr/^entry2|2|/m, +like($result, qr/^entry2\|2\|/m, Otherwise, the test is returning a false-positive. [1] https://www.postgresql.org/message-id/erpzwxoptqhuptdrtehqydzjapvroumkhh7lc6poclbhe7jk7l%40l3yfsq5q4pw7 -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi, On Sun, Feb 22, 2026 at 08:12:06PM -0600, Sami Imseih wrote: > > > I took a look at this today out of interest, > > > > Thanks! > > > > > so, instead of calling IS_INJECTION_POINT_ATTACHED macro which is > > > > I think that not calling IS_INJECTION_POINT_ATTACHED() but only relying on > > "ifdef USE_INJECTION_POINTS" would set the tiny timeout value to the entire test > > suit. > > Yes, you are right about that. And even if we are able to set a tiny timeout to say N in the test, the test would still need a pg_sleep(N+). So I wonder if the best way is not to re-introduce pg_stat_force_anytime_flush() that was in v6? > To Michael's earlier comments: > > For variable-length statistics, perhaps we can do things a bit > differently than what is currently proposed. 0005 requires > a relation anytime stat update to call > pgstat_schedule_anytime_update(). This is done this way because > it allows long-running queries to update their stats every > stats_flush_interval using a timeout. > > But maybe what we should be doing for variable-numbered stats is > to schedule an anytime update whenever a "transaction goes idle". I think the logic for fixed stats and variable stats should be the same. If not we could observe discrepancies: for example a long running select could genereate reads/hits IO visible in pg_stat_io but tuples_returned, tuples_fetched, blocks_fetched or blocks_hit would not be updated until the session goes idle. > I find it odd to ask applications/clients to trigger a flush. I am not saying > that we should not offer such an API, especially if someone want to flush > stats more frequently than stats_flush_interval, Yeah, and that could help with the tests to avoid the sleep. > but there should be > the ability for core to handle this automatically outside of the transaction > boundaries. Agreed. I think that public facing API could be an addition, not a replacement. > One comment about the current test. I think there is a bug that was > missed in the earlier review. For the var_anytime_update, we need to > have an escape before the pipe. > > -like($result, qr/^entry2|2|/m, > +like($result, qr/^entry2\|2\|/m, Oh right, thanks! The attach rewrites it like the fixed test instead. Also the attached introduces a mandatory rebase due to 308622edf17. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > For variable-length statistics, perhaps we can do things a bit > > differently than what is currently proposed. 0005 requires > > a relation anytime stat update to call > > pgstat_schedule_anytime_update(). This is done this way because > > it allows long-running queries to update their stats every > > stats_flush_interval using a timeout. > > > > But maybe what we should be doing for variable-numbered stats is > > to schedule an anytime update whenever a "transaction goes idle". > > I think the logic for fixed stats and variable stats should be the same. If > not we could observe discrepancies: for example a long running select could > genereate reads/hits IO visible in pg_stat_io but tuples_returned, tuples_fetched, > blocks_fetched or blocks_hit would not be updated until the session goes idle. After having more time to think about this, I believe it can be much simpler. As soon as we enter an idle-in-transaction (aborted) state, we can simply schedule an anytime update. This ensures that a flush is scheduled whenever the fixed stats trigger one, which will likely be the most common reason (e.g., I/O stats, WAL stats, etc.). To cover the cases where fixed stats do not schedule a flush, we can also schedule one as soon as a transaction goes idle. In my mind, this makes this whole flushing scheduling behavior easy to reason about, and if we introduce future anytime stats anywhere, we are not required to schedule a flush for each individual field. The flush callback will of course still need to decide what to flush anytime or at the transaction boundary. What do you think? -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
On Thu, Feb 19, 2026 at 08:01:36AM +0000, Bertrand Drouvot wrote: > On Thu, Feb 19, 2026 at 12:58:12PM +0900, Michael Paquier wrote: >> 2) The timeout requirement itself, relying on a timeout threshold >> controlled by a backend-side configuration. > > What are you concerns with this? I am concerned about the three additional points/requirements: 1) The need for all processes who want to flush non-transactional stats to set up timeouts, unconditionally, which is what the patch shows with the new InitializeTimeouts() calls added for example for auxiliary processes. This forces the use of SIGALRM in these processes, with a new handler, and feels like a requirement too heavy for the sake of some stats flushes. This requires an extra unconditional RegisterTimeout(), as well. 2) The need for all the stats to call pgstat_schedule_anytime_update() in strategical places. This is less of a burden compared to 1), but this leads to more complications in these code paths with the coding requirements, especially for custom stats kinds. 3) Enforcing a flush timeout unconditionally. One thing that slightly concerns me here is that it seems easier to misuse compared to a client-based facility, where a too aggressive setup could stress more the server-side pgstats. It is true that the client-side could be misused too. My main worries are mainly around 1), I guess, with the new SIGALRM handler requirements for all auxiliary processes. Using a procsignal path would allow us to rely on a solution that has the same flexibility, combined with strategic additional flush calls that we could spread depending on requirements we want to enforce in some processes, like in the WAL sender, or perhaps the checkpointer. That seems more careful in the long-run, and this can rely on the interrupt processing for the job. The addition of the property to track if a stats kind of OK to flush outside a transaction boundary is also critical to have, of course. I am sold to the point point of the design about this new property tracked in the stats kind meta-data. >> With that in mind, wouldn't it be simpler if we introduced an API that >> could be used from client applications instead, in a model similar >> what we do for procsignal.c/h? > > That's another angle to look at it but I think that giving this responsability to > the clients would not solve the concerns we had in [1] (that led to 039549d70f6 > and to this thread). It seems to me that a solution/design that does not allow > us to "revert" 039549d70f6 does not suit our needs. Thoughts? 039549d70f6 goes in line with the "client" prospective, where I would like to think that strategic flush calls are more flexible. > Yeah, after our off-list discussion yesterday, I tried to implement the same > trick that f1e251be80a has done with injection points (nice trick by the way!), > but that led to: In this case, avoiding an injpoint allocation in a critical section would be a two-step process: - INJECTION_POINT_LOAD(), before the critical section, to warm up the cache and do all the allocations. - INJECTION_POINT_CACHED() with IS_INJECTION_POINT_ATTACHED() (optional), to run the point, in the critical section. This tactic is already in use in the tree. You would have to use a more complicated scheme to make sure that the wait machinery is initialized when using it in a critical section, but that can be worked around as well. See my "state-of-the-art" work of 15f68cebdcec, which, well, happens to work. Not really the best work ever with two points, but it works for this purpose. :D -- Michael
Re: Flush some statistics within running transactions
On Mon, Feb 23, 2026 at 05:47:22PM -0600, Sami Imseih wrote: >> I think the logic for fixed stats and variable stats should be the same. If >> not we could observe discrepancies: for example a long running select could >> genereate reads/hits IO visible in pg_stat_io but tuples_returned, tuples_fetched, >> blocks_fetched or blocks_hit would not be updated until the session goes idle. > > After having more time to think about this, I believe it can be much simpler. > As soon as we enter an idle-in-transaction (aborted) state, we can simply > schedule an anytime update. This ensures that a flush is scheduled whenever > the fixed stats trigger one, which will likely be the most common reason > (e.g., I/O stats, WAL stats, etc.). To cover the cases where fixed stats > do not schedule a flush, we can also schedule one as soon as a transaction > goes idle. > > In my mind, this makes this whole flushing scheduling behavior easy to reason > about, and if we introduce future anytime stats anywhere, we are not required > to schedule a flush for each individual field. The flush callback will of course > still need to decide what to flush anytime or at the transaction boundary. > > What do you think? I cannot picture yet fully how a patch among these lines would be shaped, but having a strategic flush of the stats when we are in an idle-in-transaction state sounds like an interesting option here. I think that this leans towards two first pieces of infrastructure for this patch set: - The new stats kind option. - A new pgstats API that is able to classify the flushes depending on property assigned for each stats kind, and make these happen on a caller-basis. -- Michael
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Mon, Feb 23, 2026 at 05:47:22PM -0600, Sami Imseih wrote: > > > For variable-length statistics, perhaps we can do things a bit > > > differently than what is currently proposed. 0005 requires > > > a relation anytime stat update to call > > > pgstat_schedule_anytime_update(). This is done this way because > > > it allows long-running queries to update their stats every > > > stats_flush_interval using a timeout. > > > > > > But maybe what we should be doing for variable-numbered stats is > > > to schedule an anytime update whenever a "transaction goes idle". > > > > I think the logic for fixed stats and variable stats should be the same. If > > not we could observe discrepancies: for example a long running select could > > genereate reads/hits IO visible in pg_stat_io but tuples_returned, tuples_fetched, > > blocks_fetched or blocks_hit would not be updated until the session goes idle. > > After having more time to think about this, I believe it can be much simpler. > As soon as we enter an idle-in-transaction (aborted) state, we can simply > schedule an anytime update. This ensures that a flush is scheduled whenever > the fixed stats trigger one, which will likely be the most common reason > (e.g., I/O stats, WAL stats, etc.). To cover the cases where fixed stats > do not schedule a flush, we can also schedule one as soon as a transaction > goes idle. > > In my mind, this makes this whole flushing scheduling behavior easy to reason > about, and if we introduce future anytime stats anywhere, we are not required > to schedule a flush for each individual field. The flush callback will of course > still need to decide what to flush anytime or at the transaction boundary. > > What do you think? My understanding is that (correct me if I'm wrong): - fixed stats would still be designed the way it is in v11 - variable stats would not need the pgstat_schedule_anytime_update() calls in various places. The flush would be done/schedule when the session goes idle. Then I agree that that looks ok and that: > This ensures that a flush is scheduled whenever > the fixed stats trigger one, which will likely be the most common reason > (e.g., I/O stats, WAL stats, etc.) Though I don't think that adresses Michael's concern: "main worries are mainly around 1), I guess, with the new SIGALRM handler requirements for all auxiliary processes" in [1]. Regards, [1]: https://postgr.es/m/aZznT84Ssh8PywcH%40paquier.xyz -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Tue, Feb 24, 2026 at 08:48:31AM +0900, Michael Paquier wrote: > On Thu, Feb 19, 2026 at 08:01:36AM +0000, Bertrand Drouvot wrote: > > On Thu, Feb 19, 2026 at 12:58:12PM +0900, Michael Paquier wrote: > >> 2) The timeout requirement itself, relying on a timeout threshold > >> controlled by a backend-side configuration. > > > > What are you concerns with this? > > I am concerned about the three additional points/requirements: > 1) The need for all processes who want to flush non-transactional > stats to set up timeouts, unconditionally, which is what the patch > shows with the new InitializeTimeouts() calls added for example for > auxiliary processes. This forces the use of SIGALRM in these > processes, Right but they all already call pqsignal(SIGALRM, SIG_IGN), so I'm not sure to get the point. > This requires an extra unconditional RegisterTimeout(), as well. Yes, I'm not clear why that's an issue though. > 2) The need for all the stats to call pgstat_schedule_anytime_update() > in strategical places. This is less of a burden compared to 1), but > this leads to more complications in these code paths with the coding > requirements, especially for custom stats kinds. I think that's solved with Sami's proposal for variable stats kind (to flush or schedule when the session is idle). > 3) Enforcing a flush timeout unconditionally. What do you mean? It's done only if there is things to flush. > My main worries are mainly around 1), I guess, with the new SIGALRM > handler requirements for all auxiliary processes. Using a procsignal > path would allow us to rely on a solution that has the same > flexibility, combined with strategic additional flush calls that we > could spread depending on requirements we want to enforce in some > processes, like in the WAL sender, or perhaps the checkpointer. I see, but we know they'll have to flush IO or WAL stats at some point so enabling the timeout for those look ok. > The addition of the property to track if a > stats kind of OK to flush outside a transaction boundary is also > critical to have, of course. I am sold to the point point of the > design about this new property tracked in the stats kind meta-data. Great! > 039549d70f6 goes in line with the "client" prospective, where I would > like to think that strategic flush calls are more flexible. > > > Yeah, after our off-list discussion yesterday, I tried to implement the same > > trick that f1e251be80a has done with injection points (nice trick by the way!), > > but that led to: > > In this case, avoiding an injpoint allocation in a critical section > would be a two-step process: > - INJECTION_POINT_LOAD(), before the critical section, to warm up the > cache and do all the allocations. > - INJECTION_POINT_CACHED() with IS_INJECTION_POINT_ATTACHED() > (optional), to run the point, in the critical section. Oh okay, thanks for the explanation! Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
От:
Sami Imseih <samimseih@gmail.com>
Дата:
> > 2) The need for all the stats to call pgstat_schedule_anytime_update() > > in strategical places. This is less of a burden compared to 1), but > > this leads to more complications in these code paths with the coding > > requirements, especially for custom stats kinds. > > I think that's solved with Sami's proposal for variable stats kind (to flush or > schedule when the session is idle). Just a clarification. It is "to schedule a flush when the transaction becomes idle" PGSTAT_IDLE_INTERVAL already deals when the session is idle. -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
On Tue, Feb 24, 2026 at 01:55:48PM +0000, Bertrand Drouvot wrote: > On Tue, Feb 24, 2026 at 08:48:31AM +0900, Michael Paquier wrote: >> I am concerned about the three additional points/requirements: >> 1) The need for all processes who want to flush non-transactional >> stats to set up timeouts, unconditionally, which is what the patch >> shows with the new InitializeTimeouts() calls added for example for >> auxiliary processes. This forces the use of SIGALRM in these >> processes, > > Right but they all already call pqsignal(SIGALRM, SIG_IGN), so I'm not sure > to get the point. This design requires enabling a new signal with a signal handler in a lot of processes that did not do that. Enabling timeouts in a bunch of new processes, while claiming it is fine to do, sounds like something we should rather be careful about. Are you sure for example that some of the checkpointer code would not buzz on that, for example? At the end, this approach seems too heavy-handed to me. I am also not entirely convinced that enforcing that unconditionally is the right thing to do in some cases, either. For the bgwriter, as one example, we have a WAL report call happening in its main loop, which is quite good in terms of information frequency obtained. Wouldn't some case-by-case strategic "anytime" API flush calls make more sense for some subsystems, rather than relying on a timeout? It seems rather easy to misuse this design in some bgworker contexts, and SIGALRM could also be used for a different purpose but we would block that entirely moving on with future versions? -- Michael
Re: Flush some statistics within running transactions
On Tue, Feb 24, 2026 at 12:01:30PM +0000, Bertrand Drouvot wrote: > Though I don't think that adresses Michael's concern: "main worries are > mainly around 1), I guess, with the new SIGALRM handler requirements for all > auxiliary processes" in [1]. FWIW, I am still concerned about that, and I have pondered about what we could do here. While reviewing the existing code, one thing that I have noticed we could do is rely on the existing interface of pgstat_report_stat() without changing the existing callers, and not touching at all the flush callbacks. If we begin to require the "force" mode when the routine the called inside a transaction block, things seem to work pretty smoothly in combination with a stats kind property that allows the stats data to be flushed if we are inside a transaction while a report happens. And it is possible to enforce checks inside pgstat_report_stat() as well. So please find attached my shot at that: - Introduction of a new system function called pg_stat_report(), based on a procsignal that gives a way to signal backends for a stats update, reusing the existing code where we only do flushes when idle and not in a transaction. - Property that tracks under which contexts the reports are allowed. Here I have decided to stick with simple, as in only allowing IO and WAL stats to be flushed if we are inside a transaction. Using that, I have done a few tests with three backends: - One with a long-running transaction. - One that periodically triggers the reports. - One that looks at IO and WAL stat. And the third session is able to get refreshes for both of these stats kinds, while the other stats remain the same. Note that this is a WIP, which is check-world stable. One thing that sticks a bit in mind now is that perhaps we should not allow the function for auxiliary processes at all. A second thing is the requirement of allowing partial flushes at the end of the report path, which is OK because the variable-sized stats can have pending data. Perhaps we should just have pgstat_flush_pending_entries() provide a correct status in line with the property set in a stats kind when we try a flush while in a transaction. Thoughts or tomatoes? -- Michael
Re: Flush some statistics within running transactions
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Mon, Mar 16, 2026 at 03:26:33PM +0900, Michael Paquier wrote: > On Tue, Feb 24, 2026 at 12:01:30PM +0000, Bertrand Drouvot wrote: > > Though I don't think that adresses Michael's concern: "main worries are > > mainly around 1), I guess, with the new SIGALRM handler requirements for all > > auxiliary processes" in [1]. > > FWIW, I am still concerned about that, and I have pondered about what > we could do here. While reviewing the existing code, one thing that I > have noticed we could do is rely on the existing interface of > pgstat_report_stat() without changing the existing callers, and not > touching at all the flush callbacks. If we begin to require the > "force" mode when the routine the called inside a transaction block, > things seem to work pretty smoothly in combination with a stats kind > property that allows the stats data to be flushed if we are inside a > transaction while a report happens. Yeah, "force" makes use of GetCurrentTimestamp() (and so we avoid a failed assertion that we would get if using GetCurrentTransactionStopTimestamp()). > So please find attached my shot at that: Thanks! > - Introduction of a new system function called pg_stat_report(), based > on a procsignal that gives a way to signal backends for a stats > update, reusing the existing code where we only do flushes when idle > and not in a transaction. > - Property that tracks under which contexts the reports are allowed. > Here I have decided to stick with simple, as in only allowing IO and > WAL stats to be flushed if we are inside a transaction. > > Using that, I have done a few tests with three backends: > - One with a long-running transaction. > - One that periodically triggers the reports. > - One that looks at IO and WAL stat. > And the third session is able to get refreshes for both of these stats > kinds, while the other stats remain the same. I did not look closely at the code but did some testing too. I confirm that pg_stat_io and pg_stat_wal are updated when pg_stat_report() is triggered. But the stats update is not visible if requested through pg_stat_get_backend_io() or pg_stat_get_backend_wal()). I guess that PGSTAT_KIND_BACKEND should also get the PGSTAT_REPORT_TRANSACTION report_context? > Note that this is a WIP, which is check-world stable. One thing that > sticks a bit in mind now is that perhaps we should not allow the > function for auxiliary processes at all. Why? > A second thing is the > requirement of allowing partial flushes at the end of the report path, > which is OK because the variable-sized stats can have pending data. Right. > Perhaps we should just have pgstat_flush_pending_entries() provide a > correct status in line with the property set in a stats kind when we > try a flush while in a transaction. The idea would be to avoid trying to flush stats that don't have pending entries? > Thoughts or tomatoes? That looks "simpler" that the previous proposal but who would be responsible to call pg_stat_report()? If that's the client responsabilty that kind of look weird to me. If that's the core, how would that be scheduled? I think that the end solution should prevent to find similar issues as 039549d70f6 fixed, without delegating to the client. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Flush some statistics within running transactions
On Mon, Mar 16, 2026 at 09:20:41AM +0000, Bertrand Drouvot wrote: > I did not look closely at the code but did some testing too. I confirm that > pg_stat_io and pg_stat_wal are updated when pg_stat_report() is > triggered. But the stats update is not visible if requested through > pg_stat_get_backend_io() or pg_stat_get_backend_wal()). > I guess that PGSTAT_KIND_BACKEND should also get the PGSTAT_REPORT_TRANSACTION > report_context? Yes, I guess that the transaction-level flag should be set as well for the backend stats, due to the fact that WAL and IO stats have it set. >> Note that this is a WIP, which is check-world stable. One thing that >> sticks a bit in mind now is that perhaps we should not allow the >> function for auxiliary processes at all. > > Why? I was feeling that there would be an issue with that, and I did not test it in details yet. For the checkpointer with a busy activity, the IO stats could be interesting to see in live. >> Perhaps we should just have pgstat_flush_pending_entries() provide a >> correct status in line with the property set in a stats kind when we >> try a flush while in a transaction. > > The idea would be to avoid trying to flush stats that don't have pending > entries? I had to work around the assert at the end of pgstat_report_stat(), to tell that under an xact the partial flushes were OK. I was wondering about keeping the end assertion based on solely "force" intact, making the flush routines return a status based on if we are in an xact. > That looks "simpler" that the previous proposal but who would be responsible to > call pg_stat_report()? If that's the client responsabilty that kind of look weird > to me. If that's the core, how would that be scheduled? I think that the > end solution should prevent to find similar issues as 039549d70f6 fixed, without > delegating to the client. TBH, I don't like the requirement of setting SIGALRM in all the places where we'd require it for the sake of this proposal, where historically we have never done that, copying a mechanism that already exists in the tree for procsigs, as the previous patch I posted proves we could reuse. It's also not clear to me what a correct frequency of the stat updates should be, and why it would make sense to force that in a GUC; we want to have some information from long-running transactions, where I fear that we will want modularity. A user-settable GUC would fit with this picture, but the requirement of planting the timeouts don't stick for me.. On top of that, I am not really convinced that there is a good reason to remove the existing stat report calls we have already planted in the tree for auxiliary processes, diverging from the stable branches where these exist. With more than one release already out with them, there is more benefit with potentially planting more strategic report calls where they could matter (as added in v18 for WAL senders as one example), when we find a requirement for them. -- Michael
Re: Flush some statistics within running transactions
Hi, I have spent some time thinking about Michael's feedback and I want to see if I can propose an alternate design that we can come to a consensus on. > I had to work around the assert at the end of pgstat_report_stat(), to > tell that under an xact the partial flushes were OK. I was wondering > about keeping the end assertion based on solely "force" intact, making > the flush routines return a status based on if we are in an xact. > > > That looks "simpler" that the previous proposal but who would be responsible to > > call pg_stat_report()? If that's the client responsibility that kind of look weird > > to me. If that's the core, how would that be scheduled? I think that the > > end solution should prevent to find similar issues as 039549d70f6 fixed, without > > delegating to the client. > > TBH, I don't like the requirement of setting SIGALRM in all the places > where we'd require it for the sake of this proposal, where > historically we have never done that, copying a mechanism that already > exists in the tree for procsigs, as the previous patch I posted proves > we could reuse. How about we add a timeout when a transaction goes idle? Currently we have IDLE_STATS_UPDATE_TIMEOUT, which is the timeout interval used when we have done more than one flush within a second. This only works when the session is idle (not in a transaction), and flushes everything. However, as I mentioned earlier in this thread, we can also schedule a flush that occurs when a transaction goes idle. This means when a transaction is started (BEGIN/START TRANSACTION) the proceeding idle-in-transaction can schedule a timeout of 10 seconds based on a new #define called PGSTAT_IDLE_TXN_INTERVAL. The timeout is not a fixed repeating interval. It is set on-demand each time the transaction enters idle-in-transaction state: first after the BEGIN, then again after each subsequent command completes. This is a trade-off: if a single command runs for a long time, no flush happens until it finishes and the transaction goes idle again. So, we still introduce a new timeout in this mechanism, but it does not need to be registered all over the place. So with this all the "safe to be flushed" stats will be flushed mid-transaction at some point, and all stats will be flushed at the end of a transaction. With that said, the only way I can conceive getting away from a a new timeout in this design is to track timestamp whenever we go into idle-intransaction, but I am not too comfy adding a GetCurrentTimestamp() there. -> if no action occurs at this point, we don't set another timeout > It's also not clear to me what a correct frequency of > the stat updates should be, and why it would make sense to force that > in a GUC; No GUC will be needed in what I am proposing. A 10s flush interval should be sufficient. > On top of that, I am not really convinced that there is a good reason > to remove the existing stat report calls we have already planted in > the tree for auxiliary processes, diverging from the stable branches > where these exist. The design being proposed keeps all the existing in-tact. So attached is a new proposal with tests and docs. In terms of test I fell back to the strategy used by Bertrand [0] with the INJECTION_POINT trick to reduce the flush interval. It does mean we keep a pg_sleep in the test, but I think we should not try to do anything different here. Also, with this design we can call the flush modes FLUSH_IN_TRANSACTION and FLUSH_AT_TXN_BOUNDARY. As the earlier proposals, the callbacks will still need to make the decision what stats to flush based on if it's called in-transaction or at boundary. [0] https://www.postgresql.org/message-id/aZbDYMrOkeCyIubO%40ip-10-97-1-34.eu-west-3.compute.internal -- Sami Imseih Amazon Web Services (AWS)
Re: Flush some statistics within running transactions
On Mon, Mar 16, 2026 at 06:42:44PM -0500, Sami Imseih wrote: > So attached is a new proposal with tests and docs. In terms of > test I fell back to the strategy used by Bertrand [0] with the As far as I am reading the patch, it seems to me that this would accelerate the frequency of the stats flushes when we have a transaction with many short queries, but it does not help much in the case of an analytical single query because the flush of the stats would just happen once after the timeout set for each query? Let's imagine for example a query that takes hours to run, where we'd want to get fresh IO and WAL stats (backend included) on a periodic basis by processing interrupts while going through the executor. Thinking more about this problem, I'd really like to think that a client-side API would provide a more flexible interface for the analytical case. -- Michael