Add wait events for server logging destination writes
Add wait events for server logging destination writes
Hi hackers,
The write(2) calls that flush server log output aren't covered by wait
events. When a backend logs something, the writes go out in:
- write_pipe_chunks(): write(2) to the syslogger pipe
- write_console(): write(2) to stderr (WriteConsoleW() on Windows)
If one of those blocks -- syslogger pipe full, slow console, slow log
device -- pg_stat_activity just shows wait_event = NULL until it
returns. Since NULL usually reads as "on CPU", a backend stuck writing
logs looks like it's doing work, so logging-related stalls are easy to
miss.
Attached is a short series that adds two WaitEventIO events and reports
them around those writes:
IO / SysloggerWrite - write(2) to the syslogger pipe
IO / StderrWrite - write(2) to stderr, and WriteConsoleW()
0001 adds the events and covers the write(2) paths. 0002 does the
Windows WriteConsoleW() path, split out since it's platform-specific.
It only wraps the leaf write call and uses the existing
pgstat_report_wait_start()/end() helpers, so it stays allocation-free
and safe to call from inside the error-reporting path.
I did a quick before/after to make sure the events show up: 8 backends
each emitting large RAISE LOG lines, sampling wait_event from
pg_stat_activity every 50 ms for 20 s.
- logging_collector = on (syslogger pipe):
master: NULL 100.0% (2184/2184)
patched: IO/SysloggerWrite 99.1% (2204/2224), NULL 0.9%
- logging_collector = off (stderr):
master: NULL 100.0% (2144/2144)
patched: IO/StderrWrite 90.7% (1952/2152), NULL 9.3%
On master that wait time is just invisible; with the patch it lands on
the new events. I can send the scripts and raw samples if anyone wants
to reproduce it.
Applies on current master. A couple of things I'm unsure about and
would appreciate input on: whether the event names fit the surrounding
conventions, and whether splitting the Windows path into its own patch
is the right call.
Thanks,
Seongjun Shin
Re: Add wait events for server logging destination writes
Hi, cfbot caught a build failure on v1, in the SanityCheck task on Linux and Windows: elog.c uses pgstat_report_wait_start()/end() and the WAIT_EVENT_* constants but didn't include utils/wait_event.h. It only built here because of an accidental transitive include on my machine; on the CI images the declarations weren't visible. v2 fixes that by adding the missing #include "utils/wait_event.h" to elog.c, folded into 0001 so that patch builds on its own. No other changes; the wait events and the reported write paths are the same as in v1. v2-0001 adds the two events and covers the write(2) paths. v2-0002 covers the Windows WriteConsoleW() path, split out as before. Applies cleanly on current master; full build passes locally. Thanks, Seongjun Shin 2026년 5월 31일 (일) 오후 5:50, 신성준 님이 작성: > > Hi hackers, > > The write(2) calls that flush server log output aren't covered by wait > events. When a backend logs something, the writes go out in: > > - write_pipe_chunks(): write(2) to the syslogger pipe > - write_console(): write(2) to stderr (WriteConsoleW() on Windows) > > If one of those blocks -- syslogger pipe full, slow console, slow log > device -- pg_stat_activity just shows wait_event = NULL until it > returns. Since NULL usually reads as "on CPU", a backend stuck writing > logs looks like it's doing work, so logging-related stalls are easy to > miss. > > Attached is a short series that adds two WaitEventIO events and reports > them around those writes: > > IO / SysloggerWrite - write(2) to the syslogger pipe > IO / StderrWrite - write(2) to stderr, and WriteConsoleW() > > 0001 adds the events and covers the write(2) paths. 0002 does the > Windows WriteConsoleW() path, split out since it's platform-specific. > > It only wraps the leaf write call and uses the existing > pgstat_report_wait_start()/end() helpers, so it stays allocation-free > and safe to call from inside the error-reporting path. > > I did a quick before/after to make sure the events show up: 8 backends > each emitting large RAISE LOG lines, sampling wait_event from > pg_stat_activity every 50 ms for 20 s. > > - logging_collector = on (syslogger pipe): > master: NULL 100.0% (2184/2184) > patched: IO/SysloggerWrite 99.1% (2204/2224), NULL 0.9% > > - logging_collector = off (stderr): > master: NULL 100.0% (2144/2144) > patched: IO/StderrWrite 90.7% (1952/2152), NULL 9.3% > > On master that wait time is just invisible; with the patch it lands on > the new events. I can send the scripts and raw samples if anyone wants > to reproduce it. > > Applies on current master. A couple of things I'm unsure about and > would appreciate input on: whether the event names fit the surrounding > conventions, and whether splitting the Windows path into its own patch > is the right call. > > Thanks, > Seongjun Shin
Re: Add wait events for server logging destination writes
От:
Kirk Wolak <wolakk@gmail.com>
Дата:
On Sun, May 31, 2026 at 4:50 AM 신성준 <shinsj4653@gmail.com> wrote:
Hi hackers,
The write(2) calls that flush server log output aren't covered by wait
events. When a backend logs something, the writes go out in:
- write_pipe_chunks(): write(2) to the syslogger pipe
- write_console(): write(2) to stderr (WriteConsoleW() on Windows)
If one of those blocks -- syslogger pipe full, slow console, slow log
device -- pg_stat_activity just shows wait_event = NULL until it
returns. Since NULL usually reads as "on CPU", a backend stuck writing
logs looks like it's doing work, so logging-related stalls are easy to
miss.
Attached is a short series that adds two WaitEventIO events and reports
them around those writes:
IO / SysloggerWrite - write(2) to the syslogger pipe
IO / StderrWrite - write(2) to stderr, and WriteConsoleW()
0001 adds the events and covers the write(2) paths. 0002 does the
Windows WriteConsoleW() path, split out since it's platform-specific.
It only wraps the leaf write call and uses the existing
pgstat_report_wait_start()/end() helpers, so it stays allocation-free
and safe to call from inside the error-reporting path.
I did a quick before/after to make sure the events show up: 8 backends
each emitting large RAISE LOG lines, sampling wait_event from
pg_stat_activity every 50 ms for 20 s.
- logging_collector = on (syslogger pipe):
master: NULL 100.0% (2184/2184)
patched: IO/SysloggerWrite 99.1% (2204/2224), NULL 0.9%
- logging_collector = off (stderr):
master: NULL 100.0% (2144/2144)
patched: IO/StderrWrite 90.7% (1952/2152), NULL 9.3%
On master that wait time is just invisible; with the patch it lands on
the new events. I can send the scripts and raw samples if anyone wants
to reproduce it.
+1
Nice. We have too many waits that are registered as CPU.
Re: Add wait events for server logging destination writes
On Sun, May 31, 2026 at 07:42:41PM +0900, 신성준 wrote: > cfbot caught a build failure on v1, in the SanityCheck task on Linux > and Windows: elog.c uses pgstat_report_wait_start()/end() and the > WAIT_EVENT_* constants but didn't include utils/wait_event.h. It only > built here because of an accidental transitive include on my machine; > on the CI images the declarations weren't visible. > > v2 fixes that by adding the missing #include "utils/wait_event.h" to > elog.c, folded into 0001 so that patch builds on its own. No other > changes; the wait events and the reported write paths are the same as > in v1. > > v2-0001 adds the two events and covers the write(2) paths. > v2-0002 covers the Windows WriteConsoleW() path, split out as before. > > Applies cleanly on current master; full build passes locally. Hmm. Usually we split the event numbers so as there is one for each code path, but here we are just dealing with the same routine that sends chunks. Using the same numbers seem fine by me. If others have any thoughts or comments, feel free. -- Michael
Re: Add wait events for server logging destination writes
От:
Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Дата:
Hello. At Sun, 31 May 2026 17:50:08 +0900, 신성준 wrote in > Attached is a short series that adds two WaitEventIO events and reports > them around those writes: > > IO / SysloggerWrite - write(2) to the syslogger pipe > IO / StderrWrite - write(2) to stderr, and WriteConsoleW() > > 0001 adds the events and covers the write(2) paths. 0002 does the > Windows WriteConsoleW() path, split out since it's platform-specific. Should we also consider instrumenting ReportEventW()/ReportEventA()? They seem to be another Windows-specific logging output path. Also, if the intention is to cover all places where logging output can block, I wonder whether the syslog() calls should be covered as well. If they are intentionally excluded, perhaps a short comment explaining the rationale would be useful. Regards. -- Kyotaro Horiguchi NTT Open Source Software Center
Re: Add wait events for server logging destination writes
Hi, cfbot flagged v3 as needing a rebase -- it stopped applying after the recent changes to elog.c (the switch to a const WCHAR pointer in write_eventlog(), pgindent, etc.) and the new COPY pipe wait events in wait_event_names.txt. v4 is the same change rebased over current master, no functional difference from v3. The only real conflict was in write_eventlog(), where the EventlogWrite wrapping now sits on top of the const utf16_const pointer; everything else merged cleanly. Still applies as two patches: v4-0001 - portable part (SysloggerWrite, StderrWrite, SyslogWrite) v4-0002 - Windows part (WriteConsoleW plus EventlogWrite) Builds clean on current master with both Autoconf and Meson, no new warnings. Thanks, Seongjun Shin 2026년 6월 7일 (일) 오전 1:25, 신성준 님이 작성: > > Hi, > > Thanks Kirk, glad it's useful. > > Kyotaro Horiguchi wrote: > > Should we also consider instrumenting ReportEventW()/ReportEventA()? > > They seem to be another Windows-specific logging output path. > > > > Also, if the intention is to cover all places where logging output > > can block, I wonder whether the syslog() calls should be covered as > > well. > > Good points -- both are blocking output paths and there's no real > reason to leave them out, so v3 instruments them rather than excluding > them with a comment. The intent is exactly to cover the places where > logging output can block, so this makes the series consistent. > > v3 adds two more WaitEventIO events: > > IO / SyslogWrite - syslog(3) in write_syslog() > IO / EventlogWrite - ReportEventW()/ReportEventA() in write_eventlog() > > Same approach as before: the wait is reported only around the leaf > call, using the existing pgstat_report_wait_start()/end() helpers, so > it stays allocation-free and safe on the error-reporting path, and the > series still touches just elog.c and wait_event_names.txt. > > This also matches Michael's point on v2 -- each event covers a routine > rather than a single call site, so SyslogWrite wraps the syslog(3) > calls in write_syslog() and EventlogWrite wraps both ReportEvent > variants in write_eventlog(), the same way SysloggerWrite already > covers the two writes in write_pipe_chunks(). > > As before, 0001 is the portable part and 0002 is the Windows part > (WriteConsoleW plus the new EventlogWrite). > > One caveat: EventlogWrite is Windows-only, so I couldn't get a runtime > before/after for it here -- I've only confirmed it builds (cfbot's > Windows task should cover that). The other events still show up in the > sampling I posted earlier. If someone on Windows can exercise the > event-log path I'd appreciate a confirmation. > > Applies cleanly on current master; full build passes locally on both > Autoconf and Meson, with no new warnings. > > Thanks, > Seongjun Shin > > 2026년 6월 1일 (월) 오후 2:49, Kyotaro Horiguchi 님이 작성: > > > > Hello. > > > > At Sun, 31 May 2026 17:50:08 +0900, 신성준 wrote in > > > Attached is a short series that adds two WaitEventIO events and reports > > > them around those writes: > > > > > > IO / SysloggerWrite - write(2) to the syslogger pipe > > > IO / StderrWrite - write(2) to stderr, and WriteConsoleW() > > > > > > 0001 adds the events and covers the write(2) paths. 0002 does the > > > Windows WriteConsoleW() path, split out since it's platform-specific. > > > > Should we also consider instrumenting ReportEventW()/ReportEventA()? > > They seem to be another Windows-specific logging output path. > > > > Also, if the intention is to cover all places where logging output can > > block, I wonder whether the syslog() calls should be covered as > > well. If they are intentionally excluded, perhaps a short comment > > explaining the rationale would be useful. > > > > Regards. > > > > -- > > Kyotaro Horiguchi > > NTT Open Source Software Center
Re: Add wait events for server logging destination writes
От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
> On 6 Jun 2026, at 21:52, 신성준 wrote: > Hi Seongjun, Naming is a hard thing. Anyone who can tell syslog from syslogger without checking man is probably a computer themselves. +1: a blocking logging write shows as wait_event IS NULL today, which most tools read as on-CPU. This is very real for us. In our managed Postgres the root filesystem that holds the logs sits on slow network-backed HDD, so when the syslogger pipe backs up the backends stall on the log write and the whole node looks like a CPU overload. This patch would have made that directly visible. Worth a line in the commit message: the call that actually blocks on a slow log device is write_syslogger_file() in the syslogger, which has no shared memory and isn't in pg_stat_activity. It surfaces on backends as the pipe fills and they block on the pipe write (SysloggerWrite), so the backend side is the right, visible layer. One thing worth checking: wait events are single-slot by design (no nesting - discussed back in 2016 [0]), and pgstat_report_wait_end() just writes 0. So if any ereport() path runs while a wait event is already set, instrumenting the logging write here clobbers that outer event. Probably rare, but I'm not sure it never happens. EventlogWrite necessarily shows up in the event list on all platforms (the generator has no per-platform gating), but the description already says "Windows event log", so that seems fine... Thanks for working on this! Best regards, Andrey Borodin. [0] https://www.postgresql.org/message-id/CANP8%2BjKsS6SDo011AUWrLdBcBMv0KJha69t7eFGqEtqx9FVfag%40mail.gmail.com
Re: Add wait events for server logging destination writes
От:
신성준 <shinsj4653@gmail.com>
Дата:
Hi Andrey, > +1: a blocking logging write shows as wait_event IS NULL today, which most > tools read as on-CPU. This is very real for us. In our managed Postgres the > root filesystem that holds the logs sits on slow network-backed HDD, so when > the syslogger pipe backs up the backends stall on the log write and the whole > node looks like a CPU overload. This patch would have made that directly > visible. Thanks for the review, and for the production example. That node-looks-like-a- CPU-overload case is exactly what this is meant to make visible. > Worth a line in the commit message: the call that actually blocks on a slow > log device is write_syslogger_file() in the syslogger, which has no shared > memory and isn't in pg_stat_activity. It surfaces on backends as the pipe > fills and they block on the pipe write (SysloggerWrite), so the backend side > is the right, visible layer. Agreed. In v5 I'll add that to the commit message, and a short code comment to the same effect: the syslogger does the file write in write_syslogger_file() and isn't in pg_stat_activity, so the backend-side SysloggerWrite is where the stall becomes visible. > Naming is a hard thing. Anyone who can tell syslog from syslogger without > checking man is probably a computer themselves. Fair. I kept each name aligned with the routine it wraps, and the descriptions spell out the difference, so I'd lean toward leaving them unless others object. > One thing worth checking: wait events are single-slot by design (no nesting - > discussed back in 2016 [0]), and pgstat_report_wait_end() just writes 0. So > if any ereport() path runs while a wait event is already set, instrumenting > the logging write here clobbers that outer event. Probably rare, but I'm not > sure it never happens. Right about the mechanism. pgstat_report_wait_end() unconditionally writes 0, so a log message emitted while an outer wait event is set would briefly mask that event until the outer code reports its own end. Two things, though. First, this is a pre-existing property of the subsystem, not something the patch introduces: every pgstat_report_wait_start()/end() pair behaves this way, and as the 2016 thread you linked concluded, the single unsynchronized write is what keeps the mechanism cheap enough to stay on by default, so nesting was deliberately left out. The patch follows that convention rather than diverging from it. Second, the wrapped regions are tight and log output is normally emitted outside them, so the overlap window should be rare in practice, though I agree it isn't provably never. So I'd prefer not to add save/restore here, since that would diverge from what the rest of the tree relies on. I'll add a brief comment at these sites noting the single-slot behavior. If reviewers would rather have a guard, a minimal option that stays within the single-write model is to report the logging event only when the slot is currently 0, which preserves the outer event at the cost of not showing the logging write while nested. Happy to go that way if that's the consensus. > EventlogWrite necessarily shows up in the event list on all platforms (the > generator has no per-platform gating), but the description already says > "Windows event log", so that seems fine... Agreed, I'll leave it as-is. I'll hold v5 until Nikolay's Linux and Windows testing comments land too, so I can fold everything into one revision. Thanks again, Seongjun 2026년 6월 15일 (월) 오전 3:49, Andrey Borodin 님이 작성: > > > > > On 6 Jun 2026, at 21:52, 신성준 wrote: > > > > Hi Seongjun, > > Naming is a hard thing. Anyone who can tell syslog from syslogger > without checking man is probably a computer themselves. > > +1: a blocking logging write shows as wait_event IS NULL today, which > most tools read as on-CPU. This is very real for us. In our managed > Postgres the root filesystem that holds the logs sits on slow > network-backed HDD, so when the syslogger pipe backs up the backends > stall on the log write and the whole node looks like a CPU overload. > This patch would have made that directly visible. > > Worth a line in the commit message: the call that actually blocks on a > slow log device is write_syslogger_file() in the syslogger, which has no > shared memory and isn't in pg_stat_activity. It surfaces on backends as > the pipe fills and they block on the pipe write (SysloggerWrite), so > the backend side is the right, visible layer. > > One thing worth checking: wait events are single-slot by design (no > nesting - discussed back in 2016 [0]), and pgstat_report_wait_end() > just writes 0. So if any ereport() path runs while a wait event is > already set, instrumenting the logging write here clobbers that outer > event. Probably rare, but I'm not sure it never happens. > > EventlogWrite necessarily shows up in the event list on all platforms > (the generator has no per-platform gating), but the description already > says "Windows event log", so that seems fine... > > Thanks for working on this! > > > Best regards, Andrey Borodin. > > [0] https://www.postgresql.org/message-id/CANP8%2BjKsS6SDo011AUWrLdBcBMv0KJha69t7eFGqEtqx9FVfag%40mail.gmail.com > >
Re: Add wait events for server logging destination writes
Hi Henson,
Thanks for the review, and for tracing through
pgstat_report_wait_start()/end() first -- once the helpers are just a
single store, placement is the only thing left to check, and thanks for
going through all four events against their descriptions.
> the comment you plan to add at the wrapped sites in v5 looks right
> [...] it belongs in a separate change rather than this patch.
Agreed. v5 adds that comment and leaves any general depth-counter
handling out.
v5 folds in the review:
- a short comment at each wrapped site noting the single-slot
behavior;
- Andrey's commit-message point that the real blocking call is
write_syslogger_file() in the syslogger (no PGPROC, not in
pg_stat_activity), so the backend-side SysloggerWrite is where the
stall shows up -- now in the 0001 commit message and a comment on
write_pipe_chunks().
No functional change from v4.
I'd said I'd hold v5 for platform testing, but since the review has
landed I'd rather post it than sit on the thread. Testing is still
welcome, especially the Windows EventlogWrite path -- cfbot confirms it
builds, but I can't exercise the runtime event-log write here. I'll fold
anything that turns up into a follow-up.
v5-0001 - portable part (SysloggerWrite, StderrWrite, SyslogWrite)
v5-0002 - Windows part (WriteConsoleW plus EventlogWrite)
Applies on current master; builds clean under Autoconf and Meson.
Thanks again,
Seongjun Shin
Re: Add wait events for server logging destination writes
От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
On Tue, Jun 30, 2026 at 10:02 AM 신성준 <shinsj4653@gmail.com> wrote:
Hi Henson,
Thanks for the review, and for tracing through
pgstat_report_wait_start()/end() first -- once the helpers are just a
single store, placement is the only thing left to check, and thanks for
going through all four events against their descriptions.
> the comment you plan to add at the wrapped sites in v5 looks right
> [...] it belongs in a separate change rather than this patch.
Agreed. v5 adds that comment and leaves any general depth-counter
handling out.
v5 folds in the review:
- a short comment at each wrapped site noting the single-slot
behavior;
- Andrey's commit-message point that the real blocking call is
write_syslogger_file() in the syslogger (no PGPROC, not in
pg_stat_activity), so the backend-side SysloggerWrite is where the
stall shows up -- now in the 0001 commit message and a comment on
write_pipe_chunks().
No functional change from v4.
I'd said I'd hold v5 for platform testing, but since the review has
landed I'd rather post it than sit on the thread. Testing is still
welcome, especially the Windows EventlogWrite path -- cfbot confirms it
builds, but I can't exercise the runtime event-log write here. I'll fold
anything that turns up into a follow-up.
v5-0001 - portable part (SysloggerWrite, StderrWrite, SyslogWrite)
v5-0002 - Windows part (WriteConsoleW plus EventlogWrite)
Applies on current master; builds clean under Autoconf and Meson.
Thanks again,
Seongjun Shin
Hi Seongjun,
(I reviewed and tested v4 back in June but never sent the results;
now doing it for v5.)
I ran runtime tests of this patch set on Linux, macOS, and Windows;
results below. tl;dr: both v5 patches apply cleanly (git am) to
current master (11ed011ae22) and build clean, and all four events
show up in pg_stat_activity under load -- including EventlogWrite on
Windows, which I believe was the one path previously only
build-verified. +1 from me.
** Methodology **
8 backends each run a plpgsql loop of 50k RAISE LOG calls with an
8 kB payload, while a separate connection samples pg_stat_activity
every ~2 ms and tallies wait_event. The driver scripts and the
Windows CI job are public:
https://github.com/NikolayS/postgres/tree/ci/windows-waitevents
workflow: .github/workflows/windows-waitevents.yml
** Results **
Linux (tested June 15 with v4; gcc 13, meson debug; I did not rerun
since the v4->v5 code delta is comment-only):
logging_collector = on -> IO/SysloggerWrite 3652 (46.3% of all
samples, null wait_event included)
logging_collector = off -> IO/StderrWrite 1376 (17.6%)
macOS (v5 on master@11ed011ae22; clang 17, meson debug):
logging_collector = on -> IO/SysloggerWrite 47362 samples
(the only wait event observed)
logging_collector = off -> IO/StderrWrite 13710 samples
Windows (v5 on master@11ed011ae22; MSVC/meson, windows-latest,
log_destination = 'stderr,eventlog'):
IO/EventlogWrite 20091 samples
IO/StderrWrite 642 samples
Run: https://github.com/NikolayS/postgres/actions/runs/29425495163
(the job fails hard if EventlogWrite is never sampled; it passed)
Counts are pg_stat_activity rows summed over sampler ticks and
backends, and run lengths differed, so they are not comparable
across platforms.
One caveat on Windows coverage: GitHub Actions redirects stderr, so
the WriteConsoleW branch of write_console() is not truly exercised
there -- the samples above go through the write(fileno(stderr))
branch plus write_eventlog(). I don't see it as blocking -- the
WriteConsoleW wrapping is mechanically identical to its sibling.
The NULL share varies with how fast the log device is: these are
debug builds on fast storage, so backends spend most of their time
formatting on-CPU. On a saturated pipe or a slow log device --
exactly Andrey's network-HDD case -- the attributable share grows,
which is precisely what the patch makes visible.
** Review notes on v5 **
I checked the v4->v5 delta -- comments and commit-message text only
(single-slot masking notes at each wrapped site, and the explanation
that the on-disk write happens in write_syslogger_file() in the
syslogger, which has no PGPROC, so the backend-side SysloggerWrite on
the pipe write is where a stall becomes visible). That addresses the
points from Andrey's and Henson's reviews, thank you.
One optional thought on write_syslog(): openlog() is called with
LOG_NDELAY, so the connection to the syslog socket is opened right
there on the first call in each process, and in principle that can
block too (e.g. glibc's stream-socket fallback with a busy syslog
daemon). That call could also be wrapped with SyslogWrite. It is
once per process, so take it or leave it -- not blocking.
Nik
Re: Add wait events for server logging destination writes
> Hi Seongjun, > > (I reviewed and tested v4 back in June but never sent the results; > now doing it for v5.) > > I ran runtime tests of this patch set on Linux, macOS, and Windows; > results below. tl;dr: both v5 patches apply cleanly (git am) to > current master (11ed011ae22) and build clean, and all four events > show up in pg_stat_activity under load -- including EventlogWrite on > Windows, which I believe was the one path previously only > build-verified. +1 from me. > > ** Methodology ** > > 8 backends each run a plpgsql loop of 50k RAISE LOG calls with an > 8 kB payload, while a separate connection samples pg_stat_activity > every ~2 ms and tallies wait_event. The driver scripts and the > Windows CI job are public: > > https://github.com/NikolayS/postgres/tree/ci/windows-waitevents > workflow: .github/workflows/windows-waitevents.yml > > ** Results ** > > Linux (tested June 15 with v4; gcc 13, meson debug; I did not rerun > since the v4->v5 code delta is comment-only): > > logging_collector = on -> IO/SysloggerWrite 3652 (46.3% of all > samples, null wait_event included) > logging_collector = off -> IO/StderrWrite 1376 (17.6%) > > macOS (v5 on master@11ed011ae22; clang 17, meson debug): > > logging_collector = on -> IO/SysloggerWrite 47362 samples > (the only wait event observed) > logging_collector = off -> IO/StderrWrite 13710 samples > > Windows (v5 on master@11ed011ae22; MSVC/meson, windows-latest, > log_destination = 'stderr,eventlog'): > > IO/EventlogWrite 20091 samples > IO/StderrWrite 642 samples > > Run: https://github.com/NikolayS/postgres/actions/runs/29425495163 > (the job fails hard if EventlogWrite is never sampled; it passed) > > Counts are pg_stat_activity rows summed over sampler ticks and > backends, and run lengths differed, so they are not comparable > across platforms. > > One caveat on Windows coverage: GitHub Actions redirects stderr, so > the WriteConsoleW branch of write_console() is not truly exercised > there -- the samples above go through the write(fileno(stderr)) > branch plus write_eventlog(). I don't see it as blocking -- the > WriteConsoleW wrapping is mechanically identical to its sibling. > > The NULL share varies with how fast the log device is: these are > debug builds on fast storage, so backends spend most of their time > formatting on-CPU. On a saturated pipe or a slow log device -- > exactly Andrey's network-HDD case -- the attributable share grows, > which is precisely what the patch makes visible. > > ** Review notes on v5 ** > > I checked the v4->v5 delta -- comments and commit-message text only > (single-slot masking notes at each wrapped site, and the explanation > that the on-disk write happens in write_syslogger_file() in the > syslogger, which has no PGPROC, so the backend-side SysloggerWrite on > the pipe write is where a stall becomes visible). That addresses the > points from Andrey's and Henson's reviews, thank you. > > One optional thought on write_syslog(): openlog() is called with > LOG_NDELAY, so the connection to the syslog socket is opened right > there on the first call in each process, and in principle that can > block too (e.g. glibc's stream-socket fallback with a busy syslog > daemon). That call could also be wrapped with SyslogWrite. It is > once per process, so take it or leave it -- not blocking. > > Nik > Hi Nik, Thanks for running this on all three platforms. EventlogWrite is the one I'm happiest to see. It's Windows-only (ReportEventW/A), so until now I could only confirm it compiles. Seeing it in pg_stat_activity -- 20091 samples, with the job set to fail if it's never sampled -- is the runtime check the thread was missing, and it closes the last open item. Agreed on the WriteConsoleW caveat. I've written the coverage into the commit messages rather than leave it implicit: SysloggerWrite, StderrWrite and SyslogWrite sampled at runtime on Linux and macOS, and EventlogWrite confirmed on Windows via your CI run; WriteConsoleW is covered by build and review only, since it needs a real console. Your results are credited there. (And +1 on the NULL share -- it's small on fast debug builds and grows once the log device is the bottleneck, which is the case the patch is for.) Good catch on openlog(). With LOG_NDELAY the socket is connected on the first log in each process, so it can block the same way the syslog() calls can; wrapping those but not this felt inconsistent. v6 wraps it, reusing SyslogWrite since it's the same write_syslog() routine. That openlog() wrap is the only functional change from v5; otherwise v6 is a rebase plus the commit-message note. I checked it by: - git am of both patches onto current master (5174d157a03), clean; - full Meson build (cassert, debug) -- no warnings; - regression and isolation suites green (245 and 130 tests). v6-0001 - portable part (SysloggerWrite, StderrWrite, SyslogWrite, now including the openlog() call) v6-0002 - Windows part (WriteConsoleW plus EventlogWrite) Henson, the only change since your v5 review is the openlog() wrap above. Final comments from anyone are welcome. Thanks again for the testing and the review. Seongjun
Re: Add wait events for server logging destination writes
On Mon, Aug 10, 2026 at 6:48 PM Jakub Wartak
wrote:
> a. I have no idea why this is split into two patches, it could be just
> one to make things easier to process?
Hello,
Thanks for the review jakub and jian.
The split is by platform, not by feature: 0002 is entirely inside
#ifdef WIN32, and most reviewers cannot run it. Keeping it separate
lets a reviewer state exactly what they covered -- Jihyun did that in
the parallel subthread, testing the Unix paths in 0001 and leaving the
Windows paths to Nikolay's CI run.
That said, this is not something I feel strongly about. If a committer
would rather have one patch, I am happy to squash them.
> b. if we have nested use, let's say:
[...]
> * but if something else is stuck in the
> some_important_stuff_that_may_also_hang() that gets lost because
> wait_event is going to be zero rather than WAIT_EVENT_BLAH and how do
> we find out?
You are right that the pattern is real, and I do not think Jihyun's
scan settles it -- as that review says itself, it is lexical and
intra-procedural, so it only sees an ereport() written directly inside
the region. Your example has the ereport() in a callee, which is
exactly what that scan cannot see.
So I extended it to follow calls made inside a region, looking for an
ereport()/elog() at a level that returns (DEBUGn, INFO, NOTICE, LOG,
WARNING; ERROR and above unwind, so they cannot mask anything).
The intra-procedural part reproduces: over src/backend, src/common and
src/port I get the same single hit Jihyun reported,
AddToDataDirLockFile(), whose callers are all in the postmaster. The
two call sites in read_relmap_file() that report at a variable elevel
resolve to ERROR or FATAL at every caller, so they are not masking
candidates either.
Following callees one level down flags five regions. Going through
them:
- FileWriteback() -> pg_flush_data(). Real: pg_flush_data() can
ereport(WARNING, "could not flush dirty data") when
sync_file_range() fails with ENOSYS, and WARNING returns.
- ReorderBufferSerializeChange() and SnapBuildSerialize() (three
regions between them) -> CloseTransientFile(), which has an
elog(WARNING, "fd passed to CloseTransientFile was not obtained
from OpenTransientFile"). Reachable only on the write()/fsync()
failure branch, which ereports at ERROR immediately afterwards, so
the region is unwound rather than continued.
- RestoreArchivedFile() -> proc_exit(), which does not return.
Deeper than that, the only additional paths are the Windows
pg_pread()/pg_pwrite() wrappers reaching _dosmaperr(), which reports at
DEBUG5/LOG when the OS returns an error code that is not in its
mapping table.
So the conclusion is not "this cannot happen". It is that in every
case above, nothing blocking follows the log write inside the region --
our regions wrap a single call and then end. Masking is bounded to the
tail of the region, and the case you describe, where a stall after the
log write gets misattributed, needs a region that keeps working
afterwards. I could not find one.
But that is a property of how the regions happen to be written, not
something the mechanism enforces, and your suggestion would make it
enforced. I think it is worth doing. My hesitation about putting it
in this patch set is scope: pgstat_report_wait_end() is an inline
helper used across the whole tree, and saving a previous value needs
somewhere to put it. Henson made the same point reviewing v5, that a
general fix belongs in its own patch, so I would rather not fold it in
here. If there is interest I will write it up separately; I would
rather it were judged on its own merits than as a rider on this one.
The scan is an approximation: it resolves calls by name, so it misses
function pointers, and it does not reason about which branches are
reachable. I am happy to post the script if anyone wants to check the
numbers.
> I've seen at least one case of bank being taken down due to similiar
> issues (rsyslogd stuck due to stuck sync TCP remote connection,
> backpropagating to backends), AFAIR wait_events were NULL (so
> useless), but strack-trace collection showed processing stuck on
> syslog().
That is the case this patch exists for, and it is a better motivation
than what the commit message had. I have added it to 0001 in general
terms -- a remote syslog destination that stops accepting data, the
stall propagating back into the backends, wait_event NULL throughout,
the cause found only from stack traces -- without naming the site or
the software. Please tell me if you would rather I dropped it or
worded it differently, and likewise for the Tested-by; both are easy to
change.
> What about extensions using ereport() ? No idea..
An extension calling ereport() inside a wait event region is in the
same position as core code doing it, so this patch does not change
anything for them either way. It is another argument for fixing this
in the mechanism rather than at each call site.
On Tue, Jul 28, 2026 at 12:47 PM jihyun bahn
wrote:
> Getting there took one step that may be worth reflecting in the commit
> message: with fork()-based backends, openlog_done and the syslog fd
> are inherited from the postmaster [...]
Thank you for testing the syslog paths -- those were the ones still
resting on code reading, and the blackhole /dev/log setup is a neat way
to pin them down.
You are right about the commit message and about the description
string. Both are in v7:
- the openlog() paragraph now says the connection is normally
inherited from the postmaster, and that a backend reaches openlog()
only after syslog_ident or syslog_facility changes and the reload
is applied, via assign_syslog_facility(). The code comment says
the same;
- SYSLOG_WRITE is now "Waiting for a write to the system logger
(syslog), including connection setup."
I have also added a Tested-by for you on 0001, and left 0002 with
Nikolay's only, since you were explicit about not having tested the
Windows paths. Let me know if you would rather not be credited.
On the CommitFest status: you marked the entry Ready for Committer
before Jakub's mail arrived, and the move to PG20-2 reset it to Needs
review. That suits me while the point above is open -- please mark it
again once you think it is settled.
v7 is attached. Apart from the description string it is comments and
commit messages; there is no functional change from v6.
v7-0001 - portable part (SysloggerWrite, StderrWrite, SyslogWrite)
v7-0002 - Windows part (WriteConsoleW plus EventlogWrite)
I checked it by:
- git am of both patches onto current master (6a857156827), clean;
- full Meson build (cassert, debug) -- no warnings;
- 0001 building on its own;
- regression and isolation suites green (243 and 132 tests).
Regards,
Seongjun Shin
Re: Add wait events for server logging destination writes
Hi Nik,
Thanks for building the extension case. That is the test I did not
have, and it settles the point.
On Tue, Sep 15, 2026 at 12:32 PM Nikolay Samokhvalov wrote:
> unpatched active | Extension | HarnessOuterWait
> v8 active | NULL | NULL
>
> So v8 clears the outer event after logging returns. It is not briefly
> masked; it remains lost.
Agreed, and "briefly masks" in v8 was wrong as a description of what
happens. pgstat_report_wait_end() writes 0, so once the log write has
ended its own region the outer one is gone for as long as it lasts.
The measurement in v8 only asked whether a log write is reached from
inside a region in core, and the one case it found exits right after
logging, so the loss never had a chance to show. Your extension keeps
waiting after the log call, and there it is.
> I think the new logging sites should preserve the old event, or this
> patch should wait for the general fix. The longjmp cleanup sites can
> use a separate reset helper.
v9 does the first. Every wrapped site saves the published event before
the write and puts it back afterwards, through two inline helpers added
to wait_event.h:
pgstat_report_wait_start_nested(info) publishes info and returns
what was published before
pgstat_report_wait_end_nested(outer) publishes outer again
They are start()/end() with the restore added, so they keep the same
properties: one store, no allocation, safe before MyProc exists. With
no outer region the saved value is 0 and end_nested() does exactly what
end() does. If end() ever learns to restore the previous event itself,
these two collapse back into start()/end() and nothing else changes.
I did not want to make this patch wait for the general fix. What I
have for that today is a debug-only nesting check, not a restore; a
restore inside end() means a real stack in production builds and a
look at every site that relies on end() clearing the field, which is a
bigger discussion than this patch should carry. Agreed on the reset
helper for the longjmp sites; that is how the check patch handles them.
I rebuilt your table here with a small module whose SQL-callable
function does no more than this:
uint32 outer = WaitEventExtensionNew("HarnessOuterWait");
pgstat_report_wait_start(outer);
ereport(LOG, (errmsg("harness: logging from inside HarnessOuterWait")));
pg_usleep(6 * 1000000L);
pgstat_report_wait_end();
Another session sampled pg_stat_activity 2.5 s after the call started,
that is, after ereport(LOG) had returned and while the function was
still sleeping inside its region, for each destination the patch
touches:
unpatched v8 v9
stderr, logging_collector=off HarnessOuterWait NULL HarnessOuterWait
stderr, logging_collector=on HarnessOuterWait NULL HarnessOuterWait
syslog HarnessOuterWait NULL HarnessOuterWait
(wait_event column; wait_event_type is Extension or NULL to match, and
state is active throughout.)
Changes from v8:
- wait_event.h: the two helpers above, so 0001 now touches three
files instead of two;
- elog.c: the nine wrapped calls use the nested pair instead of
start()/end(); in write_console() the WriteConsoleW() result goes
through a local so the pair is not repeated across the success and
fallback branches;
- the "briefly masks" comments are gone; write_console() carries the
explanation and the other sites point at it;
- 0001's commit message describes the extension case and the restore,
and drops the claim that the masking is brief.
v9 is attached, rebased onto current master (1a3e782e762).
v9-0001 - portable part (SysloggerWrite, StderrWrite, SyslogWrite)
v9-0002 - Windows part (WriteConsoleW plus EventlogWrite)
I checked it by:
- git am of both patches onto 1a3e782e762, clean;
- full Meson build (cassert, debug) -- no warnings;
- 0001 building on its own;
- pgindent on elog.c and wait_event.h -- no changes;
- regression, isolation and TAP suites green: 362 tests, 0 failures.
52 are skipped here, none for a reason this patch affects: 17 behind
PG_TEST_EXTRA, 17 wanting an injection-points build, 16 expensive
checksum tests, plus ICU and SSPI. (More than in v8 because master
has gained tests in those groups since.)
I still cannot run the Windows part here; cfbot will at least build
it. If a retest is convenient on your side that would be very welcome,
and if the restore is not the shape you had in mind I am happy to do
another round.
Regards,
Seongjun Shin
Re: Add wait events for server logging destination writes
От:
신성준 <shinsj4653@gmail.com>
Дата:
A follow-up on the Windows side. v9 said I could not run that part
here; Nik pointed out off-list that a GitHub Actions runner does the
job, so I did the same thing he did in July: a throwaway branch on my
fork with v9 applied on 1a3e782e762 plus a small test module and a
workflow, run on windows-2022 (MSVC, meson, cassert).
The module is the one from my previous mail (publish
Extension/HarnessOuterWait, ereport(LOG), sleep). The workflow starts
a cluster per log destination, calls it from one session and samples
pg_stat_activity from another 3 s later, after ereport(LOG) has
returned, and fails the job unless every sample still shows the outer
event. It passed:
log_destination = eventlog Extension / HarnessOuterWait
stderr, logging_collector = off Extension / HarnessOuterWait
stderr, logging_collector = on Extension / HarnessOuterWait
The eventlog row did go through write_eventlog(): the workflow's last
step reads the Windows Application log back and fails unless the
harness line is there under the PostgreSQL source, and it found it:
2026-09-15 15:26:10.400 UTC [2232] LOG: harness: logging from
inside HarnessOuterWait
The stderr row is the write() fallback, as in July; stderr is
redirected on a runner, so WriteConsoleW() is still not exercised at
runtime.
Run: https://github.com/shinsj4653/postgres/actions/runs/34988125975
Branch: shinsj4653/postgres, ci/win-waitevents-v9 (fe909ac)
So the restore behaves the same on Windows, for the two portable paths
and for EventlogWrite. Nothing changes in the patches; this only fills
in the Windows column that was missing from v9.
Re: Add wait events for server logging destination writes
От:
신성준 <shinsj4653@gmail.com>
Дата:
Hi, With the November CF about to start, a short status update. v9 (upthread, Sep 15) still applies cleanly: I rebased it onto current master today with no conflicts, so I'm not posting a new version. cfbot is green too. v9 keeps an outer wait event across a log write by using pgstat_report_wait_start_nested() / pgstat_report_wait_end_nested() at the new logging sites. That was the open point from Nik's last review. The Windows run in my follow-up mail covers the eventlog path. What would help most now: - Nik, a rerun of your harness against v9 when you have a free moment. No hurry. - Jakub and Henson, a quick look at the two _nested helpers in wait_event.h, since v9 is the first version that touches that file. If that all looks fine, it would be great if one of you could move the entry back to Ready for Committer. Thanks, Seongjun
Re: Add wait events for server logging destination writes
От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Seongjun,
I looked at the two _nested helpers in v9.
The code is fine. Like start()/end(), each is a single store; the
previous value is kept in a local of the caller and put back.
There is an alternative: turn start()/end() themselves into macros
that open and close a block, the way PG_TRY()/PG_END_TRY() do, with
end() putting back the previous value:
#define pgstat_report_wait_start(wait_event_info) \
do { \
uint32 outer_wait_event_info_ = \
*(volatile uint32 *) my_wait_event_info; \
*(volatile uint32 *) my_wait_event_info = (wait_event_info)
#define pgstat_report_wait_end() \
*(volatile uint32 *) my_wait_event_info = \
outer_wait_event_info_; \
} while (0)
The _nested helpers are then not needed, and a mismatched pair fails
to compile.
The compiler also finds the sites to fix: change the definitions,
build, and the errors are the places to fix. There are only two
patterns.
First, end() called twice, on the failure branch and on the normal
path. Take the result into a local and move end() ahead of the
branch.
Before:
pgstat_report_wait_start(WAIT_EVENT_SLRU_READ);
if (pg_pread(fd, shared->page_buffer[slotno], BLCKSZ,
offset) != BLCKSZ)
{
pgstat_report_wait_end();
slru_errcause = SLRU_READ_FAILED;
...
return false;
}
pgstat_report_wait_end();
After:
pgstat_report_wait_start(WAIT_EVENT_SLRU_READ);
rc = pg_pread(fd, shared->page_buffer[slotno], BLCKSZ, offset);
pgstat_report_wait_end();
if (rc != BLCKSZ)
{
slru_errcause = SLRU_READ_FAILED;
...
return false;
}
Second, the LWLockReportWaitStart()/LWLockReportWaitEnd() wrappers,
which span functions. Turn them from inline functions into macros,
and their callers need no change:
#define LWLockReportWaitStart(lock) \
pgstat_report_wait_start(PG_WAIT_LWLOCK | (lock)->tranche)
#define LWLockReportWaitEnd() \
pgstat_report_wait_end()
Besides those, error cleanup paths that call end() alone, with no
start(), to reset the field to 0, such as AbortTransaction() and the
sigsetjmp blocks of the auxiliary processes, switch to a separate
reset macro:
#define pgstat_report_wait_clear() \
(*(volatile uint32 *) my_wait_event_info = 0)
There is one cost. Since end() puts back the previous value instead
of 0, a wait event left by a region that an ERROR jumped out of is
saved and put back by every later region until something clears
it. Today the next end() wipes it. So errfinish() needs to call
the reset once before longjmp (before proc_exit() for FATAL). That
also covers PG_CATCH blocks that swallow the error without a
subtransaction. As a safety net, the sigsetjmp block in
PostgresMain() should reset it too.
Two things the compiler does not catch:
- Platform-specific code (WIN32, io_uring and so on) is checked only
by a build on that platform.
- As with PG_TRY(), a region must not be left by return, goto, break
or continue. The compiler does not stop this, and a break or
continue would bind to the hidden do/while. There are none in the
tree today.
This is not a blocker. If you prefer the function form, it is fine
as it is.
Regards,
Henson
I looked at the two _nested helpers in v9.
The code is fine. Like start()/end(), each is a single store; the
previous value is kept in a local of the caller and put back.
There is an alternative: turn start()/end() themselves into macros
that open and close a block, the way PG_TRY()/PG_END_TRY() do, with
end() putting back the previous value:
#define pgstat_report_wait_start(wait_event_info) \
do { \
uint32 outer_wait_event_info_ = \
*(volatile uint32 *) my_wait_event_info; \
*(volatile uint32 *) my_wait_event_info = (wait_event_info)
#define pgstat_report_wait_end() \
*(volatile uint32 *) my_wait_event_info = \
outer_wait_event_info_; \
} while (0)
The _nested helpers are then not needed, and a mismatched pair fails
to compile.
The compiler also finds the sites to fix: change the definitions,
build, and the errors are the places to fix. There are only two
patterns.
First, end() called twice, on the failure branch and on the normal
path. Take the result into a local and move end() ahead of the
branch.
Before:
pgstat_report_wait_start(WAIT_EVENT_SLRU_READ);
if (pg_pread(fd, shared->page_buffer[slotno], BLCKSZ,
offset) != BLCKSZ)
{
pgstat_report_wait_end();
slru_errcause = SLRU_READ_FAILED;
...
return false;
}
pgstat_report_wait_end();
After:
pgstat_report_wait_start(WAIT_EVENT_SLRU_READ);
rc = pg_pread(fd, shared->page_buffer[slotno], BLCKSZ, offset);
pgstat_report_wait_end();
if (rc != BLCKSZ)
{
slru_errcause = SLRU_READ_FAILED;
...
return false;
}
Second, the LWLockReportWaitStart()/LWLockReportWaitEnd() wrappers,
which span functions. Turn them from inline functions into macros,
and their callers need no change:
#define LWLockReportWaitStart(lock) \
pgstat_report_wait_start(PG_WAIT_LWLOCK | (lock)->tranche)
#define LWLockReportWaitEnd() \
pgstat_report_wait_end()
Besides those, error cleanup paths that call end() alone, with no
start(), to reset the field to 0, such as AbortTransaction() and the
sigsetjmp blocks of the auxiliary processes, switch to a separate
reset macro:
#define pgstat_report_wait_clear() \
(*(volatile uint32 *) my_wait_event_info = 0)
There is one cost. Since end() puts back the previous value instead
of 0, a wait event left by a region that an ERROR jumped out of is
saved and put back by every later region until something clears
it. Today the next end() wipes it. So errfinish() needs to call
the reset once before longjmp (before proc_exit() for FATAL). That
also covers PG_CATCH blocks that swallow the error without a
subtransaction. As a safety net, the sigsetjmp block in
PostgresMain() should reset it too.
Two things the compiler does not catch:
- Platform-specific code (WIN32, io_uring and so on) is checked only
by a build on that platform.
- As with PG_TRY(), a region must not be left by return, goto, break
or continue. The compiler does not stop this, and a break or
continue would bind to the hidden do/while. There are none in the
tree today.
This is not a blocker. If you prefer the function form, it is fine
as it is.
Regards,
Henson
Re: Add wait events for server logging destination writes
От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
Hi Seongjun, On Wed, Oct 28, 2026 at 10:00 PM 신성준 wrote: > v9 keeps an outer wait event across a log write by using > pgstat_report_wait_start_nested() / pgstat_report_wait_end_nested() > at the new logging sites. That was the open point from Nik's last > review. > > What would help most now: > - Nik, a rerun of your harness against v9 when you have a free > moment. No hurry. My AI harness tested v9 on master at b6178c942ea7, cassert build. The outer event survives the log write now. Sampled after ereport(LOG) returned, inside the extension's region, v9 shows active | Extension | HarnessOuterWait for stderr with logging_collector off and on, csvlog, jsonlog, all three together, and syslog. v8 shows an empty wait_event_type and wait_event in the same runs, so the check can tell them apart. The core regression suite passes with v9. I also read the wrapped sites. They wrap only leaf OS calls (write(), openlog(), syslog(), and the Windows calls in 0002), and nothing in between can ereport, so I see no path that leaves start without end. No new findings. I did not test Windows or the macro alternative Henson described. From the tester's side I consider v9 ready. Thanks, Nik
Re: Add wait events for server logging destination writes
От:
신성준 <shinsj4653@gmail.com>
Дата:
Hi Henson, Nik, > This is not a blocker. If you prefer the function form, it is fine > as it is. Thanks for reading the _nested helpers, Henson. I'd like to keep the function form in this patch. The macro version would touch about 100 start/end pairs in 45 files plus the LWLock wrappers and errfinish(), and it changes what end() does for every caller, extensions included. I think that belongs in its own thread, and I'm happy to try it there once this one is in. > From the tester's side I consider v9 ready. Thanks for the rerun, Nik, and for running v8 next to it as a control. With both of your reviews in, I've moved the CF entry to Ready for Committer. v9 still applies cleanly to current master, so no new version. Thanks, Seongjun
Re: Add wait events for server logging destination writes
On Sun, Nov 08, 2026 at 01:27:49PM +0900, 신성준 wrote: > v9 still applies cleanly to current master, so no new version. + outer_wait_event_info = + pgstat_report_wait_start_nested(WAIT_EVENT_SYSLOG_WRITE); The concept of nesting is a lie. The wait events you are setting are not saved in a stack; they're just replaced and saved in place. I am wondering if something like a pgstat_report_wait_swap() would be more adapted? If you have a better idea of name, feel free. Then you would get: old_event = pgstat_report_wait_swap(new_event); //do stuff pgstat_report_wait_swap(old_event); That would avoid any cloberring of the wait events that an upper layer calling the elog functions could have set. One API, two calls each time. + * A log message can be written while another wait event is already + * published, for instance by an extension that logs from inside its own + * wait region, or by quickdie() running in a signal handler. Wait events + * are single-slot and pgstat_report_wait_end() clears the field, which + * would leave the enclosing region without its event for as long as it + * lasts. The nested variants used here and at the other logging writes + * put the outer event back once the write is done. This is AI slop to me. None of this level of details is required. Even if required, I'd limit that to a few words at most just to say that we don't want to clobber any information set, if set. But the intention would be clearly documented if one uses this "swap" API anyway (or whatever the way you would like to call it) because the old value is pushed back to my_wait_event_info. And note that I highly doubt that these commit messages need contents worth more than 3 screens. So could I suggest that you keep your agent at bay in terms of quality, please? This does not really help. Also, perhaps split your new API into a first patch, then write a second patch that makes use of it. Doing both at the same time feels confusing. -- Michael
Re: Add wait events for server logging destination writes
Hello Michael, thanks for the review. > I am wondering if something like a pgstat_report_wait_swap() would be > more adapted? That's simpler, thanks. Done in v10. > This is AI slop to me. None of this level of details is required. Agreed, removed. The commit messages are much shorter as well. And point taken on the agent. I'll check more carefully what goes out from now on. > Also, perhaps split your new API into a first patch, then write a > second patch that makes use of it. Done. 0001 adds pgstat_report_wait_swap(), 0002 uses it for the logging writes, and 0003 does the same for the Windows-only paths. Rebased on b0496e30830. -- Seongjun
Re: Add wait events for server logging destination writes
On Fri, Nov 13, 2026 at 12:23:52AM +0900, 신성준 wrote: > Done. 0001 adds pgstat_report_wait_swap(), 0002 uses it for the > logging writes, and 0003 does the same for the Windows-only paths. Thanks. I'm wondering if others feel that this idea feels like a hack, though, because it's just a workaround due to the fact that wait events are not handled in a nested way. It's not clear to me if folks would prefer that and if catalogs should be upgraded to reflect that, so perhaps it would not be a bad thing to wait for more opinions. Note that I am not convinced about adding the whole set of suggested wait events just based on the reason that they seem useful. For one, I am not able to check the Windows-specific ones and if they actually make sense on their own. -- Michael
Re: Add wait events for server logging destination writes
От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Hi all, On 13 Nov 2026, Michael Paquier wrote: > it's just a workaround due to the fact that wait > events are not handled in a nested way. I support moving towards nested waits. Keeping the previous event in the caller's frame is the approach I had in mind. Starting with the logging sites seems a useful step. The patch addresses the case that concerns me: logs on a slow boot disk not showed up in stats. For follow-up, I'd look at WaitEventSetWait() and FileReadV(). Both still clear an outer event when their wait ends. Could we reuse the debug nesting check to collect inner/outer call sites over a check-world run and identify most useful sites that can be converted to nested? Thank you! Best regards, Andrey Borodin.
Re: Add wait events for server logging destination writes
От:
신성준 <shinsj4653@gmail.com>
Дата:
Michael Paquier wrote:
> Note that I am not convinced about adding the whole set of suggested
> wait events just based on the reason that they seem useful.
The ones in 0002 come from real cases. Jakub's outage upthread was a
stuck remote syslog (SyslogWrite). With Andrey's slow boot disk,
backends block on the syslogger pipe or on stderr, depending on
logging_collector (SysloggerWrite, StderrWrite).
> For one, I am not able to check the Windows-specific ones and if they
> actually make sense on their own.
Fair. EventlogWrite has only been seen in CI runs, and WriteConsoleW
has never been exercised. I'm fine with dropping 0003 and leaving the
Windows paths for later.
Andrey Borodin wrote:
> Could we reuse the debug nesting check to collect inner/outer call
> sites over a check-world run and identify most useful sites that can
> be converted to nested?
Yes. A run in September found only two such pairs, but the check
aborts at the first one in each process. I'll make it record the pairs
instead and post the list here.
I'll hold off on a new version until there are more opinions on the
swap approach.
--
Best regards,
Seongjun
> Note that I am not convinced about adding the whole set of suggested
> wait events just based on the reason that they seem useful.
The ones in 0002 come from real cases. Jakub's outage upthread was a
stuck remote syslog (SyslogWrite). With Andrey's slow boot disk,
backends block on the syslogger pipe or on stderr, depending on
logging_collector (SysloggerWrite, StderrWrite).
> For one, I am not able to check the Windows-specific ones and if they
> actually make sense on their own.
Fair. EventlogWrite has only been seen in CI runs, and WriteConsoleW
has never been exercised. I'm fine with dropping 0003 and leaving the
Windows paths for later.
Andrey Borodin wrote:
> Could we reuse the debug nesting check to collect inner/outer call
> sites over a check-world run and identify most useful sites that can
> be converted to nested?
Yes. A run in September found only two such pairs, but the check
aborts at the first one in each process. I'll make it record the pairs
instead and post the list here.
I'll hold off on a new version until there are more opinions on the
swap approach.
--
Best regards,
Seongjun
Re: Add wait events for server logging destination writes
От:
Kirk Wolak <wolakk@gmail.com>
Дата:
On Fri, Nov 13, 2026 at 2:10 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
Hi all,
On 13 Nov 2026, Michael Paquier wrote:
> it's just a workaround due to the fact that wait
> events are not handled in a nested way.
I support moving towards nested waits. Keeping the previous event in
the caller's frame is the approach I had in mind. Starting with the
logging sites seems a useful step.
The patch addresses the case that concerns me: logs on a slow boot disk
not showed up in stats.
For follow-up, I'd look at WaitEventSetWait() and FileReadV(). Both
still clear an outer event when their wait ends.
Could we reuse the debug nesting check to collect inner/outer call
sites over a check-world run and identify most useful sites that can
be converted to nested?
+1
I like getting the waits a bit more accurate. It might take a few passes.
Re: Add wait events for server logging destination writes
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-11-13 12:10:39 +0500, Andrey Borodin wrote: > On 13 Nov 2026, Michael Paquier wrote: > > it's just a workaround due to the fact that wait > > events are not handled in a nested way. > > I support moving towards nested waits. Keeping the previous event in > the caller's frame is the approach I had in mind. Starting with the > logging sites seems a useful step. I, however, vehemently oppose anything in that direction. You're not waiting for something while waiting for something else. If there are places where wait events clear an exising wait event, that code needs to be fixed. Wait events are for reporting waits, not profiling, not general event tracing or whatnot. They won't be good at any other such task. Stop trying to make them into something else. Greetings, Andres Freund
Re: Add wait events for server logging destination writes
От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Andres, Andrey,
> You're not waiting
> for something while waiting for something else.
Agreed for what is reported: one slot, one wait at a time. The
question is what the slot holds when an inner wait ends.
A server process mostly waits idle (ClientRead, Activity
*_MAIN). When woken it runs with no wait event (NULL), and while
running it may wait on something else (a lock, I/O, a log write).
Core codes these waits one after another, each with its own
start()/end(), so end() writing 0 is correct there.
The trouble comes only when something runs inside an open wait,
between start() and end(). The inner end() then writes 0 while
the outer wait is still going on. Nikolay's harness (Nov 4) hit
this: with v8 the extension's own wait was gone after
ereport(LOG); with v9 it stayed.
I measured two such cases with the attached patches on master
(1fe0cfddf0e; line numbers below refer to it). They are for
measurement only, not a proposal. "restore" is a build where
end() puts back what start() saw. In the flat loops
(ClientRead, WalWriterMain) the two builds look the same.
1. CHECK_FOR_INTERRUPTS() logs, and the log hook waits
The hook is a test extension, but it does what pg_logfebe
does in the field: it ships each message from emit_log_hook
and waits on it.
start(InjectionPoint)
CHECK_FOR_INTERRUPTS() -> ereport(LOG) -> emit_log_hook
start(hook's wait) ... end()
... still waiting for the injection point ...
end()
After the hook, master shows 0 for the remaining 2.2 s;
restore shows InjectionPoint.
2. client_connection_check_interval fires during the wait
start(InjectionPoint)
CHECK_FOR_INTERRUPTS() -> pq_check_connection()
WaitEventSetWait(..., 0): start(0) ... end()
... still waiting for the injection point ...
end()
After each check, master shows 0 and restore shows
InjectionPoint, 62 of 62 times.
In case 2 core itself calls start(0), marking a short stretch of
activity inside the outer wait. With restore, end() then brings
the outer wait back.
Injection points are test infrastructure, but core has the same
shape: proc_exit() inside WaitEventSetWait() on postmaster death
(waiteventset.c:1264), and error context callbacks (elog.c:525)
and emit_log_hook (elog.c:1927) inside I/O waits, e.g. a failed
COPY TO write (copyto.c:651).
Monitoring reads a NULL wait_event as "on CPU". So once end()
writes 0, a process that is still waiting is counted as running.
Nesting thus already happens in core, and hooks called inside a
wait run extension code there. Core cannot control that alone.
> If there are places where
> wait events clear an exising wait event, that code needs to be
> fixed.
Fixed against what? Today the only contract is "end() writes 0",
which cannot tell whether the inner wait or the outer window is
at fault.
This thread adds waits on log writes (Jakub's stuck remote
syslog, Andrey's slow disk). ereport() can be called anywhere, so
every ereport() inside a wait becomes such a place.
Other code that runs inside waits is outside core's control:
emit_log_hook (pg_logfebe does a blocking send() there), error
context callbacks and exit callbacks. contrib/pg_prewarm's worker
waits with WL_EXIT_ON_PM_DEATH (autoprewarm.c:243), and its
before_shmem_exit callback takes an LWLock (autoprewarm.c:905).
On exit 0 is the right value, but today the slot gets it only when
some end() happens to overwrite it, not by a rule.
Fixing only the places in core found to nest, as the swap does,
cannot cover these. They would need a contract of their own:
when called inside a wait, do not start another. Nothing states
or checks that today.
A nesting count could keep the outer wait instead: a start()
inside a window leaves the slot as it is. But it cannot handle
start(0), as in case 2, where core marks a short stretch of
activity inside the outer wait.
> Wait events are for reporting waits, not profiling, not general
> event tracing or whatnot.
Agreed. It stays one slot, with no stack and no history, and it
cannot serve phase tracing: the outer value would show between
sibling phases (parse, plan, execute), and any real wait would
hide the phase. If phases were reported this way:
start(Query) slot
start(Parse) ... end() Parse, then Query again
start(Plan) Plan
start(Lock) ... end() Lock hides Plan, then Plan
end() Query again
start(Execute) ... end() Execute, then Query again
end() 0
Query shows between every two phases, so a sampler cannot tell
"between phases" from "in Query but in no phase".
PostgreSQL does not use threads, but a background thread in a
daemon commonly looks like this, and start()/end() fit the same
shape. pthread_cond_timedwait() gives up the mutex for the wait
and holds it again on return; end() likewise puts back what
start() saw:
start(BlockIdle); slot m
pthread_mutex_lock(&m); BlockIdle held
for (;;)
{
pthread_cond_timedwait(&c, &m, &ts); BlockIdle released,
then held
start(0); 0 held
... work ...
start(DataFileRead) ... end() DataFileRead, then 0
end(); BlockIdle held
}
end();
Code calling start()/end() sees only its own part of the process.
Writing 0 assumes its caller was not waiting; putting back what
start() saw does not need to know, just as above. In PG terms
the contract is three lines:
1. start() and end() pair in one block of one function, like
PG_TRY()/PG_END_TRY(); end() puts back what start() saw.
2. The value saved before sigsetjmp() is put back on ERROR and
when leaving the block, as PG_TRY() already does for
error_context_stack.
3. Switching the storage between the local variable and PGPROC
carries the value over, as SwitchToSharedLatch() does.
Each line is a save/restore pair, and the pairs nest. Errors and
exits still break the inner pairs; the nearest outer pair then
puts its own value back (proc_exit() puts back 0), so nothing is
left half restored. The code is then fixed against the contract:
no pgstat_report_wait_end() used as a reset, and no clear in
AbortSubTransaction() that would wipe what PG_CATCH() put back.
Those patches were for the measurements, not a proposal here.
SeongJun's v10 covers the logging sites with the swap; whether
that is enough for 6819 is for the committers to judge.
The cases above predate this thread, and I see two consistent
answers: forbid nesting by a documented rule, enforced with an
Assert on a start() inside an open wait, or allow it under a new
contract. Today it is neither: nesting happens in core and in
extensions, and end() clears it to 0. Which would you prefer?
Best regards,
Henson
> You're not waiting
> for something while waiting for something else.
Agreed for what is reported: one slot, one wait at a time. The
question is what the slot holds when an inner wait ends.
A server process mostly waits idle (ClientRead, Activity
*_MAIN). When woken it runs with no wait event (NULL), and while
running it may wait on something else (a lock, I/O, a log write).
Core codes these waits one after another, each with its own
start()/end(), so end() writing 0 is correct there.
The trouble comes only when something runs inside an open wait,
between start() and end(). The inner end() then writes 0 while
the outer wait is still going on. Nikolay's harness (Nov 4) hit
this: with v8 the extension's own wait was gone after
ereport(LOG); with v9 it stayed.
I measured two such cases with the attached patches on master
(1fe0cfddf0e; line numbers below refer to it). They are for
measurement only, not a proposal. "restore" is a build where
end() puts back what start() saw. In the flat loops
(ClientRead, WalWriterMain) the two builds look the same.
1. CHECK_FOR_INTERRUPTS() logs, and the log hook waits
The hook is a test extension, but it does what pg_logfebe
does in the field: it ships each message from emit_log_hook
and waits on it.
start(InjectionPoint)
CHECK_FOR_INTERRUPTS() -> ereport(LOG) -> emit_log_hook
start(hook's wait) ... end()
... still waiting for the injection point ...
end()
After the hook, master shows 0 for the remaining 2.2 s;
restore shows InjectionPoint.
2. client_connection_check_interval fires during the wait
start(InjectionPoint)
CHECK_FOR_INTERRUPTS() -> pq_check_connection()
WaitEventSetWait(..., 0): start(0) ... end()
... still waiting for the injection point ...
end()
After each check, master shows 0 and restore shows
InjectionPoint, 62 of 62 times.
In case 2 core itself calls start(0), marking a short stretch of
activity inside the outer wait. With restore, end() then brings
the outer wait back.
Injection points are test infrastructure, but core has the same
shape: proc_exit() inside WaitEventSetWait() on postmaster death
(waiteventset.c:1264), and error context callbacks (elog.c:525)
and emit_log_hook (elog.c:1927) inside I/O waits, e.g. a failed
COPY TO write (copyto.c:651).
Monitoring reads a NULL wait_event as "on CPU". So once end()
writes 0, a process that is still waiting is counted as running.
Nesting thus already happens in core, and hooks called inside a
wait run extension code there. Core cannot control that alone.
> If there are places where
> wait events clear an exising wait event, that code needs to be
> fixed.
Fixed against what? Today the only contract is "end() writes 0",
which cannot tell whether the inner wait or the outer window is
at fault.
This thread adds waits on log writes (Jakub's stuck remote
syslog, Andrey's slow disk). ereport() can be called anywhere, so
every ereport() inside a wait becomes such a place.
Other code that runs inside waits is outside core's control:
emit_log_hook (pg_logfebe does a blocking send() there), error
context callbacks and exit callbacks. contrib/pg_prewarm's worker
waits with WL_EXIT_ON_PM_DEATH (autoprewarm.c:243), and its
before_shmem_exit callback takes an LWLock (autoprewarm.c:905).
On exit 0 is the right value, but today the slot gets it only when
some end() happens to overwrite it, not by a rule.
Fixing only the places in core found to nest, as the swap does,
cannot cover these. They would need a contract of their own:
when called inside a wait, do not start another. Nothing states
or checks that today.
A nesting count could keep the outer wait instead: a start()
inside a window leaves the slot as it is. But it cannot handle
start(0), as in case 2, where core marks a short stretch of
activity inside the outer wait.
> Wait events are for reporting waits, not profiling, not general
> event tracing or whatnot.
Agreed. It stays one slot, with no stack and no history, and it
cannot serve phase tracing: the outer value would show between
sibling phases (parse, plan, execute), and any real wait would
hide the phase. If phases were reported this way:
start(Query) slot
start(Parse) ... end() Parse, then Query again
start(Plan) Plan
start(Lock) ... end() Lock hides Plan, then Plan
end() Query again
start(Execute) ... end() Execute, then Query again
end() 0
Query shows between every two phases, so a sampler cannot tell
"between phases" from "in Query but in no phase".
PostgreSQL does not use threads, but a background thread in a
daemon commonly looks like this, and start()/end() fit the same
shape. pthread_cond_timedwait() gives up the mutex for the wait
and holds it again on return; end() likewise puts back what
start() saw:
start(BlockIdle); slot m
pthread_mutex_lock(&m); BlockIdle held
for (;;)
{
pthread_cond_timedwait(&c, &m, &ts); BlockIdle released,
then held
start(0); 0 held
... work ...
start(DataFileRead) ... end() DataFileRead, then 0
end(); BlockIdle held
}
end();
Code calling start()/end() sees only its own part of the process.
Writing 0 assumes its caller was not waiting; putting back what
start() saw does not need to know, just as above. In PG terms
the contract is three lines:
1. start() and end() pair in one block of one function, like
PG_TRY()/PG_END_TRY(); end() puts back what start() saw.
2. The value saved before sigsetjmp() is put back on ERROR and
when leaving the block, as PG_TRY() already does for
error_context_stack.
3. Switching the storage between the local variable and PGPROC
carries the value over, as SwitchToSharedLatch() does.
Each line is a save/restore pair, and the pairs nest. Errors and
exits still break the inner pairs; the nearest outer pair then
puts its own value back (proc_exit() puts back 0), so nothing is
left half restored. The code is then fixed against the contract:
no pgstat_report_wait_end() used as a reset, and no clear in
AbortSubTransaction() that would wipe what PG_CATCH() put back.
Those patches were for the measurements, not a proposal here.
SeongJun's v10 covers the logging sites with the swap; whether
that is enough for 6819 is for the committers to judge.
The cases above predate this thread, and I see two consistent
answers: forbid nesting by a documented rule, enforced with an
Assert on a start() inside an open wait, or allow it under a new
contract. Today it is neither: nesting happens in core and in
extensions, and end() clears it to 0. Which would you prefer?
Best regards,
Henson
Re: Add wait events for server logging destination writes
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-11-14 11:09:11 +0900, Henson Choi wrote: > The trouble comes only when something runs inside an open wait, > between start() and end(). The inner end() then writes 0 while > the outer wait is still going on. Nikolay's harness (Nov 4) hit > this: with v8 the extension's own wait was gone after > ereport(LOG); with v9 it stayed. > I measured two such cases with the attached patches on master > (1fe0cfddf0e; line numbers below refer to it). They are for > measurement only, not a proposal. "restore" is a build where > end() puts back what start() saw. In the flat loops > (ClientRead, WalWriterMain) the two builds look the same. > > 1. CHECK_FOR_INTERRUPTS() logs, and the log hook waits > > The hook is a test extension, but it does what pg_logfebe > does in the field: it ships each message from emit_log_hook > and waits on it. > > start(InjectionPoint) > CHECK_FOR_INTERRUPTS() -> ereport(LOG) -> emit_log_hook > start(hook's wait) ... end() > ... still waiting for the injection point ... > end() > > After the hook, master shows 0 for the remaining 2.2 s; > restore shows InjectionPoint. > 2. client_connection_check_interval fires during the wait > > start(InjectionPoint) > CHECK_FOR_INTERRUPTS() -> pq_check_connection() > WaitEventSetWait(..., 0): start(0) ... end() > ... still waiting for the injection point ... > end() > > After each check, master shows 0 and restore shows > InjectionPoint, 62 of 62 times. For both of these: Doing a CFI() while a wait event is set up is bogus. A CFI can execute arbitrary code. It is not a wait. That's the problem, not that wait events don't support nesting. > In case 2 core itself calls start(0), marking a short stretch of > activity inside the outer wait. With restore, end() then brings > the outer wait back. > > Injection points are test infrastructure, but core has the same > shape: proc_exit() inside WaitEventSetWait() on postmaster death > (waiteventset.c:1264), and error context callbacks (elog.c:525) > and emit_log_hook (elog.c:1927) inside I/O waits, e.g. a failed > COPY TO write (copyto.c:651). There's hardly a need to reset outer wait events in that case, no? > > If there are places where > > wait events clear an exising wait event, that code needs to be > > fixed. > > Fixed against what? Today the only contract is "end() writes 0", > which cannot tell whether the inner wait or the outer window is > at fault. Not execute code that can start wait wait events while having a wait event set up, at least if the outer wait can continue after. > This thread adds waits on log writes (Jakub's stuck remote > syslog, Andrey's slow disk). ereport() can be called anywhere, so > every ereport() inside a wait becomes such a place. No, ereport() cannot be called anywhere. For one, you can't do it with spinlocks held. But I would also say that it is nonsensical to do it with a wait event set up. > The cases above predate this thread, and I see two consistent > answers: forbid nesting by a documented rule, enforced with an > Assert on a start() inside an open wait, or allow it under a new > contract. Today it is neither: nesting happens in core and in > extensions, and end() clears it to 0. Which would you prefer? I would prefer not getting way too long LLM generated text blocks. Greetings, Andres Freund
Re: Add wait events for server logging destination writes
Hello,
> Could we reuse the debug nesting check to collect inner/outer call
> sites over a check-world run
I changed the check to record the pairs instead of aborting, and ran
meson test with TAP and injection points enabled. On master
(b0496e30830) no wait event was started while another one was set.
With the logging events added, a log write happened inside a wait in
six processes: once in quickdie() during ClientRead, and five times in
injection_wait() when the process was canceled or terminated. In all
six the outer wait ends there, by ERROR or process exit.
Andres Freund wrote:
> If there are places where wait events clear an exising wait event,
> that code needs to be fixed.
Understood. v11 drops the swap and the Windows part. It is a single
patch with plain pgstat_report_wait_start()/end() around the log
writes.
This means an extension that logs inside its own wait and keeps
waiting loses that wait event, which is what Nikolay's harness showed
with v8.
--
Best regards,
Seongjun