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 Thu, Jul 30, 2026 at 02:41:58PM -0500, Sami Imseih wrote:
> Hi,
> 
> The discussion for mid-transaction flushes ended up taking place in
> the pg_stat_statements scalability thread [1], but I rather not have
> that thread become the place to review prerequisite patches. To keep
> things easier to follow, I am moving this patch back to its dedicated
> thread. The pg_stat_statements
> scalability work will follow as a patch set on top of this once this
> settles.
> 
> Attaching v2 of this patch.

Thanks for the new version!

A few comments:

=== 1

 void
 pgstat_force_next_flush(void)
 {
+   if (IsTransactionOrTransactionBlock())
+       pgstat_report_stat(true);
+

That causes issues for function stats. pgstat_function_flush_cb() returns
PGSTAT_FLUSH_DONE, then pgstat_delete_pending_entry() is called, freeing storage
still referenced by PgStat_FunctionCallUsage.fs. When the function returns,
pgstat_end_function_usage() writes through that stale pointer.

Example:

postgres=# SET track_functions = 'all';

postgres=#   CREATE FUNCTION force_flush_wrapper()
  RETURNS void
  LANGUAGE plpgsql
  AS $$
  BEGIN
      PERFORM pg_stat_force_next_flush();
  END
  $$;

postgres=# SELECT force_flush_wrapper();
postgres=# SELECT force_flush_wrapper();

postgres=#  SELECT funcname, calls
  FROM pg_stat_user_functions
  WHERE funcid = 'force_flush_wrapper()'::regprocedure;
      funcname       | calls
---------------------+-------
 force_flush_wrapper |     0
(1 row)

We got 0 instead of 2 but that could be worst and corrupt memory if the freed
storage is reused.

Function is a special case, see:

"
typedef struct PgStat_FunctionCallUsage
{
    /* Link to function's hashtable entry (must still be there at exit!) */
    /* NULL means we are not tracking the current function call */
    PgStat_FunctionCounts *fs;
"

but custom statistics can have the same problem if they keep a pointer to pending
data across pgstat_force_next_flush().

I think that entry_ref->pending should not be freed by an in-transaction flush.

=== 2

-   bool        (*flush_pending_cb) (PgStat_EntryRef *sr, bool nowait);
+               PgStat_FlushResult(*flush_pending_cb) (PgStat_EntryRef *sr, bool nowait,
+                                                      bool xact_boundary);

should we do the same for flush_static_cb() or exclude static callbacks from
mid-transaction flushes? (for the same reason that xact_boundary has been added
to flush_pending_cb())

=== 3 

+typedef enum PgStat_FlushResult
+{
+   /* Fully flushed; the entry can be removed from the pending list. */
+   PGSTAT_FLUSH_DONE,
+
+   /*
+    * The lock could not be acquired without waiting (nowait was true).  The
+    * entry must stay pending and be retried later.
+    */
+   PGSTAT_FLUSH_LOCK_CONFLICT,
+
+   /*
+    * Only part of the entry was flushed; some state was intentionally
+    * retained because it cannot be flushed in the current context (e.g.
+    * transactional counters flushed mid-transaction).  The entry must stay
+    * pending and be flushed again at a suitable boundary.
+    */
+   PGSTAT_FLUSH_PARTIAL,
+}          PgStat_FlushResult;

Previously, flush_pending_cb returned a bool with that meaning: false for lock
conflict and true for done.

Now 0 is PGSTAT_FLUSH_DONE and 1 is PGSTAT_FLUSH_LOCK_CONFLICT.

I think that would be better to change the enum ordering to preserve the previous
meaning. The concern is silent misbehavior in custom callbacks.

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@gmail.com>
Дата:
Вложения:
> > Adding post_flush_pending_cb can go in as a pre-requisite
> > commit. This is also better in terms of separation of
> > responsibilities between flushing the kinds stats and post
> > flush actions.
>
> I'm not sure a new callback is needed here. The relation callback already performs
> the database accumulation only after a successful flush. If pending lifetime
> and queue membership are separated, the existing pgstat_prep_database_pending()
> call could requeue the database entry and preserve the current behavior.

For now, I moved away from the extra callback idea, although I do think it
has benefits which could be hashed out in a different thread. The relation
callback still calls pgstat_prep_database_pending().

Rather than requeue individual entries, whenever a flush_pending_cb()
accumulates to another pending entry as is the case with relation -> database,
it sets a new global pgStatPendingFlushExtra = true, which then triggers
a secondary re-scan. We continue doing secondary re-scans until
pgStatPendingFlushExtra is back to false, so this can handle arbitrary numbers
of cascading pending entries, such as the case you raise earlier. This rescan
will only occur when we are mid-transaction, as it has no purpose on transaction
boundary.

I felt this is simpler than requeueing. Because each flush is a delta against
the flushed baseline, re-flushing an unchanged entry is a no-op, so the rescan
is safe without tracking per-entry queue membership; a callback only sets
pgStatPendingFlushExtra rather than managing the pending list. The rescan does
revisit entries with nothing new, but it only runs mid-transaction, so the
normal transaction boundary flush path is unaffected.

I also added an ample amount of test coverage in stats.sql and also testing
the cascading cases in test_custom_var_stats. I do create 2 new kinds to
test the cascade, which means we need to reserve 2 new Kind IDs.
If that is a problem, we can leave these tests out perhaps?

```
+/*
+ * Kind IDs for cascade flush test (A -> B -> C).
+ * Tests that pgStatPendingFlushExtra handles multi-level dependencies.
+ */
+#define PGSTAT_KIND_CASCADE_B 27
+#define PGSTAT_KIND_CASCADE_C 28
```

> I think that a post-flush callback might improve organization, but that seems
> independent of this issue and so would need to be justified on its own.

Yes, I still think there is value here, but I will table it for another idea.

With regards to the earlier comments.

> I think that the same solution for "=== 2" would work here: keep the counters
> cumulative for the transaction, record how much has already been flushed, and
> report only the difference.

done.

> === 4

> > Static callbacks (IO, WAL, SLRU, backend, lock) don't use
> > entry_ref->pending, so there is no freeing risk.
> > They also don't
> > receive xact_boundary, so no changes were needed there.

> The concern was not freeing: as flush_static_cb can now be called inside a
> transaction, I think that it should receive xact_boundary or be skipped. That
> would allow custom stats to also defer transaction dependent state.

done

> === 5

> Should we mark pg_stat_force_next_flush() as PARALLEL UNSAFE, since the patch
> can now invoke custom flush callbacks while a parallel query is active?

You're correct.

Attached is v4.

--
Sami Imseih
Amazon Web Services (AWS)
FAQ