Re: pgstat: Flush some statistics within running transactions, take 2

Поиск
Список
Период
Сортировка
Искать

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Mon, Aug 24, 2026 at 08:34:50PM -0500, Sami Imseih wrote:
> Hi,
> 
> > Yeah, that would address my concern and keep memcmp(), so +1.
> 
> Thanks. I went ahead and did that in v8-0002 (previously v7-0001).

Thanks for the new version!

> That issue is already present in HEAD and is not introduced by this
> patch set. pgstat_prep_database_pending() can already ERROR on OOM while
> setting up the database pending entry, so this is not new here.
> 
> That said, preparing the database pending entry before updating any
> stats is probably a better idea just for consistency during such cases,
> so I split that out as a standalone fix in v8-0001.

=== 1

Thanks! Looking closer, I think there is still another window though:

pgstat_unlock_entry() calls LWLockRelease(), which can process a pending
interrupt. At that point, the shared relation stats have been updated, while the
database pending stats and flushed baseline have not. A later retry could then
apply the same delta again.

That is also already possible in HEAD and should be very rare in practice. That
said, I think it is worth mentioning and deciding whether we want to handle this
case too.

=== 2

+   else if (entry_ref->flushed_this_pass)
+   {
+       /*
+        * The entry is already pending and was already visited in the current
+        * flush pass.  Move it to the tail so the data just accumulated into
+        * it is flushed again before the pass ends.
+        */
+       dlist_move_tail(&pgStatPending, &entry_ref->pending_node);

IIUC, flushed_this_pass remains set after the flush pass ends. So, the next
pgstat_update_dbstats() moves the database entry to the tail before the new pass
starts.

Should we clear this flag between passes, or at least check pgStatFlushInProgress
here?

I did not review the tests in detail yet.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Вложения:
Hi,

On Sun, Aug 30, 2026 at 09:48:38PM -0500, Sami Imseih wrote:
> Hi,
> 
> 
> > === 1
> >
> > Thanks! Looking closer, I think there is still another window though:
> >
> > pgstat_unlock_entry() calls LWLockRelease(), which can process a pending
> > interrupt. At that point, the shared relation stats have been updated,
> > while the
> > database pending stats and flushed baseline have not. A later retry could
> > then
> > apply the same delta again.
> >
> > That is also already possible in HEAD and should be very rare in practice.
> > That
> > said, I think it is worth mentioning and deciding whether we want to
> > handle this
> > case too.
> >
> 
> I looked at this a bit more. We could close the window you mention
> either by moving pgstat_unlock_entry() until after the pending
> database stats are updated, or by holding interrupts across both the
> shared relation/index update and the pending database update.
> 
> But there are still other windows where the relation/index stats and
> database stats can diverge, including a possible double count in the
> database entry, in particular between finishing the relation/index
> flush callbacks and later flushing the database stats.
> 
> So I would rather not do anything here for now, including v8-0001,
> and instead take it up in a separate thread. WDYT?

Yeah, given that those windows already exist in HEAD I think it makes sense
to open a dedicated thread.

> > Should we clear this flag between passes, or at least check
> > pgStatFlushInProgress
> > here?
> 
> 
> Yeah right. I will fix this and send out a new rev.

Thanks!

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Wed, Sep 02, 2026 at 11:16:08AM -0500, Sami Imseih wrote:
> > The scan only performs one backend local bool write per pending entry, so
> > this
> > is probably negligible compared to the actual flush work. A pass generation
> > could avoid the extra scan, but I'm not sure that would be worth the
> > additional
> > complexity.
> >
> > What do you think?
> 
> 
> Even so, I think the pass-generation approach is the better idea here. It's
> slightly more code, but it avoids the extra full-list reset pass. I will
> feel
> better with the generational counter.

Thanks! The generation counter approach makes sense to me, it avoids the extra
reset scan.

I just have 1 minor comment related to the tests:

=== 1

+CREATE TABLE trunc_stats_test5(id serial);

I think it's related DROP is missing.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Wed, Sep 09, 2026 at 09:45:58PM -0500, Sami Imseih wrote:
> overall v14-0001 LGTM.

Okay, thanks for double-checking.  Done this one as well.
--
Michael

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Вложения:
> On Wed, Sep 09, 2026 at 09:45:58PM -0500, Sami Imseih wrote:
> > overall v14-0001 LGTM.
>
> Okay, thanks for double-checking.  Done this one as well.

Thanks!

Here is a rebased 0001 with updated documentation for
pg_stat_force_next_flush()

--
Sami Imseih
Amazon Web Services (AWS)

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Вложения:
cfbot showed a few Linux failures that were not reliably reproducible. The
failure was an assertion from pgstat_shutdown_hook() calling
pgstat_report_stat() while stats were already being flushed.

I fixed that by making pgstat_shutdown_hook() avoid a recursive flush. The
failure happens when we hit a FATAL while flushing stats. Process exit runs
pgstat_shutdown_hook() before the PG_FINALLY in the original
pgstat_report_stat() call has reset pgStatFlushInProgress.

v16 attached.

--
Sami Imseih
Amazon Web Services (AWS)

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Вложения:
PFA a mandatory rebase

--
Sami

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Вложения:
PFA a mandatory rebase


--
Sami

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Wed, Nov 04, 2026 at 07:08:54PM -0600, Sami Imseih wrote:
> PFA a mandatory rebase

Thanks for the updated patch!

+       xact_boundary = !IsTransactionOrTransactionBlock();

I looks like that procedure commits are missed.

For example, in session 1:

CREATE TABLE flush_test (id integer);

CREATE PROCEDURE flush_probe()
LANGUAGE plpgsql AS $$
BEGIN
    INSERT INTO flush_test VALUES (1);
    PERFORM pg_stat_force_next_flush();
    COMMIT;

    INSERT INTO flush_test VALUES (2);
    PERFORM pg_stat_force_next_flush();
    PERFORM pg_sleep(20);
END
$$;

CALL flush_probe();

While it sleeps, session 2 reports one row:

SELECT count(*) FROM flush_test;
count
-------
   1

but no inserts:

SELECT n_tup_ins FROM pg_stat_user_tables
WHERE relname = 'flush_test';
 n_tup_ins
-----------
         0

I would have expected n_tup_ins = 1.

I wonder if the committed transaction’s counters should be flushed before the
procedure starts the next transaction?

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Вложения:
> Hi,
>
> On Wed, Nov 04, 2026 at 07:08:54PM -0600, Sami Imseih wrote:
> > PFA a mandatory rebase
>
> Thanks for the updated patch!
>
> +       xact_boundary = !IsTransactionOrTransactionBlock();
>
> I looks like that procedure commits are missed.
>
> For example, in session 1:
>
> CREATE TABLE flush_test (id integer);
>
> CREATE PROCEDURE flush_probe()
> LANGUAGE plpgsql AS $$
> BEGIN
>     INSERT INTO flush_test VALUES (1);
>     PERFORM pg_stat_force_next_flush();
>     COMMIT;
>
>     INSERT INTO flush_test VALUES (2);
>     PERFORM pg_stat_force_next_flush();
>     PERFORM pg_sleep(20);
> END
> $$;
>
> CALL flush_probe();
>
> While it sleeps, session 2 reports one row:
>
> SELECT count(*) FROM flush_test;
> count
> -------
>    1
>
> but no inserts:
>
> SELECT n_tup_ins FROM pg_stat_user_tables
> WHERE relname = 'flush_test';
>  n_tup_ins
> -----------
>          0
>
> I would have expected n_tup_ins = 1.
>
> I wonder if the committed transaction’s counters should be flushed before the
> procedure starts the next transaction?
>
> Regards,

Thanks for raising this!

In v18, pgstat_relation_flush_cb() held back tab.counts_xact whenever
tab.trans != NULL, assuming it could have counts of the running
transaction. For inserts, updates and deletes it never does. Those
stay in tab.trans until the (sub)transaction ends. The only exception
was the HOT and new-page update counts.

In your example, the procedure never goes idle, so there is no flush
at idle. After the COMMIT, counts_xact has the committed counts, the
second INSERT creates tab.trans again, and the forced flush holds them
back. A multi-statement query string hits the same thing, e.g.
"BEGIN \; INSERT ... \; COMMIT \; INSERT ... \;
SELECT pg_stat_force_next_flush()".

So I don't think we need to flush before the procedure starts the next
transaction, as you suggest. That would add a flush to every COMMIT in
a procedure, even when nobody asked for one. Instead, v19 just lets
pgstat_relation_flush_cb() flush counts_xact, along with the
nontransactional tab.counts, every time, the same way
pgstat_index_flush_cb() already does.

The one catch was the HOT and new-page update counts, since
pgstat_count_heap_update() added those to counts_xact right away. v19
now counts them in tab.trans along with tuples_updated, so a flush
can't publish the running transaction's HOT updates ahead of its
updates.

This only changes the relation callback. We still need
PGSTAT_FLUSH_PARTIAL for kinds that defer transactional counters, like
the custom stats example; the relation callback just doesn't return it
anymore.

With v19, your example reports n_tup_ins = 1 during the sleep. I added
a test for this in stats.sql.

I also spent some more time looking at this patch, and found a few
unrelated fixes:

1/ I removed the CHECK_FOR_INTERRUPTS() from the flush loop. The loop
is short anyway, and the check could let a cancel request turn the
flush at idle into an ERROR after the query had already finished.

2/ I restored the custom stats reset test in 001_custom_stats.pl,
which I dropped by mistake back in v8.

3/ I renamed the partial_flush* tables in stats.sql to xact_flush*,
since relation flushes are no longer partial.

4/ The docs and the pg_stat_force_next_flush() comment said it is
mainly useful in tests. Now that it flushes within a transaction, it
is also useful for long-running transactions and extensions, so I
updated both.

5/ A few comment fixes where the comments still described the old
behavior.

Attached is v19.

--
Sami Imseih
Amazon Web Services (AWS)

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello

 	if (lstats->tab.truncdropped)
 	{
...
+		lstats->tab.flushed_xact.delta_live_tuples = 0;
+		lstats->tab.flushed_xact.delta_dead_tuples = 0;
        }
...
+	/* This still counts aborted inserts in ins_since_vacuum. */
+	tabentry->ins_since_vacuum +=
+		lstats->tab.counts_xact.tuples_inserted -
+		lstats->tab.flushed_xact.tuples_inserted;

The truncdropped branch in pgstat_relation_flush_cb() resets the
flushed_xact baselines of delta_live_tuples and delta_dead_tuples, but
ins_since_vacuum still adds counts_xact.tuples_inserted -
flushed_xact.tuples_inserted, so the inserts published by the earlier
flush are wiped by the reset.

With this, n_ins_since_vacuum depends on whether an in-transaction
flush happened:

CREATE TABLE isv(a int);
BEGIN;
TRUNCATE isv;
SAVEPOINT s;
INSERT INTO isv SELECT generate_series(1, 5);
ROLLBACK TO SAVEPOINT s;
SELECT pg_stat_force_next_flush(); -- comment out to change the result
COMMIT;
SELECT pg_stat_force_next_flush();
SELECT n_tup_ins, n_ins_since_vacuum FROM pg_stat_user_tables WHERE
relname = 'isv';

On master, or with the first flush commented out this shows 5|5, with
the patch as-is it's 5|0.


+        delay between flushes. When called within a transaction, counters
+        that should only be updated at the end of the transaction, such as
+        tuple inserts, updates, and deletes, are deferred until the
+        transaction ends. This is useful in tests, and to make the

vs

Nontransactional counters flush right away because they describe
completed work. Transactional counters flush once the (sub)transaction
that made them has ended, so the running transaction's own counts are
never published early.

The commit message seems to be a better description to me, since
subtransactions can update counters?


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Fri, Nov 13, 2026 at 01:22:27PM -0600, Sami Imseih wrote:
> With v19, your example reports n_tup_ins = 1 during the sleep. I added
> a test for this in stats.sql.

Thanks for the new patch version!

> I also spent some more time looking at this patch, and found a few
> unrelated fixes:
> 
> 1/ I removed the CHECK_FOR_INTERRUPTS() from the flush loop. The loop
> is short anyway, and the check could let a cancel request turn the
> flush at idle into an ERROR after the query had already finished.

What about omitting the CFI only for idle flush case?

Also, I think this:

+       deadtuples -= rel->pgstat_info->tab.counts_xact.delta_dead_tuples -
+           rel->pgstat_info->tab.flushed_xact.delta_dead_tuples;

can produce a wrong n_dead_tup value after a committed TRUNCATE. For example:

"
CREATE TABLE analyze_flush_bug(id int) WITH (autovacuum_enabled = off);

CREATE PROCEDURE analyze_flush_probe(
  INOUT after_first_flush bigint DEFAULT NULL,
  INOUT after_analyze bigint DEFAULT NULL)
LANGUAGE plpgsql AS $$
BEGIN
  BEGIN
    INSERT INTO analyze_flush_bug SELECT generate_series(1, 5);
    RAISE EXCEPTION 'abort subxact';
  EXCEPTION WHEN OTHERS THEN
    NULL;
  END;

  PERFORM pg_stat_force_next_flush();

  SELECT n_dead_tup INTO after_first_flush
    FROM pg_stat_user_tables
    WHERE relname = 'analyze_flush_bug';

  TRUNCATE analyze_flush_bug;
  COMMIT;

  ANALYZE analyze_flush_bug;

  SELECT n_dead_tup INTO after_analyze
    FROM pg_stat_user_tables
    WHERE relname = 'analyze_flush_bug';
END
$$;

CALL analyze_flush_probe();
"

produces:

 after_first_flush | after_analyze
-------------------+---------------
                 5 |             5


I'd expect after_analyze to be 0. Maybe the flushed live/dead tuple baselines
should also be reset when a committed TRUNCATE resets the corresponding counts?

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Вложения:
Attached is v20 which addresses the points raised by
both Zsolt and Bertrand above.

1/ CHECK_FOR_INTERRUPTS() is back in the flush loop, but only runs
when !xact_boundary, as Bertrand suggested. A cancel can still
interrupt an in-transaction flush, while the flush at idle can no
longer ERROR after the query has finished.

2/ n_ins_since_vacuum after TRUNCATE plus an aborted savepoint is
fixed. I added a test for this.

3/ n_dead_tup after a committed TRUNCATE + ANALYZE is fixed. The
flushed live/dead baselines are now reset at commit along with the
counts, so Bertrand's example shows 0 after ANALYZE.

4/ For the docs, I went with the commit message wording, as Zsolt
suggested, but made it precise. A released savepoint's counts still
wait for the top-level commit; only rolled-back subtransactions
flush early. The commit message is updated to match.

--
Sami

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Mon, Nov 16, 2026 at 10:56:09AM -0600, Sami Imseih wrote:
> Attached is v20 which addresses the points raised by
> both Zsolt and Bertrand above.

Thanks!

> 2/ n_ins_since_vacuum after TRUNCATE plus an aborted savepoint is
> fixed. I added a test for this.

It looks like that it now makes the reverse order produce the wrong result, for
example:

"
BEGIN;
SAVEPOINT s;
INSERT INTO t SELECT generate_series(1, 5);
ROLLBACK TO SAVEPOINT s;

SELECT pg_stat_force_next_flush();

TRUNCATE t;
COMMIT;

SELECT pg_stat_force_next_flush();
"

produces 5 for n_ins_since_vacuum, while 0 is expected.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Sami Imseih <samimseih.pg@gmail.com>
Дата:
Hi,

> "
> BEGIN;
> SAVEPOINT s;
> INSERT INTO t SELECT generate_series(1, 5);
> ROLLBACK TO SAVEPOINT s;
>
> SELECT pg_stat_force_next_flush();
>
> TRUNCATE t;
> COMMIT;
>
> SELECT pg_stat_force_next_flush();
> "
>
> produces 5 for n_ins_since_vacuum, while 0 is expected.

0 is expected, I agree. This is an issue on HEAD as well so
not a product of this patch. This should be raised in a
separate thread.

--
Sami


Re: pgstat: Flush some statistics within running transactions, take 2

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Tue, Nov 17, 2026 at 08:08:37AM -0600, Sami Imseih wrote:
> 0 is expected, I agree. This is an issue on HEAD as well so
> not a product of this patch. This should be raised in a
> separate thread.

Is that, cough, something that I had the idea to break recently?
--
Michael

Re: pgstat: Flush some statistics within running transactions, take 2

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Fri, Nov 20, 2026 at 03:58:03PM +0900, Michael Paquier wrote:
> On Tue, Nov 17, 2026 at 08:08:37AM -0600, Sami Imseih wrote:
> > 0 is expected, I agree. This is an issue on HEAD as well so
> > not a product of this patch. This should be raised in a
> > separate thread.

Agreed.

> 
> Is that, cough, something that I had the idea to break recently?

Nope ;-) Looks like it's there since b07642dbcd8d. I'll start a dedicated thread
unless someone beats me to it.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


FAQ