postgresql.git
10 months agoMove resowner from common JitContext to LLVM specific
Heikki Linnakangas [Fri, 19 Jul 2024 07:27:06 +0000 (10:27 +0300)]
Move resowner from common JitContext to LLVM specific

Only the LLVM specific code uses it since resource owners were made
extensible in commit b8bff07daa85c837a2747b4d35cd5a27e73fb7b2. This is
new in v17, so backpatch there to keep the branches from diverging
just yet.

Author: Andreas Karlsson <[email protected]>
Discussion: https://www.postgresql.org/message-id/fd3a2a00-6605-4e30-a118-48418b478e6e@proxel.se

10 months agopostgres_fdw: Avoid "cursor can only scan forward" error.
Etsuro Fujita [Fri, 19 Jul 2024 04:15:01 +0000 (13:15 +0900)]
postgres_fdw: Avoid "cursor can only scan forward" error.

Commit d844cd75a disallowed rewind in a non-scrollable cursor to resolve
anomalies arising from such a cursor operation.  However, this failed to
take into account the assumption in postgres_fdw that when rescanning a
foreign relation, it can rewind the cursor created for scanning the
foreign relation without specifying the SCROLL option, regardless of its
scrollability, causing this error when it tried to do such a rewind in a
non-scrollable cursor.  Fix by modifying postgres_fdw to instead
recreate the cursor, regardless of its scrollability, when rescanning
the foreign relation.  (If we had a way to check its scrollability, we
could improve this by rewinding it if it is scrollable and recreating it
if not, but we do not have it, so this commit modifies it to recreate it
in any case.)

Per bug #17889 from Eric Cyr.  Devrim Gunduz also reported this problem.
Back-patch to v15 where that commit enforced the prohibition.

Reviewed by Tom Lane.

Discussion: https://postgr.es/m/17889-e8c39a251d258dda%40postgresql.org
Discussion: https://postgr.es/m/b415ac3255f8352d1ea921cf3b7ba39e0587768a.camel%40gunduz.org

10 months agoPropagate query IDs of utility statements in functions
Michael Paquier [Fri, 19 Jul 2024 01:21:21 +0000 (10:21 +0900)]
Propagate query IDs of utility statements in functions

For utility statements defined within a function, the query tree is
copied to a PlannedStmt as utility commands do not require planning.
However, the query ID was missing from the information passed down.

This leads to plugins relying on the query ID like pg_stat_statements to
not be able to track utility statements within function calls.  Tests
are added to check this behavior, depending on pg_stat_statements.track.

This is an old bug.  Now, query IDs for utilities are compiled using
their parsed trees rather than the query string since v16
(3db72ebcbe20), leading to less bloat with utilities, so backpatch down
only to this version.

Author: Anthonin Bonnefoy
Discussion: https://postgr.es/m/CAO6_XqrGp-uwBqi3vBPLuRULKkddjC7R5QZCgsFren=8E+m2Sg@mail.gmail.com
Backpatch-through: 16

10 months agoDo not summarize WAL if generated with wal_level=minimal.
Robert Haas [Thu, 18 Jul 2024 16:09:48 +0000 (12:09 -0400)]
Do not summarize WAL if generated with wal_level=minimal.

To do this, we must include the wal_level in the first WAL record
covered by each summary file; so add wal_level to struct Checkpoint
and the payload of XLOG_CHECKPOINT_REDO and XLOG_END_OF_RECOVERY.

This, in turn, requires bumping XLOG_PAGE_MAGIC and, since the
Checkpoint is also stored in the control file, also
PG_CONTROL_VERSION. It's not great to do that so late in the release
cycle, but the alternative seems to ship v17 without robust
protections against this scenario, which could result in corrupted
incremental backups.

A side effect of this patch is that, when a server with
wal_level=replica is started with summarize_wal=on for the first time,
summarization will no longer begin with the oldest WAL that still
exists in pg_wal, but rather from the first checkpoint after that.
This change should be harmless, because a WAL summary for a partial
checkpoint cycle can never make an incremental backup possible when
it would otherwise not have been.

Report by Fujii Masao. Patch by me. Review and/or testing by Jakub
Wartak and Fujii Masao.

Discussion: http://postgr.es/m/6e30082e-041b-4e31-9633-95a66de76f5d@oss.nttdata.com

10 months agoDoc: fix minor syntax error in example.
Tom Lane [Wed, 17 Jul 2024 19:17:52 +0000 (15:17 -0400)]
Doc: fix minor syntax error in example.

The CREATE TABLE option is GENERATED BY DEFAULT *AS* IDENTITY.

Per bug #18543 from Ondřej Navrátil.  Seems to have crept in
in a37bb7c13, so back-patch to v17 where that was added.

Discussion: https://postgr.es/m/18543-93c721689f9928e8@postgresql.org

10 months agoUse PqMsg_* macros in more places.
Nathan Bossart [Wed, 17 Jul 2024 15:51:00 +0000 (10:51 -0500)]
Use PqMsg_* macros in more places.

Commit f4b54e1ed9, which introduced macros for protocol characters,
missed updating a few places.  It also did not introduce macros for
messages sent from parallel workers to their leader processes.
This commit adds a new section in protocol.h for those.

Author: Aleksander Alekseev
Discussion: https://postgr.es/m/CAJ7c6TNTd09AZq8tGaHS3LDyH_CCnpv0oOz2wN1dGe8zekxrdQ%40mail.gmail.com
Backpatch-through: 17

10 months agoAvoid error in recovery test if history file is not yet present
Andrew Dunstan [Wed, 17 Jul 2024 14:35:50 +0000 (10:35 -0400)]
Avoid error in recovery test if history file is not yet present

Error was detected when testing use of libpq sessions instead of psql
for polling queries.

Discussion: https://postgr.es/m/e86b6d2d-20d8-4ac9-9a98-165fff7db886@dunslane.net

Backpatch to all live branches

10 months agoSQL/JSON: Rethink c2d93c3802b
Amit Langote [Wed, 17 Jul 2024 08:10:57 +0000 (17:10 +0900)]
SQL/JSON: Rethink c2d93c3802b

This essentially reverts c2d93c3802b except tests. The problem with
c2d93c3802b was that it only changed the casting behavior for types
with typmod, and had coding issues noted in the post-commit review.

This commit changes coerceJsonFuncExpr() to use assignment-level casts
instead of explicit casts to coerce the result of JSON constructor
functions to the specified or the default RETURNING type.  Using
assignment-level casts fixes the problem that using explicit casts was
leading to the wrong typmod / length coercion behavior -- truncating
results longer than the specified length instead of erroring out --
which c2d93c3802b aimed to solve.

That restricts the set of allowed target types to string types, the
same set that's currently allowed.

Discussion: https://postgr.es/m/202406291824[email protected]

10 months agoWhen creating materialized views, use REFRESH to load data.
Jeff Davis [Tue, 16 Jul 2024 22:41:22 +0000 (15:41 -0700)]
When creating materialized views, use REFRESH to load data.

Previously, CREATE MATERIALIZED VIEW ... WITH DATA populated the MV
the same way as CREATE TABLE ... AS.

Instead, reuse the REFRESH logic, which locks down security-restricted
operations and restricts the search_path. This reduces the chance that
a subsequent refresh will fail.

Reported-by: Noah Misch
Backpatch-through: 17
Discussion: https://postgr.es/m/20240630222344[email protected]

10 months agoSQL/JSON: Fix a paragraph in JSON_TABLE documentation
Amit Langote [Tue, 16 Jul 2024 05:11:10 +0000 (14:11 +0900)]
SQL/JSON: Fix a paragraph in JSON_TABLE documentation

Using <replaceable>text</replaceable> inside parantheses is not a
common or good style, so rephrase a sentence to avoid that style.
Also rephrase the text in that paragraph a bit while at it.

Reported-by: Marcos Pegoraro <[email protected]>
Author: Jian He <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/CAB-JLwZqH3Yec6Kz-4-+pa0ZG9QJBsxjJZwYcMZYzEDR_fXnKw@mail.gmail.com

10 months agoFix bad indentation introduced in 43cd30bcd1c
Andres Freund [Mon, 15 Jul 2024 22:17:37 +0000 (15:17 -0700)]
Fix bad indentation introduced in 43cd30bcd1c

Oops.

Reported-by: Nathan Bossart <[email protected]>
Discussion: https://postgr.es/m/ZpVZB9rH5tHllO75@nathan
Backpatch: 12-, like 43cd30bcd1c

10 months agoAdd missing RestrictSearchPath() calls.
Jeff Davis [Mon, 15 Jul 2024 19:08:00 +0000 (12:08 -0700)]
Add missing RestrictSearchPath() calls.

Reported-by: Noah Misch
Backpatch-through: 17
Discussion: https://postgr.es/m/20240630222344[email protected]

10 months agoci: Upgrade to Debian Bookworm
Andres Freund [Mon, 15 Jul 2024 16:26:01 +0000 (09:26 -0700)]
ci: Upgrade to Debian Bookworm

Bullseye is getting long in the tooth, upgrade to the current stable version.

Backpatch to all versions with CI support, we don't want to generate CI images
for multiple Debian versions.

Author: Nazir Bilal Yavuz <[email protected]>
Discussion: https://postgr.es/m/CAN55FZ0fY5EFHXLKCO_%3Dp4pwFmHRoVom_qSE_7B48gpchfAqzw%40mail.gmail.com
Backpatch: 15-, where CI was added

10 months agoFix type confusion in guc_var_compare()
Andres Freund [Mon, 15 Jul 2024 16:26:01 +0000 (09:26 -0700)]
Fix type confusion in guc_var_compare()

Before this change guc_var_compare() cast the input arguments to
const struct config_generic *.  That's not quite right however, as the input
on one side is often just a char * on one side.

Instead just use char *, the first field in config_generic.

This fixes a -Warray-bounds warning with some versions of gcc. While the
warning is only known to be triggered for <= 15, the issue the warning points
out seems real, so apply the fix everywhere.

Author: Nazir Bilal Yavuz <[email protected]>
Reported-by: Erik Rijkers <[email protected]>
Suggested-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/a74a1a0d-0fd2-3649-5224-4f754e8f91aa%40xs4all.nl

10 months agoDoc: minor improvements for plpgsql "Transaction Management" section.
Tom Lane [Mon, 15 Jul 2024 15:59:43 +0000 (11:59 -0400)]
Doc: minor improvements for plpgsql "Transaction Management" section.

Point out that savepoint commands cannot be issued in PL/pgSQL,
and suggest that exception blocks can usually be used instead.

Add a caveat to the discussion of cursor loops vs. transactions,
pointing out that any locks taken by the cursor query will be lost
at COMMIT.  This is implicit in what's already said, but the existing
text leaves the distinct impression that the auto-hold behavior is
transparent, which it's not really.

Per a couple of recent complaints (one unsigned, and one in bug #18531
from Dzmitry Jachnik).  Back-patch to v17, just so this makes it into
current docs in less than a year-and-a-half.

Discussion: https://postgr.es/m/172076354433.736586.14347210271966220018@wrigleys.postgresql.org
Discussion: https://postgr.es/m/18531-c6dddd33b8555fd2@postgresql.org

10 months agoUse atomics to avoid locking in InjectionPointRun()
Heikki Linnakangas [Mon, 15 Jul 2024 07:21:16 +0000 (10:21 +0300)]
Use atomics to avoid locking in InjectionPointRun()

This allows using injection points without having a PGPROC, like early
at backend startup, or in the postmaster.

The injection points facility is new in v17, so backpatch there.

Reviewed-by: Michael Paquier <[email protected]>
Disussion: https://www.postgresql.org/message-id/4317a7f7-8d24-435e-9e49-29b72a3dc418@iki.fi

10 months agoFix unstable tests in partition_merge.sql and partition_split.sql.
Fujii Masao [Mon, 15 Jul 2024 05:09:30 +0000 (14:09 +0900)]
Fix unstable tests in partition_merge.sql and partition_split.sql.

The tests added by commit c086896625 were unstable due to
missing schema names when checking pg_tables and pg_indexes.

Backpatch to v17.

Reported by buildfarm.

10 months agoFix tablespace handling in MERGE/SPLIT partition commands.
Fujii Masao [Mon, 15 Jul 2024 04:11:51 +0000 (13:11 +0900)]
Fix tablespace handling in MERGE/SPLIT partition commands.

As commit ca4103025d stated, new partitions without a specified tablespace
should inherit the parent relation's tablespace. However, previously,
ALTER TABLE MERGE PARTITIONS and ALTER TABLE SPLIT PARTITION commands
always created new partitions in the default tablespace, ignoring
the parent's tablespace. This commit ensures new partitions inherit
the parent's tablespace.

Backpatch to v17 where these commands were introduced.

Author: Fujii Masao
Reviewed-by: Masahiko Sawada
Discussion: https://postgr.es/m/abaf390b-3320-40a5-8815-ef476db5cfe7@oss.nttdata.com

10 months agoAvoid unhelpful internal error for incorrect recursive-WITH queries.
Tom Lane [Sun, 14 Jul 2024 17:49:46 +0000 (13:49 -0400)]
Avoid unhelpful internal error for incorrect recursive-WITH queries.

checkWellFormedRecursion would issue "missing recursive reference"
if a WITH RECURSIVE query contained a single self-reference but
that self-reference was inside a top-level WITH, ORDER BY, LIMIT,
etc, rather than inside the second arm of the UNION as expected.
We already intended to throw more-on-point errors for such cases,
but those error checks must be done before examining the UNION arm
in order to have the desired results.  So this patch need only
move some code (and improve the comments).

Per bug #18536 from Alexander Lakhin.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18536-0a342ec07901203e@postgresql.org

10 months agoUse correct collate.windows.win1252.out
Andrew Dunstan [Sat, 13 Jul 2024 20:19:10 +0000 (16:19 -0400)]
Use correct collate.windows.win1252.out

I inadvertently missed backporting this to Release 17 from commit 291c420747

per offlist reminder from Alexander Lakhin.

10 months agoFix new assertion for MERGE view_name ... DO NOTHING.
Noah Misch [Sat, 13 Jul 2024 15:09:33 +0000 (08:09 -0700)]
Fix new assertion for MERGE view_name ... DO NOTHING.

Such queries don't expand automatically updatable views, and ModifyTable
uses the wholerow attribute unconditionally.  The user-visible behavior
is fine, so change to more-specific assertions.  Commit
d5f788b41dc2cbdde6e7694c70dda54d829a5ed5 added the wrong assertion.
Back-patch to v17, where commit 5f2e179bd31e5f5803005101eb12a8d7bf8db8f3
introduced MERGE view_name.

Reported by Alexander Lakhin.

Discussion: https://postgr.es/m/e4b40a88-c134-6926-3196-bc4501cb87a2@gmail.com

10 months agoDon't lose partitioned table reltuples=0 after relhassubclass=f.
Noah Misch [Sat, 13 Jul 2024 15:09:33 +0000 (08:09 -0700)]
Don't lose partitioned table reltuples=0 after relhassubclass=f.

ANALYZE sets relhassubclass=f when a partitioned table no longer has
partitions.  An ANALYZE doing that proceeded to apply the inplace update
of pg_class.reltuples to the old pg_class tuple instead of the new
tuple, losing that reltuples=0 change if the ANALYZE committed.
Non-partitioning inheritance trees were unaffected.  Back-patch to v14,
where commit 375aed36ad83f0e021e9bdd3a0034c0c992c66dc introduced
maintenance of partitioned table pg_class.reltuples.

Reported by Alexander Lakhin.

Discussion: https://postgr.es/m/a295b499-dcab-6a99-c06e-01cf60593344@gmail.com

10 months agoMake sure to run pg_isready on correct port
Andrew Dunstan [Fri, 12 Jul 2024 22:29:15 +0000 (18:29 -0400)]
Make sure to run pg_isready on correct port

The current code can have pg_isready unexpectedly succeed if there is a
server running on the default port. To avoid this we delay running the
test until after a node has been created but before it starts, and then
use that node's port, so we are fairly sure there is nothing running on
the port.

Backpatch to all live branches.

10 months agoFix lost Windows socket EOF events.
Thomas Munro [Sat, 13 Jul 2024 02:59:46 +0000 (14:59 +1200)]
Fix lost Windows socket EOF events.

Winsock only signals an FD_CLOSE event once if the other end of the
socket shuts down gracefully.  Because each WaitLatchOrSocket() call
constructs and destroys a new event handle every time, with unlucky
timing we can lose it and hang.  We get away with this only if the other
end disconnects non-gracefully, because FD_CLOSE is repeatedly signaled
in that case.

To fix this design flaw in our Windows socket support fundamentally,
we'd probably need to rearchitect it so that a single event handle
exists for the lifetime of a socket, or switch to completely different
multiplexing or async I/O APIs.  That's going to be a bigger job
and probably wouldn't be back-patchable.

This brute force kludge closes the race by explicitly polling with
MSG_PEEK before sleeping.

Back-patch to all supported releases.  This should hopefully clear up
some random build farm and CI hang failures reported over the years.  It
might also allow us to try using graceful shutdown in more places again
(reverted in commit 29992a6) to fix instability in the transmission of
FATAL error messages, but that isn't done by this commit.

Reported-by: Tom Lane <[email protected]>
Tested-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/176008.1715492071%40sss.pgh.pa.us

10 months agoAdd ORDER BY to new test query
Alvaro Herrera [Fri, 12 Jul 2024 11:44:19 +0000 (13:44 +0200)]
Add ORDER BY to new test query

Per buildfarm.

10 months agoFix ALTER TABLE DETACH for inconsistent indexes
Alvaro Herrera [Fri, 12 Jul 2024 10:54:01 +0000 (12:54 +0200)]
Fix ALTER TABLE DETACH for inconsistent indexes

When a partitioned table has an index that doesn't support a constraint,
but a partition has an equivalent index that does, then a DETACH
operation would misbehave: a crash in assertion-enabled systems (because
we fail to find the constraint in the parent that we expect to), or a
broken coninhcount value (-1) in production systems (because we blindly
believe that we've successfully detached the parent).

While we should reject an ATTACH of a partition with such an index, we
have failed to do so in existing releases, so adding an error in stable
releases might break the (unlikely) existing applications that rely on
this behavior.  At this point I don't even want to reject them in
master, because it'd break pg_upgrade if such databases exist, and there
would be no easy way to fix existing databases without expensive index
rebuilds.

(Later on we could add ALTER TABLE ... ADD CONSTRAINT USING INDEX to
partitioned tables, which would allow the user to fix such patterns.  At
that point we could add more restrictions to prevent the problem from
its root.)

Also, add a test case that leaves one table in this condition, so that
we can verify that pg_upgrade continues to work if we later decide to
change the policy on the master branch.

Backpatch to all supported branches.

Co-authored-by: Tender Wang <[email protected]>
Reported-by: Alexander Lakhin <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Reviewed-by: Michael Paquier <[email protected]>
Discussion: https://postgr.es/m/18500-62948b6fe5522f56@postgresql.org

10 months agoFix unstable test in 040_pg_createsubscriber.
Amit Kapila [Fri, 12 Jul 2024 04:05:46 +0000 (09:35 +0530)]
Fix unstable test in 040_pg_createsubscriber.

The slot synchronization failed because the local slot's (created during
slot synchronization) catalog_xmin on standby is ahead of remote slot.
This happens because the INSERT before slot synchronization results in the
generation of a new xid that could be replicated to the standby. Now
before the xmin of the physical slot on the primary catches up via
hot_standby_feedback, the test has created a logical slot that got some
prior value of catalog_xmin.

To fix this we could try to ensure that the physical slot's catalog_xmin
is caught up to latest value before creating a logical slot but we took a
simpler path to move the INSERT after synchronizing the logical slot.

Reported-by: Alexander Lakhin as per buildfarm
Diagnosed-by: Amit Kapila, Hou Zhijie, Alexander Lakhin
Author: Hou Zhijie
Backpatch-through: 17
Discussion: https://postgr.es/m/bde6ac67-69cc-c104-5ab6-dd4f5deadf24@gmail.com

10 months agoFix possibility of logical decoding partial transaction changes.
Masahiko Sawada [Thu, 11 Jul 2024 13:48:21 +0000 (22:48 +0900)]
Fix possibility of logical decoding partial transaction changes.

When creating and initializing a logical slot, the restart_lsn is set
to the latest WAL insertion point (or the latest replay point on
standbys). Subsequently, WAL records are decoded from that point to
find the start point for extracting changes in the
DecodingContextFindStartpoint() function. Since the initial
restart_lsn could be in the middle of a transaction, the start point
must be a consistent point where we won't see the data for partial
transactions.

Previously, when not building a full snapshot, serialized snapshots
were restored, and the SnapBuild jumps to the consistent state even
while finding the start point. Consequently, the slot's restart_lsn
and confirmed_flush could be set to the middle of a transaction. This
could lead to various unexpected consequences. Specifically, there
were reports of logical decoding decoding partial transactions, and
assertion failures occurred because only subtransactions were decoded
without decoding their top-level transaction until decoding the commit
record.

To resolve this issue, the changes prevent restoring the serialized
snapshot and jumping to the consistent state while finding the start
point.

On v17 and HEAD, a flag indicating whether snapshot restores should be
skipped has been added to the SnapBuild struct, and SNAPBUILD_VERSION
has been bumpded.

On backbranches, the flag is stored in the LogicalDecodingContext
instead, preserving on-disk compatibility.

Backpatch to all supported versions.

Reported-by: Drew Callahan
Reviewed-by: Amit Kapila, Hayato Kuroda
Discussion: https://postgr.es/m/2444AA15-D21B-4CCE-8052-52C7C2DAFE5C%40amazon.com
Backpatch-through: 12

10 months agoMake our back branches compatible with libxml2 2.13.x.
Tom Lane [Thu, 11 Jul 2024 00:15:52 +0000 (20:15 -0400)]
Make our back branches compatible with libxml2 2.13.x.

This back-patches HEAD commits 066e8ac6e6082b3d5de7192486d,
and 896cd266f into supported branches.  Changes:

* Use xmlAddChildList not xmlAddChild in XMLSERIALIZE
(affects v16 and up only).  This was a flat-out coding mistake
that we got away with due to lax checking in previous versions
of xmlAddChild.

* Use xmlParseInNodeContext not xmlParseBalancedChunkMemory.
This is to dodge a bug in xmlParseBalancedChunkMemory in libxm2
releases 2.13.0-2.13.2.  While that bug is now fixed upstream and
will probably never be seen in any production-oriented distro, it is
currently a problem on some more-bleeding-edge-friendly platforms.

* Suppress "chunk is not well balanced" errors from libxml2,
unless it is the only error.  This eliminates an error-reporting
discrepancy between 2.13 and older releases.  This error is
almost always redundant with previous errors, if not flat-out
inappropriate, which is why 2.13 changed the behavior and why
nobody's likely to miss it.

Erik Wienhold and Tom Lane, per report from Frank Streitzig.

Discussion: https://postgr.es/m/trinity-b0161630-d230-4598-9ebc-7a23acdb37cb-1720186432160@3c-app-gmx-bap25
Discussion: https://postgr.es/m/trinity-361ba18b-541a-4fe7-bc63-655ae3a7d599-1720259822452@3c-app-gmx-bs01

10 months agoUse diff's --strip-trailing-cr flag where appropriate on Windows
Andrew Dunstan [Wed, 10 Jul 2024 13:53:47 +0000 (09:53 -0400)]
Use diff's --strip-trailing-cr flag where appropriate on Windows

Test result files might be checked out using Unix or Windows style line
endings, depening on git flags, so on Windows we use the
--strip-trailing-cr flag to tell diff to ignore line endings
differences.

The flag is added to the diff invocation for the test_json_parser module
tests and the pg_bsd_indent tests. in pg_regress.c we replace the
current use of the "-w" flag, which ignore all white space differences,
with this one which only ignores line end differences.

Discussion: https://postgr.es/m/20240707052030[email protected]

10 months agodoc: Update track_io_timing documentation to mention pg_stat_io.
Fujii Masao [Wed, 10 Jul 2024 06:56:07 +0000 (15:56 +0900)]
doc: Update track_io_timing documentation to mention pg_stat_io.

The I/O timing information collected when track_io_timing is
enabled is now documented to appear in the pg_stat_io view,
which was previously not mentioned.

This commit also enhances the description of track_io_timing
to clarify that it monitors not only block read and write
but also block extend and fsync operations. Additionally,
the description of track_wal_io_timing has been improved
to mention both WAL write and WAL fsync monitoring.

Backpatch to v16 where pg_stat_io was added.

Author: Hajime Matsunaga
Reviewed-by: Melanie Plageman, Nazir Bilal Yavuz, Fujii Masao
Discussion: https://postgr.es/m/TYWPR01MB10742EE4A6F34C33061429D38A4D52@TYWPR01MB10742.jpnprd01.prod.outlook.com

10 months agoPrevent CRLF conversion of inputs in json_parser test module
Andrew Dunstan [Tue, 9 Jul 2024 21:29:48 +0000 (17:29 -0400)]
Prevent CRLF conversion of inputs in json_parser test module

Do this by opening the file in PG_BINARY_R mode. This prevents us from
getting wrong byte count from stat().

Per complaint from Andres Freund

Discussion: https://postgr.es/m/20240707052030[email protected]

Backpatch to rlease 17 where this code was introduced

10 months agoFix missing invalidations for search_path cache.
Jeff Davis [Tue, 9 Jul 2024 18:27:10 +0000 (11:27 -0700)]
Fix missing invalidations for search_path cache.

Reported-by: Noah Misch
Discussion: https://postgr.es/m/20240630223047[email protected]
Backpatch-through: 17

10 months agoSQL/JSON: Various improvements to SQL/JSON query function docs
Amit Langote [Tue, 9 Jul 2024 07:12:22 +0000 (16:12 +0900)]
SQL/JSON: Various improvements to SQL/JSON query function docs

1. Remove the keyword SELECT from the examples to be consistent
with the examples of other JSON-related functions listed on the
same page.

2. Add <synopsis> tags around the functions' syntax definition

3. Capitalize function names in the syntax synopsis and the examples

4. Use <itemizedlist> lists for dividing the descriptions of
   individual functions into bullet points

5. Significantly rewrite the description of wrapper clauses of
   JSON_QUERY

6. Significantly rewrite the descriptions of ON ERROR / EMPTY
   clauses of JSON_QUERY() and JSON_VALUE() functions

7. Add a note about how JSON_VALUE() and JSON_QUERY() differ when
   returning a JSON null result

8. Move the description of the PASSING clause from the descriptions
   of individual functions into the top paragraph

And other miscellaneous text improvements, typo fixes.

Suggested-by: Thom Brown <[email protected]>
Suggested-by: David G. Johnston <[email protected]>
Reviewed-by: Jian He <[email protected]>
Reviewed-by: Erik Rijkers <[email protected]>
Discussion: https://postgr.es/m/CAA-aLv7Dfy9BMrhUZ1skcg=OdqysWKzObS7XiDXdotJNF0E44Q@mail.gmail.com
Discussion: https://postgr.es/m/CAKFQuwZNxNHuPk44zDF7z8qZec1Aof10aA9tWvBU5CMhEKEd8A@mail.gmail.com

10 months agoFix limit block handling in pg_wal_summary_contents().
Fujii Masao [Tue, 9 Jul 2024 00:26:54 +0000 (09:26 +0900)]
Fix limit block handling in pg_wal_summary_contents().

Previously, pg_wal_summary_contents() had two issues,
causing discrepancies between pg_wal_summary_contents()
and the pg_walsummary command on the same WAL summary file:

(1) It did not emit the limit block when that's the only data for
     a particular relation fork.
(2) It emitted the same limit block multiple times if the list of
     block numbers was long enough.

This commit fixes these issues.

Backpatch to v17 where pg_wal_summary_contents() was added.

Author: Fujii Masao
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/90980ee6-2da6-42f6-a7b0-b7bae62ae279@oss.nttdata.com

10 months agoSymlink pg_replslot robustly on Windows in pg_basebackup test
Andrew Dunstan [Mon, 8 Jul 2024 17:46:21 +0000 (13:46 -0400)]
Symlink pg_replslot robustly on Windows in pg_basebackup test

This reverts commit e9f15bc9. Instead of a hacky solution that didn't
work on Windows, we avoid trying to move the directory possibly across
drives, and instead remove it and recreate it in the new location.

Discussion: https://postgr.es/m/20240707070243[email protected]

Backpatch to release 14 like the previous patch.

10 months agoChoose ports for test servers less likely to result in conflicts
Andrew Dunstan [Mon, 8 Jul 2024 15:18:06 +0000 (11:18 -0400)]
Choose ports for test servers less likely to result in conflicts

If we choose ports in the range typically used for ephemeral ports there
is a danger of encountering a port conflict due to a race condition
between the time we choose the port in a range below that typically used
to allocate ephemeral ports, but higher than the range typically used by
well known services.

Author: Jelte Fenema-Nio, with some editing by me.

Discussion: https://postgr.es/m/d6ee8761-39d1-0033-1afb-d5a57ee056f2@gmail.com

Backpatch to all live branches (12 and up)

10 months agoForce nodes for SSL tests to start in TCP mode
Andrew Dunstan [Mon, 8 Jul 2024 09:51:26 +0000 (05:51 -0400)]
Force nodes for SSL tests to start in TCP mode

Currently they are started in unix socket mode in ost cases, and then
converted to run in TCP mode. This can result in port collisions, and
there is no virtue in startng in unix socket mode, so start as we will
be going on.

Discussion: https://postgr.es/m/d6ee8761-39d1-0033-1afb-d5a57ee056f2@gmail.com

Backpatch to all live branches (12 and up).

10 months agoFix scale clamping in numeric round() and trunc().
Dean Rasheed [Mon, 8 Jul 2024 16:51:23 +0000 (17:51 +0100)]
Fix scale clamping in numeric round() and trunc().

The numeric round() and trunc() functions clamp the scale argument to
the range between +/- NUMERIC_MAX_RESULT_SCALE (2000), which is much
smaller than the actual allowed range of type numeric. As a result,
they return incorrect results when asked to round/truncate more than
2000 digits before or after the decimal point.

Fix by using the correct upper and lower scale limits based on the
actual allowed (and documented) range of type numeric.

While at it, use the new NUMERIC_WEIGHT_MAX constant instead of
SHRT_MAX in all other overflow checks, and fix a comment thinko in
power_var() introduced by e54a758d24 -- the minimum value of
ln_dweight is -NUMERIC_DSCALE_MAX (-16383), not -SHRT_MAX, though this
doesn't affect the point being made in the comment, that the resulting
local_rscale value may exceed NUMERIC_MAX_DISPLAY_SCALE (1000).

Back-patch to all supported branches.

Dean Rasheed, reviewed by Joel Jacobson.

Discussion: https://postgr.es/m/CAEZATCXB%2BrDTuMjhK5ZxcouufigSc-X4tGJCBTMpZ3n%3DxxQuhg%40mail.gmail.com

10 months agoTypo fix
Amit Langote [Mon, 8 Jul 2024 13:11:57 +0000 (22:11 +0900)]
Typo fix

Reported-by: Junwang Zhao <[email protected]>
Discussion: https://postgr.es/m/CAEG8a3KPi=LayiTwJ11ikF7bcqnZUrcj8NgX0V8nO1mQKZ9GfQ@mail.gmail.com
Backpatch-through: 17

10 months agoFix outdated comment after removal of direct SSL fallback
Heikki Linnakangas [Mon, 8 Jul 2024 09:44:45 +0000 (12:44 +0300)]
Fix outdated comment after removal of direct SSL fallback

The option to fall back from direct SSL to negotiated SSL or a
plaintext connection was removed in commit fb5718f35f.

Discussion: https://www.postgresql.org/message-id/c82ad227-e049-4e18-8898-475a748b5a5a@iki.fi

10 months agoFix right-anti-joins when the inner relation is proven unique
Richard Guo [Mon, 8 Jul 2024 01:17:12 +0000 (10:17 +0900)]
Fix right-anti-joins when the inner relation is proven unique

For an inner_unique join, we always assume that the executor will stop
scanning for matches after the first match.  Therefore, for a mergejoin
that is inner_unique and whose mergeclauses are sufficient to identify a
match, we set the skip_mark_restore flag to true, indicating that the
executor need not do mark/restore calls.  However, merge-right-anti-join
did not get this memo and continues scanning the inner side for matches
after the first match.  If there are duplicates in the outer scan, we
may incorrectly skip matching some inner tuples, which can lead to wrong
results.

Here we fix this issue by ensuring that merge-right-anti-join also
advances to next outer tuple after the first match in inner_unique
cases.  This also saves cycles by avoiding unnecessary scanning of inner
tuples after the first match.

Although hash-right-anti-join does not suffer from this wrong results
issue, we apply the same change to it as well, to help save cycles for
the same reason.

Per bug #18522 from Antti Lampinen, and bug #18526 from Feliphe Pozzer.
Back-patch to v16 where right-anti-join was introduced.

Author: Richard Guo
Discussion: https://postgr.es/m/18522-c7a8956126afdfd0@postgresql.org

10 months agoRe-enable autoruns for for cmd.exe on Windows
Michael Paquier [Mon, 8 Jul 2024 00:35:10 +0000 (09:35 +0900)]
Re-enable autoruns for for cmd.exe on Windows

This acts as a revert of b83747a8a65b and 9886744a361b.  As pointed out
by Noah, HEAD and REL_17_STABLE are in a weird state where the code
paths adding /D would limit the spawn of child processes, but we still
have code paths where the spawn of more than one child process would be
possible.

Let's remove these /D switches for now, to bring back the code into a
state consistent with how autorun is configured on a Windows host.

Reported-by: Noah Misch
Discussion: https://postgr.es/m/20240630021211[email protected]
Backpatch-through: 17

10 months agoFix incorrect sentinel byte logic in GenerationRealloc()
David Rowley [Sat, 6 Jul 2024 02:00:06 +0000 (14:00 +1200)]
Fix incorrect sentinel byte logic in GenerationRealloc()

This only affects MEMORY_CONTEXT_CHECKING builds.

This fixes an off-by-one issue in GenerationRealloc() where the
fast-path code which tries to reuse the existing allocation if the
existing chunk is >= the new requested size.  The code there thought it
was always ok to use the existing chunk, but when oldsize == size there
isn't enough space to store the sentinel byte.  If both sizes matched
exactly set_sentinel() would overwrite the first byte beyond the chunk
and then subsequent GenerationRealloc() calls could then fail the
Assert(chunk->requested_size < oldsize) check which is trying to ensure
the chunk is large enough to store the sentinel.

The same issue does not exist in aset.c as the sentinel checking code
only adds a sentinel byte if there's enough space in the chunk.

Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/49275921-7b39-41af-5eb8-97b50ce3312e@gmail.com
Backpatch-through: 16, where the problem was introduced by 0e480385e

10 months agoCope with <regex.h> name clashes.
Thomas Munro [Fri, 5 Jul 2024 22:24:49 +0000 (10:24 +1200)]
Cope with <regex.h> name clashes.

macOS 15's SDK pulls in headers related to <regex.h> when we include
<xlocale.h>.  This causes our own regex_t implementation to clash with
the OS's regex_t implementation.  Luckily our function names already had
pg_ prefixes, but the macros and typenames did not.

Include <regex.h> explicitly on all POSIX systems, and fix everything
that breaks.  Then we can prove that we are capable of fully hiding and
replacing the system regex API with our own.

1.  Deal with standard-clobbering macros by undefining them all first.
POSIX says they are "symbolic constants".  If they are macros, this
allows us to redefine them.  If they are enums or variables, our macros
will hide them.

2.  Deal with standard-clobbering types by giving our types pg_
prefixes, and then using macros to redirect xxx_t -> pg_xxx_t.

After including our "regex/regex.h", the system <regex.h> is hidden,
because we've replaced all the standard names.  The PostgreSQL source
tree and extensions can continue to use standard prefix-less type and
macro names, but reach our implementation, if they included our
"regex/regex.h" header.

Back-patch to all supported branches, so that macOS 15's tool chain can
build them.

Reported-by: Stan Hu <[email protected]>
Suggested-by: Tom Lane <[email protected]>
Tested-by: Aleksander Alekseev <[email protected]>
Discussion: https://postgr.es/m/CAMBWrQnEwEJtgOv7EUNsXmFw2Ub4p5P%2B5QTBEgYwiyjy7rAsEQ%40mail.gmail.com

10 months agodoc PG 17 relnotes: fix psql connection cancelation item
Bruce Momjian [Fri, 5 Jul 2024 20:51:56 +0000 (16:51 -0400)]
doc PG 17 relnotes:  fix psql connection cancelation item

Reported-by: Matthias van de Meent
Discussion: https://postgr.es/m/CAEze2WiprrENrFQqeXij2XyLAdoZaFTFLGC8sE=V8c1yrWn+2A@mail.gmail.com

Backpatch-through: 17 only

10 months agoDoc: small improvements in discussion of geometric data types.
Tom Lane [Thu, 4 Jul 2024 17:23:32 +0000 (13:23 -0400)]
Doc: small improvements in discussion of geometric data types.

State explicitly that the coordinates in our geometric data types are
float8.  Also explain that polygons store their bounding box.

While here, fix the table of geometric data types to show type
"line"'s size correctly: it's 24 bytes not 32.  This has somehow
escaped notice since that table was made in 1998.

Per suggestion from Sebastian Skałacki.  The size error seems
important enough to justify back-patching.

Discussion: https://postgr.es/m/172000045661.706.1822177575291548794@wrigleys.postgresql.org

10 months agoFix copy/paste mistake in comment
Alvaro Herrera [Thu, 4 Jul 2024 11:57:47 +0000 (13:57 +0200)]
Fix copy/paste mistake in comment

Backpatch to 17

Author: Yugo NAGATA <[email protected]>
Discussion: https://postgr.es/m/20240704134638.355ad44a445fa1e764a220cd@sranhm.sraoss.co.jp

10 months agoRemove bogus assertion in pg_atomic_monotonic_advance_u64
Alvaro Herrera [Thu, 4 Jul 2024 11:25:31 +0000 (13:25 +0200)]
Remove bogus assertion in pg_atomic_monotonic_advance_u64

This code wanted to ensure that the 'exchange' variable passed to
pg_atomic_compare_exchange_u64 has correct alignment, but apparently
platforms don't actually require anything that doesn't come naturally.

While messing with pg_atomic_monotonic_advance_u64: instead of using
Max() to determine the value to return, just use
pg_atomic_compare_exchange_u64()'s return value to decide; also, use
pg_atomic_compare_exchange_u64 instead of the _impl version; also remove
the unnecessary underscore at the end of variable name "target".

Backpatch to 17, where this code was introduced by commit bf3ff7bf83bc.

Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/36796438-a718-cf9b-2071-b2c1b947c1b5@gmail.com

10 months agodoc: Specify when ssl_prefer_server_ciphers was added
Daniel Gustafsson [Thu, 4 Jul 2024 10:10:12 +0000 (12:10 +0200)]
doc: Specify when ssl_prefer_server_ciphers was added

The ssl_prefer_server_ciphers setting is quite important from a
security point of view, so simply stating that older versions
doesn't have it isn't very helpful.  This adds the version when
the GUC was added to help readers.

Backpatch to all supported versions since this setting has been
around since 9.4.

Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/5D7E0F5E-E620-4D54-8788-66D421AC76F0@yesql.se
Backpatch-through: v12

10 months agoSQL/JSON: Fix some obsolete comments.
Amit Langote [Fri, 28 Jun 2024 06:09:59 +0000 (15:09 +0900)]
SQL/JSON: Fix some obsolete comments.

JSON_OBJECT(), JSON_OBJETAGG(), JSON_ARRAY(), and JSON_ARRAYAGG()
added in 7081ac46ace are not transformed into direct calls to
user-defined functions as the comments claim. Fix by mentioning
instead that they are transformed into JsonConstructorExpr nodes,
which may call them, for example, for the *AGG() functions.

Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/058c856a-e090-ac42-ff00-ffe394f52a87%40gmail.com
Backpatch-through: 16

10 months agoFix typo in GetRunningTransactionData()
Alexander Korotkov [Wed, 3 Jul 2024 23:05:27 +0000 (02:05 +0300)]
Fix typo in GetRunningTransactionData()

e85662df44 made GetRunningTransactionData() calculate the oldest running
transaction id within the current database.  However, because of the typo,
the new code uses oldestRunningXid instead of oldestDatabaseRunningXid
in comparison before updating oldestDatabaseRunningXid.  This commit fixes
that issue.

Reported-by: Noah Misch
Discussion: https://postgr.es/m/20240630231816.bf.nmisch%40google.com
Backpatch-through: 17

10 months agoAvoid 0-length memcpy to NULL with EXEC_BACKEND
Heikki Linnakangas [Wed, 3 Jul 2024 12:58:14 +0000 (15:58 +0300)]
Avoid 0-length memcpy to NULL with EXEC_BACKEND

memcpy(NULL, src, 0) is forbidden by POSIX, even though every
production version of libc allows it. Let's be tidy.

Per report from Thomas Munro, running UBSan with EXEC_BACKEND.
Backpatch to v17, where this code was added.

Discussion: https://www.postgresql.org/message-id/CA%2BhUKG%2Be-dV7YWBzfBZXsgovgRuX5VmvmOT%[email protected]

10 months agoTighten check for --forkchild argument when spawning child process
Heikki Linnakangas [Wed, 3 Jul 2024 12:53:30 +0000 (15:53 +0300)]
Tighten check for --forkchild argument when spawning child process

Commit aafc05de1b removed all the other --fork* arguments. Altough
this is inconsequential, backpatch to v17 since this is new.

Author: Nathan Bossart
Discussion: https://www.postgresql.org/message-id/ZnCCEN0l3qWv-XpW@nathan

10 months agoFix the testcase introduced in commit 81d20fbf7a.
Amit Kapila [Wed, 3 Jul 2024 09:27:07 +0000 (14:57 +0530)]
Fix the testcase introduced in commit 81d20fbf7a.

The failed test was syncing failover replication slot to standby to test
that we remove such slots after the standby is converted to subscriber by
pg_createsubscriber.

In one of the buildfarm members, the sync of the slot failed because the
LSN on the standby was before the syncslot's LSN. We need to wait for
standby to catch up before trying to sync the slot with
pg_sync_replication_slots().

The other buildfarm failed because autovacuum generated a xid which is
replicated to the standby at some random point making slots at primary
lag behind standby during slot sync.

Both these failures wouldn't have occurred if we had used built-in
slotsync worker as it would have waited for the standby to sync with
primary but for this test, it is sufficient to use
pg_sync_replication_slots().

Reported-by: Alexander Lakhin as per buildfarm
Author: Kuroda Hayato
Reviewed-by: Amit Kapila
Backpatch-through: 17
Discussion: https://postgr.es/m/0dffca12-bf17-4a7a-334d-225569de5e6e@gmail.com
Discussion: https://postgr.es/m/OSBPR01MB25528300C71FDD83EA1DCA12F5DD2@OSBPR01MB2552.jpnprd01.prod.outlook.com

10 months agoDrop pre-existing subscriptions from the converted subscriber.
Amit Kapila [Tue, 2 Jul 2024 05:50:06 +0000 (11:20 +0530)]
Drop pre-existing subscriptions from the converted subscriber.

We don't need the pre-existing subscriptions on the newly formed
subscriber by using pg_createsubscriber. The apply workers corresponding
to these subscriptions can connect to other publisher nodes and either get
some unwarranted data or can lead to ERRORs in connecting to such nodes.

Author: Kuroda Hayato
Reviewed-by: Amit Kapila, Shlok Kyal, Vignesh C
Backpatch-through: 17
Discussion: https://postgr.es/m/OSBPR01MB25526A30A1FBF863ACCDDA3AF5C92@OSBPR01MB2552.jpnprd01.prod.outlook.com

10 months agoRemove unused structure member in pg_createsubscriber.c.
Amit Kapila [Tue, 2 Jul 2024 04:45:11 +0000 (10:15 +0530)]
Remove unused structure member in pg_createsubscriber.c.

Author: Kuroda Hayato
Backpatch-through: 17
Discussion: https://postgr.es/m/OSBPR01MB25526A30A1FBF863ACCDDA3AF5C92@OSBPR01MB2552.jpnprd01.prod.outlook.com

10 months agoUpdate release notes to reflect recent commit 0f934b0739.
Amit Kapila [Tue, 2 Jul 2024 03:47:41 +0000 (09:17 +0530)]
Update release notes to reflect recent commit 0f934b0739.

Author: Hou Zhijie
Discussion: https://postgr.es/m/[email protected]
Discussion: https://postgr.es/m/OS3PR01MB57187B959C1ECC78B0C7C91A94D32@OS3PR01MB5718.jpnprd01.prod.outlook.com

10 months agoPreserve CurrentMemoryContext across notify and sinval interrupts.
Tom Lane [Mon, 1 Jul 2024 16:21:07 +0000 (12:21 -0400)]
Preserve CurrentMemoryContext across notify and sinval interrupts.

ProcessIncomingNotify is called from the main processing loop that
normally runs in MessageContext.  That outer-loop code assumes that
whatever it allocates will be cleaned up when we're done processing
the current client message --- but if we service a notify interrupt,
then whatever gets allocated before the next switch into
MessageContext will be permanently leaked in TopMemoryContext,
because CommitTransactionCommand sets CurrentMemoryContext to
TopMemoryContext.  There are observable leaks associated with
(at least) encoding conversion of incoming queries and parameters
attached to Bind messages.

sinval catchup interrupts have a similar problem.  There might be
others, but I've not identified any other clear cases.

To fix, take care to save and restore CurrentMemoryContext across
the Start/CommitTransactionCommand calls in these functions.

Per bug #18512 from wizardbrony.  Commit to back branches only;
in HEAD, this was dealt with by the riskier but more thoroughgoing
approach in commit 1afe31f03.

Discussion: https://postgr.es/m/3478884.1718656625@sss.pgh.pa.us

10 months agoFix copy-paste mistake in PQcancelCreate
Alvaro Herrera [Mon, 1 Jul 2024 11:58:22 +0000 (13:58 +0200)]
Fix copy-paste mistake in PQcancelCreate

When an OOM occurred, this function was incorrectly setting a status of
CONNECTION_BAD on the passed in PGconn instead of on the newly created
PGcancelConn.

Mistake introduced with 61461a300c1c.  Backpatch to 17.

Author: Jelte Fennema-Nio <[email protected]>
Reported-by: Noah Misch <[email protected]>
Discussion: https://postgr.es/m/20240630190040[email protected]

10 months agoRename standby_slot_names to synchronized_standby_slots.
Amit Kapila [Mon, 1 Jul 2024 05:32:04 +0000 (11:02 +0530)]
Rename standby_slot_names to synchronized_standby_slots.

The standby_slot_names GUC allows the specification of physical standby
slots that must be synchronized before the logical walsenders associated
with logical failover slots. However, for this purpose, the GUC name is
too generic.

Author: Hou Zhijie
Reviewed-by: Bertrand Drouvot, Masahiko Sawada
Backpatch-through: 17
Discussion: https://postgr.es/m/[email protected]

10 months agoFurther weaken new pg_createsubscriber test on Windows.
Tom Lane [Mon, 1 Jul 2024 03:20:57 +0000 (23:20 -0400)]
Further weaken new pg_createsubscriber test on Windows.

Also omit backslashes (\) in the generated database names on Windows.
As before, perhaps we can revert this after updating affected
buildfarm animals.

Discussion: https://postgr.es/m/2509767.1719773880@sss.pgh.pa.us

10 months agoAdapt REL_17_STABLE to its new status as a stable branch
Michael Paquier [Sun, 30 Jun 2024 23:05:35 +0000 (08:05 +0900)]
Adapt REL_17_STABLE to its new status as a stable branch

Per the checklist in RELEASE_CHANGES for the creation of a new stable
branch, this commit does the following things:
- Arm gen_node_support.pl's nodetag ABI stability, based on the contents
of nodetags.h.
- Update URLs of top-level README and Makefile to point to the new
stable version.

In passing, this fixes an incorrect comment in release-17.sgml.

10 months agoRun pgperltidy
Michael Paquier [Sun, 30 Jun 2024 22:35:01 +0000 (07:35 +0900)]
Run pgperltidy

This is required before the creation of a new branch.  pgindent is
clean, as well as is reformat-dat-files.

perltidy version is v20230309, as documented in pgindent's README.

10 months agoTemporarily(?) weaken new pg_createsubscriber test on Windows.
Tom Lane [Sun, 30 Jun 2024 21:33:06 +0000 (17:33 -0400)]
Temporarily(?) weaken new pg_createsubscriber test on Windows.

Don't include double-quotes (") in the generated database names
on Windows.  Doing so tickles a bug in older versions of IPC::Run,
which fail to quote command line arguments correctly for that
platform.  Possibly we can revert this after updating affected
buildfarm animals.

Discussion: https://postgr.es/m/2509767.1719773880@sss.pgh.pa.us

11 months agoAdd PG_TEST_PG_COMBINEBACKUP_MODE
Tomas Vondra [Sun, 30 Jun 2024 17:26:12 +0000 (19:26 +0200)]
Add PG_TEST_PG_COMBINEBACKUP_MODE

Introduces an environment variable PG_TEST_PG_COMBINEBACKUP_MODE, that
determines copy mode used by pg_combinebackup in TAP tests. Defaults to
"--copy" but may be set to "--clone" or "--copy-file-range" to use the
alternative stategies.

Reported-by: Peter Eisentraut
Discussion: https://postgr.es/m/48da4a1f-ccd9-4988-9622-24f37b1de2b4%40eisentraut.org

11 months agoAdd pg_combinebackup --copy option
Tomas Vondra [Sun, 30 Jun 2024 17:20:02 +0000 (19:20 +0200)]
Add pg_combinebackup --copy option

Introduces --copy as an alternative to --clone and --copy-file-range.
This option simply picks the default mode to copy files, as if none of
the options was specified. This makes pg_combinebackup options more
consistent with pg_upgrade, and it makes testing simpler.

Reported-by: Peter Eisentraut
Discussion: https://postgr.es/m/48da4a1f-ccd9-4988-9622-24f37b1de2b4%40eisentraut.org

11 months agoAdd headers needed by pg_combinebackup --clone
Tomas Vondra [Sun, 30 Jun 2024 17:02:00 +0000 (19:02 +0200)]
Add headers needed by pg_combinebackup --clone

The code for file cloning existed, but was not reachable as it relied on
constants from missing headers. Due to that, on Linux --clone always
failed with

  error: file cloning not supported on this platform

Fixed by including the missing headers to relevant places. Adding the
headers revealed a couple compile errors in copy_file_clone(), so fix
those too.

Reported-by: Peter Eisentraut
Discussion: https://postgr.es/m/48da4a1f-ccd9-4988-9622-24f37b1de2b4%40eisentraut.org

11 months agoMake pg_createsubscriber warn if publisher has two-phase commit enabled.
Tom Lane [Sun, 30 Jun 2024 18:24:14 +0000 (14:24 -0400)]
Make pg_createsubscriber warn if publisher has two-phase commit enabled.

pg_createsubscriber currently always sets up logical replication
with two-phase commit disabled.  Improving that is not going to
happen for v17.  In the meantime, document the deficiency, and
adjust pg_createsubscriber so that it will emit a warning if
the source installation has max_prepared_transactions > 0.

Hayato Kuroda (some mods by Amit Kapila and me), per complaint from
Noah Misch

Discussion: https://postgr.es/m/20240623062157[email protected]

11 months agoMake pg_createsubscriber more wary about quoting connection parameters.
Tom Lane [Sun, 30 Jun 2024 17:45:24 +0000 (13:45 -0400)]
Make pg_createsubscriber more wary about quoting connection parameters.

The original coding here could fail with database names, user names,
etc that contain spaces or other special characters.

As partial test coverage, extend the 040_pg_createsubscriber.pl
test script so that it uses a generated database name containing
funny characters.

Hayato Kuroda (some mods by me), per complaint from Noah Misch

Discussion: https://postgr.es/m/20240623062157[email protected]

11 months agoFix .gitignore for new injection suite.
Noah Misch [Fri, 28 Jun 2024 18:17:50 +0000 (11:17 -0700)]
Fix .gitignore for new injection suite.

Commit c35f419d6efbdf1a050250d84b687e6705917711 missed this.

11 months agoRemove configuration-dependent output from new inplace-inval test.
Noah Misch [Fri, 28 Jun 2024 16:33:40 +0000 (09:33 -0700)]
Remove configuration-dependent output from new inplace-inval test.

Per buildfarm members prion and trilobite.  Back-patch to v12 (all
supported versions), like commit
0844b3968985447ed0a6937cfc8639e379da2fe6.

Strategy reviewed by Tom Lane.

Discussion: https://postgr.es/m/20240628051353[email protected]

11 months agopgindent, because I forgot to do that.
Robert Haas [Fri, 28 Jun 2024 14:45:51 +0000 (10:45 -0400)]
pgindent, because I forgot to do that.

Commit 065583cf460f980a182498941ac52810f709a897 should have
included these changes.

11 months agoSQL/JSON: Always coerce JsonExpr result at runtime
Amit Langote [Fri, 28 Jun 2024 12:58:13 +0000 (21:58 +0900)]
SQL/JSON: Always coerce JsonExpr result at runtime

Instead of looking up casts at parse time for converting the result
of JsonPath* query functions to the specified or the default
RETURNING type, always perform the conversion at runtime using either
the target type's input function or the function
json_populate_type().

There are two motivations for this change:

1. json_populate_type() coerces to types with typmod such that any
   string values that exceed length limit cause an error instead of
   silent truncation, which is necessary to be standard-conforming.

2. It was possible to end up with a cast expression that doesn't
   support soft handling of errors causing bugs in the of handling
   ON ERROR clause.

JsonExpr.coercion_expr which would store the cast expression is no
longer necessary, so remove.

Bump catversion because stored rules change because of the above
removal.

Reported-by: Alvaro Herrera <[email protected]>
Reviewed-by: Jian He <[email protected]>
Discussion: Discussion: https://postgr.es/m/202405271326.5a5rprki64aw%40alvherre.pgsql

11 months agoSQL/JSON: Fix coercion of constructor outputs to types with typmod
Amit Langote [Fri, 28 Jun 2024 12:37:14 +0000 (21:37 +0900)]
SQL/JSON: Fix coercion of constructor outputs to types with typmod

Ensure SQL/JSON constructor functions that allow specifying the
target type using the RETURNING clause perform implicit cast to
that type.  This ensures that output values that exceed the specified
length produce an error rather than being  silently truncated. This
behavior conforms to the SQL standard.

Reported-by: Alvaro Herrera <[email protected]>
Reviewed-by: Jian He <[email protected]>
Discussion: https://postgr.es/m/202405271326.5a5rprki64aw%40alvherre.pgsql

11 months agoPrevent summarizer hang when summarize_wal turned off and back on.
Robert Haas [Tue, 25 Jun 2024 19:42:36 +0000 (15:42 -0400)]
Prevent summarizer hang when summarize_wal turned off and back on.

Before this commit, when the WAL summarizer started up or recovered
from an error, it would resume summarization from wherever it left
off. That was OK normally, but wrong if summarize_wal=off had been
turned off temporary, allowing some WAL to be removed, and then turned
back on again. In such cases, the WAL summarizer would simply hang
forever. This commit changes the reinitialization sequence for WAL
summarizer to rederive the starting position in the way we were
already doing at initial startup, fixing the problem.

Per report from Israel Barth Rubio. Reviewed by Tom Lane.

Discussion: http://postgr.es/m/CA+TgmoYN6x=YS+FoFOS6=nr6=qkXZFWhdiL7k0oatGwug2hcuA@mail.gmail.com

11 months agoSQL/JSON: Validate values in ON ERROR/EMPTY clauses
Amit Langote [Fri, 28 Jun 2024 04:59:57 +0000 (13:59 +0900)]
SQL/JSON: Validate values in ON ERROR/EMPTY clauses

Currently, the grammar allows any supported values in the ON ERROR
and ON EMPTY clauses for SQL/JSON functions, regardless of whether
the values are appropriate for the function. This commit ensures
that during parse analysis, the provided value is checked for
validity for the given function and throws a syntax error if it is
not.

While at it, this fixes some omissions in the documentation of the
ON ERROR/EMPTY clauses for JSON_TABLE().

Reported-by: Jian He <[email protected]>
Reviewed-by: Jian He <[email protected]>
Discussion: https://postgr.es/m/CACJufxFgWGqpESSYzyJ6tSurr3vFYBSNEmCfkGyB_dMdptFnZQ%40mail.gmail.com

11 months agoSQL/JSON: Prevent ON EMPTY for EXISTS columns in JSON_TABLE()
Amit Langote [Fri, 28 Jun 2024 04:59:13 +0000 (13:59 +0900)]
SQL/JSON: Prevent ON EMPTY for EXISTS columns in JSON_TABLE()

Due to an oversight in de3600452b61, the ON EMPTY clause was
incorrectly allowed in the EXISTS column. Fix the grammar to prevent
this.

Discussion: https://postgr.es/m/CA%2BHiwqHh3YDXTpccgAo4CdfV9Mhy%2Bmg%3Doh6t8rfM5uLW1BJN4g%40mail.gmail.com

11 months agoUpdate modules/injection_points/.gitignore
Michael Paquier [Fri, 28 Jun 2024 04:41:39 +0000 (13:41 +0900)]
Update modules/injection_points/.gitignore

Thinko in c35f419d6efb, where an isolation test has been added to the
module.

11 months agoFix comments in heaptuple.c
Michael Paquier [Fri, 28 Jun 2024 04:30:47 +0000 (13:30 +0900)]
Fix comments in heaptuple.c

Since e27f4ee0a701, fastgetattr() and heap_getattr() are not macros, but
inlined functions.

Author: Junwang Zhao
Reviewed-by: Stepan Neretin
Discussion: https://postgr.es/m/CAEG8a3JS-JKWWyOcM7BU=vPqFXa3W7mZSHnvc3CBqx=tC+3SCA@mail.gmail.com

11 months agoImprove locking around InjectionPointRun()
Michael Paquier [Fri, 28 Jun 2024 03:31:29 +0000 (12:31 +0900)]
Improve locking around InjectionPointRun()

As coded, an injection point could be loaded into the local cache
without the LWLock InjectionPointLock taken, hence a point detached and
re-attached concurrently of a point running calling InjectionPointRun()
may finish by loading a callback it did no set initially.  Based on all
the cases discussed until now on the lists, it is fine to delay the lock
release until the callback is run, so let's do that.

While on it, remove a useless LWLockRelease() called before an error in
InjectionPointAttach().

Per discussion with Heikki Linnakangas and Noah Misch.

Discussion: https://postgr.es/m/e1ffb822-054e-4006-ac06-50532767f75b@iki.fi

11 months agoRemove comment about xl_heap_inplace "AT END OF STRUCT".
Noah Misch [Fri, 28 Jun 2024 02:21:06 +0000 (19:21 -0700)]
Remove comment about xl_heap_inplace "AT END OF STRUCT".

Commit 2c03216d831160bedd72d45f712601b6f7d03f1c moved the tuple data
from there to the buffer-0 data.  Back-patch to v12 (all supported
versions), the plan for the next change to this struct.

Discussion: https://postgr.es/m/20240523000548[email protected]

11 months agoCope with inplace update making catcache stale during TOAST fetch.
Noah Misch [Fri, 28 Jun 2024 02:21:06 +0000 (19:21 -0700)]
Cope with inplace update making catcache stale during TOAST fetch.

This extends ad98fb14226ae6456fbaed7990ee7591cbe5efd2 to invals of
inplace updates.  Trouble requires an inplace update of a catalog having
a TOAST table, so only pg_database was at risk.  (The other catalog on
which core code performs inplace updates, pg_class, has no TOAST table.)
Trouble would require something like the inplace-inval.spec test.
Consider GRANT ... ON DATABASE fetching a stale row from cache and
discarding a datfrozenxid update that vac_truncate_clog() has already
relied upon.  Back-patch to v12 (all supported versions).

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240114201411[email protected]
Discussion: https://postgr.es/m/20240512232923[email protected]

11 months agoAccessExclusiveLock new relations just after assigning the OID.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
AccessExclusiveLock new relations just after assigning the OID.

This has no user-visible, important consequences, since other sessions'
catalog scans can't find the relation until we commit.  However, this
unblocks introducing a rule about locks required to heap_update() a
pg_class row.  CREATE TABLE has been acquiring this lock eventually, but
it can heap_update() pg_class.relchecks earlier.  create_toast_table()
has been acquiring only ShareLock.  Back-patch to v12 (all supported
versions), the plan for the commit relying on the new rule.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525[email protected]

11 months agoLock before setting relhassubclass on RELKIND_PARTITIONED_INDEX.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Lock before setting relhassubclass on RELKIND_PARTITIONED_INDEX.

Commit 5b562644fec696977df4a82790064e8287927891 added a comment that
SetRelationHasSubclass() callers must hold this lock.  When commit
17f206fbc824d2b4b14480199ca9ff7dea417eda extended use of this column to
partitioned indexes, it didn't take the lock.  As the latter commit
message mentioned, we currently never reset a partitioned index to
relhassubclass=f.  That largely avoids harm from the lock omission.  The
cause for fixing this now is to unblock introducing a rule about locks
required to heap_update() a pg_class row.  This might cause more
deadlocks.  It gives minor user-visible benefits:

- If an ALTER INDEX SET TABLESPACE runs concurrently with ALTER TABLE
  ATTACH PARTITION or CREATE PARTITION OF, one transaction blocks
  instead of failing with "tuple concurrently updated".  (Many cases of
  DDL concurrency still fail that way.)

- Match ALTER INDEX ATTACH PARTITION in choosing to lock the index.

While not user-visible today, we'll need this if we ever make something
set the flag to false for a partitioned index, like ANALYZE does today
for tables.  Back-patch to v12 (all supported versions), the plan for
the commit relying on the new rule.  In back branches, add
LockOrStrongerHeldByMe() instead of adding a LockHeldByMe() parameter.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525[email protected]

11 months agoLock owned sequences during ALTER TABLE SET { LOGGED | UNLOGGED }.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Lock owned sequences during ALTER TABLE SET { LOGGED | UNLOGGED }.

These commands already make the persistence of owned sequences follow
owned table persistence changes.  They didn't lock those sequences.
They lost the effect of nextval() calls that other sessions make after
the ALTER TABLE command, before the ALTER TABLE transaction commits.
Fix by acquiring the same lock that ALTER SEQUENCE SET { LOGGED |
UNLOGGED } acquires.  This might cause more deadlocks.  Back-patch to
v15, where commit 344d62fb9a978a72cf8347f0369b9ee643fd0b31 introduced
unlogged sequences.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525[email protected]

11 months agoExpand comments and add an assertion in nodeModifyTable.c.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Expand comments and add an assertion in nodeModifyTable.c.

Most comments concern RELKIND_VIEW.  One addresses the ExecUpdate()
"tupleid" parameter.  A later commit will rely on these facts, but they
hold already.  Back-patch to v12 (all supported versions), the plan for
that commit.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

11 months agoAdd an injection_points isolation test suite.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Add an injection_points isolation test suite.

Make the isolation harness recognize injection_points wait events as a
type of blocked state.  Test an extant inplace-update bug.

Reviewed by Robert Haas and Michael Paquier.

Discussion: https://postgr.es/m/20240512232923[email protected]

11 months agoCreate waitfuncs.c for pg_isolation_test_session_is_blocked().
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Create waitfuncs.c for pg_isolation_test_session_is_blocked().

The next commit makes the function inspect an additional non-lock
contention source, so it no longer fits in lockfuncs.c.

Reviewed by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

11 months agoAdd wait event type "InjectionPoint", a custom type like "Extension".
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Add wait event type "InjectionPoint", a custom type like "Extension".

Both injection points and customization of type "Extension" are new in
v17, so this just changes a detail of an unreleased feature.

Reported by Robert Haas.  Reviewed by Michael Paquier.

Discussion: https://postgr.es/m/CA+TgmobfMU5pdXP36D5iAwxV5WKE_vuDLtp_1QyH+H5jMMt21g@mail.gmail.com

11 months agoImprove test coverage for changes to inplace-updated catalogs.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Improve test coverage for changes to inplace-updated catalogs.

This covers both regular and inplace changes, since bugs arise at their
intersection.  Where marked, these witness extant bugs.  Back-patch to
v12 (all supported versions).

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

11 months agoMake TAP todo_start effects the same under Meson and prove_check.
Noah Misch [Fri, 28 Jun 2024 02:21:04 +0000 (19:21 -0700)]
Make TAP todo_start effects the same under Meson and prove_check.

This could have caused spurious failures only on SPARC Linux, because
today's only todo_start tests for that platform.  Back-patch to v16,
where Meson support first appeared.

Reviewed by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

11 months agoSQL/JSON: Document behavior when input document is not jsonb
Amit Langote [Fri, 28 Jun 2024 00:42:13 +0000 (09:42 +0900)]
SQL/JSON: Document behavior when input document is not jsonb

The input document to functions JSON_EXISTS(), JSON_QUERY(),
JSON_VALUE(), and JSON_TABLE() can be specified as character or
UTF8-encoded bytea strings. These are automatically converted to
jsonb with an implicit cast before being passed to the jsonpath
machinery.

In the current implementation, errors that occur when parsing the
specified string into a valid JSON document are thrown
unconditionally. This means they are not subject to the explicit or
implicit ON ERROR clause of those functions, which is a standard-
conforming behavior.  Add a note to the documentation to mention
that.

Reported-by: Markus Winand
Discussion: https://postgr.es/m/F7DD1442-265C-4220-A603-CB0DEB77E91D%40winand.at

11 months agoAvoid crashing when a JIT-inlined backend function throws an error.
Tom Lane [Thu, 27 Jun 2024 18:43:59 +0000 (14:43 -0400)]
Avoid crashing when a JIT-inlined backend function throws an error.

errfinish() assumes that the __FUNC__ and __FILE__ arguments it's
passed are compile-time constant strings that can just be pointed
to rather than physically copied.  However, it's possible for LLVM
to generate code in which those pointers point into a dynamically
loaded code segment.  If that segment gets unloaded before we're
done with the ErrorData struct, we have dangling pointers that
will lead to SIGSEGV.  In simple cases that won't happen, because we
won't unload LLVM code before end of transaction.  But it's possible
to happen if the error is thrown within end-of-transaction code run by
_SPI_commit or _SPI_rollback, because since commit 2e517818f those
functions clean up by ending the transaction and starting a new one.

Rather than fixing this by adding pstrdup() overhead to every
elog/ereport sequence, let's fix it by copying the risky pointers
in CopyErrorData().  That solves it for _SPI_commit/_SPI_rollback
because they use that function to preserve the error data across
the transaction end/restart sequence; and it seems likely that
any other code doing something similar would need to do that too.

I'm suspicious that this behavior amounts to an LLVM bug (or a
bug in our use of it?), because it implies that string constant
references that should be pointer-equal according to a naive
understanding of C semantics will sometimes not be equal.
However, even if it is a bug and someday gets fixed, we'll have
to cope with the current behavior for a long time to come.

Report and patch by me.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/1565654.1719425368@sss.pgh.pa.us

11 months agoFix MVCC bug with prepared xact with subxacts on standby
Heikki Linnakangas [Thu, 27 Jun 2024 18:06:32 +0000 (21:06 +0300)]
Fix MVCC bug with prepared xact with subxacts on standby

We did not recover the subtransaction IDs of prepared transactions
when starting a hot standby from a shutdown checkpoint. As a result,
such subtransactions were considered as aborted, rather than
in-progress. That would lead to hint bits being set incorrectly, and
the subtransactions suddenly becoming visible to old snapshots when
the prepared transaction was committed.

To fix, update pg_subtrans with prepared transactions's subxids when
starting hot standby from a shutdown checkpoint. The snapshots taken
from that state need to be marked as "suboverflowed", so that we also
check the pg_subtrans.

Backport to all supported versions.

Discussion: https://www.postgresql.org/message-id/6b852e98-2d49-4ca1-9e95-db419a2696e0@iki.fi

11 months agotests: Trim newline from result returned by BackgroundPsql->query
Heikki Linnakangas [Thu, 27 Jun 2024 18:06:27 +0000 (21:06 +0300)]
tests: Trim newline from result returned by BackgroundPsql->query

This went unnoticed, because only a few existing callers of
BackgroundPsql->query used the result, and the ones that did were not
bothered by an extra newline. I noticed because I was about to add a
new test that checks the result.

Backport to all supported versions, since I just backported the
BackgroundPsql facility to all supported versions too.

11 months agoFix thinkos in comments
Alvaro Herrera [Thu, 27 Jun 2024 17:51:47 +0000 (19:51 +0200)]
Fix thinkos in comments

The first one was noticed by Tender Wang and introduced with
8aba9322511f; the other one was newly introduced with dbca3469ebf8.

11 months agoDrop the temporary tuple slots allocated by pgoutput.
Amit Kapila [Thu, 27 Jun 2024 06:05:00 +0000 (11:35 +0530)]
Drop the temporary tuple slots allocated by pgoutput.

In pgoutput, when converting the child table's tuple format to match the
parent table's, we temporarily create a new slot to store the converted
tuple. However, we missed to drop such temporary slots, leading to
resource leakage.

Reported-by: Bowen Shi
Author: Hou Zhijie
Reviewed-by: Amit Kapila
Backpatch-through: 15
Discussion: https://postgr.es/m/CAM_vCudv8dc3sjWiPkXx5F2b27UV7_YRKRbtSCcE-pv=cVACGA@mail.gmail.com

11 months agoFix overflow with pgstats DSA reference count
Michael Paquier [Thu, 27 Jun 2024 00:44:47 +0000 (09:44 +0900)]
Fix overflow with pgstats DSA reference count

When pgstats is initialized for a backend, it uses dsa_attach_in_place()
without a "segment" provided.  Hence, no callback is registered to
automatically release the DSA attached once a backend exits.  Not doing
any cleanup causes the reference count of the pgstats DSA to
continuously increment, at some point overflowing it (the more the
number of connections, the faster it is to reach this state).  Once the
reference count overflows and then gets back to 0, new backends are not
able to attach to the pgstats DSA, failing startup.

This issue is resolved by adding in the pgstats shutdown hook a call to
dsa_release_in_place(), ensuring that the DSA attached at backend
startup is correctly released, keeping the reference count at bay.

The author of this patch has been able to see this issue on a server
with a long uptime and a high connection turnover.

Issue introduced by 5891c7a8ed8f, so backpatch down to 15.

Author: Anthonin Bonnefoy
Discussion: https://postgr.es/m/CAO6_XqqJbJBL=M7Ym13TcB4Xnq58vRa2jcC+gwEPBgbAda6B1Q@mail.gmail.com
Backpatch-through: 15

11 months agoFix bugs in MultiXact truncation
Heikki Linnakangas [Fri, 21 Jun 2024 15:31:15 +0000 (18:31 +0300)]
Fix bugs in MultiXact truncation

1. TruncateMultiXact() performs the SLRU truncations in a critical
section. Deleting the SLRU segments calls ForwardSyncRequest(), which
will try to compact the request queue if it's full
(CompactCheckpointerRequestQueue()). That in turn allocates memory,
which is not allowed in a critical section. Backtrace:

    TRAP: failed Assert("CritSectionCount == 0 || (context)->allowInCritSection"), File: "../src/backend/utils/mmgr/mcxt.c", Line: 1353, PID: 920981
    postgres: autovacuum worker template0(ExceptionalCondition+0x6e)[0x560a501e866e]
    postgres: autovacuum worker template0(+0x5dce3d)[0x560a50217e3d]
    postgres: autovacuum worker template0(ForwardSyncRequest+0x8e)[0x560a4ffec95e]
    postgres: autovacuum worker template0(RegisterSyncRequest+0x2b)[0x560a50091eeb]
    postgres: autovacuum worker template0(+0x187b0a)[0x560a4fdc2b0a]
    postgres: autovacuum worker template0(SlruDeleteSegment+0x101)[0x560a4fdc2ab1]
    postgres: autovacuum worker template0(TruncateMultiXact+0x2fb)[0x560a4fdbde1b]
    postgres: autovacuum worker template0(vac_update_datfrozenxid+0x4b3)[0x560a4febd2f3]
    postgres: autovacuum worker template0(+0x3adf66)[0x560a4ffe8f66]
    postgres: autovacuum worker template0(AutoVacWorkerMain+0x3ed)[0x560a4ffe7c2d]
    postgres: autovacuum worker template0(+0x3b1ead)[0x560a4ffecead]
    postgres: autovacuum worker template0(+0x3b620e)[0x560a4fff120e]
    postgres: autovacuum worker template0(+0x3b3fbb)[0x560a4ffeefbb]
    postgres: autovacuum worker template0(+0x2f724e)[0x560a4ff3224e]
    /lib/x86_64-linux-gnu/libc.so.6(+0x27c8a)[0x7f62cc642c8a]
    /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x85)[0x7f62cc642d45]
    postgres: autovacuum worker template0(_start+0x21)[0x560a4fd16f31]

To fix, bail out in CompactCheckpointerRequestQueue() without doing
anything, if it's called in a critical section. That covers the above
call path, as well as any other similar cases where
RegisterSyncRequest might be called in a critical section.

2. After fixing that, another problem became apparent: Autovacuum
process doing that truncation can deadlock with the checkpointer
process. TruncateMultiXact() sets "MyProc->delayChkptFlags |=
DELAY_CHKPT_START". If the sync request queue is full and cannot be
compacted, the process will repeatedly sleep and retry, until there is
room in the queue. However, if the checkpointer is trying to start a
checkpoint at the same time, and is waiting for the DELAY_CHKPT_START
processes to finish, the queue will never shrink.

More concretely, the autovacuum process is stuck here:

    #0  0x00007fc934926dc3 in epoll_wait () from /lib/x86_64-linux-gnu/libc.so.6
    #1  0x000056220b24348b in WaitEventSetWaitBlock (set=0x56220c2e4b50, occurred_events=0x7ffe7856d040, nevents=1, cur_timeout=<optimized out>) at ../src/backend/storage/ipc/latch.c:1570
    #2  WaitEventSetWait (set=0x56220c2e4b50, timeout=timeout@entry=10, occurred_events=<optimized out>, occurred_events@entry=0x7ffe7856d040, nevents=nevents@entry=1,
        wait_event_info=wait_event_info@entry=150994949) at ../src/backend/storage/ipc/latch.c:1516
    #3  0x000056220b243224 in WaitLatch (latch=<optimized out>, latch@entry=0x0, wakeEvents=wakeEvents@entry=40, timeout=timeout@entry=10, wait_event_info=wait_event_info@entry=150994949)
        at ../src/backend/storage/ipc/latch.c:538
    #4  0x000056220b26cf46 in RegisterSyncRequest (ftag=ftag@entry=0x7ffe7856d0a0, type=type@entry=SYNC_FORGET_REQUEST, retryOnError=true) at ../src/backend/storage/sync/sync.c:614
    #5  0x000056220af9db0a in SlruInternalDeleteSegment (ctl=ctl@entry=0x56220b7beb60 <MultiXactMemberCtlData>, segno=segno@entry=11350) at ../src/backend/access/transam/slru.c:1495
    #6  0x000056220af9dab1 in SlruDeleteSegment (ctl=ctl@entry=0x56220b7beb60 <MultiXactMemberCtlData>, segno=segno@entry=11350) at ../src/backend/access/transam/slru.c:1566
    #7  0x000056220af98e1b in PerformMembersTruncation (oldestOffset=<optimized out>, newOldestOffset=<optimized out>) at ../src/backend/access/transam/multixact.c:3006
    #8  TruncateMultiXact (newOldestMulti=newOldestMulti@entry=3221225472, newOldestMultiDB=newOldestMultiDB@entry=4) at ../src/backend/access/transam/multixact.c:3201
    #9  0x000056220b098303 in vac_truncate_clog (frozenXID=749, minMulti=<optimized out>, lastSaneFrozenXid=749, lastSaneMinMulti=3221225472) at ../src/backend/commands/vacuum.c:1917
    #10 vac_update_datfrozenxid () at ../src/backend/commands/vacuum.c:1760
    #11 0x000056220b1c3f76 in do_autovacuum () at ../src/backend/postmaster/autovacuum.c:2550
    #12 0x000056220b1c2c3d in AutoVacWorkerMain (startup_data=<optimized out>, startup_data_len=<optimized out>) at ../src/backend/postmaster/autovacuum.c:1569

and the checkpointer is stuck here:

    #0  0x00007fc9348ebf93 in clock_nanosleep () from /lib/x86_64-linux-gnu/libc.so.6
    #1  0x00007fc9348fe353 in nanosleep () from /lib/x86_64-linux-gnu/libc.so.6
    #2  0x000056220b40ecb4 in pg_usleep (microsec=microsec@entry=10000) at ../src/port/pgsleep.c:50
    #3  0x000056220afb43c3 in CreateCheckPoint (flags=flags@entry=108) at ../src/backend/access/transam/xlog.c:7098
    #4  0x000056220b1c6e86 in CheckpointerMain (startup_data=<optimized out>, startup_data_len=<optimized out>) at ../src/backend/postmaster/checkpointer.c:464

To fix, add AbsorbSyncRequests() to the loops where the checkpointer
waits for DELAY_CHKPT_START or DELAY_CHKPT_COMPLETE operations to
finish.

Backpatch to v14. Before that, SLRU deletion didn't call
RegisterSyncRequest, which avoided this failure. I'm not sure if there
are other similar scenarios on older versions, but we haven't had
any such reports.

Discussion: https://www.postgresql.org/message-id/ccc66933-31c1-4f6a-bf4b-45fef0d4f22e@iki.fi