From a5b67703a32f2d79f1a924d2d9685b92fae38939 Mon Sep 17 00:00:00 2001 From: Brian Macy Date: Wed, 2 Dec 2026 20:24:50 +0000 Subject: [PATCH v1] Open only the target segment to reach existing blocks To read or write a block in segment N of a relation it does not have open, a backend opens segments 0 to N, checking that each of the earlier ones is full. AtEOXact_SMgr() closes SMgrRelations that are not pinned by a relcache entry at the end of each transaction (ff3f9c8de5, 21d9c3ee4e), so a backend repeats those opens in every transaction in which it touches such a relation. The common case is a backend writing out a dirty victim buffer of a relation it is not otherwise using, perhaps one in another database. With large relations accessed at random, much of the system time then goes into open() and close(). For reads, writes and prefetches of existing blocks, open only the target segment; we call such a segment detached. If the target segment is missing, fall back to opening the segments in sequence, which reports the error as before. Extension and WAL replay still open the segments in sequence, since they may have to create or pad the segments in between. The sequential open checks that the earlier segments are full because md_seg_fds must contain only active segments (72a98a6395). Detached segments are not in md_seg_fds, so that does not apply to them. A block beyond the end of the relation can be reached only through a corrupt reference; it is now treated like a block beyond the end of the last segment. Detached segments are kept in a per-fork hash table keyed by segment number, so that md_seg_fds remains the gap-free array of active segments that mdnblocks(), mdtruncate() and the sync functions rely on. When md_seg_fds grows to reach a detached segment, its descriptor is moved over instead of the file being opened again. Keeping SMgrRelations open across transactions instead would undo what ff3f9c8de5 set out to do. A backend sitting idle after writing out buffers of a table reads no invalidation messages until it starts a transaction or falls far enough behind to be sent a catchup interrupt, so it would keep descriptors for the table's truncated, unlinked files open for as long as it stays idle. A larger segment size also shortens the walk, but it is chosen when the server is built (--with-segsize) and cannot be changed for an existing cluster. In a pgbench test where half of the clients update a table in a second database, so that backends write out each other's dirty buffers, throughput rose 4.7 to 5.3 times with 8 MB segments, and by 25% with 8 clients and 4% with 64 clients with the default 1 GB segments; system CPU time per transaction fell by 36% to 96%. Workloads that do not write out other relations' buffers were unchanged. Author: Brian Macy --- src/backend/storage/smgr/md.c | 238 +++++++++- src/include/storage/smgr.h | 6 + src/test/modules/test_misc/Makefile | 1 + src/test/modules/test_misc/meson.build | 1 + .../test_misc/t/017_md_detached_segments.pl | 433 ++++++++++++++++++ src/tools/pgindent/typedefs.list | 3 + 6 files changed, 674 insertions(+), 8 deletions(-) create mode 100644 src/test/modules/test_misc/t/017_md_detached_segments.pl diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c index de630aa6ef..94067e1480 100644 --- a/src/backend/storage/smgr/md.c +++ b/src/backend/storage/smgr/md.c @@ -29,6 +29,7 @@ #include "access/xlogutils.h" #include "commands/tablespace.h" #include "common/file_utils.h" +#include "common/hashfn.h" #include "miscadmin.h" #include "pg_trace.h" #include "pgstat.h" @@ -39,6 +40,7 @@ #include "storage/relfilelocator.h" #include "storage/smgr.h" #include "storage/sync.h" +#include "utils/injection_point.h" #include "utils/memutils.h" #include "utils/wait_event.h" @@ -86,7 +88,30 @@ StaticAssertDecl(RELSEG_SIZE > 0 && RELSEG_SIZE <= INT_MAX, * entries for inactive segments, however; as soon as we find a partial * segment, we assume that any subsequent segments are inactive. * - * The entire MdfdVec array is palloc'd in the MdCxt memory context. + * Opening segment N that way opens every segment before it as well. A + * backend that does not keep the relation open repeats that in each + * transaction, which is expensive when it reaches into large relations at + * random, for instance to write out dirty buffers of relations it is not + * otherwise using. Reads and writes of existing blocks therefore open only + * the target segment; we call such a segment detached. Extension and WAL + * replay still open segments in sequence, since the segments in between may + * have to be created or padded. + * + * A detached open fails, with the error a sequential open reports, if the + * target segment is missing. A block beyond the end of the relation, which + * only a corrupt reference such as a bad index entry reaches, is read or + * written as one beyond the end of the last segment would be. + * + * A fork's detached segments are kept in md_detached_segs, a hash table keyed + * by segment number, not in md_seg_fds, so md_seg_fds remains the gap-free + * array that mdnblocks(), mdtruncate() and the sync functions work on. Every + * detached segment has a segment number of at least md_num_open_segs; when + * md_seg_fds grows to reach one, _mdfd_openseg() moves its descriptor over + * instead of opening the file again. Inserting or deleting an entry can move + * other entries, so a pointer to a detached segment is valid only until a + * segment of the fork is next opened or closed. + * + * All of these are palloc'd in the MdCxt memory context. */ typedef struct _MdfdVec @@ -95,6 +120,26 @@ typedef struct _MdfdVec BlockNumber mdfd_segno; /* segment number, from 0 */ } MdfdVec; +/* An entry in a fork's hash table of detached segments */ +typedef struct MdDetachedSeg +{ + MdfdVec vec; /* the segment; vec.mdfd_segno is the key */ + char status; /* hash entry status */ +} MdDetachedSeg; + +#define SH_PREFIX mdds +#define SH_ELEMENT_TYPE MdDetachedSeg +#define SH_KEY_TYPE BlockNumber +#define SH_KEY vec.mdfd_segno +#define SH_HASH_KEY(tb, key) murmurhash32(key) +#define SH_EQUAL(tb, a, b) ((a) == (b)) +#define SH_SCOPE static inline +#define SH_DECLARE +#define SH_DEFINE +#include "lib/simplehash.h" + +#define MD_DETACHED_INITIAL_SIZE 8 + static MemoryContext MdCxt; /* context for all MdfdVec objects */ @@ -158,6 +203,11 @@ static MdPathStr _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno); static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno, int oflags); +static MdfdVec *_mdfd_detached_lookup(SMgrRelation reln, ForkNumber forknum, + BlockNumber segno); +static MdfdVec *_mdfd_detached_open(SMgrRelation reln, ForkNumber forknum, + BlockNumber segno); +static void _mdfd_detached_closeall(SMgrRelation reln, ForkNumber forknum); static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno, bool skipFsync, int behavior); static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum, @@ -714,7 +764,10 @@ mdopen(SMgrRelation reln) { /* mark it not open */ for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++) + { reln->md_num_open_segs[forknum] = 0; + reln->md_detached_segs[forknum] = NULL; + } } /* @@ -725,6 +778,14 @@ mdclose(SMgrRelation reln, ForkNumber forknum) { int nopensegs = reln->md_num_open_segs[forknum]; + /* close and forget any detached segments */ + if (reln->md_detached_segs[forknum] != NULL) + { + _mdfd_detached_closeall(reln, forknum); + mdds_destroy(reln->md_detached_segs[forknum]); + reln->md_detached_segs[forknum] = NULL; + } + /* No work if already closed */ if (nopensegs == 0) return; @@ -1317,6 +1378,12 @@ mdtruncate(SMgrRelation reln, ForkNumber forknum, if (nblocks == curnblk) return; /* no work */ + /* + * The loop below works on md_seg_fds only, so any detached segments still + * open are not needed by it. Close them. + */ + _mdfd_detached_closeall(reln, forknum); + /* * Truncate segments, starting at the last one. Starting at the end makes * managing the memory for the fd array easier, should there be errors. @@ -1711,17 +1778,31 @@ static MdfdVec * _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno, int oflags) { + mdds_hash *detached = reln->md_detached_segs[forknum]; + MdDetachedSeg *entry = NULL; MdfdVec *v; - File fd; - MdPathStr fullpath; + File fd = -1; + bool adopt; - fullpath = _mdfd_segpath(reln, forknum, segno); + /* + * If the segment is open as a detached segment, take that descriptor over + * instead of opening the file again. + */ + if (detached != NULL) + entry = mdds_lookup(detached, segno); + adopt = (entry != NULL); + if (!adopt) + { + MdPathStr fullpath; - /* open the file */ - fd = PathNameOpenFile(fullpath.str, _mdfd_open_flags() | oflags); + fullpath = _mdfd_segpath(reln, forknum, segno); - if (fd < 0) - return NULL; + /* open the file */ + fd = PathNameOpenFile(fullpath.str, _mdfd_open_flags() | oflags); + + if (fd < 0) + return NULL; + } /* * Segments are always opened in order from lowest to highest, so we must @@ -1731,11 +1812,24 @@ _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno, _fdvec_resize(reln, forknum, segno + 1); + /* + * Remove the detached entry only now that there is room in md_seg_fds, so + * that an allocation failure above cannot lose track of the file. + */ + if (adopt) + { + fd = entry->vec.mdfd_vfd; + mdds_delete_item(detached, entry); + } + /* fill the entry */ v = &reln->md_seg_fds[forknum][segno]; v->mdfd_vfd = fd; v->mdfd_segno = segno; + if (adopt) + INJECTION_POINT("md-detached-adopt", NULL); + Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE)); /* all done */ @@ -1772,10 +1866,43 @@ _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno, return v; } + /* + * Likewise if it is open as a detached segment. Extension does not use + * those: it opens the segments in sequence below, which checks, and where + * allowed pads, each segment before the target. _mdfd_openseg() moves + * the detached segments it comes across into md_seg_fds. + */ + if (!(behavior & EXTENSION_CREATE)) + { + v = _mdfd_detached_lookup(reln, forknum, targetseg); + if (v != NULL) + return v; + } + /* The caller only wants the segment if we already had it open. */ if (behavior & EXTENSION_DONT_OPEN) return NULL; + /* + * When the caller is accessing a block it expects to exist, and the + * target segment lies beyond the next one in sequence, open just the + * target segment. If the open fails, fall through to the loop below, + * which reports the error. + * + * WAL replay (InRecovery) never does this, since it may have to create or + * pad the segments in between. Other processes may during recovery, for + * instance backends in hot standby and I/O workers reading blocks for the + * startup process: replay creates and pads the earlier segments before a + * block beyond them can be read. + */ + if ((behavior & EXTENSION_FAIL) && !InRecovery && + targetseg > reln->md_num_open_segs[forknum]) + { + v = _mdfd_detached_open(reln, forknum, targetseg); + if (v != NULL) + return v; + } + /* * The target segment is not yet open. Iterate over all the segments * between the last opened and the target segment. This way missing @@ -1876,6 +2003,93 @@ _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno, return v; } +/* + * _mdfd_detached_lookup() -- Find a detached segment, or return NULL. + */ +static MdfdVec * +_mdfd_detached_lookup(SMgrRelation reln, ForkNumber forknum, BlockNumber segno) +{ + mdds_hash *detached = reln->md_detached_segs[forknum]; + MdDetachedSeg *entry; + + if (detached == NULL) + return NULL; + + entry = mdds_lookup(detached, segno); + if (entry == NULL) + return NULL; + + Assert(segno >= (BlockNumber) reln->md_num_open_segs[forknum]); + return &entry->vec; +} + +/* + * _mdfd_detached_open() -- Open one segment without opening those before it. + * + * Returns NULL, without raising an error, if the segment cannot be opened; + * the caller then opens the segments in sequence, which reports the problem + * with the usual error. + */ +static MdfdVec * +_mdfd_detached_open(SMgrRelation reln, ForkNumber forknum, BlockNumber segno) +{ + mdds_hash *detached = reln->md_detached_segs[forknum]; + MdDetachedSeg *entry; + MdPathStr fullpath; + File fd; + bool found; + + /* the caller has checked that segno is beyond the next one in sequence */ + Assert(segno > (BlockNumber) reln->md_num_open_segs[forknum]); + + if (detached == NULL) + { + detached = mdds_create(MdCxt, MD_DETACHED_INITIAL_SIZE, NULL); + reln->md_detached_segs[forknum] = detached; + } + + fullpath = _mdfd_segpath(reln, forknum, segno); + fd = PathNameOpenFile(fullpath.str, _mdfd_open_flags()); + if (fd < 0) + return NULL; + + /* + * Inserting may grow the table. As in _mdfd_openseg(), where + * _fdvec_resize() follows the open, running out of memory then leaves the + * file open. + */ + entry = mdds_insert(detached, segno, &found); + Assert(!found); + entry->vec.mdfd_vfd = fd; + + INJECTION_POINT("md-detached-open", NULL); + + return &entry->vec; +} + +/* + * _mdfd_detached_closeall() -- Close all of a fork's detached segments. + * + * The hash table itself is kept, so that this does not allocate memory and + * may be used in a critical section. + */ +static void +_mdfd_detached_closeall(SMgrRelation reln, ForkNumber forknum) +{ + mdds_hash *detached = reln->md_detached_segs[forknum]; + mdds_iterator iter; + MdDetachedSeg *entry; + + if (detached == NULL || detached->members == 0) + return; + + mdds_start_iterate(detached, &iter); + while ((entry = mdds_iterate(detached, &iter)) != NULL) + FileClose(entry->vec.mdfd_vfd); + + mdds_reset(detached); +} + /* * Get number of blocks present in a single disk file */ @@ -1904,6 +2118,7 @@ int mdsyncfiletag(const FileTag *ftag, char *path) { SMgrRelation reln = smgropen(ftag->rlocator, INVALID_PROC_NUMBER); + MdfdVec *v; File file; instr_time io_start; bool need_to_close; @@ -1917,6 +2132,13 @@ mdsyncfiletag(const FileTag *ftag, char *path) strlcpy(path, FilePathName(file), MAXPGPATH); need_to_close = false; } + else if ((v = _mdfd_detached_lookup(reln, ftag->forknum, + ftag->segno)) != NULL) + { + file = v->mdfd_vfd; + strlcpy(path, FilePathName(file), MAXPGPATH); + need_to_close = false; + } else { MdPathStr p; diff --git a/src/include/storage/smgr.h b/src/include/storage/smgr.h index 09bd42fcf4..85d894c3ab 100644 --- a/src/include/storage/smgr.h +++ b/src/include/storage/smgr.h @@ -61,6 +61,12 @@ typedef struct SMgrRelationData int md_num_open_segs[MAX_FORKNUM + 1]; struct _MdfdVec *md_seg_fds[MAX_FORKNUM + 1]; + /* + * for md.c; per-fork sets of segments that are open without the segments + * before them being open, or NULL. See the comments in md.c. + */ + struct mdds_hash *md_detached_segs[MAX_FORKNUM + 1]; + /* * Pinning support. If unpinned (ie. pincount == 0), 'node' is a list * link in list of all unpinned SMgrRelations. diff --git a/src/test/modules/test_misc/Makefile b/src/test/modules/test_misc/Makefile index fedbef071e..671e9da8c8 100644 --- a/src/test/modules/test_misc/Makefile +++ b/src/test/modules/test_misc/Makefile @@ -3,6 +3,7 @@ TAP_TESTS = 1 EXTRA_INSTALL=src/test/modules/injection_points \ + contrib/pg_buffercache \ contrib/test_decoding # The injection points are cluster-wide, so disable installcheck diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index 5225aa280c..529a7151a3 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -25,6 +25,7 @@ tests += { 't/014_log_statement_max_length.pl', 't/015_temp_schema_exit_deferrable.pl', 't/016_heap_scan_stream.pl', + 't/017_md_detached_segments.pl', ], # The injection points are cluster-wide, so disable installcheck 'runningcheck': false, diff --git a/src/test/modules/test_misc/t/017_md_detached_segments.pl b/src/test/modules/test_misc/t/017_md_detached_segments.pl new file mode 100644 index 0000000000..5cdd10b71a --- /dev/null +++ b/src/test/modules/test_misc/t/017_md_detached_segments.pl @@ -0,0 +1,433 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Test detached relation segments, which md.c opens without opening the +# segments before them. +# +# A backend opens segments that way when it writes out dirty buffers of a +# relation it is not otherwise using. pg_buffercache_evict() makes a backend +# do that for chosen buffers. Injection points raise a NOTICE in that backend +# for each detached open, and for each detached segment that is later moved +# into the array of segments opened in sequence. +# +# The tables used span many segments, so the test runs only with segments of +# at most 32 blocks, for example with -Dsegsize_blocks=6. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +if ($ENV{enable_injection_points} ne 'yes') +{ + plan skip_all => 'Injection points not supported by this build'; +} + +my $common_conf = q( +shared_buffers = 128MB +autovacuum = off +bgwriter_lru_maxpages = 0 +checkpoint_timeout = 1h +); + +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init(allows_streaming => 1); + +my ($controldata) = run_command([ 'pg_controldata', $node->data_dir ]); +my ($segblocks) = + $controldata =~ /^Blocks per segment of large relation:\s+(\d+)$/m; +my ($blcksz) = $controldata =~ /^Database block size:\s+(\d+)$/m; +plan skip_all => "segment size is $segblocks blocks, more than 32" + if $segblocks > 32; +plan skip_all => "block size is $blcksz, more than 8192" + if $blcksz > 8192; + +$node->append_conf('postgresql.conf', $common_conf); +$node->start; + +foreach my $ext ('injection_points', 'pg_buffercache') +{ + plan skip_all => "Extension $ext not installed" + if !$node->check_extension($ext); +} + +# Run a script in one session, and return the last line of its output together +# with the number of detached opens and of adoptions the session reported. The +# injection points are attached for this session only. +sub run_session +{ + my ($n, $db, $sql) = @_; + my ($stdout, $stderr) = ('', ''); + + $n->psql( + $db, qq{ +SELECT injection_points_set_local(); +SELECT injection_points_attach('md-detached-open', 'notice'); +SELECT injection_points_attach('md-detached-adopt', 'notice'); +$sql}, + stdout => \$stdout, + stderr => \$stderr, + on_error_die => 1, + on_error_stop => 1); + my $opens = () = $stderr =~ /injection point md-detached-open/g; + my $adopts = () = $stderr =~ /injection point md-detached-adopt/g; + return ((split /\n/, $stdout)[-1], $opens, $adopts); +} + +# With debug_discard_caches, every cache flush closes all segments, so that a +# session may open a segment again, and move fewer over. +my $discard = + $node->safe_psql('postgres', 'SHOW debug_discard_caches') ne '0'; + +sub opens_is +{ + my ($got, $expected, $name) = @_; + + return cmp_ok($got, '>=', $expected, $name) if $discard; + return is($got, $expected, $name); +} + +sub adopts_is +{ + my ($got, $expected, $name) = @_; + + return cmp_ok($got, '<=', $expected, $name) if $discard; + return is($got, $expected, $name); +} + +# Run a script once beforehand, while it finds nothing to write out, so that +# the catalog blocks it reads are in shared buffers. A read that misses could +# open a segment of a catalog as a detached segment, which would count too. +sub warm +{ + my ($n, $db, $sql) = @_; + + $n->safe_psql($db, $sql); + return; +} + +# A query that writes out and evicts the dirty buffers of the main fork of a +# relation beyond its first segment, from any database, in block order, and +# returns the number of segments written to. +sub evict_query +{ + my ($dboid, $filenode) = @_; + + return qq{ +SELECT count(DISTINCT b.relblocknumber / $segblocks) + FROM (SELECT bufferid, relblocknumber FROM pg_buffercache + WHERE reldatabase = $dboid AND relfilenode = $filenode + AND relforknumber = 0 AND relblocknumber >= $segblocks + ORDER BY relblocknumber) b, + LATERAL pg_buffercache_evict(b.bufferid) e + WHERE e.buffer_flushed; +}; +} + +sub evict_table +{ + my ($n, $table) = @_; + + return evict_query( + split /\|/, + $n->safe_psql( + 'postgres', qq{ +SELECT oid, pg_relation_filenode('$table') FROM pg_database + WHERE datname = current_database()})); +} + +# A table of $rows rows filled across many segments. +sub create_filled +{ + my ($name, $rows) = @_; + + return qq{ +CREATE TABLE $name (id int, n int, pad text) WITH (fillfactor = 10); +INSERT INTO $name SELECT g, 0, repeat('x', 200) FROM generate_series(1, $rows) g; +CREATE INDEX ON $name (id); +}; +} + +$node->safe_psql('postgres', + 'CREATE EXTENSION injection_points; CREATE EXTENSION pg_buffercache;'); +$node->safe_psql('postgres', 'CREATE DATABASE other'); +$node->safe_psql('other', + 'CREATE EXTENSION injection_points; CREATE EXTENSION pg_buffercache;'); +$node->safe_psql('postgres', + create_filled('t', 3600) . create_filled('td', 1200)); + +# Pick two rows, in the first and the last block, of each of 16 segments +# after the first, neighbors among them: more than the hash table of detached +# segments holds before it grows, which moves its entries. Writing out a +# segment's second block finds the segment open. %id_in_seg maps those +# segment numbers to the id of the first row. +my (%min_id, %max_id); +foreach ( + split /\n/, + $node->safe_psql( + 'postgres', qq{ +SELECT (ctid::text::point)[0]::int / $segblocks, min(id), max(id) + FROM t GROUP BY 1})) +{ + my ($seg, $lo, $hi) = split /\|/; + $min_id{$seg} = $lo; + $max_id{$seg} = $hi; +} +my $last = (sort { $b <=> $a } keys %min_id)[0]; +cmp_ok($last, '>=', 20, 't spans many segments'); +my @segs = (1, 2, map { $last - $_ } reverse(0 .. 13)); +my %id_in_seg = map { $_ => $min_id{$_} } @segs; + +my $nseg = scalar(@segs); +my $ids = join(',', map { ($min_id{$_}, $max_id{$_}) } @segs); + +# Dirty the buffer of each chosen row, keeping track of the sum of n over +# them. +my $sum_n = 0; + +sub dirty_rows +{ + $node->safe_psql( + 'postgres', qq{ +SET enable_seqscan = off; +UPDATE t SET n = n + 1 WHERE id IN ($ids); +}); + $sum_n += 2 * $nseg; + return; +} +my $read_rows = qq{ +SET enable_seqscan = off; +SELECT sum(n) FROM t WHERE id IN ($ids); +}; +my $evict_t = evict_table($node, 't'); + +# Write out the buffers dirtied by setting hint bits above. +$node->safe_psql('postgres', 'CHECKPOINT'); + +$node->backup('bkp'); +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($node, 'bkp', has_streaming => 1); +$standby->start; + + +# A backend of another database writes out the dirty buffers. It has no +# relcache entry for t, and opens each segment as a detached segment. +warm($node, 'other', $evict_t); +dirty_rows(); +my ($out, $opens, $adopts) = run_session($node, 'other', $evict_t); +is($out, $nseg, 'a dirty buffer in each chosen segment written out'); +opens_is($opens, $nseg, 'each written through a detached open'); +adopts_is($adopts, 0, 'no detached segment moved over'); +$node->safe_psql('postgres', 'CHECKPOINT'); +$node->append_conf('postgresql.conf', + "fsync = on\nlog_min_messages = notice\nlog_line_prefix = '%m [%p] %b '"); +$node->restart; +is($node->safe_psql('postgres', $read_rows), + $sum_n, 'those writes survive restart'); + +# The checkpointer writes out dirty buffers through detached opens as well, +# and then syncs those segments through the descriptors it holds, which needs +# fsync on. Its notices go to the server log. +$node->safe_psql('postgres', + "SELECT injection_points_attach('md-detached-open', 'notice')"); +dirty_rows(); +my $log_offset = -s $node->logfile; +$node->safe_psql('postgres', 'CHECKPOINT'); +$node->safe_psql('postgres', + "SELECT injection_points_detach('md-detached-open')"); +my $ckpt_opens = () = slurp_file($node->logfile, $log_offset) =~ + /checkpointer NOTICE: notice triggered for injection point md-detached-open/g; +cmp_ok($ckpt_opens, '>=', $nseg, + 'checkpointer writes through detached opens'); +$node->stop('immediate'); +$node->start; +is($node->safe_psql('postgres', $read_rows), + $sum_n, 'checkpointed writes survive crash recovery'); + +# In one transaction, write out the buffers before using t, then scan t +# sequentially. Computing its size for that opens its segments in sequence, +# which moves the detached segments over. +my $own_session = qq{ +BEGIN; +$evict_t +SELECT count(*) FROM t WHERE n >= 0; +$read_rows +COMMIT; +}; +warm($node, 'postgres', $own_session); +dirty_rows(); +($out, $opens, $adopts) = run_session($node, 'postgres', $own_session); +is($out, $sum_n, 'read after detached opens'); +opens_is($opens, $nseg, 'own buffers written through detached opens'); +adopts_is($adopts, $nseg, 'detached segments moved over'); + +# Recovery. After a checkpoint, the next change of each block is logged as a +# full-page image, and replay writes those to the high segments again. Also +# write to a high segment of a table that is then dropped, so that replay +# finds its files gone, and have a hot standby backend write the replayed +# blocks through detached opens. +$node->safe_psql('postgres', 'CHECKPOINT'); +my $tdpath = $node->data_dir . '/' + . $node->safe_psql('postgres', "SELECT pg_relation_filepath('td')"); +my $evict_td = evict_table($node, 'td'); +warm($node, 'other', $evict_td); +$node->safe_psql( + 'postgres', q{ +SET enable_seqscan = off; +UPDATE td SET n = n + 1 WHERE id = 1200; +}); +($out, $opens, $adopts) = run_session($node, 'other', $evict_td); +opens_is($opens, 1, + 'buffer of the table to drop written through a detached open'); +$node->safe_psql('postgres', 'DROP TABLE td'); + +$node->wait_for_replay_catchup($standby); +warm($standby, 'other', $evict_t); +warm($standby, 'postgres', $read_rows); +warm($node, 'other', $evict_t); +dirty_rows(); +$node->wait_for_replay_catchup($standby); +($out, $opens, $adopts) = run_session($standby, 'other', $evict_t); +is($out, $nseg, 'replayed changes written out on standby'); +opens_is($opens, $nseg, 'through detached opens'); +is($standby->safe_psql('postgres', $read_rows), + $sum_n, 'standby has the changes'); + +($out, $opens, $adopts) = run_session($node, 'other', $evict_t); +opens_is($opens, $nseg, + 'buffers written through detached opens before crash'); +$node->stop('immediate'); +$node->start; +is($node->safe_psql('postgres', $read_rows), + $sum_n, 'changes survive crash recovery'); +$node->safe_psql('postgres', 'CHECKPOINT'); +my @leftover = grep { -e } glob("$tdpath $tdpath.* ${tdpath}_*"); +is(scalar(@leftover), 0, 'no files of the dropped table remain'); + +dirty_rows(); +$node->wait_for_replay_catchup($standby); +is($standby->safe_psql('postgres', $read_rows), + $sum_n, 'standby follows after crash recovery'); +$standby->stop; + +my $stderr; + +# Reads. Fetching a toasted value does not compute the size of the toast +# relation, so a new session reads the chunks through detached opens. With +# the segment of the first chunk removed, the read fails with the error it +# reports when the segments are opened in sequence. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE tt (id int, v text); +ALTER TABLE tt ALTER COLUMN v SET STORAGE EXTERNAL; +INSERT INTO tt SELECT g, repeat(md5(g::text), 3200) + FROM generate_series(1, 8) g; +CHECKPOINT; +}); +my ($toastrel, $toastfilenode, $toastpath, $pgdboid) = split /\|/, + $node->safe_psql( + 'postgres', q{ +SELECT c.reltoastrelid::regclass, pg_relation_filenode(c.reltoastrelid), + pg_relation_filepath(c.reltoastrelid), d.oid + FROM pg_class c, pg_database d + WHERE c.relname = 'tt' AND d.datname = current_database()}); +$toastpath = $node->data_dir . "/$toastpath"; +my ($vfirst, $vlast) = split /\|/, $node->safe_psql( + 'postgres', qq{ +SELECT min((ctid::text::point)[0]::int / $segblocks), + max((ctid::text::point)[0]::int / $segblocks) + FROM $toastrel + WHERE chunk_id::text = + (SELECT pg_column_toast_chunk_id(v)::text FROM tt WHERE id = 8)}); +cmp_ok($vfirst, '>=', 2, 'toasted value lies beyond the second segment'); +my $evict_toast = qq{ +SELECT count(*) + FROM pg_buffercache b, LATERAL pg_buffercache_evict(b.bufferid) e + WHERE b.reldatabase = $pgdboid AND b.relfilenode = $toastfilenode + AND e.buffer_evicted; +}; +my $read_toast = 'SELECT length(v) FROM tt WHERE id = 8;'; + +warm($node, 'postgres', $read_toast); +$node->safe_psql('postgres', $evict_toast); +($out, $opens, $adopts) = run_session($node, 'postgres', $read_toast); +is($out, 102400, 'toasted value read'); +opens_is( + $opens, + $vlast - $vfirst + 1, + 'its chunks read through detached opens'); + +my $path = "$toastpath.$vfirst"; +$node->safe_psql('postgres', $evict_toast); +rename($path, "$path.moved") or die "could not rename $path: $!"; +$stderr = ''; +$node->psql('postgres', $read_toast, stderr => \$stderr); +like( + $stderr, + qr/could not open file ".*\.$vfirst" \(target block \d+\): No such file or directory/, + "read fails with segment $vfirst missing"); +rename("$path.moved", $path) or die "could not rename $path.moved: $!"; +is($node->safe_psql('postgres', $read_toast), + 102400, 'toasted value read once the segments are back'); + +$node->stop; + +# A table created in the current transaction is not WAL-logged but synced at +# commit, and is truncated in place. Have another backend write out its +# buffers through detached opens while the transaction is open, before and +# after truncating and refilling it, then crash right after commit. +my $minimal = PostgreSQL::Test::Cluster->new('minimal'); +$minimal->init; +$minimal->append_conf( + 'postgresql.conf', qq( +$common_conf +wal_level = minimal +max_wal_senders = 0 +wal_skip_threshold = 0 +)); +$minimal->start; +$minimal->safe_psql('postgres', + 'CREATE EXTENSION injection_points; CREATE EXTENSION pg_buffercache;'); + +my $ts_ids = '150, 350, 550, 750, 940, 1040, 1190'; +my $ts_update = "UPDATE ts SET n = n + 1 WHERE id IN ($ts_ids);"; +my $ts_nseg_query = qq{ +SELECT count(DISTINCT (ctid::text::point)[0]::int / $segblocks) FROM ts + WHERE id IN ($ts_ids)}; + +my $dboid = $minimal->safe_psql('postgres', + "SELECT oid FROM pg_database WHERE datname = current_database()"); +warm($minimal, 'postgres', evict_query($dboid, 0)); +my $session = $minimal->background_psql('postgres', on_error_stop => 1); +$session->query_safe('BEGIN; ' . create_filled('ts', 1200) . $ts_update); +my $evict_ts = + evict_query($dboid, + $session->query_safe("SELECT pg_relation_filenode('ts')")); +my $ts_nseg = $session->query_safe($ts_nseg_query); +cmp_ok($ts_nseg, '>=', 5, 'chosen rows of ts lie in several segments'); + +($out, $opens, $adopts) = run_session($minimal, 'postgres', $evict_ts); +cmp_ok($out, '>=', $ts_nseg, 'buffers of the new table written out'); +opens_is($opens, $out, 'through detached opens'); + +$session->query_safe( + "TRUNCATE ts; INSERT INTO ts SELECT g, 0, repeat('z', 200) FROM generate_series(1, 1200) g; $ts_update" +); +($out, $opens, $adopts) = run_session($minimal, 'postgres', $evict_ts); +cmp_ok($out, '>=', $ts_nseg, 'buffers of the refilled table written out'); +opens_is($opens, $out, 'through detached opens'); + +$session->query_safe('COMMIT'); +$session->quit; + +my $ts_state = q{ +SELECT count(*), sum(n), count(*) FILTER (WHERE pad LIKE 'z%') FROM ts}; +is($minimal->safe_psql('postgres', $ts_state), + '1200|7|1200', 'contents of truncated and refilled table'); +$minimal->stop('immediate'); +$minimal->start; +is($minimal->safe_psql('postgres', $ts_state), + '1200|7|1200', 'synced table survives crash recovery'); +$minimal->stop; + +done_testing(); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb46926..afb982fe65 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1732,6 +1732,7 @@ Material MaterialInstrumentation MaterialPath MaterialState +MdDetachedSeg MdPathStr MdfdVec Memoize @@ -3962,6 +3963,8 @@ max_parallel_hazard_context mbcharacter_incrementer mblen_function mbverifychar_function +mdds_hash +mdds_iterator memoize_hash memoize_iterator metastring -- 2.43.0