Fix cumulative WAL statistics double-counting from parallel workers
Fix cumulative WAL statistics double-counting from parallel workers
Hi,
Over in [0] we were recently discussing how parallel workers
accumulate their buffer usage into the leader and how that makes it
hard to pass pgBufferUsage instrumentation into the cumulative stats
system, and I've also been looking into this for the stack-based
instrumentation work [1], because it's really hard to avoid double
counting due to how we accumulate into the leader's
pgBufferUsage/pgWalUsage today.
Turns out there is a current bug in master in how pg_stat_wal and
pg_stat_get_backend_wal() report activity from parallel workers. This
issue has existed since the introduction of pg_stat_wal in Postgres
14: We double count WAL produced in parallel workers, because we add
WAL activity from the parallel workers to both the worker's pgWalUsage
(direct) and the leader's pgWalUsage (via InstrAccumParallelQuery),
and each of them emits that activity to the cumulative stats.
Here is a reproducer for parallel index vacuuming, but the same issue
applies to WAL activity from pruning, or hint bits set during parallel
sequential scans:
SET max_parallel_maintenance_workers = 4;
SET min_parallel_index_scan_size = 0;
SET maintenance_work_mem = '256MB';
CREATE TABLE t (id int, a int, b int, c int, d int) WITH
(autovacuum_enabled = off);
INSERT INTO t SELECT g, g, g, g, g FROM generate_series(1, 2000000) g;
CREATE INDEX ON t (a);
CREATE INDEX ON t (b);
CREATE INDEX ON t (c);
CREATE INDEX ON t (d);
DELETE FROM t WHERE id % 2 = 0;
CHECKPOINT;
SELECT pg_stat_force_next_flush();
SELECT pg_current_wal_lsn() AS lsn_before,
(SELECT wal_bytes FROM pg_stat_wal) AS reported_before \gset
VACUUM (PARALLEL 4) t;
SELECT pg_stat_force_next_flush();
SELECT pg_current_wal_lsn() AS lsn_after,
(SELECT wal_bytes FROM pg_stat_wal) AS reported_after \gset
SELECT pg_wal_lsn_diff(:'lsn_after', :'lsn_before') AS actual_wal_bytes,
:reported_after - :reported_before AS reported_wal_bytes,
round((:reported_after - :reported_before) * 100.0
/ pg_wal_lsn_diff(:'lsn_after', :'lsn_before'), 1) AS
reported_pct_of_actual;
On master this returns:
-[ RECORD 1 ]----------+----------
actual_wal_bytes | 195781792
reported_wal_bytes | 257020498
reported_pct_of_actual | 131.3
---
In terms of how to fix this, I first tried to invent a mechanism that
would keep instrumentation imported from workers separate in the
leader (so we never double count in the global). But that turns out to
be pretty tricky, because we have use cases (pg_stat_statements being
the main one, but e.g. also EXPLAIN ANALYZE of a query calling a
function that itself runs a parallel query) where we want to track
whole-statement activity (leader + workers), including utility
statements, and we want to be able to do so in a nested manner.
Instead, at least for now, the easier solution seems to be to
accumulate imported instrumentation data into both the existing
pg(Wal|Buffer)Usage globals, and a separate set called
pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the
workers. Any caller that wants to isolate the leader-only activity for
reporting to the cumulative statistics system then subtracts the
worker portion from the global instrumentation using a helper function
(ComputeOwnWalUsage), and workers continue to report their own
activity directly to the cumulative statistics system.
See attached.
This same approach will also be useful to replace the use of
pgStatBlock(Read|Write)Time with diffing pgBufferUsage instead for the
cumulative reporting in pg_stat_database, as discussed in [0]. The
stack-based instrumentation proposal [1] will have to follow this
change of having a separate global to remember what came from the
workers, but that's pretty straightforward to update.
Thoughts?
Thanks,
Lukas
[0]: https://www.postgresql.org/message-id/flat/605732d2-c6bd-4c65-ac83-8d071935d860%40gmx.at
[1]: https://www.postgresql.org/message-id/flat/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
--
Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Thu, Oct 29, 2026 at 03:58:03PM -0700, Lukas Fittl wrote: > Hi, > > Over in [0] we were recently discussing how parallel workers > accumulate their buffer usage into the leader and how that makes it > hard to pass pgBufferUsage instrumentation into the cumulative stats > system, and I've also been looking into this for the stack-based > instrumentation work [1], because it's really hard to avoid double > counting due to how we accumulate into the leader's > pgBufferUsage/pgWalUsage today. > > Turns out there is a current bug in master in how pg_stat_wal and > pg_stat_get_backend_wal() report activity from parallel workers. This > issue has existed since the introduction of pg_stat_wal in Postgres > 14: We double count WAL produced in parallel workers, because we add > WAL activity from the parallel workers to both the worker's pgWalUsage > (direct) and the leader's pgWalUsage (via InstrAccumParallelQuery), > and each of them emits that activity to the cumulative stats. Ouch, nice catch! > In terms of how to fix this, I first tried to invent a mechanism that > would keep instrumentation imported from workers separate in the > leader (so we never double count in the global). But that turns out to > be pretty tricky, because we have use cases (pg_stat_statements being > the main one, but e.g. also EXPLAIN ANALYZE of a query calling a > function that itself runs a parallel query) where we want to track > whole-statement activity (leader + workers), including utility > statements, and we want to be able to do so in a nested manner. Agreed. > Instead, at least for now, the easier solution seems to be to > accumulate imported instrumentation data into both the existing > pg(Wal|Buffer)Usage globals, and a separate set called > pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the > workers. Any caller that wants to isolate the leader-only activity for > reporting to the cumulative statistics system then subtracts the > worker portion from the global instrumentation using a helper function > (ComputeOwnWalUsage), and workers continue to report their own > activity directly to the cumulative statistics system. Yeah that looks like the best way to proceed currently. I wonder if the extra additions could be reduced though. What about first accumulating all workers into a local BufferUsage/WalUsage and then calling InstrAccumParallelQuery() once for all workers? Also, worth to add some tests? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
Hi Bertrand, On Fri, Oct 30, 2026 at 12:27 AM Bertrand Drouvot wrote: > > In terms of how to fix this, I first tried to invent a mechanism that > > would keep instrumentation imported from workers separate in the > > leader (so we never double count in the global). But that turns out to > > be pretty tricky, because we have use cases (pg_stat_statements being > > the main one, but e.g. also EXPLAIN ANALYZE of a query calling a > > function that itself runs a parallel query) where we want to track > > whole-statement activity (leader + workers), including utility > > statements, and we want to be able to do so in a nested manner. > > Agreed. > > > Instead, at least for now, the easier solution seems to be to > > accumulate imported instrumentation data into both the existing > > pg(Wal|Buffer)Usage globals, and a separate set called > > pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the > > workers. Any caller that wants to isolate the leader-only activity for > > reporting to the cumulative statistics system then subtracts the > > worker portion from the global instrumentation using a helper function > > (ComputeOwnWalUsage), and workers continue to report their own > > activity directly to the cumulative statistics system. > > Yeah that looks like the best way to proceed currently. Great, thanks for thinking through it! > I wonder if the extra additions could be reduced though. What about first > accumulating all workers into a local BufferUsage/WalUsage and then calling > InstrAccumParallelQuery() once for all workers? Hmm. Not sure if the extra additions really matter (I don't think its a particularly performance critical code section), and I'm hesitant to have more duplicated code in the different call sites of InstrAccumParallelQuery. We could refactor it a bit by having InstrAccumParallelQuery take arrays of WalUsage/BufferUsage, as well as a worker count argument, and then save on the additions that way inside InstrAccumParallelQuery? We have this pattern of working on multiple instrumentation structs already in e.g. InstrAllocTrigger, so it doesn't seem too far fetched to do - and all callers of InstrAccumParallelQuery have a (currently duplicated) loop over the workers. > Also, worth to add some tests? Maybe? I'm always on the fence with how much tests we should be adding for instrumentation fixes, because it needs a bunch of setup, can be brittle in terms of comparing numbers (especially since producing a certain amount of WAL is involved), and more tests slow down the regression test suite. But happy to add it if we feel its worth it. FWIW, what I'd really wish for is a better way to guarantee the invariant (i.e. nobody starts diffing pgWalUsage/pgBufferUsage and emitting it into cumulative stats without taking care of this), but I feel the only way to achieve that would be to make the globals private to instrument.c and require the use of an appropriately named method to access them, which doesn't seem worth it. Writing this out though makes me wonder though if we should add a comment above pgBufferUsage/pgWalUsage in instrument.h warning of this hazard, instead of just on the new globals below. Thanks, Lukas -- Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
ahmed <gouda0x@gmail.com>
Дата:
Turns out there is a current bug in master in how pg_stat_wal and
pg_stat_get_backend_wal() report activity from parallel workers. This
issue has existed since the introduction of pg_stat_wal in Postgres
14: We double count WAL produced in parallel workers, because we add
WAL activity from the parallel workers to both the worker's pgWalUsage
(direct) and the leader's pgWalUsage (via InstrAccumParallelQuery),
and each of them emits that activity to the cumulative stats.
Nice Catch!
Here is a reproducer for parallel index vacuuming, but the same issue
applies to WAL activity from pruning, or hint bits set during parallel
sequential scans:
SET max_parallel_maintenance_workers = 4;
SET min_parallel_index_scan_size = 0;
SET maintenance_work_mem = '256MB';
CREATE TABLE t (id int, a int, b int, c int, d int) WITH
(autovacuum_enabled = off);
INSERT INTO t SELECT g, g, g, g, g FROM generate_series(1, 2000000) g;
CREATE INDEX ON t (a);
CREATE INDEX ON t (b);
CREATE INDEX ON t (c);
CREATE INDEX ON t (d);
DELETE FROM t WHERE id % 2 = 0;
CHECKPOINT;
SELECT pg_stat_force_next_flush();
SELECT pg_current_wal_lsn() AS lsn_before,
(SELECT wal_bytes FROM pg_stat_wal) AS reported_before \gset
VACUUM (PARALLEL 4) t;
SELECT pg_stat_force_next_flush();
SELECT pg_current_wal_lsn() AS lsn_after,
(SELECT wal_bytes FROM pg_stat_wal) AS reported_after \gset
SELECT pg_wal_lsn_diff(:'lsn_after', :'lsn_before') AS actual_wal_bytes,
:reported_after - :reported_before AS reported_wal_bytes,
round((:reported_after - :reported_before) * 100.0
/ pg_wal_lsn_diff(:'lsn_after', :'lsn_before'), 1) AS
reported_pct_of_actual;
On master this returns:
-[ RECORD 1 ]----------+----------
actual_wal_bytes | 195781792
reported_wal_bytes | 257020498
reported_pct_of_actual | 131.3
---
In terms of how to fix this, I first tried to invent a mechanism that
would keep instrumentation imported from workers separate in the
leader (so we never double count in the global). But that turns out to
be pretty tricky, because we have use cases (pg_stat_statements being
the main one, but e.g. also EXPLAIN ANALYZE of a query calling a
function that itself runs a parallel query) where we want to track
whole-statement activity (leader + workers), including utility
statements, and we want to be able to do so in a nested manner.
Instead, at least for now, the easier solution seems to be to
accumulate imported instrumentation data into both the existing
pg(Wal|Buffer)Usage globals, and a separate set called
pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the
workers. Any caller that wants to isolate the leader-only activity for
reporting to the cumulative statistics system then subtracts the
worker portion from the global instrumentation using a helper function
(ComputeOwnWalUsage), and workers continue to report their own
activity directly to the cumulative statistics system.
See attached.
This same approach will also be useful to replace the use of
pgStatBlock(Read|Write)Time with diffing pgBufferUsage instead for the
cumulative reporting in pg_stat_database, as discussed in [0]. The
stack-based instrumentation proposal [1] will have to follow this
change of having a separate global to remember what came from the
workers, but that's pretty straightforward to update.
Thoughts?
Thanks,
Lukas
[0]: https://www.postgresql.org/message-id/flat/605732d2-c6bd-4c65-ac83-8d071935d860%40gmx.at
[1]: https://www.postgresql.org/message-id/flat/CAP53PkzdBK8VJ1fS4AZ481LgMN8f9mJiC39ZRHqkFUSYq6KWmg%40mail.gmail.com
--
Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
ahmed <gouda0x@gmail.com>
Дата:
Hi Lukas,
First, sorry for the previous incomplete email, sent by accident; please ignore it.
> Turns out there is a current bug in master in how pg_stat_wal and
> pg_stat_get_backend_wal() report activity from parallel workers. This
> issue has existed since the introduction of pg_stat_wal in Postgres
> 14: We double count WAL produced in parallel workers, because we add
> WAL activity from the parallel workers to both the worker's pgWalUsage
> (direct) and the leader's pgWalUsage (via InstrAccumParallelQuery),
> and each of them emits that activity to the cumulative stats.
Nice Catch!
> Instead, at least for now, the easier solution seems to be to
> accumulate imported instrumentation data into both the existing
> pg(Wal|Buffer)Usage globals, and a separate set called
> pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the
> workers. Any caller that wants to isolate the leader-only activity for
> reporting to the cumulative statistics system then subtracts the
> worker portion from the global instrumentation using a helper function
> (ComputeOwnWalUsage), and workers continue to report their own
> activity directly to the cumulative statistics system.
I was thinking: instead of introducing new pg(Wal|Buffer)UsageFromWorkers global variables, could we make the existing `static WalUsage prevWalUsage` a global variable, rename it to reportedWalUsage, and increment it directly in InstrAccumParallelQuery() and on flush subtract it from pgWalUsage? That would also minimize the number of subtraction operations on flush.
And we can do the same with pgStatBlock(Read|Write)Time, rename it to reportedBlock(Read|Write)Time, etc…
Regards,
First, sorry for the previous incomplete email, sent by accident; please ignore it.
> Turns out there is a current bug in master in how pg_stat_wal and
> pg_stat_get_backend_wal() report activity from parallel workers. This
> issue has existed since the introduction of pg_stat_wal in Postgres
> 14: We double count WAL produced in parallel workers, because we add
> WAL activity from the parallel workers to both the worker's pgWalUsage
> (direct) and the leader's pgWalUsage (via InstrAccumParallelQuery),
> and each of them emits that activity to the cumulative stats.
Nice Catch!
> Instead, at least for now, the easier solution seems to be to
> accumulate imported instrumentation data into both the existing
> pg(Wal|Buffer)Usage globals, and a separate set called
> pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the
> workers. Any caller that wants to isolate the leader-only activity for
> reporting to the cumulative statistics system then subtracts the
> worker portion from the global instrumentation using a helper function
> (ComputeOwnWalUsage), and workers continue to report their own
> activity directly to the cumulative statistics system.
I was thinking: instead of introducing new pg(Wal|Buffer)UsageFromWorkers global variables, could we make the existing `static WalUsage prevWalUsage` a global variable, rename it to reportedWalUsage, and increment it directly in InstrAccumParallelQuery() and on flush subtract it from pgWalUsage? That would also minimize the number of subtraction operations on flush.
And we can do the same with pgStatBlock(Read|Write)Time, rename it to reportedBlock(Read|Write)Time, etc…
Regards,
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Thu, Oct 29, 2026 at 03:58:03PM -0700, Lukas Fittl wrote:
> Instead, at least for now, the easier solution seems to be to
> accumulate imported instrumentation data into both the existing
> pg(Wal|Buffer)Usage globals, and a separate set called
> pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the
> workers. Any caller that wants to isolate the leader-only activity for
> reporting to the cumulative statistics system then subtracts the
> worker portion from the global instrumentation using a helper function
> (ComputeOwnWalUsage), and workers continue to report their own
> activity directly to the cumulative statistics system.
If I am reading the patch right, it means that a leader's pgWalUsage
includes both its own activity *and* the activity of its workers. It
sounds to me like a mistake to do that. Why aren't pgWalUsage and
friends handled in such a way that they only include the activity of
their own process? That would be a lot cheaper, especially for the
pgstats parts.
+void
+ComputeOwnWalUsage(WalUsage *walusage)
+{
+ memset(walusage, 0, sizeof(WalUsage));
+ WalUsageAccumDiff(walusage, &pgWalUsage, &pgWalUsageFromWorkers);
Yeah, so I feel that I am reading that right, then. When we want to
get the WAL usage from the leader, before aggregating it back to
pgstats, we substract the data that came from the workers. That seems
like a waste, we're doing diffs calculations because we gather all the
data in one single place. But all that should just be about
additions. You are making it additions then subtractions, leaving the
places where we want aggregates untouched.
You will need the data from the workers, but I'd suggest to do that
the other way around: gather the data from the workers in a secondary
WalUsage, apply the sum of all only when you want to have a view of
the aggregate. That should sum up to:
heap_vacuum_rel()
do_analyze_rel()
PGSS
instrument.c
And there should be no need to touch at the pgstats code paths.
--
Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi Lukas, On Fri, Oct 30, 2026 at 12:19:51PM -0700, Lukas Fittl wrote: > On Fri, Oct 30, 2026 at 12:27 AM Bertrand Drouvot > wrote: > > We could refactor it a bit by having InstrAccumParallelQuery take > arrays of WalUsage/BufferUsage, as well as a worker count argument, > and then save on the additions that way inside > InstrAccumParallelQuery? Yeah that makes sense. That said, as this should be backpatched, we'd either have to change the function signature in the back branches or make master diverge from them. Neither option looks appealing. I'm not sure either is worth it given this is not performance critical though, so I'd vote to keep v1 as is in all branches. > > Also, worth to add some tests? > > Maybe? I'm always on the fence with how much tests we should be adding > for instrumentation fixes, because it needs a bunch of setup, can be > brittle in terms of comparing numbers (e Right, and a test relying on workers actually processing enough WAL work might also be fragile in the buildfarm. So I would not insist on adding one here. > FWIW, what I'd really wish for is a better way to guarantee the > invariant (i.e. nobody starts diffing pgWalUsage/pgBufferUsage and > emitting it into cumulative stats without taking care of this), but I > feel the only way to achieve that would be to make the globals private > to instrument.c and require the use of an appropriately named method > to access them, which doesn't seem worth it. Agreed. > Writing this out though makes me wonder though if we should add a > comment above pgBufferUsage/pgWalUsage in instrument.h warning of this > hazard, instead of just on the new globals below. +1, I think that should be enough for now. One comment about the patch. === 1 +extern PGDLLIMPORT BufferUsage pgBufferUsageFromWorkers; +extern PGDLLIMPORT WalUsage pgWalUsageFromWorkers; I wonder if those shouldn't remain private to instrument.c? Contrary to pgWalUsage, no callers need to access them directly, and they look more like internal such as save_pgWalUsage. So maybe they could be static and only ComputeOwnWalUsage() exposed? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Mon, Nov 02, 2026 at 05:16:29PM +0900, Michael Paquier wrote: > On Thu, Oct 29, 2026 at 03:58:03PM -0700, Lukas Fittl wrote: > > Instead, at least for now, the easier solution seems to be to > > accumulate imported instrumentation data into both the existing > > pg(Wal|Buffer)Usage globals, and a separate set called > > pg(Wal|Buffer)UsageFromWorkers that counts only the activity from the > > workers. Any caller that wants to isolate the leader-only activity for > > reporting to the cumulative statistics system then subtracts the > > worker portion from the global instrumentation using a helper function > > (ComputeOwnWalUsage), and workers continue to report their own > > activity directly to the cumulative statistics system. > > If I am reading the patch right, it means that a leader's pgWalUsage > includes both its own activity *and* the activity of its workers. It > sounds to me like a mistake to do that. Why aren't pgWalUsage and > friends handled in such a way that they only include the activity of > their own process? Wouldn't that change the semantics of pgWalUsage for out of core extensions using it (if any) the same way as PGSS? We can adjust PGSS, but those extensions would start seeing leader only activity once running a version with this change? Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Mon, Nov 02, 2026 at 08:41:15AM +0000, Bertrand Drouvot wrote: > On Mon, Nov 02, 2026 at 05:16:29PM +0900, Michael Paquier wrote: >> If I am reading the patch right, it means that a leader's pgWalUsage >> includes both its own activity *and* the activity of its workers. It >> sounds to me like a mistake to do that. Why aren't pgWalUsage and >> friends handled in such a way that they only include the activity of >> their own process? > > Wouldn't that change the semantics of pgWalUsage for out of core extensions using > it (if any) the same way as PGSS? We can adjust PGSS, but those extensions would > start seeing leader only activity once running a version with this change? We don't have to change the meaning of pgWalUsage in the stable branches. We could keep it there, where I'd suggest to invent a third WalUsage then that aggregates only the data of its own. Then, we use the "own" WalUsage for the stats, and for the combined view use the "own" WalUsage and pgWalUsageFromWorkers. Finally, remove all traces of pgWalUsage from the backend code, remove its definition on HEAD. Perhaps the last point is not required. My point is that I don't get the meaning of these new WalUsageAccumDiff(), especially as we could design things so as we avoid them. -- Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
Hi Michael,
Thanks for taking a look!
On Mon, Nov 2, 2026 at 1:32 AM Michael Paquier wrote:
>
> On Mon, Nov 02, 2026 at 08:41:15AM +0000, Bertrand Drouvot wrote:
> > On Mon, Nov 02, 2026 at 05:16:29PM +0900, Michael Paquier wrote:
> >> If I am reading the patch right, it means that a leader's pgWalUsage
> >> includes both its own activity *and* the activity of its workers. It
> >> sounds to me like a mistake to do that. Why aren't pgWalUsage and
> >> friends handled in such a way that they only include the activity of
> >> their own process?
> >
> > Wouldn't that change the semantics of pgWalUsage for out of core extensions using
> > it (if any) the same way as PGSS? We can adjust PGSS, but those extensions would
> > start seeing leader only activity once running a version with this change?
>
> We don't have to change the meaning of pgWalUsage in the stable
> branches. We could keep it there, where I'd suggest to invent a third
> WalUsage then that aggregates only the data of its own. Then, we use
> the "own" WalUsage for the stats, and for the combined view use the
> "own" WalUsage and pgWalUsageFromWorkers. Finally, remove all traces
> of pgWalUsage from the backend code, remove its definition on HEAD.
> Perhaps the last point is not required.
>
> My point is that I don't get the meaning of these new
> WalUsageAccumDiff(), especially as we could design things so as we
> avoid them.
The problem isn't just out of core extensions using pgWalUsage, its
that we also look at pgWalUsage for reporting in EXPLAIN and on
statements that ran parallel that were called by a node, as mentioned
in my initial email.
Here is an example:
CREATE TABLE t (a int) WITH (autovacuum_enabled = off);
INSERT INTO t SELECT generate_series(1, 1000000);
CHECKPOINT; -- so that setting hint bits (checksums on) emits FPIs
CREATE FUNCTION f() RETURNS bigint LANGUAGE plpgsql AS
$$ DECLARE n bigint; BEGIN SELECT count(*) INTO n FROM t; RETURN n; END $$;
SET parallel_setup_cost = 0;
SET parallel_tuple_cost = 0;
SET max_parallel_workers_per_gather = 2;
SET parallel_leader_participation = off; -- all WAL comes from the workers
EXPLAIN (ANALYZE, WAL, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY
OFF) SELECT f();
QUERY PLAN
----------------------------------------------------------------------------------
Result (actual rows=1.00 loops=1)
WAL: records=8849 fpi=4426 bytes=36596662 fpi bytes=36114392
buffers full=3975
(2 rows)
Now, taking that example, here are three possible approaches to the
problem overall that I can see, focusing on what to do on master (i.e.
ignoring extension compatibility concerns):
1) pgWalUsage keeps today's meaning, pgWalUsageFromWorkers is
additionally accumulated in InstrAccumParallelQuery (the v1 patch)
- When the function finishes executing, the worker instrumentation
gets fed into the parent process pgWalUsage and pgWalUsageFromWorkers
- That pgWalUsage is then seen by the Result node as part of its
InstrStartNode/InstrStopNode, which results in the correct reporting
- Use cases like pg_stat_statements that want to report worker
activity as part of the statement only look at pgWalUsage
- The pg_stat_wal reporting in the leader subtracts
pgWalUsageFromWorkers with WalUsageAccumDiff so it correctly skips the
data from this invocation
2) pgWalUsage does not include the worker instrumentation, maybe
rename to pgWalUsageOwn (basically your suggestion for master, if I
understood correctly), we also introduce pgWalUsageFromWorkers
- When the function finishes executing, the worker instrumentation
only gets fed into pgWalUsageFromWorkers
- In order for the Result node to see the activity, it needs to diff
both pgWalUsage and pgWalUsageFromWorkers in InstrStopNode, to
correctly increment its instrumentation data to include workers
- Use cases like pg_stat_statements need to look at both pgWalUsage
and pgWalUsageFromWorkers
- The pg_stat_wal reporting in the leader can simply work with
pgWalUsage like today
3) pgWalUsage keeps today's meaning, we introduce a separate
pgWalUsageOwn that includes only the leader
- pgWalUsageOwn gets additionally incremented in all places where we
currently increment pgWalUsage
- When the function finishes executing, the worker instrumentation
only gets fed into pgWalUsage
- That pgWalUsage is then seen by the Result node as part of its
InstrStartNode/InstrStopNode, which results in the correct reporting
- Use cases like pg_stat_statements that want to report worker
activity as part of the statement only look at pgWalUsage
- The pg_stat_wal reporting in the leader only looks at the new pgWalUsageOwn
I don't think (2) is workable, especially if we want a design that
also works for pgBufferUsage - doing any extra work in InstrStopNode
is too expensive (instruction-wise, and because of the size of the
memory being accessed).
I think (3) could potentially be an alternate, but I don't know if its
worth the trouble just to avoid the WalUsageAccumDiff on flush, which
is not in the hot path.
Did I miss something in how you think this could work?
Thanks,
Lukas
--
Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Tue, Nov 03, 2026 at 02:58:31PM -0800, Lukas Fittl wrote: > I don't think (2) is workable, especially if we want a design that > also works for pgBufferUsage - doing any extra work in InstrStopNode > is too expensive (instruction-wise, and because of the size of the > memory being accessed). Hmm. I have not looked at that. But would it really matter if we just drop pgWalUsage? We only need the aggregated data from the leaders and its workers when we are ready to report the data. > I think (3) could potentially be an alternate, but I don't know if its > worth the trouble just to avoid the WalUsageAccumDiff on flush, which > is not in the hot path. With only HEAD in mind, (2) just seems like the simplest alternative, because there is less to consider about all these states except summing them up, where necessary. The origin of the double-counting comes from the point of pgWalUsage being rather confusing in itself, because we do not define when it is okay or when is is not okay to use. If it's confusing, I would not be sad to see it gone on HEAD, replaced by a WalUsage that just tracks the activity within the process, combined with a secondary WalUsage where we aggregate from activity from the workers. -- Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
On Tue, Nov 3, 2026 at 3:18 PM Michael Paquier wrote: > > On Tue, Nov 03, 2026 at 02:58:31PM -0800, Lukas Fittl wrote: > > I don't think (2) is workable, especially if we want a design that > > also works for pgBufferUsage - doing any extra work in InstrStopNode > > is too expensive (instruction-wise, and because of the size of the > > memory being accessed). > > Hmm. I have not looked at that. But would it really matter if we > just drop pgWalUsage? We only need the aggregated data from the > leaders and its workers when we are ready to report the data. When you say "ready to report the data", which moment are you thinking of? The problem in the EXPLAIN example shown is that we need some way to have the instrumentation for the Result node capture the function's query parallel worker activity. Currently this works because we're inside an open InstrStartNode / InstrStopNode pair, and the InstrAccumParallelQuery call when the function's query ends makes the leader pgWalUsage move forward the expected amount. The only way to avoid extra work in InstrStopNode is to have a global that represents what pgWalUsage currently is (leader + worker), but maybe I'm missing something in your argument? > > > I think (3) could potentially be an alternate, but I don't know if its > > worth the trouble just to avoid the WalUsageAccumDiff on flush, which > > is not in the hot path. > > With only HEAD in mind, (2) just seems like the simplest alternative, > because there is less to consider about all these states except > summing them up, where necessary. The origin of the double-counting > comes from the point of pgWalUsage being rather confusing in itself, > because we do not define when it is okay or when is is not okay to > use. If it's confusing, I would not be sad to see it gone on HEAD, > replaced by a WalUsage that just tracks the activity within the > process, combined with a secondary WalUsage where we aggregate from > activity from the workers. I agree on the goal (I think its very confusing right now), but I don't see a good way forward for (2) due to the InstrStopNode overhead problem. What we could theoretically do is a variant of (3), where we rename the current pgWalUsage to pgWalUsageWithWorkers, and introduce a new pgWalUsage that doesn't factor in the workers. But we'd still have the extra instructions in all the places where we increment the activity. Thanks, Lukas -- Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Tue, Nov 03, 2026 at 04:56:43PM -0800, Lukas Fittl wrote: > The only way to avoid extra work in InstrStopNode is to have a global > that represents what pgWalUsage currently is (leader + worker), but > maybe I'm missing something in your argument? Speaking HEAD-only here, I still think that accumulating the worker numbers in pgWalUsage is an abuse of the facility. I'm finding this point to be what itches me the most regarding this thread. -- Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
On Tue, Nov 3, 2026 at 11:32 PM Michael Paquier wrote: > > On Tue, Nov 03, 2026 at 04:56:43PM -0800, Lukas Fittl wrote: > > The only way to avoid extra work in InstrStopNode is to have a global > > that represents what pgWalUsage currently is (leader + worker), but > > maybe I'm missing something in your argument? > > Speaking HEAD-only here, I still think that accumulating the worker > numbers in pgWalUsage is an abuse of the facility. I'm finding this > point to be what itches me the most regarding this thread. +1 on that, I'd love to find a way to avoid that. I think ultimately our problem is that we need some way to "attach" the worker WAL/buffer activity to the right executor node (i.e. the one that caused a nested statement to be called that had worker activity), and that node then needs to be able to accumulate that activity upwards to parent nodes, potentially other parent statements, and the query-level instrumentation, all without affecting the global top value like it does today. There is some overlap here with the stack-based instrumentation work (which has a more explicit accumulation pass to propagate information upwards on query end, vs relying on the nested nature of InstrStopNode), and with that in place we might be able to devise a design where we just remember the extra instrumentation on the current stack entry, and then can keep it separated, avoiding mixing it up with the leader-only global. If helpful I can prototype that to illustrate it. That said, I'm still leaning towards going with one of the "simpler" approaches I sketched out, FWIW, just because it seems less ambitious in terms of overall code change. Thanks, Lukas -- Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Tue, Nov 03, 2026 at 11:49:03PM -0800, Lukas Fittl wrote: > I think ultimately our problem is that we need some way to "attach" > the worker WAL/buffer activity to the right executor node (i.e. the > one that caused a nested statement to be called that had worker > activity), and that node then needs to be able to accumulate that > activity upwards to parent nodes, potentially other parent statements, > and the query-level instrumentation, all without affecting the global > top value like it does today. Could it help if the instrument structure had a secondary set of fields for the worker data, then, when you want to pass its information across the stack? Or would that impact the performance of InstrStopNode() as well? For example, for pgWalUsage just a pgWalUsageWorkers? (If I'm missing something and I am not in line with your previous arguments, sorry, it's been a long day and it's the end of the so-said day..) -- Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-11-02 18:32:18 +0900, Michael Paquier wrote: > On Mon, Nov 02, 2026 at 08:41:15AM +0000, Bertrand Drouvot wrote: > > On Mon, Nov 02, 2026 at 05:16:29PM +0900, Michael Paquier wrote: > >> If I am reading the patch right, it means that a leader's pgWalUsage > >> includes both its own activity *and* the activity of its workers. It > >> sounds to me like a mistake to do that. Why aren't pgWalUsage and > >> friends handled in such a way that they only include the activity of > >> their own process? > > > > Wouldn't that change the semantics of pgWalUsage for out of core extensions using > > it (if any) the same way as PGSS? We can adjust PGSS, but those extensions would > > start seeing leader only activity once running a version with this change? > > We don't have to change the meaning of pgWalUsage in the stable branches. FWIW, I think it'd be fine to change the behavior in the back branches in this case. As it is today, it is inaccurate, so the numbers such extensions were collecting weren't right already. And depending on what hook the extension is using to collect the information, I think the answer what number we ought to present is not very clear anyway. - Andres
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-11-03 14:58:31 -0800, Lukas Fittl wrote: > The problem isn't just out of core extensions using pgWalUsage, its > that we also look at pgWalUsage for reporting in EXPLAIN and on > statements that ran parallel that were called by a node, as mentioned > in my initial email. > > Here is an example: > > CREATE TABLE t (a int) WITH (autovacuum_enabled = off); > INSERT INTO t SELECT generate_series(1, 1000000); > CHECKPOINT; -- so that setting hint bits (checksums on) emits FPIs > > CREATE FUNCTION f() RETURNS bigint LANGUAGE plpgsql AS > $$ DECLARE n bigint; BEGIN SELECT count(*) INTO n FROM t; RETURN n; END $$; > > SET parallel_setup_cost = 0; > SET parallel_tuple_cost = 0; > SET max_parallel_workers_per_gather = 2; > SET parallel_leader_participation = off; -- all WAL comes from the workers > > EXPLAIN (ANALYZE, WAL, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY > OFF) SELECT f(); > > QUERY PLAN > ---------------------------------------------------------------------------------- > Result (actual rows=1.00 loops=1) > WAL: records=8849 fpi=4426 bytes=36596662 fpi bytes=36114392 > buffers full=3975 > (2 rows) > > Now, taking that example, here are three possible approaches to the > problem overall that I can see, focusing on what to do on master (i.e. > ignoring extension compatibility concerns): I'm not actually sure that its entirely the right thing to include the parallel worker WAL generated in this kind of example. If the parallel query directly triggers WAL it is counted, but if there's e.g. FDWs involved, it won't be. If DML triggers autovacuum doing the cleanup, it won't be, despite directly associated with DML happening inside a function. If checkpointer or bgwriter do a lot of IO triggered by a query, its not counted either. Those examples are all different, but it still feels all not quite right. I feel like mashing all this into one counter really was a bad idea from the get go, so I have a lot of sympathy for Michael's point that that's not a sane way forward. But that doesn't necessarily mean I have a great alternative :( > 1) pgWalUsage keeps today's meaning, pgWalUsageFromWorkers is > additionally accumulated in InstrAccumParallelQuery (the v1 patch) > > - When the function finishes executing, the worker instrumentation > gets fed into the parent process pgWalUsage and pgWalUsageFromWorkers I'm a bit confused about what you mean by that? Why would the end of the function need to do anything? I don't think your patch did anything like that? Did you just mean that it happend within the function, in one of the InstrAccumParallelQuery() calls? > - That pgWalUsage is then seen by the Result node as part of its > InstrStartNode/InstrStopNode, which results in the correct reporting > - Use cases like pg_stat_statements that want to report worker > activity as part of the statement only look at pgWalUsage > - The pg_stat_wal reporting in the leader subtracts > pgWalUsageFromWorkers with WalUsageAccumDiff so it correctly skips the > data from this invocation > 2) pgWalUsage does not include the worker instrumentation, maybe > rename to pgWalUsageOwn (basically your suggestion for master, if I > understood correctly), we also introduce pgWalUsageFromWorkers > > - When the function finishes executing, the worker instrumentation > only gets fed into pgWalUsageFromWorkers > - In order for the Result node to see the activity, it needs to diff > both pgWalUsage and pgWalUsageFromWorkers in InstrStopNode, to > correctly increment its instrumentation data to include workers > - Use cases like pg_stat_statements need to look at both pgWalUsage > and pgWalUsageFromWorkers > - The pg_stat_wal reporting in the leader can simply work with > pgWalUsage like today > I don't think (2) is workable, especially if we want a design that > also works for pgBufferUsage - doing any extra work in InstrStopNode > is too expensive (instruction-wise, and because of the size of the > memory being accessed). Doing it twice for WAL would be not awesome, but doing it twice for pgBufferUsage is quite a bit worse, that's a lot of counters :/ > 3) pgWalUsage keeps today's meaning, we introduce a separate > pgWalUsageOwn that includes only the leader > > - pgWalUsageOwn gets additionally incremented in all places where we > currently increment pgWalUsage I think that's also decidedly not attractive. That accounting often happens with exclusive content locks held. We shouldn't add more work to that... > I don't think (2) is workable, especially if we want a design that > also works for pgBufferUsage - doing any extra work in InstrStopNode > is too expensive (instruction-wise, and because of the size of the > memory being accessed). I unfortunately don't immediately see a way other than 1) for the back branches. With your stack based query executor instrumentation infrastructure the big downside of 2) can afaict be addressed. I think we really ought to make all access by extensions (be it our own or external ones) go through helper functions to get this kind of information. Right now they're way to tied to how we represent this information internally. Greetings, Andres Freund
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
Hi Andres, Thanks for taking a look! On Wed, Nov 4, 2026 at 12:16 PM Andres Freund wrote: > I'm not actually sure that its entirely the right thing to include the > parallel worker WAL generated in this kind of example. If the parallel query > directly triggers WAL it is counted, but if there's e.g. FDWs involved, it > won't be. If DML triggers autovacuum doing the cleanup, it won't be, despite > directly associated with DML happening inside a function. If checkpointer or > bgwriter do a lot of IO triggered by a query, its not counted either. Those > examples are all different, but it still feels all not quite right. Yeah, that's a fair point - in the back of my mind I'm mostly thinking of buffer usage reporting, where its much more likely users will see the difference - WAL from parallel workers is more an edge case. The architectural problem becomes a lot easier to solve if we don't worry about putting WAL and buffer usage on the parent statement EXPLAIN nodes, but e.g. instead displayed nested statements separately with their activity under the main EXPLAIN plan. I'll do some experimenting in that direction to see how much it'd buy us in terms of reducing complexity - there is also Mohamed's patch on that topic of how we display nested statements in EXPLAIN from a while ago [0], but that was a rough draft (I think the actual implementation needed a lot of work) and didn't really address this I think. > > 1) pgWalUsage keeps today's meaning, pgWalUsageFromWorkers is > > additionally accumulated in InstrAccumParallelQuery (the v1 patch) > > > > - When the function finishes executing, the worker instrumentation > > gets fed into the parent process pgWalUsage and pgWalUsageFromWorkers > > I'm a bit confused about what you mean by that? Why would the end of the > function need to do anything? I don't think your patch did anything like that? > Did you just mean that it happend within the function, in one of the > InstrAccumParallelQuery() calls? Yeah, I was referencing the InstrAccumParallelQuery call that occurs inside the function's statement that then causes the process pgWalUsage to include the function's activity. > I unfortunately don't immediately see a way other than 1) for the back > branches. > > With your stack based query executor instrumentation infrastructure the big > downside of 2) can afaict be addressed. Ack, thanks for chiming in - I'll await for Michael to take another look but will otherwise post an updated v2 addressing Bertrand's comments, staying on the (1) approach. > I think we really ought to make all access by extensions (be it our own or > external ones) go through helper functions to get this kind of > information. Right now they're way to tied to how we represent this > information internally. Agreed - I think we've actually made good progress on that in 19 with Instrumentation now having a clear API that is usable outside of executor instrumentation, so there is less need to read pgWalUsage/pgBufferUsage directly. The stack-based instrumentation series [1] actually has two prep patches that drop the remaining direct users of pgBufferUsage to further clean up the API (it keeps a user of pgWalUsage in pruneheap.c, which is a special case), after which I think the main unsolved use case is how we want the instrumentation fed into the cumulative stats system without directly accessing a global variable. Thanks, Lukas [0]: https://www.postgresql.org/message-id/flat/CAGnOmWp96ZHNyQ%2B4YijH9wqc%3DCcGm8cuBq9rRCXsaz0SO86tLg%40mail.gmail.com [1]: https://www.postgresql.org/message-id/flat/CAP53Pkwd6Gd4OL6cgh449wtdznWitz_V%3D-PRoswLHOzsMbcftA%40mail.gmail.com#891ae8e91928207e840ef194bb90b29a -- Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Wed, Nov 04, 2026 at 12:50:33PM -0800, Lukas Fittl wrote: > Ack, thanks for chiming in - I'll await for Michael to take another > look but will otherwise post an updated v2 addressing Bertrand's > comments, staying on the (1) approach. Is that referring to the patch set posted here? I mean here: https://www.postgresql.org/message-id/CAP53Pkwd6Gd4OL6cgh449wtdznWitz_V%3D-PRoswLHOzsMbcftA%40mail.gmail.com >> I think we really ought to make all access by extensions (be it our own or >> external ones) go through helper functions to get this kind of >> information. Right now they're way to tied to how we represent this >> information internally. > > Agreed - I think we've actually made good progress on that in 19 with > Instrumentation now having a clear API that is usable outside of > executor instrumentation, so there is less need to read > pgWalUsage/pgBufferUsage directly. A layer of routines may make the contract behind the numbers one gets easier to understand. That could also be combined with things like bitwise flags to decide which parts you'd like to get computed. Just one idea. > The stack-based instrumentation series [1] actually has two prep > patches that drop the remaining direct users of pgBufferUsage to > further clean up the API (it keeps a user of pgWalUsage in > pruneheap.c, which is a special case), after which I think the main > unsolved use case is how we want the instrumentation fed into the > cumulative stats system without directly accessing a global variable. Do the suggestions on the other thread make what is presented on this thread irrelevant? I don't like much what's been sent now on this thread, but I could see myself like something sent on the other thread if my concerns about the numbers and the way they're aggregated for the leader and workers are lifted. I have not looked at what you have sent on the other thread, just what you have sent on this thread. -- Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
On Wed, Nov 4, 2026 at 2:22 PM Michael Paquier wrote: > > On Wed, Nov 04, 2026 at 12:50:33PM -0800, Lukas Fittl wrote: > > Ack, thanks for chiming in - I'll await for Michael to take another > > look but will otherwise post an updated v2 addressing Bertrand's > > comments, staying on the (1) approach. > > Is that referring to the patch set posted here? I mean here: > https://www.postgresql.org/message-id/CAP53Pkwd6Gd4OL6cgh449wtdznWitz_V%3D-PRoswLHOzsMbcftA%40mail.gmail.com No, sorry if that got confusing - this is referencing the original patch on this thread, which is the "simple" way of solving the immediate problem (pg_stat_wal overcounting) by keeping a separate accumulation of the statistics that were imported from the worker, and then subtracting that when reporting to the cumulative stats system. Basically the original approach on this thread here is ugly, but it works, doesn't have performance impact, and is easy to reason about. I'm advocating for getting this in to both master and the back branches, and then separately work on solving it more elegantly, which in my perspective makes most sense in combination with the stack-based instrumentation thread you linked. > > The stack-based instrumentation series [1] actually has two prep > > patches that drop the remaining direct users of pgBufferUsage to > > further clean up the API (it keeps a user of pgWalUsage in > > pruneheap.c, which is a special case), after which I think the main > > unsolved use case is how we want the instrumentation fed into the > > cumulative stats system without directly accessing a global variable. > > Do the suggestions on the other thread make what is presented on this > thread irrelevant? I don't like much what's been sent now on this > thread, but I could see myself like something sent on the other thread > if my concerns about the numbers and the way they're aggregated for > the leader and workers are lifted. I have not looked at what you have > sent on the other thread, just what you have sent on this thread. As it stands the other thread on stack-based instrumentation does not solve this problem (yet), but it contains the prerequisite infrastructure that's needed, because it avoids the global counters (pgWalUsage, etc) that move forward as activity happens, and instead records into the current stack entry that then accumulates into the parent separately on query end. I'm working on an updated version for that thread that illustrates how that helps us with the problem at hand. FWIW, the prep work I was referring to was specifically in regards to making the API contract clearer, and avoiding people looking at pgBufferUsage/pgWalUsage directly - I think that's a no-brainer that we should get in in any case. Thanks, Lukas -- Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
On Wed, Nov 04, 2026 at 04:10:08PM -0800, Lukas Fittl wrote: > Basically the original approach on this thread here is ugly, but it > works, doesn't have performance impact, and is easy to reason about. > I'm advocating for getting this in to both master and the back > branches, and then separately work on solving it more elegantly, which > in my perspective makes most sense in combination with the stack-based > instrumentation thread you linked. It still feels itchy because that's still abusing of what I think should not be the definition of pgWalUsage, and it's a workaround. I'm wondering if Andres' extra argument about just breaking pgWalUsage to not include worker data would not be the best move, actually, even on stable branches.. That feels risky, still simpler logic links to a simpler definition of these objects, not mixing more concepts into them. > As it stands the other thread on stack-based instrumentation does not > solve this problem (yet), but it contains the prerequisite > infrastructure that's needed, because it avoids the global counters > (pgWalUsage, etc) that move forward as activity happens, and instead > records into the current stack entry that then accumulates into the > parent separately on query end. I'm working on an updated version for > that thread that illustrates how that helps us with the problem at hand. Ah, OK. Good to now, even if that does not address the double counting. -- Michael
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Lukas,
Reading v1, I think the pgstat_backend.c part makes the leader drop
the WAL of its workers from pg_stat_get_backend_wal(). A worker drops
its own backend stats entry when it exits. So on master the leader
entry is the only place that counts that WAL, and it counts it once.
I checked it with your parallel VACUUM case. On master I get
actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes
95926320 | 128524537 | 97581712
With v1 I get
actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes
97900592 | 97581712 | 66638887
So pg_stat_wal is right with v1, but the leader entry lost about
31MB. Is leader only intended here, to match pg_stat_get_backend_io()?
If not, maybe the pgstat_backend.c part can be left out.
Reading v1, I think the pgstat_backend.c part makes the leader drop
the WAL of its workers from pg_stat_get_backend_wal(). A worker drops
its own backend stats entry when it exits. So on master the leader
entry is the only place that counts that WAL, and it counts it once.
I checked it with your parallel VACUUM case. On master I get
actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes
95926320 | 128524537 | 97581712
With v1 I get
actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes
97900592 | 97581712 | 66638887
So pg_stat_wal is right with v1, but the leader entry lost about
31MB. Is leader only intended here, to match pg_stat_get_backend_io()?
If not, maybe the pgstat_backend.c part can be left out.
Thanks,
Shihao
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi Shihao, On Mon, Nov 09, 2026 at 09:51:13PM -0500, shihao zhong wrote: > Hi Lukas, > > Reading v1, I think the pgstat_backend.c part makes the leader drop > the WAL of its workers from pg_stat_get_backend_wal(). A worker drops > its own backend stats entry when it exits. So on master the leader > entry is the only place that counts that WAL, and it counts it once. > > I checked it with your parallel VACUUM case. On master I get > > actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes > 95926320 | 128524537 | 97581712 > > With v1 I get > > actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes > 97900592 | 97581712 | 66638887 > > So pg_stat_wal is right with v1, but the leader entry lost about > 31MB. Is leader only intended here, to match pg_stat_get_backend_io()? Yeah, I think so. The documentation says that pg_stat_get_backend_wal() reports statistics about the backend with the specified process ID, so worker's WAL should not be attributed to the leader. So I think the pgstat_backend.c changes should stay, but the commit message should probably clarify that this part fixes attribution rather than double counting. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Lukas Fittl <lukas@fittl.com>
Дата:
Hi, On Mon, Nov 9, 2026 at 8:14 PM Bertrand Drouvot wrote: > On Mon, Nov 09, 2026 at 09:51:13PM -0500, shihao zhong wrote: > > Reading v1, I think the pgstat_backend.c part makes the leader drop > > the WAL of its workers from pg_stat_get_backend_wal(). A worker drops > > its own backend stats entry when it exits. So on master the leader > > entry is the only place that counts that WAL, and it counts it once. > > > > I checked it with your parallel VACUUM case. On master I get > > > > actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes > > 95926320 | 128524537 | 97581712 > > > > With v1 I get > > > > actual_wal_bytes | pg_stat_wal_bytes | leader_backend_wal_bytes > > 97900592 | 97581712 | 66638887 > > > > So pg_stat_wal is right with v1, but the leader entry lost about > > 31MB. Is leader only intended here, to match pg_stat_get_backend_io()? > > Yeah, I think so. The documentation says that pg_stat_get_backend_wal() reports > statistics about the backend with the specified process ID, so worker's WAL should > not be attributed to the leader. > > So I think the pgstat_backend.c changes should stay, but the commit message > should probably clarify that this part fixes attribution rather than double > counting. Yeah - this is a bit of an odd case, since in practice you won't be able to call pg_stat_get_backend_wal() on a worker, since the workers are too short-lived. I'm leaning towards Bertrand's point to leave this as is, so we match what the documentation already says, and clarify in the commit message. In the future we could invent a mechanism to get aggregated parallel worker activity for a given leader PID in a separate statistics kind. An updated patch I'm drafting for stack-based instrumentation keeps the worker imported statistics cleanly separated (in the per-query Instrumentation struct), so it would be an easy extension on top of that. Thanks, Lukas -- Lukas Fittl
Re: Fix cumulative WAL statistics double-counting from parallel workers
От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi, On Tue, Nov 10, 2026 at 02:47:56PM -0800, Lukas Fittl wrote: > I'm leaning towards Bertrand's point to leave this as is, so we match > what the documentation already says, and clarify in the commit > message. Thanks for confirming, and it's also consistent with the per bakend IO and Lock stats. > In the future we could invent a mechanism to get aggregated parallel > worker activity for a given leader PID in a separate statistics kind. Yeah, that would be a good addition. I haven't thought about it in detail, so I'm not sure that a separate statistics kind would be the way to go, though. Regards, -- Bertrand Drouvot PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com