Re: Fix tracing of BackendKeyData and CancelRequest messages
Re: Fix tracing of BackendKeyData and CancelRequest messages
От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 03/07/2026 12:42, Anthonin Bonnefoy wrote:
> BackendKeyData length was increased from 4 bytes to a variable sized
> length (up to 256 bytes) in a460251f0a. However, PQtrace still traces
> it as a 4 bytes key, leading to a "mismatched message length" warning
> message. The same issue impacts the tracing of CancelRequest.
>
> This shows the lack of coverage of tracing startup packets:
> libpq_pipeline only starts traces once the connection is established.
> There's also no way to test this with psql.
>
> The attached patchset fixes the traces BackendKeyData and
> CancelRequest, add the possibility of tracing any connection created
> by libpq, and add test coverage for the startup packets. It contains
> the following files:
>
> 0001: Fix tracing of BackendKeyData and CancelRequest messages
> @@ -762,7 +762,7 @@ pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
> /* No message content */
> break;
> case PqMsg_BackendKeyData:
> - pqTraceOutput_BackendKeyData(conn->Pfdebug, message, &logCursor, regress);
> + pqTraceOutput_BackendKeyData(conn->Pfdebug, message, conn->be_cancel_key_len, &logCursor, regress);
> break;
> case PqMsg_NoData:
> fprintf(conn->Pfdebug, "NoData");
This should use the 'length' parsed from the message, instead of relying
on conn->be_cancel_key_len. Same in pqTraceOutputNoTypeByteMessage(). I
changed that, and committed and backpatched. Thanks!
I did not look closely at the rest of the patches, but more test
coverage sounds like a good idea. Some quick comments just based on the
descriptions though:
> 0002: Add PGTRACE env var in libpq to enable protocol tracing to the
> target file (or '-' for stdout). One limitation of this approach is
> that you should only have one connection writing to a trace file. If
> an application opens multiple connections to the same PGTRACE, each
> connection will open its own fd and erase others traces. But given
> this is to debug protocol messages, it sounds like an acceptable
> limitation.
While testing just the first patch, I noticed that PQcancel() doesn't do
the tracing even if it was enabled in the main connection, which made it
a little hard to test. I didn't try this patch, but I hope it fixes that
problem too.
> 0003: Replace libpq_pipeline PQtrace calls by PGTRACE, adding tracing
> of startup messages, with some additional regress masking. I've also
> added a warning message to report mismatch length similar to what's
> done in pqTraceOutputMessage.
Could you achieve the same by calling PQtrace() earlier? Perhaps switch
to PQconnectStart() interface, and call PQtrace() right after
PQconnectStart()?
> 0004: Add tracing of cancel requests in libpq_pipeline test. Calling
> PQuntrace on the main and monitor connections was necessary to allow
> the cancel connections to append the cancel messages without conflict.
Seems unrelated to pipelining, so perhaps this should go somewhere else.
Then again, we already crossed that bridge when we added the
"protocol_version" test there, which is also unrelated to pipelining.
Maybe we should rename the test module, or add some comments noting that
it's not just for pipelining anymore.
As a side note, I find the output from pqTraceOutputNchar() awkward for
things like the cancel key, which is raw binary bytes:
> BackendKeyData 711421 'm[\x80\x95\xd6\x81{I\x8b\x04>\xab\x7fwMG\xda!\xc1\xb8\xa7\x8d\xb0.\xcd\xaa\x15\x9c\x0f\xd2\xe8\x1b'
We don't need to invest too much in making the trace output pretty, but
I think it would make sense to print that as a hex string.
- Heikki
Re: Fix tracing of BackendKeyData and CancelRequest messages
От:
Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
Дата:
Вложения:
Hi,
Thanks for the review!
On Fri, Jul 3, 2026 at 2:10 PM Heikki Linnakangas wrote:
> While testing just the first patch, I noticed that PQcancel() doesn't do
> the tracing even if it was enabled in the main connection, which made it
> a little hard to test. I didn't try this patch, but I hope it fixes that
> problem too.
Yeah, as PQcancel is signal-safe, it doesn't go through the normal
message construction, and thus is not traced. I've done an attempt to
fix that, but that requires a new flag that's enabled in the signal
handler, and then trying to generate the trace for the cancel request
after that, and it isn't great.
Given there's an active thread to get rid of PQcancel calls[0], maybe
it's not worth it to add more logic to the signal handler and PQcancel
to trace those cancel requests?
> > 0003: Replace libpq_pipeline PQtrace calls by PGTRACE, adding tracing
> > of startup messages, with some additional regress masking. I've also
> > added a warning message to report mismatch length similar to what's
> > done in pqTraceOutputMessage.
>
> Could you achieve the same by calling PQtrace() earlier? Perhaps switch
> to PQconnectStart() interface, and call PQtrace() right after
> PQconnectStart()?
That could be doable. However, another benefit of the PGTRACE approach
is to make tracing available in psql and make testing protocol changes
easier. With this, it should be possible to add a regression suite
using trace outputs that doesn't depend on the libpq_pipeline module.
I've also been trying to implement libpq compression, and my current
way to check the packet content is Wireshark which isn't very
practical. Which is why I've been looking into using PQtrace with psql
to make testing easier (and how I've stumbled on the BackendKeyData
issue).
> > 0004: Add tracing of cancel requests in libpq_pipeline test. Calling
> > PQuntrace on the main and monitor connections was necessary to allow
> > the cancel connections to append the cancel messages without conflict.
>
> Seems unrelated to pipelining, so perhaps this should go somewhere else.
> Then again, we already crossed that bridge when we added the
> "protocol_version" test there, which is also unrelated to pipelining.
> Maybe we should rename the test module, or add some comments noting that
> it's not just for pipelining anymore.
Given the module seems focused on testing the libpq API itself rather
than pipeline, would renaming it to test_libpq be good?
> As a side note, I find the output from pqTraceOutputNchar() awkward for
> things like the cancel key, which is raw binary bytes:
>
> > BackendKeyData 711421 'm[\x80\x95\xd6\x81{I\x8b\x04>\xab\x7fwMG\xda!\xc1\xb8\xa7\x8d\xb0.\xcd\xaa\x15\x9c\x0f\xd2\xe8\x1b'
>
> We don't need to invest too much in making the trace output pretty, but
> I think it would make sense to print that as a hex string.
Agreed. I've created a pqTraceOutputNbyte function to print a hex
string and use it for BackendKeyData and CancelRequest.
The new updated patchset has now:
0001: Create the pqTraceOutputNbyte and use it for BackendKeyData and
CancelRequest to print the backend key as hex string
0002: Additional regress masking for StartupMessage and ParameterValue
0003: Make pqtrace write line atomically. Instead of writing a line in
multiple fprintf, a line is now buffered in a PQExpBuffer and written
in a single fprintf. This is needed for 0004 and the tracing of cancel
requests.
0004: Add the PGTRACE var env to libpq. The previous version didn't
handle cancel requests correctly, as the cancel connection would open
a new fd to the trace file, truncating it while the source connection
was using it.
Now, PQcancelCreate copies the Pfdebug to the cancelConn to use it
when the cancel request is sent. As the lines are now written to
Pfdebug atomically, the source connection and cancel connection can
share the same Pfdebug.
This does make the assumption that the source connection outlives the
cancel connection to keep the Pfdebug fd opened.
0005: Switch libpq_pipeline to use PGTRACE and add the additional
startup messages to the traces
0006: Enable tracing of the cancel test in libpq_pipeline.
[0]: https://www.postgresql.org/message-id/flat/DEY0N7FS8NCU.1F7QXGG37MQ09%40jeltef.nl
Regards,
Anthonin Bonnefoy
Re: aio: Async fsyncs for crash recovery and checkpointer
Hi Nazir! Thanks for working on this. The overall direction looks promising and the patch splits are easy to follow. I reviewed the v1 series and found a few issues/questions. pg_stat_io.fsync_time no longer measures fsync wait time. In mdsyncfiletag(), the time attributed to IOOP_FSYNC is measured around FileStartSync(). With io_method=worker or io_method=io_uring, FileStartSync() generally returns after submitting the operation, before the fsync has completed. As a result, pg_stat_io.fsync_time records mostly submission overhead rather than time spent waiting for the fsync. This appears inconsistent with the documented meaning of fsync_time, which is "time spent waiting for fsync operations." It also makes the statistic method-dependent - synchronous execution includes the fsync itself, while worker and io_uring execution generally do not. A synchronous fallback under the worker method would change the semantics. Should the timing instead be accounted when completion is observed or the request is reaped? Alternatively, if asynchronous fsyncs require different accounting semantics, should those semantics be explicitly defined and documented? SLRU reopen errors terminate I/O workers and lose the original errno. sync_aio_reopen() raises ERROR if an I/O worker cannot reopen an SLRU segment. The worker’s exception-recovery path completes every reopen failure as ENOENT. An ENOENT here can be an expected race - the SLRU segment may have been truncated after the fsync was submitted but before the worker reopened it. ProcessSyncRequests() already has cancellation and FILE_POSSIBLY_DELETED() handling for this case. However, before that logic sees the result, the I/O worker has emitted an error and exited. Repeated SLRU truncation concurrent with checkpoints could therefore cause unnecessary logging and worker churn. There is also an errno-preservation issue. Failures such as EACCES, EMFILE, or EIO are delivered to the issuing process as ENOENT. The worker’s initial error report may contain the original %m , but the AIO completion result does not. The checkpointer may consequently treat the first failure as a possible deletion race and retry it, then eventually report a misleading “No such file or directory” error. Could the reopen interface return an errno for ordinary open failures instead of raising ERROR ? The worker could complete the request with -errno and continue processing. That would preserve the actual error, allow the existing cancellation/retry logic to handle ENOENT, and reserve worker termination for genuinely unexpected failures. The new worker-side SLRU target does not appear to be covered by the test. The updated test_slru_page_sync() test uses ".sync_handler = SYNC_HANDLER_NONE". That causes SlruSyncFileTag() to select PGAIO_TID_SYNC rather than PGAIO_TID_SYNC_FILETAG. Since PGAIO_TID_SYNC has no reopen callback, io_method=worker executes this request synchronously in the submitting process instead of handing it to an I/O worker. The test therefore covers the refactored local fsync path, but not the main path introduced by patch 0004. Could we add a TAP test to cover this? Best Regards, Nitin Jadhav Azure Database for PostgreSQL Microsoft
Re: aio: Async fsyncs for crash recovery and checkpointer
От:
Nazir Bilal Yavuz <byavuz81@gmail.com>
Дата:
Вложения:
Hi, Thank you for looking into this! On Thu, 3 Sept 2026 at 16:15, Yuhang Qiu wrote: > > The overall direction looks good to me. A few points: > > > This patch implements async fsyncs for crash recovery and checkpoints by > > using the AIO system. > > For crash recovery, Linux already has `recovery_init_sync_method=syncfs` as an > alternative to per-file fsyncs. I think it would be useful to include that in > the `SyncDataDirectory()` benchmark. Good point. I tested recovery_init_sync_method=syncfs and it seems it is better than or on par with fsync and AIO. Here are two different benchmark results: io_method | recovery_init_sync_method | startup (ms) | speedup -----------+---------------------------+----------------------+---------------- sync | fsync | 609.4 | 1.00x worker | fsync | 610.8 | 1.00x io_uring | fsync | 308.6 | 1.97x sync | syncfs | 210.7 | 2.89x io_method | recovery_init_sync_method | startup (ms) | speedup -----------+---------------------------+----------------------+---------------- sync | fsync | 609.2 | 1.00x worker | fsync | 610.0 | 1.00x io_uring | fsync | 211.0 | 2.89x sync | syncfs | 209.0 | 2.91x > > I will change the reopen interface so that ordinary failures return > > `-errno`. > > Agreed. I think all AIO target reopen callbacks should follow this convention. > Relation fsyncs can hit the same problem through `smgr_aio_reopen()`, not only > SLRUs. I played with that a bit but there were some problems; it was more complicated than I thought. If we want to return -errno, we lose quite a bit of error information because we don't reach the actual error message. We short-circuit these error messages to return -errno and continue without terminating the worker process. For now, ordinary reopen failures for both relation and SLRU fsyncs return -errno. This allows the checkpointer to apply its cancellation, retry, and error-handling policy without terminating the I/O worker. Read and write IO reopening retains its existing error handling. I will continue working to improve this. > > It uses both io_max_concurrency and the file descriptor budget to determine > > max number of available in-flight fsync I/Os. > > I wonder whether submitting a batch of concurrent fsyncs could cause an I/O > storm and hurt foreground I/O latency. I think this is a valid concern. With io_method=worker, fsyncs also share the worker pool with reads so that could cause a performance problems. However, I think increasing the number of worker processes should solve this problem. > The `max_safe_fds / 6` cap protects the `AllocateDesc` budget used by > `OpenTransientFile()`, while relation fsyncs use VFDs. Should the descriptor > cap apply only to handlers that use `OpenTransientFile()`? Done. Relation fsync requests now use io_max_concurrency as their limit. For handlers that hold transient descriptors in the issuingprocess, the limit is also capped at max_safe_fds / 6. Here are some additional updates compared to v1: - 0001 enables fsync on tests so CI will run tests with fsync enabled. - 0002 clears SMGR caches for the worker processes. These caches are created on the smgr_reopen path and not get destroyed later so these remain for the lifetime of worker processes. Patch clears the SMGR cache after a checkpoint and when the worker is not busy. I created another thread for this [1]. - 0005 for reopen error changes. - 0008 is for doc changes. I am still working on the tests; no tests are included yet. [1] https://postgr.es/m/CAN55FZ2BesKUnajdgpw1fPSe3S6_CHOugryaUEtD7vdP%3DdRKEQ%40mail.gmail.com -- Regards, Nazir Bilal Yavuz Microsoft
Re: aio: Async fsyncs for crash recovery and checkpointer
От:
Yuhang Qiu <iamqyh@gmail.com>
Дата:
Hi Nazir, Thanks for the comparison. The main benefit of this patch series seems to be in checkpointing rather than crash recovery, so I think further testing should focus on that. > For now, ordinary reopen failures for both relation and SLRU fsyncs > return -errno. > > Done. Relation fsync requests now use io_max_concurrency as their > limit. These two changes LGTM. > However, I think increasing the number of worker processes > should solve this problem. Increasing the worker count may help with worker availability, but it doesn't address contention for storage bandwidth. One more point: when a worker calls pg_fsync() or pg_fdatasync(), it checks its own enableFsync. If the issuer has reloaded fsync=on but the worker still has the old off value, the worker can skip the sync and report success. Should the issuer's setting or the worker's determine whether the sync is performed? Best regards, Yuhang Qiu
Re: aio: Async fsyncs for crash recovery and checkpointer
От:
Nitin Jadhav <nitinjadhavpostgres@gmail.com>
Дата:
Hi Nazir, Thanks for the updated patch set. I reviewed v2. The changes address my earlier comments about fsync timing and reopen-error handling. In particular, wait time is now accounted for when the issuer actually blocks for completion, and ordinary reopen failures preserve the errno without terminating the I/O worker. I found two further points, and the worker-side SLRU test-coverage question from v1 still appears applicable. An I/O worker can skip a required fsync after fsync is enabled. As Yuhang noted, there appears to be a race when reloading fsync from off to on. pgaio_io_start_fsync() makes the dispatch decision using the issuing process's enableFsync. Therefore, once the checkpointer has processed the new configuration and sees fsync=on, it can submit the operation to an I/O worker. However, worker execution eventually calls pg_fsync() or pg_fdatasync(). Those functions check the worker process's own enableFsync. An I/O worker can consume and execute a queued request before processing its pending configuration reload. If the worker still has the old fsync=off value, pg_fsync() returns success without issuing the syscall. The checkpointer then treats the operation as successfully completed even though the required synchronization did not occur. The unsafe direction is specifically off to on; the reverse direction can cause an unnecessary fsync but does not lose durability. Could the decision to perform the fsync be captured in the AIO operation when it is submitted, with worker execution using a syscall helper that does not re-evaluate the worker-local enableFsync value? Alternatively, the worker would need to guarantee that it has applied the relevant configuration generation before executing the request. I think this should be treated as blocking because it can allow a checkpoint to complete without executing a required fsync. Worker SMGR cleanup appears dependent on the worker becoming idle. Patch 0002 calls smgrdestroyall() only after the worker finds that no request is available. This means a continuously busy worker may never perform the cleanup. Worker-side relation reopening calls smgropen(), and those unpinned SMgrRelation objects remain in the worker's SMGR hash until smgrdestroyall() is called. With sustained I/O over many distinct relations, a worker whose queue never becomes empty could therefore retain an increasing number of SMGR entries, including entries for relations that have since been dropped. Would it be safer to check FirstCallSinceLastCheckpoint() at a safe point after completing each request, before consuming the next request, rather than only on the idle path? At that point any descriptor reopened for the completed operation has already been released. The worker-side SLRU path does not appear to have targeted test coverage. The test_slru_page_sync() still registers the test SLRU with SYNC_HANDLER_NONE. Consequently, SlruSyncFileTag() selects PGAIO_TID_SYNC, which has no reopen callback and is executed synchronously in the submitting process under io_method=worker. Best Regards, Nitin Jadhav Azure Database for PostgreSQL Microsoft
Re: aio: Async fsyncs for crash recovery and checkpointer
От:
Nazir Bilal Yavuz <byavuz81@gmail.com>
Дата:
Вложения:
Hi, On Tue, 22 Sept 2026 at 07:03, Yuhang Qiu wrote: > > Thanks for the comparison. The main benefit of this patch series seems > to be in checkpointing rather than crash recovery, so I think further > testing should focus on that. I agree. Crash recovery is useful but checkpoint's impact is much greater than that IMO. > > However, I think increasing the number of worker processes > > should solve this problem. > > Increasing the worker count may help with worker availability, but it > doesn't address contention for storage bandwidth. Could you please elaborate more on this? > One more point: when a worker calls pg_fsync() or pg_fdatasync(), it checks > its own enableFsync. If the issuer has reloaded fsync=on but the worker > still has the old off value, the worker can skip the sync and report > success. Should the issuer's setting or the worker's determine whether > the sync is performed? Nice find. I think it makes sense to use the issuing process's enableFsync. Done like that in v3-0002. -- Regards, Nazir Bilal Yavuz Microsoft
Re: aio: Async fsyncs for crash recovery and checkpointer
От:
Nazir Bilal Yavuz <byavuz81@gmail.com>
Дата:
Hi, On Tue, 22 Sept 2026 at 18:21, Nitin Jadhav wrote: > > I found two further points, and the worker-side SLRU test-coverage > question from v1 still appears applicable. > > An I/O worker can skip a required fsync after fsync is enabled. As > Yuhang noted, there appears to be a race when reloading fsync from off > to on. pgaio_io_start_fsync() makes the dispatch decision using the > issuing process's enableFsync. You are right, that is fixed in v3 [1]. I used the issuing process's enableFsync > Worker SMGR cleanup appears dependent on the worker becoming idle. > Patch 0002 calls smgrdestroyall() only after the worker finds that no > request is available. This means a continuously busy worker may never > perform the cleanup. Worker-side relation reopening calls smgropen(), > and those unpinned SMgrRelation objects remain in the worker's SMGR > hash until smgrdestroyall() is called. With sustained I/O over many > distinct relations, a worker whose queue never becomes empty could > therefore retain an increasing number of SMGR entries, including > entries for relations that have since been dropped. Would it be safer > to check FirstCallSinceLastCheckpoint() at a safe point after > completing each request, before consuming the next request, rather > than only on the idle path? At that point any descriptor reopened for > the completed operation has already been released. We have created another thread for this. Now, we have a dedicated SMGR entry limits, and the worker can't surpass this limit. For more information you can look [2], but briefly, SMGR entries can't surpass this limit when the worker is busy; they are cleaned when we reach this limit. Also, SMGR entries are cleaned before the worker goes to idle. These should solve the problem. > The worker-side SLRU path does not appear to have targeted test > coverage. The test_slru_page_sync() still registers the test SLRU with > SYNC_HANDLER_NONE. Consequently, SlruSyncFileTag() selects > PGAIO_TID_SYNC, which has no reopen callback and is executed > synchronously in the submitting process under io_method=worker. Yes, that is not tested. I will add that. [1] https://postgr.es/m/CAN55FZ2NT6529QhB_dcrZ5LaSL20aayhP33ZisZVFSg2hOqLXg%40mail.gmail.com [2] https://postgr.es/m/CAN55FZ2BesKUnajdgpw1fPSe3S6_CHOugryaUEtD7vdP%3DdRKEQ%40mail.gmail.com -- Regards, Nazir Bilal Yavuz Microsoft