| From: | Dmitry Fomin <fomin(dot)list(at)gmail(dot)com> |
|---|---|
| To: | pgsql-hackers(at)lists(dot)postgresql(dot)org, Andres Freund <andres(at)anarazel(dot)de>, Ilmar Yunusov <tanswis42(at)gmail(dot)com>, Andrey Borodin <x4mmm(at)yandex-team(dot)ru> |
| Cc: | Kirk Wolak <wolakk(at)gmail(dot)com>, Nikolay Samokhvalov <nik(at)postgres(dot)ai> |
| Subject: | Re: [PATCH v1 0/7] Wait event timing and tracing instrumentation |
| Date: | 2026-11-30 10:24:47 |
| Message-ID: | CAPHG-0kZjsrkB3oRXmMct7_nnWBipc0A=e9=Xpuv-+u2Vxxprg@mail.gmail.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hi hackers,
v18 is attached, three patches on 77bba5454f9. It is a different design
from v1 to v17, written to address Andres's two objections to the hooks:
no third-party code runs inside a wait site any more, and the wait sites
do not grow beyond one compare and one branch. The consumer side
(statement attribution, the trace ring, the totals) is no longer in the
series; it becomes an extension on top of the API below. I am posting
the core part first, for feedback on the buffer and drain design before
the consumer port is finished; v18 is the core part only.
What the patches do
0001 adds the infrastructure and leaves pgstat_report_wait_start() and
pgstat_report_wait_end() exactly as on master, so it has no effect on
the hot path at all. A process that wants wait timing enables a small
backend-local ring buffer (2048 records of 24 bytes by default). Core
writes one record per completed wait into it from fixed C code: no
hook, no allocation, no lock, no error report, no latch. The records
are handed to registered consumer callbacks later, at safe points,
where a consumer may do what ordinary backend code may. Core copies one
opaque uint32 context tag into each record and never interprets it;
that is how a consumer attaches "in statement X / in a transaction /
idle" to the waits without core knowing those concepts.
A finished wait asks for a drain (WaitEventDrainPending plus
InterruptPending) when the buffer passes 3/4 of its capacity or 10 ms
have passed since the last drain, reusing the timestamp already taken
for the record. The request is served by the next interrupt hub:
ProcessInterrupts() and the per-iteration Process*Interrupts() of the
auxiliary processes call pgstat_drain_wait_events_if_pending(), which
drains only when InterruptHoldoffCount == 0 && CritSectionCount == 0.
The callbacks run under PG_TRY/PG_FINALLY, so a consumer that raises an
error loses its batch but cannot wedge the buffer.
The slow path does not SetLatch(): a wait-reporting function that arms
MyLatch makes the next WaitLatch() return at once and breaks latch-paced
loops (bgwriter hibernation, walwriter pacing, the IO workers' wakeup
accounting). The consequence is a visibility trade-off: a process that
does buffered work and then sleeps for a long time holds its
undelivered records until it next wakes up or reaches an interrupt
check. The four loops with long or unbounded idle sleeps (IO worker
idle loop, bgwriter and walwriter hibernation, archiver idle sleep)
drain explicitly before sleeping; a client backend that goes idle keeps
at most 3/4 of a buffer, all of it from less than 10 ms after its last
drain, until the client's next command. A before_shmem_exit callback
delivers the remainder at process exit, so no record is lost. A
consumer that shows per-backend state has to accept that idle lag or
read the live state from pg_stat_activity, which is unchanged.
pgstat_report_wait_end_abort() clears an in-flight wait without writing
a record and is used at the ten error-recovery cleanup ends, so the gap
until error unwind is not counted as a wait. InitPostmasterChild()
resets the per-process state so a forked child never inherits the
postmaster's buffer or registry.
ABI note: my_wait_event_info is now a macro over
wait_event_report_state.info instead of an exported PGDLLIMPORT
pointer. Code that includes utils/wait_event.h is source compatible; an
extension that declared the extern by hand would no longer link.
0002 is the whole hot-path change, 12 lines in utils/wait_event.h
(4 lines of code, the rest comments):
*(volatile uint32 *) my_wait_event_info = wait_event_info;
if (unlikely(wait_event_report_state.buf != NULL))
pgstat_wait_timing_begin_slow(wait_event_info);
and the mirror image in pgstat_report_wait_end(), with the store of 0
before the test. There is no parallel _timed API and no call site is
converted; every wait, in core and in extensions, is timed the same way
once a consumer has enabled it.
0003 is a test module, test_wait_timing, with fake in-core consumers:
delivery with the context in force at wait start, a wait in flight
across a drain, overflow accounting, both drain triggers, a consumer
that raises an error, consumers that register or unregister from their
own callback, the public inlines and _end_abort, and the final drain at
backend exit (TAP). It uses its own custom wait events and filters on
them, so incidental real waits do not make it flaky.
What it costs with timing off
Machine code (GCC 8.5, -O2, x86-64): each inlined start/end compiles to
one cmpq $0,wait_event_report_state+8(%rip) and one conditional branch
to an out-of-line .cold block that holds the call; 95 of the 97 begin
calls and all 107 end calls are out of line. No function changes its
callee-saved register set or its stack frame on a hot path (eleven
file-I/O and recovery functions grow their frame by 16 bytes for spills
inside the cold fragment). On the uncontended statement path (SPI,
executor, snapshot, LWLockAcquire/LWLockRelease fast path) a build with
the two branches compiled out and the patched build generate identical
instruction sequences. .text grows by 2,608 bytes for 0001 and 5,792
bytes for 0002; wait_event_report_state is 16 bytes in .data and sits
inside one cache line.
Measured on a bare-metal Xeon (Sapphire Rapids, SMT and turbo off, fixed
2.8 GHz, Rocky 8, GCC 8.5 -O2), four builds: two identical master
builds (A/A), master+0001+0002 with timing off, and the control build
with the two branches compiled out, 16 paired repetitions in balanced
Latin squares. Deltas are means of the 16 paired differences against
the first master build; "A/A pair" is the second master build:
Workload (ns/iter) vanilla A/A patched control
pair off
--------------------------------- ------- ------ ------- -------
W1e plain start/end pair 0.364 0.00 +0.37 0.00
W1f64 cycle over 64 wait events 0.725 0.00 +0.36 0.00
W1p one fixed wait event 0.511 0.00 +0.22 +0.04
W1b WaitLatch timeout 283 -0.36 +0.20 +1.21
W1c cached 8 kB pread 505 -0.05 +2.70 +0.71
S1 SELECT 1 (no wait) 825 -0.28 +6.89 +2.43
S2 EXECUTE, replanned (no wait) 2882 +1.54 +78.7 +55.9
S3 SET LOCAL (no wait) 355 +1.92 +19.3 +22.3
S9 EXCEPTION block (no wait) 285 -0.13 -1.26 -16.0
S10rw COMMIT + INSERT (rare wait) 3195 +1.25 +18.1 +78.3
(S1's mean is pulled down by two slow runs in the first master build;
its Hodges-Lehmann estimate is +8.9 for patched-off and +4.2 for
control.)
- One pgstat_report_wait_start()/_end() pair with nothing in between,
in a tight C loop: +0.19 to +0.37 ns per pair, about one cycle, with
interval half-widths below 0.03 ns. That is the whole disabled-path
cost, at every wait-reporting call site. For scale, the cheapest real
waits in the same harness are a WaitLatch timeout at about 283 ns and
a cached 8 kB pread at about 505 ns.
- Statement micro-loops that take no wait events (SELECT 1 through the
executor, EXECUTE, SET LOCAL, COMMIT without an xid) moved by up to
about 6% in either direction, in the patched build and in the control
build alike, although the control build's added code never runs, and
individual loops flip sign between the two. Those rows measure code
placement, not the branch; I report them because a benchmark of a
patch that adds 8 kB of text has to expect them.
- Compared with v17 (separate session, same master source and host):
v17 with its module loaded and tracing off cost about 22 ns per
SELECT 1 statement over master, 12 ns of it over v17 with nothing
loaded; v18 has no loaded-but-off tax and sits at the level of v17
with nothing loaded. Per pair, v18 is not cheaper than v17: it
charges every call site, v17 charged only the converted ones.
No pgbench numbers yet: the harness for that exists but its A/A pair
turned out to be two byte-identical binaries, so it cannot bound the
layout variance that the control build shows. I will fix that and run
it. The enabled path (clock read, 24-byte append, drain) is not measured
either; that needs the consumer, which is being ported.
Tests and CI
make check and the module's SQL and TAP tests pass on Linux with
assertions, debug and injection points enabled, 0 compiler warnings.
The standalone s_lock_test (make -C src/backend/storage/lmgr check)
still links and runs to its expected "stuck spinlock" exit.
CI on my fork, tip 807fcba7b6e: all jobs passed (Linux 64-bit and
32-bit, autoconf, compiler warnings, macOS, Visual Studio, MinGW).
https://github.com/DmitryNFomin/postgres/actions/runs/46389792411
Dmitry
| Attachment | Content-Type | Size |
|---|---|---|
| 0001-v18-0001-core-local-wait-event-buffer-and-safe-point.patch | application/octet-stream | 43.9 KB |
| 0003-v18-0003-test_wait_timing-coverage-for-the-local-buf.patch | application/octet-stream | 68.6 KB |
| 0002-v18-0002-time-wait-events-via-the-existing-report-AP.patch | application/octet-stream | 2.5 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | vignesh C | 2026-11-30 10:37:00 | Re: Preserve conflict log table during upgrade |
| Previous Message | Alain LESAGE | 2026-11-30 10:22:45 | Re: Improve hash aggregate spilling by writing only the needed columns |