From 89007b7de300dd3212149bbf6f507fcb288234ec Mon Sep 17 00:00:00 2001 From: Greg Burd Date: Thu, 26 Nov 2026 12:14:05 -0500 Subject: [PATCH v17] nbtree: add opt-in leaf key prefix compression. Add a prefix_compression storage parameter for btree indexes, default off. When it is on, a leaf page written as a whole (by CREATE INDEX, or as either half of a split) stores the leading bytes that runs of its data items share once, in a per-page directory, and keeps only each item's remainder. Indexes on keys with long shared prefixes, such as URLs, paths, and multi-column keys with low-cardinality leading columns, get smaller. A variable-length key column stores a 1- or 4-byte length header ahead of its bytes, and that header changes with each datum's length, so a run of keys that share a long value but differ in length would have the differing header break the shared span. The coder shares across that by carving out the header of the one column where a member first differs from its group's representative: every earlier column the member shares whole has the same length, hence an identical header and alignment, and shares as ordinary bytes, while the differing column's header stays with the member. A coded item records the fully shared leading bytes and the divergent column's shared value bytes. Keys that share a low-cardinality leading column and a long prefix of a later variable-length column (a tenant id and an order id, a path and a filename) compress where sharing the raw bytes would stop at the first header. Finding the divergence walks the key columns by their stored layout (attlen, attalign, by-value) and the null bitmap, the same walk for the build estimate, the page layout, encoding, decoding, and the corruption check, so they cannot disagree. Keys whose stored bytes differ within the first column still gain little. Sharing is by identical stored bytes, never by opclass equality, and decoding reproduces each tuple byte for byte. That makes the feature correct for every type and collation without equalimage support, and lets decoding use only the page, never the catalog. The key-column layout the walk needs lives in the directory, written by the primary from the catalog and read back from the page. Deduplication keeps its existing equalimage gate and composes with prefix compression: it merges decoded copies and re-codes the result. A coded leaf carries the new BTP_PREFIX flag and one directory item at the first data offset. Data items keep their real heap TIDs and posting lists in the standard layout, and pivot tuples are never coded, so VACUUM, deletion, LP_DEAD hinting, and suffix truncation work unchanged. Neither BTREE_VERSION nor BTPageOpaqueData changes. Pages convert only when next written whole, so existing indexes and pg_upgrade need nothing, and changing the parameter rewrites nothing. A server without this change cannot read coded pages. A coded leaf can hold more than a page of decoded data, yet must always split into two plain pages. The directory caches the decoded size of its items, and an insert splits the page before that guarantee could fail; an incoming tuple too large to leave a legal split point causes the existing items to be split alone and the insert retried. Admission also checks the INDEX_SIZE_MASK limit on the directory and on each coded item, which a page can exceed while still having free space. Splits of coded pages use the ordinary split chooser when the decoded items fit on one page, and honor fillfactor on the rightmost page otherwise. WAL replay rebuilds coded pages by repeating the primary's steps, without full-page images. xl_btree_split gains a flags field recording whether the original page and each half were coded, which requires an XLOG_PAGE_MAGIC bump. Rebuilding a coded left half needs the key-column layout; redo takes it from the original page's directory when that page was coded, and when the original was plain the primary logs the layout after the record under XLH_SPLIT_LEFT_DESC. Either source keeps redo off the catalog without a full-page image. amcheck and pageinspect validate coded pages before decoding them, and pageinspect shows coded items decoded. Coding adds CPU work to index builds, inserts, and scans that read keys; scans that need only heap TIDs skip decoding when every scan key is already satisfied for the page. Reviewed-by: Peter Geoghegan Reviewed-by: Yao Feng Discussion: https://postgr.es/m/at-01F1wsXLRH0qo@floki --- contrib/amcheck/Makefile | 2 +- contrib/amcheck/expected/check_btree.out | 41 + contrib/amcheck/meson.build | 4 + contrib/amcheck/sql/check_btree.sql | 28 + contrib/amcheck/t/004_verify_nbtree_unique.pl | 37 + contrib/amcheck/t/007_prefix.pl | 263 +++ contrib/amcheck/t/008_prefix_limits.pl | 186 ++ contrib/amcheck/t/009_prefix_split.pl | 143 ++ contrib/amcheck/t/010_prefix_multicol.pl | 211 ++ contrib/amcheck/verify_nbtree.c | 118 +- contrib/pageinspect/btreefuncs.c | 24 +- contrib/pageinspect/expected/btree.out | 42 + contrib/pageinspect/sql/btree.sql | 30 + doc/src/sgml/pageinspect.sgml | 12 + doc/src/sgml/ref/create_index.sgml | 41 + src/backend/access/common/reloptions.c | 10 + src/backend/access/nbtree/Makefile | 1 + src/backend/access/nbtree/README | 124 ++ src/backend/access/nbtree/meson.build | 1 + src/backend/access/nbtree/nbtdedup.c | 142 +- src/backend/access/nbtree/nbtinsert.c | 393 +++- src/backend/access/nbtree/nbtpage.c | 2 + src/backend/access/nbtree/nbtprefix.c | 1833 +++++++++++++++++ src/backend/access/nbtree/nbtreadpage.c | 119 +- src/backend/access/nbtree/nbtree.c | 1 + src/backend/access/nbtree/nbtsearch.c | 47 +- src/backend/access/nbtree/nbtsort.c | 284 ++- src/backend/access/nbtree/nbtsplitloc.c | 7 + src/backend/access/nbtree/nbtutils.c | 4 +- src/backend/access/nbtree/nbtxlog.c | 239 ++- src/backend/access/rmgrdesc/nbtdesc.c | 6 + src/include/access/nbtree.h | 161 +- src/include/access/nbtxlog.h | 24 +- src/test/recovery/Makefile | 4 +- src/test/recovery/meson.build | 1 + src/test/recovery/t/062_nbtree_prefix.pl | 470 +++++ src/test/regress/expected/btree_index.out | 355 ++++ src/test/regress/sql/btree_index.sql | 210 ++ src/tools/pgindent/typedefs.list | 9 + 39 files changed, 5466 insertions(+), 163 deletions(-) create mode 100644 contrib/amcheck/t/007_prefix.pl create mode 100644 contrib/amcheck/t/008_prefix_limits.pl create mode 100644 contrib/amcheck/t/009_prefix_split.pl create mode 100644 contrib/amcheck/t/010_prefix_multicol.pl create mode 100644 src/backend/access/nbtree/nbtprefix.c create mode 100644 src/test/recovery/t/062_nbtree_prefix.pl diff --git a/contrib/amcheck/Makefile b/contrib/amcheck/Makefile index 1b7a63cbaa4..49ea1b3076f 100644 --- a/contrib/amcheck/Makefile +++ b/contrib/amcheck/Makefile @@ -15,7 +15,7 @@ PGFILEDESC = "amcheck - function for verifying relation integrity" REGRESS = check check_btree check_gin check_heap -EXTRA_INSTALL = contrib/pg_walinspect +EXTRA_INSTALL = contrib/pageinspect contrib/pg_walinspect TAP_TESTS = 1 ifdef USE_PGXS diff --git a/contrib/amcheck/expected/check_btree.out b/contrib/amcheck/expected/check_btree.out index 4fcee5da463..6826bd3df27 100644 --- a/contrib/amcheck/expected/check_btree.out +++ b/contrib/amcheck/expected/check_btree.out @@ -283,6 +283,46 @@ SELECT bt_index_check('varlena_bug_idx', true); (1 row) +-- amcheck must decode prefix-compressed leaves and check the BTP_PREFIX +-- invariants. Most keys share a long prefix; the unshared key and the NULL +-- stay uncoded. The row count forces splits and deduplication. +CREATE TABLE prefix_bug (v text COLLATE "C"); +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad((g % 100)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug VALUES ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_check('prefix_bug_idx', heapallindexed => true); + bt_index_check +---------------- + +(1 row) + +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + bt_index_parent_check +----------------------- + +(1 row) + +-- The final leaf's decoded split budget includes its last posting tuple, +-- not the smaller high key that would replace it on a non-rightmost leaf. +DROP INDEX prefix_bug_idx; +TRUNCATE prefix_bug; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || lpad(g::text, 4, '0') + FROM generate_series(1, 106) g; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || '0107' FROM generate_series(1, 113); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + bt_index_parent_check +----------------------- + +(1 row) + -- cleanup DROP TABLE bttest_a; DROP TABLE bttest_b; @@ -294,3 +334,4 @@ DROP TABLE bttest_unique_nulls; DROP OWNED BY regress_bttest_role; -- permissions DROP ROLE regress_bttest_role; DROP TABLE varlena_bug; +DROP TABLE prefix_bug; diff --git a/contrib/amcheck/meson.build b/contrib/amcheck/meson.build index d5137ef691d..0cdb7ac85a0 100644 --- a/contrib/amcheck/meson.build +++ b/contrib/amcheck/meson.build @@ -50,6 +50,10 @@ tests += { 't/004_verify_nbtree_unique.pl', 't/005_pitr.pl', 't/006_verify_gin.pl', + 't/007_prefix.pl', + 't/008_prefix_limits.pl', + 't/009_prefix_split.pl', + 't/010_prefix_multicol.pl', ], }, } diff --git a/contrib/amcheck/sql/check_btree.sql b/contrib/amcheck/sql/check_btree.sql index a5585085fad..ee3964633bc 100644 --- a/contrib/amcheck/sql/check_btree.sql +++ b/contrib/amcheck/sql/check_btree.sql @@ -183,6 +183,33 @@ INSERT INTO varlena_bug VALUES (repeat('Test', 250)); ALTER TABLE varlena_bug ALTER COLUMN v SET STORAGE extended; SELECT bt_index_check('varlena_bug_idx', true); +-- amcheck must decode prefix-compressed leaves and check the BTP_PREFIX +-- invariants. Most keys share a long prefix; the unshared key and the NULL +-- stay uncoded. The row count forces splits and deduplication. +CREATE TABLE prefix_bug (v text COLLATE "C"); +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad((g % 100)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug VALUES ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_check('prefix_bug_idx', heapallindexed => true); +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + +-- The final leaf's decoded split budget includes its last posting tuple, +-- not the smaller high key that would replace it on a non-rightmost leaf. +DROP INDEX prefix_bug_idx; +TRUNCATE prefix_bug; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || lpad(g::text, 4, '0') + FROM generate_series(1, 106) g; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || '0107' FROM generate_series(1, 113); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + -- cleanup DROP TABLE bttest_a; DROP TABLE bttest_b; @@ -194,3 +221,4 @@ DROP TABLE bttest_unique_nulls; DROP OWNED BY regress_bttest_role; -- permissions DROP ROLE regress_bttest_role; DROP TABLE varlena_bug; +DROP TABLE prefix_bug; diff --git a/contrib/amcheck/t/004_verify_nbtree_unique.pl b/contrib/amcheck/t/004_verify_nbtree_unique.pl index 7d5c387325a..b750e5311ab 100644 --- a/contrib/amcheck/t/004_verify_nbtree_unique.pl +++ b/contrib/amcheck/t/004_verify_nbtree_unique.pl @@ -250,5 +250,42 @@ like( qr/index uniqueness is violated for index "bttest_unique_idx3"/, 'detected uniqueness violation for index "bttest_unique_idx3"'); +# Mark an index containing duplicates as unique. Prefix decoding reuses its +# tuple buffer, but the diagnostic must retain the previous entry's heap TID. +$node->safe_psql( + 'postgres', q( + CREATE TABLE bttest_unique_prefix (u text COLLATE "C"); + INSERT INTO bttest_unique_prefix + SELECT repeat('prefix/', 12) || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; + INSERT INTO bttest_unique_prefix + SELECT u FROM bttest_unique_prefix + WHERE u = repeat('prefix/', 12) || '0010'; + CREATE INDEX bttest_unique_prefix_idx ON bttest_unique_prefix (u) + WITH (prefix_compression = on, deduplicate_items = off); + UPDATE pg_index SET indisunique = true + WHERE indexrelid = 'bttest_unique_prefix_idx'::regclass; +)); +my $duplicate_tids = $node->safe_psql( + 'postgres', q( + SELECT string_agg('tid=' || ctid::text, ' and ' ORDER BY ctid) + FROM bttest_unique_prefix + WHERE u = repeat('prefix/', 12) || '0010'; +)); +for my $check ('bt_index_check', 'bt_index_parent_check') +{ + my $args = $check eq 'bt_index_check' ? 'true, true' : 'true, true, true'; + ($result, $stdout, $stderr) = $node->psql( + 'postgres', "SELECT $check('bttest_unique_prefix_idx', $args)"); + like( + $stderr, + qr/index uniqueness is violated for index "bttest_unique_prefix_idx"/, + "$check detects uniqueness violation in prefix-compressed index"); + like( + $stderr, + qr/point to heap \Q$duplicate_tids\E/, + "$check reports both distinct heap TIDs in prefix-compressed index"); +} + $node->stop; done_testing(); diff --git a/contrib/amcheck/t/007_prefix.pl b/contrib/amcheck/t/007_prefix.pl new file mode 100644 index 00000000000..b32d580edb4 --- /dev/null +++ b/contrib/amcheck/t/007_prefix.pl @@ -0,0 +1,263 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Corrupt prefix metadata must make amcheck and index scans report data +# corruption rather than crash. +use strict; +use warnings FATAL => 'all'; + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('prefix'); +$node->init(no_data_checksums => 1); +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; +$node->safe_psql( + 'postgres', q( + CREATE EXTENSION amcheck; + CREATE TABLE prefix_data (u text COLLATE "C"); + INSERT INTO prefix_data + SELECT repeat('prefix/', 12) || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; + CREATE TABLE prefix_posting AS + SELECT u FROM prefix_data CROSS JOIN generate_series(1, 4); +)); +my $blksize = $node->safe_psql('postgres', 'SHOW block_size'); +my $align = $node->safe_psql('postgres', + 'SELECT max_data_alignment FROM pg_control_init()'); +my $little_endian = pack('L', 1) eq "\x01\x00\x00\x00"; + +# ItemIdData is a native-endian bitfield; tuple metadata uses native uint16. +sub itemid +{ + my ($page, $offnum) = @_; + my $lp = unpack('L', substr($page, 24 + 4 * ($offnum - 1), 4)); + return $little_endian + ? ($lp & 0x7fff, $lp >> 17) + : ($lp >> 17, $lp & 0x7fff); +} + +sub put_short +{ + my ($page, $offset, $value) = @_; + substr($$page, $offset, 2) = pack('S', $value); + return; +} + +# anchoroff[0] follows the fixed header (IndexTupleData 8, ngroups, decodedsz, +# maxdecoded, natts: through byte 16) and then natts 4-byte layout records. +sub anchoroff0 +{ + my ($p, $d) = @_; + my $natts = unpack('S', substr($$p, $d + 14, 2)); + return $d + 16 + 4 * $natts; +} + +# Each case changes one field in its own index. Include a later member so a +# comparison with the next item cannot decode it before it has been checked. +my @cases = ( + [ + 'group', 0, + sub { my ($p, $d, $m) = @_; put_short($p, $m + 8, 65535); } + ], + [ + 'shared length', + 0, sub { my ($p, $d, $m) = @_; put_short($p, $m + 12, 65535); } + ], + [ + 'original size', + 0, sub { my ($p, $d, $m) = @_; put_short($p, $m + 14, 0); } + ], + [ + 'residual extent', + 0, sub { my ($p, $d, $m) = @_; put_short($p, $m + 12, 0); } + ], + [ + 'directory group count', + 0, sub { my ($p, $d) = @_; put_short($p, $d + 8, 65535); } + ], + [ + 'anchor offset', + 0, sub { my ($p, $d) = @_; put_short($p, anchoroff0($p, $d), 65535); } + ], + [ + 'anchor size', + 0, + sub { + my ($p, $d) = @_; + my $a = unpack('S', substr($$p, anchoroff0($p, $d), 2)); + put_short($p, $d + $a, 65535); + } + ], + [ + 'anchor tuple size', + 0, + sub { + my ($p, $d) = @_; + my $a = unpack('S', substr($$p, anchoroff0($p, $d), 2)); + put_short($p, $d + $a + $align + 6, 0); + } + ], + [ + 'decoded size cache', + 0, sub { my ($p, $d) = @_; put_short($p, $d + 10, 0); } + ], + [ + 'short code header', + 0, + sub { + my ($p, $d, $m) = @_; + my $lp = unpack('L', substr($$p, 32, 4)); + $lp = + $little_endian + ? (($lp & 0x1ffff) | (8 << 17)) + : (($lp & 0xffff8000) | 8); + substr($$p, 32, 4) = pack('L', $lp); + put_short($p, $m + 6, 8); + } + ], + [ + 'posting offset', + 1, + sub { + my ($p, $d, $m) = @_; + put_short($p, $m, 0); + put_short($p, $m + 2, 65535); + } + ], + [ + 'posting count', + 1, + sub { + my ($p, $d, $m) = @_; + put_short($p, $m + 4, 0x2000 | 0x0fff); + } + ], + [ + 'pivot member', + 0, + sub { + my ($p) = @_; + my $maxoff = (unpack('S', substr($$p, 12, 2)) - 24) / 4; + my ($m) = itemid($$p, 2 + int(($maxoff - 1) / 2)); + my $info = unpack('S', substr($$p, $m + 6, 2)); + put_short($p, $m + 6, $info | 0x2000); + } + ], + [ + 'member line pointer', + 0, + sub { + my ($p) = @_; + my $maxoff = (unpack('S', substr($$p, 12, 2)) - 24) / 4; + my $lp_off = 24 + 4 * (1 + int(($maxoff - 1) / 2)); + my $lp = unpack('L', substr($$p, $lp_off, 4)); + $lp = $little_endian + ? (($lp & 0xffff8000) | 32760) + : (($lp & 0x1ffff) | (32760 << 17)); + substr($$p, $lp_off, 4) = pack('L', $lp); + } + ],); + +my @paths; +for my $i (0 .. $#cases) +{ + my $table = $cases[$i][1] ? 'prefix_posting' : 'prefix_data'; + $node->safe_psql('postgres', + "CREATE TABLE prefix_case_$i AS TABLE $table; + CREATE INDEX prefix_idx_$i ON prefix_case_$i (u) + WITH (prefix_compression = on)" + ); + is( $node->safe_psql( + 'postgres', + "SELECT bt_index_parent_check('prefix_idx_$i', true, true)"), + '', + "$cases[$i][0]: clean index passes"); + push @paths, + $node->data_dir . '/' + . $node->safe_psql('postgres', + "SELECT pg_relation_filepath('prefix_idx_$i')"); +} + +# Stop before opening relation files, avoiding stale buffers and background +# writes. Checksums are disabled so the errors come from prefix validation. +$node->stop; +for my $i (0 .. $#cases) +{ + open(my $fh, '+<', $paths[$i]) or BAIL_OUT("open: $!"); + binmode $fh; + defined(sysseek($fh, $blksize, 0)) or BAIL_OUT("seek: $!"); + my $page; + sysread($fh, $page, $blksize) == $blksize or BAIL_OUT("read: $!"); + my $special = unpack('S', substr($page, 16, 2)); + my $flags = unpack('S', substr($page, $special + 12, 2)); + ($flags & 0x201) == 0x201 or BAIL_OUT('fixture is not a coded leaf'); + unpack('L', substr($page, $special + 4, 4)) == 0 + or BAIL_OUT('fixture leaf is not rightmost'); + my ($directory) = itemid($page, 1); + my ($member, $membersz) = itemid($page, 3); + my $info = unpack('S', substr($page, $member + 6, 2)); + ($info & 0x1fff) == $membersz or BAIL_OUT('fixture tuple size mismatch'); + + if ($cases[$i][1]) + { + ($info & 0x2000) + && (unpack('S', substr($page, $member + 4, 2)) & 0x2000) + or BAIL_OUT('fixture member is not a posting tuple'); + } + $cases[$i][2]->(\$page, $directory, $member); + defined(sysseek($fh, $blksize, 0)) or BAIL_OUT("seek: $!"); + syswrite($fh, $page) == $blksize or BAIL_OUT("write: $!"); + close($fh) or BAIL_OUT("close: $!"); +} +$node->start; + +for my $i (0 .. $#cases) +{ + for my $check ('bt_index_check', 'bt_index_parent_check') + { + my ($ret, $out, $err) = $node->psql('postgres', + "\\set VERBOSITY verbose\nSELECT $check('prefix_idx_$i');"); + is($ret, 3, "$cases[$i][0]: $check reports an error"); + like($err, qr/ERROR:\s+XX002:.*prefix/i, + "$cases[$i][0]: prefix corruption diagnostic"); + unlike( + $err, + qr/server closed the connection|terminated by signal/i, + "$cases[$i][0]: no backend crash"); + } +} + +# Index scans use the shared decoder without amcheck's whole-page +# validation. The pivot member and member line pointer cases damage the +# first binary-search midpoint, before any member is decoded. +my $scan_settings = q( + SET enable_seqscan = off; + SET enable_bitmapscan = off; + SET enable_indexonlyscan = off; +); +for my $i (0 .. $#cases) +{ + next unless $cases[$i][0] =~ + /^(group|shared length|short code header|posting offset|posting count|pivot member|member line pointer)$/; + my $query = "SELECT u FROM prefix_case_$i + WHERE u >= repeat('prefix/', 12) || '0001'"; + my $plan = $node->safe_psql('postgres', + "$scan_settings EXPLAIN (COSTS OFF) $query"); + like($plan, qr/Index Scan using prefix_idx_$i on prefix_case_$i\b/, + "$cases[$i][0]: direct index scan plan"); + note($plan); + my ($ret, $out, $err) = $node->psql('postgres', + "\\set VERBOSITY verbose\n$scan_settings $query"); + is($ret, 3, "$cases[$i][0]: direct scan reports an error"); + like($err, qr/ERROR:\s+XX002:.*prefix/i, + "$cases[$i][0]: direct scan prefix diagnostic"); + unlike($err, qr/server closed the connection|terminated by signal/i, + "$cases[$i][0]: direct scan does not crash"); +} + +is($node->safe_psql('postgres', 'SELECT 1'), + '1', 'node remains usable after corruption checks'); +$node->stop; +done_testing(); diff --git a/contrib/amcheck/t/008_prefix_limits.pl b/contrib/amcheck/t/008_prefix_limits.pl new file mode 100644 index 00000000000..c68abc380ce --- /dev/null +++ b/contrib/amcheck/t/008_prefix_limits.pl @@ -0,0 +1,186 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# A 32KB page can hold index tuples that exceed the prefix format's limits. +use strict; +use warnings FATAL => 'all'; +use Digest::MD5 qw(md5_hex); +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# The sizes asserted below assume 32KB pages and 8-byte alignment. +plan skip_all => 'prefix representation limits require 32KB pages and 8-byte alignment' + unless check_pg_config('^#define BLCKSZ 32768$') + && check_pg_config('^#define MAXIMUM_ALIGNOF 8$'); + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; + +$node->safe_psql('postgres', + 'CREATE EXTENSION amcheck; CREATE EXTENSION pageinspect;'); + +my $small_hash = md5_hex(pack('H*', 'ab' x 1024)); +my $large_hash = md5_hex(pack('H*', 'cd' x 8168)); + +# Check the structure and the exact indexed values, not just heap row counts. +# btpo_flags bits from nbtree.h: BTP_ROOT is 2, BTP_PREFIX is 512. +# Each table has only the index under test when this is called. +sub check_index +{ + my ($table, $expected, $description) = @_; + $node->safe_psql('postgres', "VACUUM ANALYZE $table"); + is( $node->safe_psql('postgres', + "SELECT bt_index_parent_check('${table}_idx', true, true)"), + '', "$description: amcheck"); + my $query = "SELECT a, count(*), octet_length(b), md5(b) FROM $table " + . 'GROUP BY a, b ORDER BY a'; + my $settings = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + like( + $node->safe_psql('postgres', + $settings . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using ${table}_idx/, + "$description: index-only scan"); + is($node->safe_psql('postgres', $settings . $query), + $expected, "$description: indexed values"); +} + +# Ten full anchors cannot fit in one directory IndexTuple, even though the +# page can hold them. The 50-row case also exceeds a plain page's capacity. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE directory (a smallint, b bytea); +ALTER TABLE directory ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO directory + SELECT a, decode(repeat('ab', 1024), 'hex') + FROM generate_series(1, 10) a, generate_series(1, 3) b; +}); +foreach my $copies (3, 5) +{ + $node->safe_psql( + 'postgres', q{ +CREATE INDEX directory_idx ON directory (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); + check_index('directory', + join("\n", map { "$_|$copies|1024|$small_hash" } 1 .. 10), + 'directory with ' . (10 * $copies) . ' rows'); + $node->safe_psql('postgres', 'DROP INDEX directory_idx'); + $node->safe_psql( + 'postgres', q{ +INSERT INTO directory + SELECT a, decode(repeat('ab', 1024), 'hex') + FROM generate_series(1, 10) a, generate_series(1, 2) b; +}) if $copies == 3; +} + +$node->safe_psql( + 'postgres', q{ +CREATE TABLE member (a smallint, b bytea); +ALTER TABLE member ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO member + SELECT 1, decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 3); +CREATE INDEX member_idx ON member (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); +is( $node->safe_psql('postgres', + "SELECT btpo_flags & 512 <> 0 FROM bt_page_stats('member_idx', 1)"), + 't', 'retail insertion starts with a coded leaf'); + +# Establish that the large key is legal in an ordinary index. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE plain (LIKE member); +ALTER TABLE plain ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO plain SELECT * FROM member; +CREATE INDEX plain_idx ON plain (a, b) WITH (deduplicate_items = off); +INSERT INTO plain VALUES (2, decode(repeat('cd', 8168), 'hex')); +}); +is( $node->safe_psql('postgres', + "SELECT max(itemlen) = 8184 FROM bt_page_items('plain_idx', 1)"), + 't', 'large plain tuple fits the index tuple size field'); +check_index('plain', "1|3|1024|$small_hash\n2|1|8168|$large_hash", + 'plain control'); + +# With no shared bytes, the coded header pushes the size over INDEX_SIZE_MASK. +$node->safe_psql('postgres', + "INSERT INTO member VALUES (2, decode(repeat('cd', 8168), 'hex'))"); +check_index('member', "1|3|1024|$small_hash\n2|1|8168|$large_hash", + 'retail member limit'); + +# A dense coded leaf can fit a plain page without leaving BTMaxItemSize free. +# Force a representation-limit split before, between, and after its key groups. +foreach my $incoming (0, 2, 4) +{ + my $table = "dense_$incoming"; + $node->safe_psql('postgres', qq{ +CREATE TABLE $table (a smallint, b bytea); +ALTER TABLE $table ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO $table + SELECT CASE WHEN n <= 12 THEN 1 ELSE 3 END, + decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 23) n; +CREATE INDEX ${table}_idx ON $table (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); + is( $node->safe_psql('postgres', qq{ +SELECT btpo_flags & 512 <> 0 AND btpo_level = 0 AND btpo_next = 0 + FROM bt_page_stats('${table}_idx', 1); +}), 't', "$table starts with a coded rightmost leaf"); + is( $node->safe_psql('postgres', qq{ +SELECT decoded = 23 * (1040 + 4) AND decoded <= 32724 + AND 32724 - decoded < 10896 AND decoded + 8184 + 4 <= 32724 + FROM (SELECT sum(8 + octet_length(decode(replace(data, ' ', ''), 'hex')) + 4) + AS decoded + FROM bt_page_items('${table}_idx', 1) WHERE itemoffset > 1) s; +}), 't', "$table fits plain but lacks the maximum-item reserve"); + $node->safe_psql('postgres', + "INSERT INTO $table VALUES ($incoming, decode(repeat('cd', 8168), 'hex'))"); + is( $node->safe_psql('postgres', qq{ +SELECT btpo_next <> 0 FROM bt_page_stats('${table}_idx', 1); +}), 't', "$table splits for an unrepresentable coded member"); + my %expected = (1 => "1|12|1024|$small_hash", + 3 => "3|11|1024|$small_hash", $incoming => "$incoming|1|8168|$large_hash"); + check_index($table, join("\n", map { $expected{$_} } sort { $a <=> $b } keys %expected), + "dense member insertion at $incoming"); +} + +# On little-endian hosts, 1 and 257 share one smallint byte; on big-endian +# hosts they share none. Either way the build estimator must reject the +# oversized member. +$node->safe_psql( + 'postgres', q{ +DELETE FROM member WHERE a = 2; +DROP INDEX member_idx; +INSERT INTO member VALUES (257, decode(repeat('cd', 8168), 'hex')); +CREATE INDEX member_idx ON member (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); +check_index('member', "1|3|1024|$small_hash\n257|1|8168|$large_hash", + 'build member limit'); + +# VACUUM removes the directory when the root becomes empty. +$node->safe_psql( + 'postgres', q{ +TRUNCATE member; +DROP INDEX member_idx; +INSERT INTO member + SELECT 1, decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 3); +CREATE INDEX member_idx ON member (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +DELETE FROM member; +VACUUM member; +}); +is( $node->safe_psql( + 'postgres', q{ +SELECT btpo_flags & 512 = 0 AND btpo_flags & 2 <> 0 + AND live_items = 0 AND dead_items = 0 + FROM bt_page_stats('member_idx', 1); +}), + 't', 'vacuum removes the empty root directory'); +$node->safe_psql('postgres', + "INSERT INTO member VALUES (2, decode(repeat('cd', 8168), 'hex'))"); +check_index('member', "2|1|8168|$large_hash", 'empty root insertion'); + +$node->stop; +done_testing(); diff --git a/contrib/amcheck/t/009_prefix_split.pl b/contrib/amcheck/t/009_prefix_split.pl new file mode 100644 index 00000000000..1a48c14f38d --- /dev/null +++ b/contrib/amcheck/t/009_prefix_split.pl @@ -0,0 +1,143 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Fillfactor must steer a rightmost split of a coded leaf. Both indexes split +# byte-identical pages, so only fillfactor differs. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +plan skip_all => 'prefix split fixture requires 8KB pages and 8-byte alignment' + unless check_pg_config('^#define BLCKSZ 8192$') + && check_pg_config('^#define MAXIMUM_ALIGNOF 8$'); + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; + +# Each key shares the long leading value, so a leaf codes tightly. The build +# loads 507 distinct keys with four duplicates each; deduplication merges each +# key's duplicates into one posting list, and the rightmost leaf ends coded, +# one directory short of a split. make_key(507..511) fill it; make_key(512) +# tips it. bt_page_stats block numbers are stable for this fixed build. +my $distinct = 507; + +$node->safe_psql( + 'postgres', qq{ +CREATE EXTENSION amcheck; +CREATE EXTENSION pageinspect; +CREATE FUNCTION make_key(n integer) RETURNS text LANGUAGE sql IMMUTABLE AS \$\$ + SELECT '/srv/objects/customer-0042/archive/' || lpad(n::text, 9, '0') || + '/' || repeat('a', 96) || '.json' +\$\$; +CREATE TABLE low (k text COLLATE "C"); +INSERT INTO low SELECT make_key(g / 4) + FROM generate_series(0, $distinct * 4 - 1) g; +CREATE INDEX low_idx ON low (k) WITH (prefix_compression = on); +CREATE TABLE high (LIKE low); +INSERT INTO high SELECT make_key(g / 4) + FROM generate_series(0, $distinct * 4 - 1) g; +CREATE INDEX high_idx ON high (k) WITH (prefix_compression = on); +}); + +# Find the rightmost leaf (btpo_next = 0) by block number rather than assuming +# an offset, so the test survives directory-layout changes. +my $rightblk = sub { + my ($table) = @_; + return $node->safe_psql('postgres', qq{ +SELECT b FROM generate_series(1, pg_relation_size('${table}_idx')/8192 - 1) b, + LATERAL bt_page_stats('${table}_idx', b) s + WHERE s.btpo_level = 0 AND s.btpo_next = 0; +}); +}; + +foreach my $table ('low', 'high') +{ + my $blk = $rightblk->($table); + is( $node->safe_psql('postgres', qq{ +SELECT btpo_flags & 512 <> 0 AND btpo_level = 0 + FROM bt_page_stats('${table}_idx', $blk); +}), 't', "$table rightmost leaf is coded"); +} + +# Skip pd_lsn, pd_checksum and pd_flags, which differ between the two pages. +my $lowblk = $rightblk->('low'); +my $highblk = $rightblk->('high'); +is( $node->safe_psql('postgres', qq{ +SELECT substring(get_raw_page('low_idx', $lowblk) FROM 13) = + substring(get_raw_page('high_idx', $highblk) FROM 13); +}), 't', 'fillfactor comparison starts with identical page contents'); + +# Even merging every equal key into a posting list cannot produce a plain +# page. The split must use the decoded-item array, not a temporary plain page. +is( $node->safe_psql('postgres', qq{ +SELECT sum(((8 + octet_length(decode(replace(data, ' ', ''), 'hex')) + + CASE WHEN n > 1 THEN n * 6 ELSE 0 END + 7) / 8) * 8 + 4) > + current_setting('block_size')::integer + FROM (SELECT data, sum(coalesce(cardinality(tids), 1)) n + FROM bt_page_items('low_idx', $lowblk) + WHERE itemoffset > 1 GROUP BY data) s; +}), 't', 'decoded leaf exceeds a page even after deduplication'); + +# Fill the rightmost leaf one directory short of a split, then tip both at the +# same insertion. Only fillfactor differs across the two indexes. +$node->safe_psql('postgres', qq{ +ALTER INDEX low_idx SET (fillfactor = 10); +ALTER INDEX high_idx SET (fillfactor = 90); +INSERT INTO low SELECT make_key(g) FROM generate_series($distinct, 511) g; +INSERT INTO high SELECT make_key(g) FROM generate_series($distinct, 511) g; +}); + +my %left_tids; +foreach my $table ('low', 'high') +{ + my $blk = $table eq 'low' ? $lowblk : $highblk; + is( $node->safe_psql('postgres', qq{ +SELECT btpo_next = 0 FROM bt_page_stats('${table}_idx', $blk); +}), 't', "$table rightmost leaf is one insertion short of a split"); +} + +$node->safe_psql('postgres', q{ +INSERT INTO low VALUES (make_key(512)); +INSERT INTO high VALUES (make_key(512)); +}); + +foreach my $table ('low', 'high') +{ + my $blk = $table eq 'low' ? $lowblk : $highblk; + is( $node->safe_psql('postgres', qq{ +SELECT btpo_next <> 0 FROM bt_page_stats('${table}_idx', $blk); +}), 't', "$table splits on the same insertion"); + $left_tids{$table} = $node->safe_psql('postgres', qq{ +SELECT sum(coalesce(cardinality(tids), 1)) + FROM bt_page_items('${table}_idx', $blk), bt_page_stats('${table}_idx', $blk) + WHERE itemoffset > 1 + CASE WHEN btpo_flags & 512 <> 0 THEN 1 ELSE 0 END; +}); + $node->safe_psql('postgres', "VACUUM ANALYZE $table"); + is( $node->safe_psql('postgres', + "SELECT bt_index_parent_check('${table}_idx', true, true)"), + '', "$table: amcheck"); + my $query = "SELECT md5(string_agg(k, ',' ORDER BY k)) FROM $table"; + my $expected = $node->safe_psql('postgres', + "SELECT md5(string_agg(k, ',' ORDER BY k)) FROM (" + . "SELECT make_key(g / 4) AS k" + . " FROM generate_series(0, $distinct * 4 - 1) g" + . " UNION ALL SELECT make_key(g)" + . " FROM generate_series($distinct, 512) g) s"); + my $settings = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + like( + $node->safe_psql('postgres', + $settings . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using ${table}_idx/, + "$table: index-only scan"); + is($node->safe_psql('postgres', $settings . $query), + $expected, "$table: indexed values"); +} + +cmp_ok($left_tids{high}, '>', $left_tids{low}, + 'higher fillfactor leaves more TIDs on the finalized left page'); + +$node->stop; +done_testing(); diff --git a/contrib/amcheck/t/010_prefix_multicol.pl b/contrib/amcheck/t/010_prefix_multicol.pl new file mode 100644 index 00000000000..b4ad47f8b5e --- /dev/null +++ b/contrib/amcheck/t/010_prefix_multicol.pl @@ -0,0 +1,211 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Prefix compression of a key with more than one variable-length column. When +# a run of rows shares a leading text column whole and shares a long prefix of +# the next text column, the coder shares the leading column across the next +# column's length-header boundary (lead_shared > 0) and still carves only the +# divergent column's header. The earlier format shared nothing past the first +# column's differing header, so lead_shared was always zero. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init(no_data_checksums => 1); +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; + +$node->safe_psql('postgres', + 'CREATE EXTENSION amcheck; CREATE EXTENSION pageinspect;'); + +# Rows share the whole first column (a) and a long, length-varying prefix of +# the second (b). b varies only in its trailing counter, so every b differs in +# length behind a 90-byte common prefix: the earlier format stops sharing at +# b's length header, v17 shares a fully and b's prefix. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE mc (a text COLLATE "C", b text COLLATE "C"); +INSERT INTO mc + SELECT '/srv/objects/customer-0042/archive', + '/path/segment/' || repeat('x', 76) || '/' || g + FROM generate_series(1, 4000) g; +CREATE INDEX mc_on ON mc (a, b) WITH (prefix_compression = on); +CREATE INDEX mc_off ON mc (a, b) WITH (prefix_compression = off); +}); + +# Every data leaf of mc_on is coded (BTP_PREFIX is 512). +is( $node->safe_psql( + 'postgres', q{ +SELECT count(*) FILTER (WHERE (btpo_flags & 512) = 0) = 0 + AND count(*) FILTER (WHERE (btpo_flags & 512) <> 0) > 0 + FROM generate_series(1, pg_relation_size('mc_on') / 8192 - 1) b, + LATERAL bt_page_stats('mc_on', b) s + WHERE s.type = 'l'; +}), + 't', + 'every data leaf of the multicolumn index is coded'); + +# Compression pays off: the coded index is materially smaller than the plain +# one. The saving comes from sharing a and b's common prefix together. +is( $node->safe_psql( + 'postgres', q{ +SELECT pg_relation_size('mc_on') * 4 < pg_relation_size('mc_off') * 3; +}), + 't', + 'multicolumn prefix compression shrinks the index'); + +# amcheck with heapallindexed compares every indexed datum with the heap, so a +# decode that lost or altered a byte would fail here. +is( $node->safe_psql('postgres', + "SELECT bt_index_parent_check('mc_on', true, true)"), + '', + 'multicolumn coded index passes bt_index_parent_check(heapallindexed)'); + +# An index-only scan returns bytes straight from the coded leaves; a heap +# sequential scan returns the stored heap bytes. They must agree exactly, +# including b's length, which the counter varies. +my $digest = q{md5(string_agg(a || '\x00' || b, '|' ORDER BY a, b))}; +my $ios = $node->safe_psql('postgres', qq{ +SET enable_seqscan = off; SET enable_bitmapscan = off; +SET enable_indexonlyscan = on; SET enable_indexscan = off; +SELECT count(*), $digest FROM mc; +}); +my $heap = $node->safe_psql('postgres', qq{ +SET enable_indexscan = off; SET enable_indexonlyscan = off; +SET enable_bitmapscan = off; SET enable_seqscan = on; +SELECT count(*), $digest FROM mc; +}); +is($ios, $heap, 'index-only scan is byte-identical to the heap'); + +like( + $node->safe_psql('postgres', qq{ +SET enable_seqscan = off; SET enable_bitmapscan = off; +SET enable_indexonlyscan = on; SET enable_indexscan = off; +EXPLAIN (COSTS OFF) SELECT count(*), $digest FROM mc; +}), + qr/Index Only Scan using mc_on/, + 'digest query uses an index-only scan on the coded index'); + +# The format change itself, read from the live page through pageinspect: every +# coded member carries lead_shared > 0, meaning the coder shared the first +# column across the second column's length header. The earlier single-column +# format always stored lead_shared = 0, so this subtest fails if the +# multi-column walk stops engaging. +# +# A coded member's item is [IndexTupleData 8 bytes][BTPrefixCode], and +# BTPrefixCode is group@+0, lead_shared@+2, shared_len@+4, so lead_shared sits +# at item byte +10 as a native-endian uint16. get_raw_page gives the raw page; +# the line pointer at page offset 24 + 4*(offnum-1) packs lp_off (bits 0..14) +# and lp_len (bits 17..31). bt_page_items reports the same length as itemlen, +# so lp_len = itemlen cross-checks the hand-parsed line pointer before the +10 +# read is trusted. Items 1 (high key) and 2 (prefix directory) are skipped; +# coded members start at offset 3 and are at least 16 bytes. The anchor's +# reference member shares b whole (lead_shared = total data-area bytes); the +# rest share a (35 bytes) plus b's common value prefix, so lead_shared is 35. +my $leadcheck = $node->safe_psql( + 'postgres', q{ +WITH leaves AS ( + SELECT blk + FROM generate_series(1, pg_relation_size('mc_on') / 8192 - 1) blk + WHERE (bt_page_stats('mc_on', blk::int)).type = 'l' + AND ((bt_page_stats('mc_on', blk::int)).btpo_flags & 512) <> 0 +), +raw AS (SELECT blk, get_raw_page('mc_on', blk::int) AS pg FROM leaves), +lp AS ( + SELECT r.blk, r.pg, off, + (v & 32767) AS lp_off, + (v >> 17) AS lp_len + FROM raw r, + LATERAL (SELECT get_byte(r.pg, 12) + get_byte(r.pg, 13) * 256 + AS pd_lower) hdr, + LATERAL generate_series(3, (hdr.pd_lower - 24) / 4) off, + LATERAL (SELECT get_byte(r.pg, 24 + 4 * (off - 1)) + + get_byte(r.pg, 24 + 4 * (off - 1) + 1) * 256 + + get_byte(r.pg, 24 + 4 * (off - 1) + 2) * 65536 + + get_byte(r.pg, 24 + 4 * (off - 1) + 3) * 16777216 + AS v) t +), +member AS ( + SELECT blk, off, lp_off, lp_len, + get_byte(pg, lp_off + 10) + get_byte(pg, lp_off + 11) * 256 + AS lead_shared + FROM lp + WHERE lp_len >= 16 +), +xcheck AS ( + SELECT bool_and(m.lp_len = i.itemlen) AS ok + FROM member m + JOIN LATERAL bt_page_items('mc_on', m.blk::int) i + ON i.itemoffset = m.off +) +SELECT (SELECT count(*) FROM member) > 0 + AND (SELECT count(*) FILTER (WHERE lead_shared = 0) FROM member) = 0 + AND (SELECT min(lead_shared) FROM member) = 35 + AND (SELECT ok FROM xcheck); +}); +is($leadcheck, 't', + 'every coded member shares a leading column past the next column header'); + +# Straddle the varlena short/long header boundary. b keeps a 118-byte common +# prefix, then a run of 'q' whose length (2..18) carries the total across 127, +# then '/' and the unique counter. Members below 127 bytes store a one-byte +# length header, members at or above store a four-byte one, so one group mixes +# both header widths. Decode splices the shared value after each member's own +# header using the anchor's header width; a one-byte error there (ahdr off by +# one) reads the anchor's shared bytes shifted by a byte and corrupts a byte +# that survived into the reconstructed key. amcheck heapallindexed and the +# index-only-scan digest below both catch that corruption. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE sm (a text COLLATE "C", b text COLLATE "C"); +INSERT INTO sm + SELECT 'const-a', + repeat('p', 118) || repeat('q', (g % 17) + 2) || '/' || g + FROM generate_series(1, 4000) g; +CREATE INDEX sm_on ON sm (a, b) WITH (prefix_compression = on); +}); + +# Both header widths occur, and the index is coded. +is( $node->safe_psql( + 'postgres', q{ +SELECT count(*) FILTER (WHERE length(b) <= 126) > 0 + AND count(*) FILTER (WHERE length(b) >= 127) > 0 + FROM sm; +}), + 't', + 'straddle data mixes one-byte and four-byte varlena headers'); + +is( $node->safe_psql( + 'postgres', q{ +SELECT count(*) FILTER (WHERE (btpo_flags & 512) = 0) = 0 + AND count(*) FILTER (WHERE (btpo_flags & 512) <> 0) > 0 + FROM generate_series(1, pg_relation_size('sm_on') / 8192 - 1) b, + LATERAL bt_page_stats('sm_on', b) s + WHERE s.type = 'l'; +}), + 't', + 'every data leaf of the straddle index is coded'); + +is( $node->safe_psql('postgres', + "SELECT bt_index_parent_check('sm_on', true, true)"), + '', + 'straddle coded index passes bt_index_parent_check(heapallindexed)'); + +my $sm_digest = q{md5(string_agg(a || '\x00' || b, '|' ORDER BY a, b))}; +my $sm_ios = $node->safe_psql('postgres', qq{ +SET enable_seqscan = off; SET enable_bitmapscan = off; +SET enable_indexonlyscan = on; SET enable_indexscan = off; +SELECT count(*), $sm_digest FROM sm; +}); +my $sm_heap = $node->safe_psql('postgres', qq{ +SET enable_indexscan = off; SET enable_indexonlyscan = off; +SET enable_bitmapscan = off; SET enable_seqscan = on; +SELECT count(*), $sm_digest FROM sm; +}); +is($sm_ios, $sm_heap, + 'straddle index-only scan is byte-identical to the heap'); + +$node->stop; +done_testing(); diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c index 97c519b47f5..3821e9eeacd 100644 --- a/contrib/amcheck/verify_nbtree.c +++ b/contrib/amcheck/verify_nbtree.c @@ -131,6 +131,10 @@ typedef struct BtreeCheckState bloom_filter *filter; /* Debug counter */ int64 heaptuplespresent; + + /* Decode workspaces for prefix-compressed leaf items */ + BTItemBuf itembuf; /* current target item */ + BTItemBuf nextbuf; /* any other item looked at meanwhile */ } BtreeCheckState; /* @@ -158,7 +162,8 @@ typedef struct BtreeLastVisibleEntry OffsetNumber offset; /* Offset on index block */ int postingIndex; /* Number in the posting list (-1 for * non-deduplicated tuples) */ - ItemPointer tid; /* Heap tid */ + ItemPointerData tid; /* Heap tid, copied: a decoded item's buffer + * is reused */ } BtreeLastVisibleEntry; /* @@ -230,6 +235,7 @@ static inline bool invariant_l_nontarget_offset(BtreeCheckState *state, Page nontarget, OffsetNumber upperbound); static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum); +static void bt_prefix_page_check(BtreeCheckState *state, Page page, BlockNumber blocknum); static inline BTScanInsert bt_mkscankey_pivotsearch(Relation rel, IndexTuple itup); static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, @@ -868,8 +874,8 @@ bt_report_duplicate(BtreeCheckState *state, *pnposting = ""; htid = psprintf("tid=(%u,%u)", - ItemPointerGetBlockNumberNoCheck(lVis->tid), - ItemPointerGetOffsetNumberNoCheck(lVis->tid)); + ItemPointerGetBlockNumberNoCheck(&lVis->tid), + ItemPointerGetOffsetNumberNoCheck(&lVis->tid)); nhtid = psprintf("tid=(%u,%u)", ItemPointerGetBlockNumberNoCheck(nexttid), ItemPointerGetOffsetNumberNoCheck(nexttid)); @@ -916,7 +922,7 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, if (heap_entry_is_visible(state, tid)) { has_visible_entry = true; - if (ItemPointerIsValid(lVis->tid)) + if (ItemPointerIsValid(&lVis->tid)) { bt_report_duplicate(state, lVis, @@ -929,13 +935,13 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, * between the posting list entries of the first tuple on the * page after cross-page check. */ - if (lVis->blkno != targetblock && ItemPointerIsValid(lVis->tid)) + if (lVis->blkno != targetblock && ItemPointerIsValid(&lVis->tid)) return; lVis->blkno = targetblock; lVis->offset = offset; lVis->postingIndex = i; - lVis->tid = tid; + lVis->tid = *tid; } } } @@ -951,7 +957,7 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, if (heap_entry_is_visible(state, tid)) { has_visible_entry = true; - if (ItemPointerIsValid(lVis->tid)) + if (ItemPointerIsValid(&lVis->tid)) { bt_report_duplicate(state, lVis, @@ -961,7 +967,7 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, lVis->blkno = targetblock; lVis->offset = offset; - lVis->tid = tid; + lVis->tid = *tid; lVis->postingIndex = -1; } } @@ -981,8 +987,8 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, RelationGetRelationName(state->rel)), errdetail("It doesn't have visible heap tids and key is equal to the tid=(%u,%u)%s (points to heap tid=(%u,%u)).", lVis->blkno, lVis->offset, posting, - ItemPointerGetBlockNumberNoCheck(lVis->tid), - ItemPointerGetOffsetNumberNoCheck(lVis->tid)), + ItemPointerGetBlockNumberNoCheck(&lVis->tid), + ItemPointerGetOffsetNumberNoCheck(&lVis->tid)), errhint("VACUUM the table and repeat the check."))); } } @@ -1230,7 +1236,12 @@ bt_target_page_check(BtreeCheckState *state) BTPageOpaque topaque; /* Last visible entry info for checking indexes with unique constraint */ - BtreeLastVisibleEntry lVis = {InvalidBlockNumber, InvalidOffsetNumber, -1, NULL}; + BtreeLastVisibleEntry lVis; + + lVis.blkno = InvalidBlockNumber; + lVis.offset = InvalidOffsetNumber; + lVis.postingIndex = -1; + ItemPointerSetInvalid(&lVis.tid); topaque = BTPageGetOpaque(state->target); max = PageGetMaxOffsetNumber(state->target); @@ -1313,6 +1324,16 @@ bt_target_page_check(BtreeCheckState *state) LSN_FORMAT_ARGS(state->targetlsn)), errhint("This could be a torn page problem."))); + /* + * The coded size was checked against lp_len above; the checks below + * apply to the decoded item. + */ + if (P_HASPREFIX(topaque)) + { + itup = _bt_getitem(state->target, offset, &state->itembuf); + tupsize = IndexTupleSize(itup); + } + /* Check the number of index tuple attributes */ if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target, offset)) @@ -1606,7 +1627,8 @@ bt_target_page_check(BtreeCheckState *state) itemid = PageGetItemIdCareful(state, state->targetblock, state->target, OffsetNumberNext(offset)); - itup = (IndexTuple) PageGetItem(state->target, itemid); + itup = _bt_getitem(state->target, OffsetNumberNext(offset), + &state->nextbuf); tid = BTreeTupleGetPointsToTID(itup); nhtid = psprintf("(%u,%u)", ItemPointerGetBlockNumberNoCheck(tid), @@ -1634,7 +1656,7 @@ bt_target_page_check(BtreeCheckState *state) */ if (state->checkunique && state->indexinfo->ii_Unique && P_ISLEAF(topaque) && !skey->anynullkeys && - (BTreeTupleIsPosting(itup) || ItemPointerIsValid(lVis.tid))) + (BTreeTupleIsPosting(itup) || ItemPointerIsValid(&lVis.tid))) { bt_entry_unique_check(state, itup, state->targetblock, offset, &lVis); @@ -1668,7 +1690,7 @@ bt_target_page_check(BtreeCheckState *state) lVis.blkno = InvalidBlockNumber; lVis.offset = InvalidOffsetNumber; lVis.postingIndex = -1; - lVis.tid = NULL; + ItemPointerSetInvalid(&lVis.tid); } else if (!unique_checked) { @@ -1793,7 +1815,8 @@ bt_target_page_check(BtreeCheckState *state) itemid = PageGetItemIdCareful(state, rightblock_number, rightpage, rightfirstoffset); - itup = (IndexTuple) PageGetItem(rightpage, itemid); + itup = _bt_getitem(rightpage, rightfirstoffset, + &state->nextbuf); bt_entry_unique_check(state, itup, rightblock_number, rightfirstoffset, &lVis); @@ -2047,7 +2070,11 @@ bt_right_page_check_scankey(BtreeCheckState *state, OffsetNumber *rightfirstoffs * Return first real item scankey. Note that this relies on right page * memory remaining allocated. */ - firstitup = (IndexTuple) PageGetItem(rightpage, rightitem); + if (P_ISLEAF(opaque)) + firstitup = CopyIndexTuple(_bt_getitem(rightpage, *rightfirstoffset, + &state->nextbuf)); + else + firstitup = (IndexTuple) PageGetItem(rightpage, rightitem); return bt_mkscankey_pivotsearch(state->rel, firstitup); } @@ -3029,10 +3056,14 @@ bt_rootdescend(BtreeCheckState *state, IndexTuple itup) insertstate.bounds_valid = false; insertstate.buf = lbuf; + /* The search bypasses palloc_btree_page's structural checks. */ + page = BufferGetPage(lbuf); + if (P_HASPREFIX(BTPageGetOpaque(page))) + bt_prefix_page_check(state, page, BufferGetBlockNumber(lbuf)); + /* Get matching tuple on leaf page */ offnum = _bt_binsrch_insert(state->rel, &insertstate); /* Compare first >= matching item on leaf page, if any */ - page = BufferGetPage(lbuf); /* Should match on first heap TID when tuple has a posting list */ if (offnum <= PageGetMaxOffsetNumber(page) && insertstate.postingoff <= 0 && @@ -3095,14 +3126,13 @@ static inline bool invariant_l_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound) { - ItemId itemid; int32 cmp; Assert(!key->nextkey && key->backward); /* Verify line pointer before checking tuple */ - itemid = PageGetItemIdCareful(state, state->targetblock, state->target, - upperbound); + (void) PageGetItemIdCareful(state, state->targetblock, state->target, + upperbound); /* pg_upgrade'd indexes may legally have equal sibling tuples */ if (!key->heapkeyspace) return invariant_leq_offset(state, key, upperbound); @@ -3126,8 +3156,8 @@ invariant_l_offset(BtreeCheckState *state, BTScanInsert key, ItemPointer rheaptid; bool nonpivot; - ritup = (IndexTuple) PageGetItem(state->target, itemid); topaque = BTPageGetOpaque(state->target); + ritup = _bt_getitem(state->target, upperbound, &state->nextbuf); nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque); /* Get number of keys + heap TID for item to the right */ @@ -3218,14 +3248,13 @@ invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, BlockNumber nontargetblock, Page nontarget, OffsetNumber upperbound) { - ItemId itemid; int32 cmp; Assert(!key->nextkey && key->backward); /* Verify line pointer before checking tuple */ - itemid = PageGetItemIdCareful(state, nontargetblock, nontarget, - upperbound); + (void) PageGetItemIdCareful(state, nontargetblock, nontarget, + upperbound); cmp = _bt_compare(state->rel, key, nontarget, upperbound); /* pg_upgrade'd indexes may legally have equal sibling tuples */ @@ -3241,8 +3270,8 @@ invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, BTPageOpaque copaque; bool nonpivot; - child = (IndexTuple) PageGetItem(nontarget, itemid); copaque = BTPageGetOpaque(nontarget); + child = _bt_getitem(nontarget, upperbound, &state->nextbuf); nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque); /* Get number of keys + heap TID for child/non-target item */ @@ -3259,6 +3288,29 @@ invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, return cmp < 0; } +/* Add relation and block identification to catalog-free prefix diagnostics. */ +static void +bt_prefix_error_callback(void *arg) +{ + errcontext("%s", (char *) arg); +} + +static void +bt_prefix_page_check(BtreeCheckState *state, Page page, BlockNumber blocknum) +{ + ErrorContextCallback errcallback; + + errcallback.callback = bt_prefix_error_callback; + errcallback.arg = psprintf("Index \"%s\", block %u, page LSN %X/%08X.", + RelationGetRelationName(state->rel), blocknum, + LSN_FORMAT_ARGS(PageGetLSN(page))); + errcallback.previous = error_context_stack; + error_context_stack = &errcallback; + _bt_prefix_check(page); + error_context_stack = errcallback.previous; + pfree(errcallback.arg); +} + /* * Given a block number of a B-Tree page, return page in palloc()'d memory. * While at it, perform some basic checks of the page. @@ -3398,6 +3450,22 @@ palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum) errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item", blocknum, RelationGetRelationName(state->rel)))); + /* + * A prefix-compressed page is a live leaf holding its directory item and + * at least one coded data item (an emptied page drops the directory). + */ + if (P_HASPREFIX(opaque) && + (!P_ISLEAF(opaque) || P_ISDELETED(opaque) || P_ISHALFDEAD(opaque) || + maxoffset < P_FIRSTDATAKEY(opaque))) + ereport(ERROR, + (errcode(ERRCODE_INDEX_CORRUPTED), + errmsg("block %u in index \"%s\" has an invalid prefix-compressed layout", + blocknum, RelationGetRelationName(state->rel)))); + + /* Validate all members before a comparison can decode any of them. */ + if (P_HASPREFIX(opaque)) + bt_prefix_page_check(state, page, blocknum); + /* * In general, internal pages are never marked half-dead, except on * versions of Postgres prior to 9.4, where it can be valid transient diff --git a/contrib/pageinspect/btreefuncs.c b/contrib/pageinspect/btreefuncs.c index f5433f10acc..d40641fad4d 100644 --- a/contrib/pageinspect/btreefuncs.c +++ b/contrib/pageinspect/btreefuncs.c @@ -96,6 +96,7 @@ typedef struct ua_page_items bool leafpage; bool rightmost; TupleDesc tupd; + BTItemBuf decodebuf; /* decoded data item of a BTP_PREFIX leaf */ } ua_page_items; @@ -497,11 +498,20 @@ bt_page_print_tuples(ua_page_items *uargs) itup = (IndexTuple) PageGetItem(page, id); + /* + * Show a prefix-compressed leaf's data items decoded, but itemlen as the + * stored (coded) size. The prefix directory item is shown raw. + */ + if (leafpage && + P_HASPREFIX(BTPageGetOpaque(page)) && + offset >= P_FIRSTDATAKEY(BTPageGetOpaque(page))) + itup = _bt_getitem(page, offset, &uargs->decodebuf); + j = 0; memset(nulls, 0, sizeof(nulls)); values[j++] = Int16GetDatum(offset); values[j++] = ItemPointerGetDatum(&itup->t_tid); - values[j++] = Int16GetDatum(IndexTupleSize(itup)); + values[j++] = Int16GetDatum(ItemIdGetLength(id)); values[j++] = BoolGetDatum(IndexTupleHasNulls(itup)); values[j++] = BoolGetDatum(IndexTupleHasVarwidths(itup)); @@ -663,6 +673,8 @@ bt_page_items_internal(PG_FUNCTION_ARGS, enum pageinspect_version ext_version) uargs->offset = FirstOffsetNumber; opaque = BTPageGetOpaque(uargs->page); + if (P_HASPREFIX(opaque)) + _bt_prefix_check(uargs->page); if (!P_ISDELETED(opaque)) fctx->max_calls = PageGetMaxOffsetNumber(uargs->page); @@ -756,6 +768,13 @@ bt_page_items_bytea(PG_FUNCTION_ARGS) uargs->offset = FirstOffsetNumber; + /* The raw header's page size cannot establish allocation bounds. */ + if (((PageHeader) uargs->page)->pd_special != + BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData))) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("input page is not a valid %s page", "btree"))); + /* verify the special space has the expected size */ if (PageGetSpecialSize(uargs->page) != MAXALIGN(sizeof(BTPageOpaqueData))) ereport(ERROR, @@ -777,6 +796,9 @@ bt_page_items_bytea(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("block is not a valid btree leaf page"))); + if (P_HASPREFIX(opaque)) + _bt_prefix_check(uargs->page); + if (P_ISDELETED(opaque)) elog(NOTICE, "page is deleted"); diff --git a/contrib/pageinspect/expected/btree.out b/contrib/pageinspect/expected/btree.out index 0aa5d73322f..9448dd5f1cc 100644 --- a/contrib/pageinspect/expected/btree.out +++ b/contrib/pageinspect/expected/btree.out @@ -211,6 +211,13 @@ SELECT bt_page_items(get_raw_page('test1', 0)); ERROR: input page is not a valid btree page SELECT bt_page_items(get_raw_page('test1_a_brin', 0)); ERROR: input page is not a valid btree page +-- A forged page size must not make an out-of-bounds special area look valid. +WITH raw AS (SELECT get_raw_page('test1_a_idx', 1) AS p) +SELECT bt_page_items(set_byte(set_byte(set_byte(set_byte(p, + 16, CASE WHEN get_byte(p, 18) = 4 THEN 240 ELSE 255 END), + 17, CASE WHEN get_byte(p, 18) = 4 THEN 255 ELSE 240 END), 18, 0), 19, 0)) +FROM raw; +ERROR: input page is not a valid btree page \set VERBOSITY default -- Tests with all-zero pages. SHOW block_size \gset @@ -219,3 +226,38 @@ SELECT bt_page_items(decode(repeat('00', :block_size), 'hex')); bt_page_items | DROP TABLE test1; +-- A prefix-compressed leaf: data items are shown decoded, so data and htid +-- read as on a plain page, while itemlen shows the stored (coded) size. +CREATE TABLE test_prefix (u text COLLATE "C"); +INSERT INTO test_prefix + SELECT 'https://example.com/path/' || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; +CREATE INDEX test_prefix_idx ON test_prefix (u) WITH (prefix_compression = on); +CREATE INDEX test_plain_idx ON test_prefix (u); +SELECT btpo_flags & 512 <> 0 AS coded FROM bt_page_stats('test_prefix_idx', 1); +-[ RECORD 1 ] +coded | t + +-- same decoded items as the plain index (offset 1 is the prefix directory) +SELECT count(*) AS mismatches + FROM bt_page_items('test_prefix_idx', 1) c + FULL JOIN bt_page_items('test_plain_idx', 1) p ON p.itemoffset = c.itemoffset - 1 + WHERE c.itemoffset > 1 AND (c.data IS DISTINCT FROM p.data OR c.htid IS DISTINCT FROM p.htid); +-[ RECORD 1 ]- +mismatches | 0 + +-- and the same from a raw page image +SELECT count(*) AS mismatches + FROM bt_page_items(get_raw_page('test_prefix_idx', 1)) c + JOIN bt_page_items('test_prefix_idx', 1) r USING (itemoffset) + WHERE c.data IS DISTINCT FROM r.data; +-[ RECORD 1 ]- +mismatches | 0 + +-- coded items are smaller than the plain ones +SELECT (SELECT sum(itemlen) FROM bt_page_items('test_prefix_idx', 1) WHERE itemoffset > 1) < + (SELECT sum(itemlen) FROM bt_page_items('test_plain_idx', 1)) AS smaller; +-[ RECORD 1 ] +smaller | t + +DROP TABLE test_prefix; diff --git a/contrib/pageinspect/sql/btree.sql b/contrib/pageinspect/sql/btree.sql index 102ebdefe3c..d0893e6450f 100644 --- a/contrib/pageinspect/sql/btree.sql +++ b/contrib/pageinspect/sql/btree.sql @@ -53,6 +53,12 @@ SELECT bt_page_items('aaa'::bytea); CREATE INDEX test1_a_brin ON test1 USING brin(a); SELECT bt_page_items(get_raw_page('test1', 0)); SELECT bt_page_items(get_raw_page('test1_a_brin', 0)); +-- A forged page size must not make an out-of-bounds special area look valid. +WITH raw AS (SELECT get_raw_page('test1_a_idx', 1) AS p) +SELECT bt_page_items(set_byte(set_byte(set_byte(set_byte(p, + 16, CASE WHEN get_byte(p, 18) = 4 THEN 240 ELSE 255 END), + 17, CASE WHEN get_byte(p, 18) = 4 THEN 255 ELSE 240 END), 18, 0), 19, 0)) +FROM raw; \set VERBOSITY default -- Tests with all-zero pages. @@ -60,3 +66,27 @@ SHOW block_size \gset SELECT bt_page_items(decode(repeat('00', :block_size), 'hex')); DROP TABLE test1; + +-- A prefix-compressed leaf: data items are shown decoded, so data and htid +-- read as on a plain page, while itemlen shows the stored (coded) size. +CREATE TABLE test_prefix (u text COLLATE "C"); +INSERT INTO test_prefix + SELECT 'https://example.com/path/' || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; +CREATE INDEX test_prefix_idx ON test_prefix (u) WITH (prefix_compression = on); +CREATE INDEX test_plain_idx ON test_prefix (u); +SELECT btpo_flags & 512 <> 0 AS coded FROM bt_page_stats('test_prefix_idx', 1); +-- same decoded items as the plain index (offset 1 is the prefix directory) +SELECT count(*) AS mismatches + FROM bt_page_items('test_prefix_idx', 1) c + FULL JOIN bt_page_items('test_plain_idx', 1) p ON p.itemoffset = c.itemoffset - 1 + WHERE c.itemoffset > 1 AND (c.data IS DISTINCT FROM p.data OR c.htid IS DISTINCT FROM p.htid); +-- and the same from a raw page image +SELECT count(*) AS mismatches + FROM bt_page_items(get_raw_page('test_prefix_idx', 1)) c + JOIN bt_page_items('test_prefix_idx', 1) r USING (itemoffset) + WHERE c.data IS DISTINCT FROM r.data; +-- coded items are smaller than the plain ones +SELECT (SELECT sum(itemlen) FROM bt_page_items('test_prefix_idx', 1) WHERE itemoffset > 1) < + (SELECT sum(itemlen) FROM bt_page_items('test_plain_idx', 1)) AS smaller; +DROP TABLE test_prefix; diff --git a/doc/src/sgml/pageinspect.sgml b/doc/src/sgml/pageinspect.sgml index 3a113439e1d..3d4345f099e 100644 --- a/doc/src/sgml/pageinspect.sgml +++ b/doc/src/sgml/pageinspect.sgml @@ -471,6 +471,18 @@ test=# SELECT itemoffset, ctid, itemlen, nulls, vars, data, dead, htid, tids[0:2 valid downlink in its ctid field, however. + + On a leaf page of an index with + prefix_compression + enabled, the item after the high key (or the first item, on a rightmost + page) may be the page's prefix directory, which holds the leading bytes + that the page's data items share. Such a page has bit 512 + (BTP_PREFIX) set in btpo_flags. + Its data items are shown decoded, so data + and htid read as they would on an + uncompressed page, while itemlen shows the + item's stored, compressed size. + For more details about the structure of B-tree indexes, see . For more details about diff --git a/doc/src/sgml/ref/create_index.sgml b/doc/src/sgml/ref/create_index.sgml index bb7505d171b..813d238c0f4 100644 --- a/doc/src/sgml/ref/create_index.sgml +++ b/doc/src/sgml/ref/create_index.sgml @@ -477,6 +477,47 @@ CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] + + + prefix_compression (boolean) + + prefix_compression storage parameter + + + + + Controls leaf key prefix compression. When set to + ON, a leaf page may store the leading bytes that a + run of its tuples share just once and record only each tuple's + unshared remainder, which can substantially shrink indexes whose keys + share long leading bytes (for example URLs, jsonb paths, + zero-padded codes, or low-cardinality leading columns of a multicolumn + index). It applies to key columns of any data type. Compression can + save space and I/O, but adds CPU overhead during index builds, inserts, + and scans that reconstruct key values, including index-only scans. + Savings depend on the stored representation: different string length + headers can prevent sharing even when the strings have a common prefix. + Set to + ON or OFF to enable or disable the + optimization. The default is OFF. + + + + + Prefix compression only changes how keys are stored; comparisons always + see the original key values, so every collation and operator class + behaves identically with it on or off. A leaf is compressed only when + it is written as a whole (during an index build, or either half of a + page split), so turning prefix_compression on or off + via ALTER INDEX does not rewrite the index: existing + pages are left as they are and are converted the next time they are + written whole (REINDEX converts them all at once). No REINDEX is required, and indexes + upgraded with pg_upgrade keep working + unchanged. + + + + diff --git a/src/backend/access/common/reloptions.c b/src/backend/access/common/reloptions.c index ea9a0417909..be1fcd9a15b 100644 --- a/src/backend/access/common/reloptions.c +++ b/src/backend/access/common/reloptions.c @@ -153,6 +153,16 @@ static relopt_bool boolRelOpts[] = }, true }, + { + { + "prefix_compression", + "Enables leaf key prefix compression for this btree index", + RELOPT_KIND_BTREE, + ShareUpdateExclusiveLock /* since it applies only to later + * whole-page writes */ + }, + false + }, /* list terminator */ {{NULL}} }; diff --git a/src/backend/access/nbtree/Makefile b/src/backend/access/nbtree/Makefile index 0daf640af96..0044d77f548 100644 --- a/src/backend/access/nbtree/Makefile +++ b/src/backend/access/nbtree/Makefile @@ -18,6 +18,7 @@ OBJS = \ nbtinsert.o \ nbtpage.o \ nbtpreprocesskeys.o \ + nbtprefix.o \ nbtreadpage.o \ nbtree.o \ nbtsearch.o \ diff --git a/src/backend/access/nbtree/README b/src/backend/access/nbtree/README index f3867547691..55c6061eb9d 100644 --- a/src/backend/access/nbtree/README +++ b/src/backend/access/nbtree/README @@ -1081,3 +1081,127 @@ item is irrelevant, and need not be stored at all. This arrangement corresponds to the fact that an L&Y non-leaf page has one more pointer than key. Suffix truncation's negative infinity attributes behave in the same way. + +Notes about leaf key prefix compression +---------------------------------------- + +With the prefix_compression storage parameter (default off) a leaf page may +store the leading bytes that a run of its data tuples share just once, in a +per-page directory, and record only each tuple's unshared remainder. This +shrinks indexes whose keys share long leading bytes: URLs, jsonb paths, +zero-padded codes, multi-column keys with low-cardinality leading columns. +Like deduplication, it alters the physical representation of tuples without +changing the logical contents of the index, and comparisons always operate on +the reconstructed original values, so every collation and operator class is +unaffected. + +Sharing is decided by equality of stored bytes, never by the opclass notion +of equality. That is what makes it sound for every column type, including +types whose equal values can have different representations (numeric 1.0 and +1.00): only bytes that are already identical are shared, so an index-only +scan gets back exactly the bytes that were stored, and no equalimage support +function is needed. Deduplication needs equalimage because it merges tuples +the comparator calls equal and keeps one copy; prefix compression never +merges anything. Sharing is not tied to column boundaries: a member shares +the longest common prefix of its data area with its group's anchor, which +covers whole leading columns plus any leading bytes of the first column that +differs. + +A leaf that uses the technique carries the BTP_PREFIX page flag and one extra +item, the PREFIX DIRECTORY, at the offset where its first data item would +otherwise be (P_HIKEY on a rightmost page, P_FIRSTKEY otherwise); data items +begin one offset later, which P_FIRSTDATAKEY() accounts for. Keeping the +whole directory in a single item preserves the "exactly one item before the +data" property, so P_FIRSTDATAKEY depends only on the page flag, neither +BTPageOpaqueData nor the on-disk page header changes, and binary search over +the data items is unaffected. The directory holds one or more GROUPS of +consecutive data items. A group's ANCHOR is a copy of the key part of its +first member; a new group starts when an item shares no byte with the current +anchor, or when it shares strictly more with its immediate predecessor than +with the current anchor (by at least a MAXALIGN quantum) -- the latter lets a +long run of tuples that share a long prefix with one another form its own +group even when the leaf's first tuple only shares a short leading prefix (say +a low-cardinality leading column) with them. The rule looks only backwards, +so the running size estimate used when filling pages during CREATE INDEX makes +the identical grouping decisions one tuple at a time. + +Each data item is stored "coded": an IndexTupleData header whose +t_tid is the item's own heap TID (no t_tid bit is stolen), a small code header +(group, shared byte count, the original's t_info), the original's null bitmap, +the residual -- the original's data-area bytes after the shared ones -- and, +for a posting list tuple, its posting list in the standard layout. Code that +reads only heap TIDs (VACUUM, LP_DEAD hinting, index deletion, posting list +splits) therefore works on coded items as is. Pivots (high keys and +downlinks) are never coded. Decoding splices the anchor's shared bytes back +in front of the residual and reproduces the original tuple byte for byte. + +Coding and decoding depend only on the page and the tuple, never on the +catalog. _bt_getitem() is the one accessor through which readers obtain a +decoded leaf data item; _bt_compare() decodes the item it compares against, +and _bt_readpage() skips decoding altogether when a scan needs only heap TIDs +and no key comparison remains to be made on the page (not an index-only scan, +every scan key already satisfied for the whole page, no array keys). + +A page gets a directory only when it is written as a whole: a leaf during an +index build, or either half of a leaf page split. An index build collects a +leaf's tuples and fills it according to a running estimate of the coded size, +honoring fillfactor in coded bytes, so a compressible index is built dense +rather than coded after the fact. An insert codes the new tuple against the +group of its neighbor, sharing however much it happens to share (possibly +nothing); no insert, VACUUM or deduplication ever rewrites a page to keep its +directory "good". Deduplication and bottom-up deletion both work on decoded +copies of a coded page's items; deduplication re-codes each resulting tuple +against the page's existing directory, so the page can only shrink. When +VACUUM or page deletion empties a coded leaf, the directory is removed and the +flag cleared, so an emptied leaf holds only its high key, as page deletion +expects. + +A coded page can hold more data than fits on a plain page, and it must still +be possible to split it into two plain pages. The directory caches the +decoded size of the page's items (their sum and the largest), maintained +exactly by every change and repeated by redo, and an insert splits the page +before its decoded content would exceed what a size-balanced split can always +place on two pages, counting the left half's new high key +(_bt_prefix_split_needed has the argument). A split decodes the page, +chooses a split point by plain sizes (upstream _bt_findsplitloc when the +decoded items fit one page, otherwise a size-checked balanced point), writes +both halves plain, and codes each half as a whole page. For the rare case +where a large incoming tuple leaves no legal split point once it is added, the +existing items are split alone and the insert is retried from the top. + +Because the format is a per-page opt-in flag with no btree version change, +pages without the flag are read exactly as before, so pg_upgrade and +replication keep working and existing indexes continue to work with no +REINDEX. Turning the parameter on with ALTER INDEX rewrites nothing; each +leaf is converted the next time it is written whole, and compressed and +uncompressed leaves coexist in the same index indefinitely. Turning it off +likewise rewrites nothing: existing BTP_PREFIX leaves keep their coded form +and are still read correctly, since every reader decodes based on the page +flag, not on the current setting. Index-only scans keep their per-page tuple +workspace sized for a plain page and grow it the first time they read a +BTP_PREFIX page, since a decoded page can exceed one block. + +WAL replay never needs a full-page image for a coded page. An in-place +insert logs the coded tuple, which redo adds verbatim before updating the +directory's cached size. A split record says, in its flags, whether the +original page and each half were coded; for a coded original page its +offsets refer to the decoded item sequence. Redo decodes the original page's +items, collects the left half's items exactly as the primary did, and lays +the left half out with the same routine the primary used +(_bt_prefix_form_page); the right half arrives as its coded items, directory +included, which _bt_restore_page lays out exactly as the primary did. +Deduplication and posting list splits on a coded page are replayed by +repeating the primary's decode, merge and re-code steps. The coded records +are smaller than the plain ones, since every item and the right half travel +in coded form. + +Prefix compression is a separate mechanism from deduplication rather than an +extension of it because the two attack different redundancy. Deduplication +collapses tuples whose whole key is equal into one posting list tuple; it does +nothing for keys that are all distinct. Prefix compression factors out a +leading run shared by distinct keys and leaves their differing suffixes alone; +it does nothing for exact duplicates that a posting list already collapses. +The common case this targets -- a URL or jsonb-path column whose values are +distinct but share a long prefix -- is exactly where deduplication does not +help. The two compose on one page: a posting list tuple is coded like any +other, carrying its posting list after the residual. diff --git a/src/backend/access/nbtree/meson.build b/src/backend/access/nbtree/meson.build index 812f067e710..cbd34201328 100644 --- a/src/backend/access/nbtree/meson.build +++ b/src/backend/access/nbtree/meson.build @@ -6,6 +6,7 @@ backend_sources += files( 'nbtinsert.c', 'nbtpage.c', 'nbtpreprocesskeys.c', + 'nbtprefix.c', 'nbtreadpage.c', 'nbtree.c', 'nbtsearch.c', diff --git a/src/backend/access/nbtree/nbtdedup.c b/src/backend/access/nbtree/nbtdedup.c index af7affdf409..17869e33678 100644 --- a/src/backend/access/nbtree/nbtdedup.c +++ b/src/backend/access/nbtree/nbtdedup.c @@ -70,6 +70,8 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, bool singlevalstrat = false; int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel); XLogRecPtr recptr; + bool coded = P_HASPREFIX(opaque); + IndexTuple *ditems = NULL; /* Passed-in newitemsz is MAXALIGNED but does not include line pointer */ newitemsz += sizeof(ItemIdData); @@ -131,12 +133,36 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, elog(ERROR, "deduplication failed to add highkey"); } + /* + * On a prefix-compressed page, merge decoded copies of the items, and + * keep the page's directory: each output tuple is coded against the group + * of its interval's base item (_bt_dedup_finish_pending_coded). Merging + * never enlarges a coded page, so the result always fits. + */ + if (coded) + { + OffsetNumber prefixoff = BTPageGetPrefixOff(opaque); + ItemId diritemid = PageGetItemId(page, prefixoff); + IndexTuple dummyhikey; + Size dummyhikeysz; + + if (PageAddItem(newpage, PageGetItem(page, diritemid), + ItemIdGetLength(diritemid), prefixoff, + false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add prefix directory"); + (void) _bt_prefix_decode_items(page, &ditems, &dummyhikey, + &dummyhikeysz); + if (dummyhikey) + pfree(dummyhikey); + } + for (offnum = minoff; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid = PageGetItemId(page, offnum); - IndexTuple itup = (IndexTuple) PageGetItem(page, itemid); + IndexTuple itup = coded ? ditems[offnum - minoff] : + (IndexTuple) PageGetItem(page, itemid); Assert(!ItemIdIsDead(itemid)); @@ -170,7 +196,10 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, * form new posting tuple and add it to our temp page (newpage). * Else add pending interval's base tuple to the temp page as-is. */ - pagesaving += _bt_dedup_finish_pending(newpage, state); + if (coded) + _bt_dedup_finish_pending_coded(page, newpage, state); + else + pagesaving += _bt_dedup_finish_pending(newpage, state); if (singlevalstrat) { @@ -203,7 +232,17 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, } /* Handle the last item */ - pagesaving += _bt_dedup_finish_pending(newpage, state); + if (coded) + _bt_dedup_finish_pending_coded(page, newpage, state); + else + pagesaving += _bt_dedup_finish_pending(newpage, state); + + if (ditems) + { + for (int i = 0; i <= maxoff - minoff; i++) + pfree(ditems[i]); + pfree(ditems); + } /* * If no items suitable for deduplication were found, newpage must be @@ -240,6 +279,9 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, START_CRIT_SECTION(); + /* the copied directory's cached sizes describe the old items */ + if (coded) + _bt_prefix_recount(newpage); PageRestoreTempPage(newpage, page); MarkBufferDirty(buf); @@ -272,7 +314,8 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, END_CRIT_SECTION(); /* Local space accounting should agree with page accounting */ - Assert(pagesaving < newitemsz || PageGetExactFreeSpace(page) >= newitemsz); + Assert(coded || pagesaving < newitemsz || + PageGetExactFreeSpace(page) >= newitemsz); /* cannot leak memory here */ pfree(state->htids); @@ -317,6 +360,7 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, BTDedupState state; TM_IndexDeleteOp delstate; bool neverdedup; + IndexTuple *ditems = NULL; int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel); /* Passed-in newitemsz is MAXALIGNED but does not include line pointer */ @@ -362,12 +406,30 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, minoff = P_FIRSTDATAKEY(opaque); maxoff = PageGetMaxOffsetNumber(page); + + /* + * On a prefix-compressed page compare decoded copies of the items. Coded + * tuples keep their heap TIDs and posting lists in the standard layout, + * so the code below that reads only TIDs works on them as is. + */ + if (P_HASPREFIX(opaque)) + { + IndexTuple dummyhikey; + Size dummyhikeysz; + + (void) _bt_prefix_decode_items(page, &ditems, &dummyhikey, + &dummyhikeysz); + if (dummyhikey) + pfree(dummyhikey); + } + for (offnum = minoff; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid = PageGetItemId(page, offnum); - IndexTuple itup = (IndexTuple) PageGetItem(page, itemid); + IndexTuple itup = ditems ? ditems[offnum - minoff] : + (IndexTuple) PageGetItem(page, itemid); Assert(!ItemIdIsDead(itemid)); @@ -393,6 +455,13 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, /* Finalize final interval -- move its TIDs to delete state */ _bt_bottomupdel_finish_pending(page, state, &delstate); + if (ditems) + { + for (int i = 0; i <= maxoff - minoff; i++) + pfree(ditems[i]); + pfree(ditems); + } + /* * We don't give up now in the event of having few (or even zero) * promising tuples for the tableam because it's not up to us as the index @@ -419,7 +488,11 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, return true; /* Don't dedup when we won't end up back here any time soon anyway */ - return PageGetExactFreeSpace(page) >= Max(BLCKSZ / 24, newitemsz); + return PageGetExactFreeSpace(page) >= + Max(BLCKSZ / 24, newitemsz + + (P_HASPREFIX(opaque) ? BTREE_PREFIX_CODE_OVERHEAD : 0)) && + (!P_HASPREFIX(opaque) || + !_bt_prefix_split_needed(page, newitemsz - sizeof(ItemIdData))); } /* @@ -608,6 +681,55 @@ _bt_dedup_finish_pending(Page newpage, BTDedupState state) return spacesaving; } +/* + * _bt_dedup_finish_pending for a prefix-compressed page. The tuple added to + * newpage is coded against the group of the interval's base item, using the + * source page's directory, which newpage carries unchanged. A lone base item + * is copied in its existing coded form. Uses only the two pages, so WAL redo + * calls it to repeat the primary's deduplication exactly. + */ +void +_bt_dedup_finish_pending_coded(Page page, Page newpage, BTDedupState state) +{ + OffsetNumber tupoff = OffsetNumberNext(PageGetMaxOffsetNumber(newpage)); + IndexTuple out; + Size outsz; + + Assert(state->nitems > 0); + Assert(state->nitems <= state->nhtids); + Assert(state->intervals[state->nintervals].baseoff == state->baseoff); + + if (state->nitems == 1) + { + ItemId itemid = PageGetItemId(page, state->baseoff); + + out = (IndexTuple) PageGetItem(page, itemid); + outsz = ItemIdGetLength(itemid); + if (PageAddItem(newpage, out, outsz, tupoff, false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add tuple to page"); + } + else + { + IndexTuple final; + + final = _bt_form_posting(state->base, state->htids, state->nhtids); + Assert(IndexTupleSize(final) <= state->maxpostingsize); + state->intervals[state->nintervals].nitems = state->nitems; + + out = _bt_prefix_recode(page, state->baseoff, final); + outsz = IndexTupleSize(out); + if (PageAddItem(newpage, out, outsz, tupoff, false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add tuple to page"); + pfree(out); + pfree(final); + state->nintervals++; + } + + state->nhtids = 0; + state->nitems = 0; + state->phystupsize = 0; +} + /* * Finalize interval during bottom-up index deletion. * @@ -783,16 +905,14 @@ _bt_do_singleval(Relation rel, Page page, BTDedupState state, OffsetNumber minoff, IndexTuple newitem) { int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel); - ItemId itemid; IndexTuple itup; + BTItemBuf buf; - itemid = PageGetItemId(page, minoff); - itup = (IndexTuple) PageGetItem(page, itemid); + itup = _bt_getitem(page, minoff, &buf); if (_bt_keep_natts_fast(rel, newitem, itup) > nkeyatts) { - itemid = PageGetItemId(page, PageGetMaxOffsetNumber(page)); - itup = (IndexTuple) PageGetItem(page, itemid); + itup = _bt_getitem(page, PageGetMaxOffsetNumber(page), &buf); if (_bt_keep_natts_fast(rel, newitem, itup) > nkeyatts) return true; diff --git a/src/backend/access/nbtree/nbtinsert.c b/src/backend/access/nbtree/nbtinsert.c index d5d964301c1..30e58cc1c6b 100644 --- a/src/backend/access/nbtree/nbtinsert.c +++ b/src/backend/access/nbtree/nbtinsert.c @@ -46,7 +46,7 @@ static OffsetNumber _bt_findinsertloc(Relation rel, Relation heapRel); static void _bt_stepright(Relation rel, Relation heaprel, BTInsertState insertstate, BTStack stack); -static void _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key, +static bool _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer cbuf, BTStack stack, @@ -58,7 +58,8 @@ static void _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key static Buffer _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer cbuf, OffsetNumber newitemoff, Size newitemsz, IndexTuple newitem, IndexTuple orignewitem, - IndexTuple nposting, uint16 postingoff); + IndexTuple nposting, uint16 postingoff, + bool *newitemplaced); static void _bt_insert_parent(Relation rel, Relation heaprel, Buffer buf, Buffer rbuf, BTStack stack, bool isroot, bool isonly); static void _bt_freestack(BTStack stack); @@ -260,9 +261,27 @@ search: */ newitemoff = _bt_findinsertloc(rel, &insertstate, checkingunique, indexUnchanged, stack, heapRel); - _bt_insertonpg(rel, heapRel, itup_key, insertstate.buf, InvalidBuffer, - stack, itup, insertstate.itemsz, newitemoff, - insertstate.postingoff, false); + if (!_bt_insertonpg(rel, heapRel, itup_key, insertstate.buf, + InvalidBuffer, stack, itup, insertstate.itemsz, + newitemoff, insertstate.postingoff, false)) + { + /* + * A prefix leaf was split without placing itup, because no split + * point kept both decoded halves within a page with itup added. + * Retry from the top. The uniqueness check must be redone too: + * the page lock was released, so a conflicting duplicate may have + * been inserted meanwhile. + */ + if (stack) + _bt_freestack(stack); + if (checkingunique && itup_key->heapkeyspace && + !itup_key->anynullkeys) + itup_key->scantid = NULL; + insertstate.buf = InvalidBuffer; + insertstate.bounds_valid = false; + insertstate.postingoff = 0; + goto search; + } } else { @@ -347,9 +366,11 @@ _bt_search_insert(Relation rel, Relation heaprel, BTInsertState insertstate) if (P_RIGHTMOST(opaque) && P_ISLEAF(opaque) && !P_IGNORE(opaque) && + !P_HASPREFIX(opaque) && PageGetFreeSpace(page) > insertstate->itemsz && - PageGetMaxOffsetNumber(page) >= P_HIKEY && - _bt_compare(rel, insertstate->itup_key, page, P_HIKEY) > 0) + PageGetMaxOffsetNumber(page) >= P_FIRSTDATAKEY(opaque) && + _bt_compare(rel, insertstate->itup_key, page, + P_FIRSTDATAKEY(opaque)) > 0) { /* * Caller can use the fastpath optimization because cached @@ -910,12 +931,28 @@ _bt_findinsertloc(Relation rel, /* * If the target page cannot fit newitem, try to avoid splitting the - * page on insert by performing deletion or deduplication now + * page on insert by performing deletion or deduplication now. On a + * prefix page the coded item can exceed the plain tuple by up to + * BTREE_PREFIX_CODE_OVERHEAD, so reserve that slack; otherwise a + * coded PageAddItem could fail after the fit check passed. */ - if (PageGetFreeSpace(page) < insertstate->itemsz) - _bt_delete_or_dedup_one_page(rel, heapRel, insertstate, false, - checkingunique, uniquedup, - indexUnchanged); + { + Size need = insertstate->itemsz; + + if (P_HASPREFIX(opaque)) + need += BTREE_PREFIX_CODE_OVERHEAD; + + /* + * A prefix page also splits once its decoded content nears the + * split-fit limit, often before it is physically full. + */ + if (PageGetFreeSpace(page) < need || + (P_HASPREFIX(opaque) && + _bt_prefix_split_needed(page, insertstate->itemsz))) + _bt_delete_or_dedup_one_page(rel, heapRel, insertstate, false, + checkingunique, uniquedup, + indexUnchanged); + } } else { @@ -1111,9 +1148,12 @@ _bt_stepright(Relation rel, Relation heaprel, BTInsertState insertstate, * inserting to a non-leaf page, 'cbuf' is the left-sibling of the page * we're inserting the downlink for. This function will clear the * INCOMPLETE_SPLIT flag on it, and release the buffer. + * + * Returns false if a prefix leaf was split without placing itup (see + * _bt_split); caller must retry the insertion. Otherwise true. *---------- */ -static void +static bool _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key, @@ -1135,6 +1175,11 @@ _bt_insertonpg(Relation rel, IndexTuple oposting = NULL; IndexTuple origitup = NULL; IndexTuple nposting = NULL; + IndexTuple codedposting = NULL; /* nposting coded (prefix leaf) */ + IndexTuple additup; /* tuple actually added (coded or plain) */ + Size additemsz; + bool needsplit; + bool newitemplaced = true; XLogRecPtr recptr; page = BufferGetPage(buf); @@ -1181,7 +1226,13 @@ _bt_insertonpg(Relation rel, * insert or page split critical section. */ Assert(isleaf && itup_key->heapkeyspace && itup_key->allequalimage); - oposting = (IndexTuple) PageGetItem(page, itemid); + if (P_HASPREFIX(opaque)) + { + /* swap on the decoded tuple; recoded below, outside crit section */ + oposting = _bt_prefix_decode_copy(page, newitemoff); + } + else + oposting = (IndexTuple) PageGetItem(page, itemid); /* * postingoff value comes from earlier call to _bt_binsrch_posting(). @@ -1209,18 +1260,57 @@ _bt_insertonpg(Relation rel, nposting = _bt_swap_posting(itup, oposting, postingoff); /* itup now contains rightmost/max TID from oposting */ + if (P_HASPREFIX(opaque)) + { + /* + * The coded post-split posting tuple overwrites the coded + * original in place; it has the same size because the posting + * list only trades one TID. nposting stays plain, which is what + * _bt_split expects since it decodes the page itself. + */ + codedposting = _bt_prefix_recode(page, newitemoff, nposting); + Assert(IndexTupleSize(codedposting) == ItemIdGetLength(itemid)); + pfree(oposting); + oposting = (IndexTuple) PageGetItem(page, itemid); + } + /* Alter offset so that newitem goes after posting list */ newitemoff = OffsetNumberNext(newitemoff); } /* - * Do we need to split the page to fit the item on it? + * On a prefix leaf the new item is stored coded. Code it here, before + * any critical section, because coding pallocs. + */ + if (isleaf && P_HASPREFIX(opaque)) + { + additup = _bt_prefix_encode_insert(page, newitemoff, itup); + additemsz = additup ? MAXALIGN(IndexTupleSize(additup)) : 0; + } + else + { + additup = itup; + additemsz = itemsz; + } + + /* + * Do we need to split the page to fit the item? A prefix leaf also + * splits when the item cannot be coded against the page, or when its + * plain form would exceed the decoded split-fit budget. * * Note: PageGetFreeSpace() subtracts sizeof(ItemIdData) from its result, * so this comparison is correct even though we appear to be accounting * only for the item and not for its line pointer. */ - if (PageGetFreeSpace(page) < itemsz) + if (isleaf && P_HASPREFIX(opaque)) + needsplit = + additup == NULL || + PageGetFreeSpace(page) < additemsz || + _bt_prefix_split_needed(page, itemsz); + else + needsplit = PageGetFreeSpace(page) < itemsz; + + if (needsplit) { Buffer rbuf; @@ -1228,7 +1318,7 @@ _bt_insertonpg(Relation rel, /* split the buffer into left and right halves */ rbuf = _bt_split(rel, heaprel, itup_key, buf, cbuf, newitemoff, itemsz, - itup, origitup, nposting, postingoff); + itup, origitup, nposting, postingoff, &newitemplaced); PredicateLockPageSplit(rel, BufferGetBlockNumber(buf), BufferGetBlockNumber(rbuf)); @@ -1259,6 +1349,19 @@ _bt_insertonpg(Relation rel, #endif _bt_insert_parent(rel, heaprel, buf, rbuf, stack, isroot, isonly); + + if (additup != NULL && additup != itup) + pfree(additup); + + /* be tidy (posting split path) */ + if (postingoff != 0) + { + pfree(nposting); + pfree(itup); + if (codedposting) + pfree(codedposting); + } + return newitemplaced; } else { @@ -1295,11 +1398,17 @@ _bt_insertonpg(Relation rel, START_CRIT_SECTION(); if (postingoff != 0) - memcpy(oposting, nposting, MAXALIGN(IndexTupleSize(nposting))); + { + IndexTuple src = codedposting ? codedposting : nposting; + + memcpy(oposting, src, MAXALIGN(IndexTupleSize(src))); + } - if (PageAddItem(page, itup, itemsz, newitemoff, false, false) == InvalidOffsetNumber) + if (PageAddItem(page, additup, additemsz, newitemoff, false, false) == InvalidOffsetNumber) elog(PANIC, "failed to add new item to block %u in index \"%s\"", BufferGetBlockNumber(buf), RelationGetRelationName(rel)); + if (isleaf && P_HASPREFIX(opaque)) + _bt_prefix_note_insert(page, additup); MarkBufferDirty(buf); @@ -1384,8 +1493,8 @@ _bt_insertonpg(Relation rel, XLogRegisterBuffer(0, buf, REGBUF_STANDARD); if (postingoff == 0) { - /* Just log itup from caller */ - XLogRegisterBufData(0, itup, IndexTupleSize(itup)); + /* Log the tuple as added: coded on a prefix leaf */ + XLogRegisterBufData(0, additup, IndexTupleSize(additup)); } else { @@ -1418,6 +1527,9 @@ _bt_insertonpg(Relation rel, END_CRIT_SECTION(); + if (additup != itup) + pfree(additup); + /* Release subsidiary buffers */ if (BufferIsValid(metabuf)) _bt_relbuf(rel, metabuf); @@ -1453,7 +1565,11 @@ _bt_insertonpg(Relation rel, /* itup is actually a modified copy of caller's original */ pfree(nposting); pfree(itup); + if (codedposting) + pfree(codedposting); } + + return true; } /* @@ -1481,19 +1597,27 @@ _bt_insertonpg(Relation rel, * nbtree/README for details on the design of posting list splits. * * Returns the new right sibling of buf, pinned and write-locked. - * The pin and lock on buf are maintained. + * The pin and lock on buf are maintained. *newitemplaced is set false + * when a coded leaf's decoded items left no legal split point with + * newitem added; the existing items alone are split then, and caller + * must insert newitem afterwards. */ static Buffer _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer cbuf, OffsetNumber newitemoff, Size newitemsz, IndexTuple newitem, - IndexTuple orignewitem, IndexTuple nposting, uint16 postingoff) + IndexTuple orignewitem, IndexTuple nposting, uint16 postingoff, + bool *newitemplaced) { + bool placenewitem = true; /* false: split existing items only */ + bool leftcoded; /* left half written in BTP_PREFIX form? */ Buffer rbuf; Page origpage; Page leftpage, rightpage; PGAlignedBlock leftpage_buf, rightpage_buf; + Page plainscratch = NULL; /* decoded plain copy of a coded + * origpage, palloc'd */ BlockNumber origpagenumber, rightpagenumber; BTPageOpaque ropaque, @@ -1502,6 +1626,13 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer sbuf = InvalidBuffer; Page spage = NULL; BTPageOpaque sopaque = NULL; + bool origprefix = false; /* was origpage a coded prefix page? */ + bool origprefix_array = false; /* using decoded-item array path? */ + Page origbufpage; /* the real buffer page (origpage may be + * scratch) */ + IndexTuple *ditems = NULL; /* decoded data items (prefix split) */ + int nditems = 0; + IndexTuple ditemposting = NULL; /* decoded copy displaced by nposting */ Size itemsz; ItemId itemid; IndexTuple firstright, @@ -1532,12 +1663,59 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * only workspace. */ origpage = BufferGetPage(buf); + origbufpage = origpage; oopaque = BTPageGetOpaque(origpage); isleaf = P_ISLEAF(oopaque); isrightmost = P_RIGHTMOST(oopaque); maxoff = PageGetMaxOffsetNumber(origpage); origpagenumber = BufferGetBlockNumber(buf); + /* + * A coded (BTP_PREFIX) leaf is split on its decoded items, and both + * halves are built plain, then coded as whole pages at the end. When the + * decoded items fit one page, split a plain scratch copy, so that + * _bt_findsplitloc and its heap TID tiebreak at duplicate boundaries + * apply unchanged. A heavily compressed page whose decoded items exceed + * BLCKSZ cannot be laid out that way; split an array of the decoded items + * instead, with a size-balanced split point from _bt_prefix_findsplitloc. + */ + if (P_HASPREFIX(oopaque)) + { + Page plain; + + origprefix = true; + + plainscratch = (Page) palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE, 0); + plain = _bt_prefix_try_plain_page(rel, origpage, plainscratch); + if (plain != NULL) + { + OffsetNumber codedfirst = P_FIRSTDATAKEY(oopaque); + + origpage = plain; + oopaque = BTPageGetOpaque(origpage); + maxoff = PageGetMaxOffsetNumber(origpage); + origprefix_array = false; + + /* + * newitemoff is in the coded page's offset space, where the + * directory item shifts data items one later; the scratch page + * has no directory. + */ + newitemoff -= (codedfirst - P_FIRSTDATAKEY(oopaque)); + } + else + { + IndexTuple dhikey; + Size dhikeysz; + + nditems = _bt_prefix_decode_items(origpage, &ditems, &dhikey, + &dhikeysz); + if (dhikey) + pfree(dhikey); + origprefix_array = true; + } + } + /* * Choose a point to split origpage at. * @@ -1562,8 +1740,32 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * newitem the firstright tuple, though, so this case isn't a special * case. */ - firstrightoff = _bt_findsplitloc(rel, origpage, newitemoff, newitemsz, - newitem, &newitemonleft); + if (origprefix_array) + { + firstrightoff = _bt_prefix_findsplitloc(rel, origpage, ditems, + newitemoff, newitemsz, + &newitemonleft); + if (!OffsetNumberIsValid(firstrightoff)) + { + /* + * No split of the decoded items plus newitem keeps both halves + * within a plain page. Split the existing items alone and let + * caller re-insert newitem. newitemoff is made unreachable so + * the transfer loop below never places newitem. + */ + placenewitem = false; + firstrightoff = _bt_prefix_findsplitloc(rel, origpage, ditems, + InvalidOffsetNumber, 0, + &newitemonleft); + newitemonleft = false; + newitemoff = maxoff + 2; /* past the "goes at end" case too */ + postingoff = 0; /* posting split is part of the deferred + * insert */ + } + } + else + firstrightoff = _bt_findsplitloc(rel, origpage, newitemoff, newitemsz, + newitem, &newitemonleft); /* Use temporary buffer for leftpage */ leftpage = leftpage_buf.data; @@ -1588,7 +1790,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * updated version of the page. We need this because XLogInsert will * examine the LSN and possibly dump it in a page image. */ - PageSetLSN(leftpage, PageGetLSN(origpage)); + PageSetLSN(leftpage, PageGetLSN(origbufpage)); /* * Determine page offset number of existing overlapped-with-orignewitem @@ -1616,6 +1818,13 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, &newitem->t_tid) < 0); Assert(BTreeTupleIsPosting(nposting)); origpagepostingoff = OffsetNumberPrev(newitemoff); + if (origprefix_array) + { + int pidx = origpagepostingoff - P_FIRSTDATAKEY(oopaque); + + ditemposting = ditems[pidx]; + ditems[pidx] = nposting; + } } /* @@ -1647,11 +1856,19 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, else { /* existing item at firstrightoff becomes firstright */ - itemid = PageGetItemId(origpage, firstrightoff); - itemsz = ItemIdGetLength(itemid); - firstright = (IndexTuple) PageGetItem(origpage, itemid); - if (firstrightoff == origpagepostingoff) - firstright = nposting; + if (origprefix_array) + { + firstright = ditems[firstrightoff - P_FIRSTDATAKEY(oopaque)]; + itemsz = IndexTupleSize(firstright); + } + else + { + itemid = PageGetItemId(origpage, firstrightoff); + itemsz = ItemIdGetLength(itemid); + firstright = (IndexTuple) PageGetItem(origpage, itemid); + if (firstrightoff == origpagepostingoff) + firstright = nposting; + } } if (isleaf) @@ -1671,10 +1888,15 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, /* existing item before firstrightoff becomes lastleft */ lastleftoff = OffsetNumberPrev(firstrightoff); Assert(lastleftoff >= P_FIRSTDATAKEY(oopaque)); - itemid = PageGetItemId(origpage, lastleftoff); - lastleft = (IndexTuple) PageGetItem(origpage, itemid); - if (lastleftoff == origpagepostingoff) - lastleft = nposting; + if (origprefix_array) + lastleft = ditems[lastleftoff - P_FIRSTDATAKEY(oopaque)]; + else + { + itemid = PageGetItemId(origpage, lastleftoff); + lastleft = (IndexTuple) PageGetItem(origpage, itemid); + if (lastleftoff == origpagepostingoff) + lastleft = nposting; + } } lefthighkey = _bt_truncate(rel, lastleft, firstright, itup_key); @@ -1818,12 +2040,20 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, { IndexTuple dataitem; - itemid = PageGetItemId(origpage, i); - itemsz = ItemIdGetLength(itemid); - dataitem = (IndexTuple) PageGetItem(origpage, itemid); + if (origprefix_array) + { + dataitem = ditems[i - P_FIRSTDATAKEY(oopaque)]; + itemsz = IndexTupleSize(dataitem); + } + else + { + itemid = PageGetItemId(origpage, i); + itemsz = ItemIdGetLength(itemid); + dataitem = (IndexTuple) PageGetItem(origpage, itemid); + } /* replace original item with nposting due to posting split? */ - if (i == origpagepostingoff) + if (!origprefix_array && i == origpagepostingoff) { Assert(BTreeTupleIsPosting(dataitem)); Assert(itemsz == MAXALIGN(IndexTupleSize(nposting))); @@ -1884,7 +2114,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, } /* Handle case where newitem goes at the end of rightpage */ - if (i <= newitemoff) + if (placenewitem && i <= newitemoff) { /* * Can't have newitemonleft here; that would imply we were told to put @@ -1947,6 +2177,26 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * not starting the critical section till here because we haven't been * scribbling on the original page yet; see comments above. */ + + /* + * Both halves were built plain but may have inherited BTP_PREFIX from a + * coded original page. Code them here, before the critical section, + * because coding pallocs. + */ + if (isleaf) + { + lopaque->btpo_flags &= ~BTP_PREFIX; + ropaque->btpo_flags &= ~BTP_PREFIX; + if (_bt_prefix_enabled(rel)) + { + _bt_prefix_compress_page(rel, leftpage); + _bt_prefix_compress_page(rel, rightpage); + lopaque = BTPageGetOpaque(leftpage); + ropaque = BTPageGetOpaque(rightpage); + } + } + leftcoded = P_HASPREFIX(lopaque); + START_CRIT_SECTION(); /* @@ -1956,7 +2206,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * original. We need to do this before writing the WAL record, so that * XLogInsert can WAL log an image of the page if necessary. */ - memcpy(origpage, leftpage, BLCKSZ); + memcpy(origbufpage, leftpage, BLCKSZ); /* leftpage, lopaque must not be used below here */ /* @@ -2005,8 +2255,47 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, if (postingoff != 0 && origpagepostingoff < firstrightoff) xlrec.postingoff = postingoff; + /* + * A coded original page is described to redo in its decoded offset + * space (see XLH_SPLIT_ORIG_CODED). The plain-scratch path already + * works there; the decoded-array path works in the coded page's + * offsets, one past the directory item. + */ + xlrec.flags = 0; + if (origprefix) + { + xlrec.flags |= XLH_SPLIT_ORIG_CODED; + if (origprefix_array) + { + xlrec.firstrightoff--; + xlrec.newitemoff--; + } + } + if (leftcoded) + xlrec.flags |= XLH_SPLIT_LEFT_CODED; + if (P_HASPREFIX(ropaque)) + xlrec.flags |= XLH_SPLIT_RIGHT_CODED; + + /* + * A coded left half from a plain original has no layout on any page + * redo can read, so log the key-column layout in the record (see + * XLH_SPLIT_LEFT_DESC). A coded original carries it in its + * directory. + */ + if (leftcoded && !origprefix) + xlrec.flags |= XLH_SPLIT_LEFT_DESC; + XLogBeginInsert(); XLogRegisterData(&xlrec, SizeOfBtreeSplit); + if (xlrec.flags & XLH_SPLIT_LEFT_DESC) + { + BTPrefixAttr descattrs[INDEX_MAX_KEYS]; + uint16 descnatts; + + descnatts = (uint16) _bt_prefix_build_layout(rel, descattrs); + XLogRegisterData(&descnatts, sizeof(uint16)); + XLogRegisterData(descattrs, sizeof(BTPrefixAttr) * descnatts); + } XLogRegisterBuffer(0, buf, REGBUF_STANDARD); XLogRegisterBuffer(1, rbuf, REGBUF_WILL_INIT); @@ -2083,7 +2372,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, else recptr = XLogGetFakeLSN(rel); - PageSetLSN(origpage, recptr); + PageSetLSN(origbufpage, recptr); PageSetLSN(rightpage, recptr); if (!isrightmost) PageSetLSN(spage, recptr); @@ -2103,8 +2392,23 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, /* be tidy */ if (isleaf) pfree(lefthighkey); + if (ditems) + { + /* nposting belongs to the caller; free the decoded copy it displaced */ + for (int k = 0; k < nditems; k++) + { + if (ditems[k] != nposting) + pfree(ditems[k]); + } + if (ditemposting) + pfree(ditemposting); + pfree(ditems); + } + if (plainscratch) + pfree(plainscratch); /* split's done */ + *newitemplaced = placenewitem; return rbuf; } @@ -2770,7 +3074,10 @@ _bt_delete_or_dedup_one_page(Relation rel, Relation heapRel, insertstate->bounds_valid = false; /* Return when a page split has already been avoided */ - if (PageGetFreeSpace(page) >= insertstate->itemsz) + if (PageGetFreeSpace(page) >= insertstate->itemsz + + (P_HASPREFIX(opaque) ? BTREE_PREFIX_CODE_OVERHEAD : 0) && + (!P_HASPREFIX(opaque) || + !_bt_prefix_split_needed(page, insertstate->itemsz))) return; /* Might as well assume duplicates (if checkingunique) */ diff --git a/src/backend/access/nbtree/nbtpage.c b/src/backend/access/nbtree/nbtpage.c index 83d6d367f81..9fc8e9f1fea 100644 --- a/src/backend/access/nbtree/nbtpage.c +++ b/src/backend/access/nbtree/nbtpage.c @@ -1211,6 +1211,7 @@ _bt_delitems_vacuum(Relation rel, Buffer buf, /* Now handle simple deletes of entire tuples */ if (ndeletable > 0) PageIndexMultiDelete(page, deletable, ndeletable); + _bt_prefix_recount(page); /* * We can clear the vacuum cycle ID since this page has certainly been @@ -1331,6 +1332,7 @@ _bt_delitems_delete(Relation rel, Buffer buf, if (ndeletable > 0) PageIndexMultiDelete(page, deletable, ndeletable); + _bt_prefix_recount(page); /* * Unlike _bt_delitems_vacuum, we *must not* clear the vacuum cycle ID at diff --git a/src/backend/access/nbtree/nbtprefix.c b/src/backend/access/nbtree/nbtprefix.c new file mode 100644 index 00000000000..c64c62feaac --- /dev/null +++ b/src/backend/access/nbtree/nbtprefix.c @@ -0,0 +1,1833 @@ +/*------------------------------------------------------------------------- + * + * nbtprefix.c + * Leaf key prefix compression for Postgres btrees. + * + * A leaf of an index whose prefix_compression reloption is on may be flagged + * BTP_PREFIX: its data items are stored "coded" against per-page group + * anchors, dropping the leading bytes each shares with its anchor. The + * on-disk format is described at BTP_PREFIX in nbtree.h; the README covers how + * the rest of nbtree uses it. + * + * Everything here works on pages and tuples alone, never the catalog, so WAL + * redo can lay out a coded page exactly as the primary did. A page gets its + * directory when it is written as a whole (CREATE INDEX, either half of a + * split); an insert codes the new tuple against an existing group, sharing + * however much it happens to share, and deduplication re-codes against the + * page's existing directory. + * + * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * IDENTIFICATION + * src/backend/access/nbtree/nbtprefix.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#include "access/itup.h" +#include "access/nbtree.h" +#include "access/tupmacs.h" +#include "storage/bufpage.h" +#include "utils/rel.h" +#include "varatt.h" + +/* In-memory anchor: the group's first member, as a plain tuple. */ +typedef struct BTPrefixAnchor +{ + IndexTuple rep; /* representative tuple owning the shared + * bytes */ +} BTPrefixAnchor; + +/* In-memory directory of a page being laid out by _bt_prefix_form_page. */ +typedef struct BTPrefixDir +{ + int ngroups; + BTPrefixAnchor anchors[FLEXIBLE_ARRAY_MEMBER]; +} BTPrefixDir; + +/* + * On-disk per-key-attribute layout (BTPrefixAttr in nbtree.h), enough to parse + * a tuple's data area without the catalog. The primary fills it from + * RelationGetDescr(index); decode reads it from the directory so decoding + * stays page-only. The column walk (_bt_prefix_walk) uses every key column's + * attlen, attalignby, and by-value flag to find where two tuples diverge, so + * the whole key-column layout is stored. + */ +#define BTPREFIX_ATTR_BYVAL 0x01 + +/* + * On-disk directory item header. decodedsz and maxdecoded cache the decoded + * (plain) size of the page's data items, each counted with its line pointer: + * their sum and the largest. They make _bt_prefix_split_needed O(1). Every + * change to the data items keeps them exact, through page-only routines that + * WAL redo repeats (_bt_prefix_note_insert, _bt_prefix_recount). + * + * The variable tail is, in order: `natts' BTPrefixAttr records (the key-column + * layout), the `ngroups' anchor offsets, and the packed anchors. Only the + * first two are fixed-position; the anchor-offset array starts after the + * layout, so _bt_prefix_anchoroff computes its base from natts. natts == 0 + * means no layout is recorded, so coding falls back to sharing the whole data + * area from offset 0 (the pre-layout behavior); the primary always records the + * real layout, but a redo path that cannot obtain it page-only writes 0. + */ +typedef struct BTPrefixDirHdr +{ + IndexTupleData header; /* t_tid invalid; t_info = whole item size */ + uint16 ngroups; + uint16 decodedsz; /* sum of decoded item sizes + line pointers */ + uint16 maxdecoded; /* largest of those */ + uint16 natts; /* key-column count, layout records that + * follow */ + BTPrefixAttr attrs[FLEXIBLE_ARRAY_MEMBER]; /* [natts], then anchoroff[] */ +} BTPrefixDirHdr; + +/* One packed anchor in the directory item. */ +typedef struct BTPrefixAnchorDisk +{ + uint16 repsz; /* size of the representative tuple blob */ + /* IndexTupleData rep[repsz] follows, MAXALIGN'd */ +} BTPrefixAnchorDisk; + +/* + * Code header of a coded member, right after its IndexTupleData header. The + * member layout is described at BTP_PREFIX in nbtree.h. + * + * lead_shared (= D) is the data-area byte offset of the divergent column: the + * first key column whose value differs from the anchor's. Every byte before + * it, the fully-shared leading columns and their length headers, is identical + * across the group and comes from the anchor. shared_len (= sv) is the + * divergent column's shared value bytes, after its length header. Only that + * one column's header is kept private to each member, so a run of equal + * leading columns is shared whole even when the divergent column's length + * header differs between members. + */ +typedef struct BTPrefixCode +{ + uint16 group; /* anchor index in the directory */ + uint16 lead_shared; /* data-area bytes of fully-shared leading + * cols */ + uint16 shared_len; /* divergent column's shared value bytes */ + uint16 orig_info; /* original tuple's t_info (size, flags) */ +} BTPrefixCode; + +/* + * A coded member is never larger than its plain form by more than + * BTREE_PREFIX_CODE_OVERHEAD, which _bt_findinsertloc reserves before coding. + * The worst case is a posting tuple, whose body and posting list are each + * MAXALIGN'd: MAXALIGN(code header + key) + MAXALIGN(posting list) exceeds + * the plain MAXALIGN(key + posting list) by at most the code header plus one + * alignment of the posting list. + */ +StaticAssertDecl(BTREE_PREFIX_CODE_OVERHEAD >= + MAXALIGN(sizeof(BTPrefixCode)) + MAXALIGN(sizeof(ItemPointerData)), + "BTREE_PREFIX_CODE_OVERHEAD too small for the coded member header"); + +/* + * _bt_prefix_enabled + * Is prefix compression turned on for this index? + */ +bool +_bt_prefix_enabled(Relation index) +{ + return index->rd_options && + ((BTOptions *) index->rd_options)->prefix_compression; +} + +/* + * Size of a tuple's key part: everything but a posting list. Index tuples are + * MAXALIGN'd, and so is a posting list's offset, so this is MAXALIGN'd too. + */ +static inline Size +_bt_prefix_keysz(IndexTuple itup) +{ + return BTreeTupleIsPosting(itup) ? BTreeTupleGetPostingOffset(itup) : + IndexTupleSize(itup); +} + +/* + * Byte offset of the anchor-offset array within a directory item holding + * `natts' layout records. The layout precedes it; the anchors follow it. + */ +static inline Size +_bt_prefix_anchoroff_base(int natts) +{ + return offsetof(BTPrefixDirHdr, attrs) + sizeof(BTPrefixAttr) * natts; +} + +/* The anchor-offset array of a directory header (natts layout records). */ +static inline uint16 * +_bt_prefix_anchoroff(BTPrefixDirHdr *hdr) +{ + return (uint16 *) ((char *) hdr + _bt_prefix_anchoroff_base(hdr->natts)); +} + +/* + * Size of a directory item for `ngroups' groups and `natts' key-column layout + * records, whose MAXALIGN'd anchor blobs total `anchorsz' bytes. + */ +static inline Size +_bt_prefix_diritem_size(int natts, int ngroups, Size anchorsz) +{ + return MAXALIGN(_bt_prefix_anchoroff_base(natts) + + sizeof(uint16) * ngroups) + anchorsz; +} + +/* + * Where two tuples first diverge inside one key column. D (lead_shared) is + * the data-area offset of that divergent column, so [0..D) is byte-identical + * between the two (they share every leading column whole, header and value). + * sv (shared_len) is the divergent column's common value-byte prefix, after + * its length header. Decode and coding carry both through BTPrefixCode. + */ +typedef struct BTPrefixSplit +{ + Size lead_shared; /* D: data-area bytes of fully-shared cols */ + Size shared_len; /* sv: divergent col's shared value bytes */ +} BTPrefixSplit; + +/* + * Validated splice offsets of a coded member, filled by + * _bt_prefix_check_member and consumed by _bt_prefix_decode so the two cannot + * disagree: D (lead_shared), sv (shared_len), the member's and the anchor's + * divergent-column prefix widths (mhdr, ahdr), and the member's stored residual + * length. All are bounded against the member and the anchor before use. + */ +typedef struct BTPrefixSplice +{ + Size lead_shared; /* D */ + Size shared_len; /* sv */ + Size mhdr; /* member's divergent-column prefix */ + Size ahdr; /* anchor's divergent-column prefix */ + Size residual; /* member's stored residual bytes */ +} BTPrefixSplice; + +/* + * Width of the length header of a key column whose value begins at `data'. + * + * `attr' is the column's stored layout. A varlena column's header is 1 or 4 + * bytes, read from `data'; any fixed-length or by-value column has none. The + * column walk uses this to step over each column's header. + */ +static inline Size +_bt_prefix_header_width(const BTPrefixAttr * attr, const char *data) +{ + if (attr->attlen != -1 || (attr->flags & BTPREFIX_ATTR_BYVAL) != 0) + return 0; + return VARATT_IS_1B(data) ? VARHDRSZ_SHORT : VARHDRSZ; +} + +/* + * Advance `off' (a data-area byte offset) past key column `i' of a tuple whose + * data area starts at `data' and whose null bitmap is `bitmap' (NULL when the + * tuple has no nulls). Sets *valoff to the column's value offset (after any + * length header) and *vallen to its value length; a null column occupies no + * bytes and reports *vallen 0. `attrs'/`natts' is the stored layout, `limit' + * the data-area length (a bound so a malformed length cannot walk off the + * tuple). Returns false if column `i' does not fit within `limit'. + */ +static inline bool +_bt_prefix_column(const BTPrefixAttr * attrs, int natts, int i, + const char *data, const uint8 *bitmap, Size limit, + Size *off, Size *valoff, Size *vallen) +{ + const BTPrefixAttr *attr = &attrs[i]; + Size start; + Size hdr; + Size len; + + if (bitmap != NULL && att_isnull(i, bitmap)) + { + *valoff = *off; + *vallen = 0; + return true; /* a null column occupies no data bytes */ + } + + /* align the column start, honoring the packed-varlena rule */ + if (attr->attlen == -1 && *off < limit && VARATT_NOT_PAD_BYTE(data + *off)) + start = *off; + else + start = att_nominal_alignby(*off, attr->attalignby); + if (start > limit) + return false; + + if (attr->attlen > 0) + { + hdr = 0; + len = attr->attlen; + } + else if (attr->attlen == -1) + { + if (start >= limit) + return false; /* no room for a length header */ + hdr = _bt_prefix_header_width(attr, data + start); + if (start + hdr > limit) + return false; + len = VARSIZE_ANY(data + start); + } + else + { + Assert(attr->attlen == -2); /* cstring */ + hdr = 0; + len = strnlen(data + start, limit - start) + 1; + } + + if (start + len > limit) + return false; + *valoff = start + hdr; + *vallen = len - hdr; + *off = start + len; + return true; +} + +/* + * Walk `rep' and `itup' column by column and set *split to where their key + * values first diverge: the data-area offset D of the first column whose value + * bytes differ, and sv the common value-byte prefix of that column. + * + * Every column before the divergent one has byte-identical value bytes in both + * tuples; a column equal by value has equal length, hence an identical length + * header and identical alignment padding, so [0..D) is byte-identical and can + * be shared whole from the anchor. The divergent column is the last shared + * one, so re-inserting its (possibly different-width) header per member cannot + * shift the alignment of any shared column. Without a layout (`attrs' NULL, + * CREATE INDEX before the descriptor exists), it shares the whole data area as + * v15 did: D = 0 and sv = the common byte prefix from offset 0. A single + * leading varlena column makes the divergent column column 0, so D = 0 and the + * on-disk form is byte-identical to v16. + */ +static void +_bt_prefix_walk(const BTPrefixAttr * attrs, int natts, + IndexTuple rep, IndexTuple itup, BTPrefixSplit *split) +{ + Size rephoff = IndexInfoFindDataOffset(rep->t_info); + Size hoff = IndexInfoFindDataOffset(itup->t_info); + const char *rd = (const char *) rep + rephoff; + const char *md = (const char *) itup + hoff; + const uint8 *rbitmap = IndexTupleHasNulls(rep) ? + (const uint8 *) rep + sizeof(IndexTupleData) : NULL; + const uint8 *mbitmap = IndexTupleHasNulls(itup) ? + (const uint8 *) itup + sizeof(IndexTupleData) : NULL; + Size replim = _bt_prefix_keysz(rep) - rephoff; + Size mlim = _bt_prefix_keysz(itup) - hoff; + Size roff = 0; + Size moff = 0; + + /* No layout: share the whole data area, with no carved header (v15). */ + if (attrs == NULL) + { + Size limit = Min(replim, mlim); + Size n = 0; + + while (n < limit && rd[n] == md[n]) + n++; + split->lead_shared = 0; + split->shared_len = n; + return; + } + + for (int i = 0; i < natts; i++) + { + Size rvaloff, + rvallen, + mvaloff, + mvallen; + Size common; + Size cmplen; + Size divoff = Max(roff, moff); + + if (!_bt_prefix_column(attrs, natts, i, rd, rbitmap, replim, + &roff, &rvaloff, &rvallen) || + !_bt_prefix_column(attrs, natts, i, md, mbitmap, mlim, + &moff, &mvaloff, &mvallen)) + { + split->lead_shared = divoff; + split->shared_len = 0; + return; + } + + /* + * A column stays in the shared leading span only when its whole + * data-area footprint is byte-identical in both tuples: the same + * total length (roff == moff) and the same bytes. That covers the + * length header and any alignment padding, and it separates a null + * column (no bytes) from an empty value (a bare varlena header), + * which share the same empty value but occupy different footprints. + * Compare from divoff, where both columns began in lockstep. + */ + if (roff == moff && + memcmp(rd + divoff, md + divoff, roff - divoff) == 0) + continue; + + /* + * The divergent column: D is its data-area offset, sv its common + * value-byte prefix (0 when one side is null, since a null column has + * no value to share). + */ + cmplen = Min(rvallen, mvallen); + common = 0; + while (common < cmplen && rd[rvaloff + common] == md[mvaloff + common]) + common++; + split->lead_shared = divoff; + split->shared_len = common; + return; + } + + /* Every key column matched: share the whole data area, no divergent col. */ + Assert(roff == moff); + split->lead_shared = roff; + split->shared_len = 0; +} + +/* + * Divergent-column prefix (alignment padding plus length header) at data-area + * offset D: the bytes decode must keep with each member before splicing in the + * shared value. Columns [0..D) are byte-identical across the group, so this + * walks `data' (any group member's data area, bounded by `limit') with null + * bitmap `bitmap' to the column that begins at D, then measures that column in + * `divdata' (the bytes of the data area from D, bounded by `divlimit'). For + * the anchor, `divdata' is `data + D'; for a coded member it is the member's + * residual, whose [0..D) bytes equal the anchor's. Returns 0 when D is at or + * past the data area, the divergent column is null, or every column is shared; + * sets *ok false (returns 0) on a malformed length that would overrun. + * + * A short (packed) varlena carries a 1-byte header with no padding; a long one + * aligns and carries a 4-byte header. Two members of one group can therefore + * store prefixes of different width and still reconstruct. + */ +static Size +_bt_prefix_divprefix(const BTPrefixAttr * attrs, int natts, + const char *data, const uint8 *bitmap, Size limit, + const char *divdata, Size divlimit, Size lead_shared, + bool *ok) +{ + Size off = 0; + + *ok = true; + if (attrs == NULL || lead_shared >= limit) + return 0; + + for (int i = 0; i < natts; i++) + { + const BTPrefixAttr *attr = &attrs[i]; + Size valoff, + vallen; + Size pad; + + if (off > lead_shared) + return 0; /* D fell inside a column, not a boundary */ + if (bitmap != NULL && att_isnull(i, bitmap)) + continue; /* null column: no bytes, no carved header */ + if (off < lead_shared) + { + if (!_bt_prefix_column(attrs, natts, i, data, bitmap, limit, + &off, &valoff, &vallen)) + { + *ok = false; + return 0; + } + continue; + } + + /* column i is the first non-null column beginning at D */ + if (attr->attlen != -1 || (attr->flags & BTPREFIX_ATTR_BYVAL) != 0) + return 0; /* fixed or by-value: value starts at D */ + + /* varlena: packed short stays unaligned, else align for a 4-byte hdr */ + if (divlimit > 0 && VARATT_NOT_PAD_BYTE(divdata)) + pad = 0; + else + pad = att_nominal_alignby(lead_shared, attr->attalignby) - + lead_shared; + if (pad + VARHDRSZ_SHORT > divlimit) + { + *ok = false; + return 0; + } + if (VARATT_IS_1B(divdata + pad)) + return pad + VARHDRSZ_SHORT; + if (pad + VARHDRSZ > divlimit) + { + *ok = false; + return 0; + } + return pad + VARHDRSZ; + } + return 0; /* every column shared: no divergent column */ +} + +/* + * Divergent-column prefix of whole tuple `itup' at offset D (see + * _bt_prefix_divprefix). For the anchor, which is a complete tuple; the + * caller has bounded D against the key size. + */ +static inline Size +_bt_prefix_divhdr(const BTPrefixAttr * attrs, int natts, + IndexTuple itup, Size lead_shared) +{ + Size hoff = IndexInfoFindDataOffset(itup->t_info); + Size limit = _bt_prefix_keysz(itup) - hoff; + const char *data = (const char *) itup + hoff; + const uint8 *bitmap = IndexTupleHasNulls(itup) ? + (const uint8 *) itup + sizeof(IndexTupleData) : NULL; + bool ok; + + return _bt_prefix_divprefix(attrs, natts, data, bitmap, limit, + data + lead_shared, limit - lead_shared, + lead_shared, &ok); +} + +/* + * Total data-area bytes `itup' shares with `rep': the fully-shared leading + * columns D plus the divergent column's shared value prefix sv. This is what + * coding removes from the member, so grouping and the size estimate rank by + * it. + */ +static inline Size +_bt_prefix_shared(const BTPrefixSplit *split) +{ + return split->lead_shared + split->shared_len; +} + +/* + * Size of `itup' coded against representative `rep' (what + * _bt_prefix_encode_against would produce), without forming it. `shared' + * counts the data-area bytes dropped (leading columns plus the divergent + * value prefix); the member keeps its own divergent-column header, which is + * part of the residual, so the residual is the data area minus `shared'. + */ +static Size +_bt_prefix_coded_size(IndexTuple itup, Size shared) +{ + Size hoff = IndexInfoFindDataOffset(itup->t_info); + Size sz; + + sz = MAXALIGN(sizeof(IndexTupleData) + sizeof(BTPrefixCode) + + (hoff - sizeof(IndexTupleData)) + + (_bt_prefix_keysz(itup) - hoff - shared)); + if (BTreeTupleIsPosting(itup)) + sz = MAXALIGN(sz + BTreeTupleGetNPosting(itup) * sizeof(ItemPointerData)); + return sz; +} + +/* + * _bt_prefix_group_start + * Should `itup' start a new group? + * + * `rep' is the current group's representative and `prev' the preceding tuple + * (both NULL for the page's first tuple). Sets *shared to the data-area bytes + * `itup' shares with the representative it ends up under (itself if it starts + * a group): the fully-shared leading columns plus the divergent value prefix. + * This is the only grouping rule, shared by the CREATE INDEX estimate + * (_bt_prefix_est_add) and the layout (_bt_prefix_choose_groups), so the two + * cannot disagree. + * + * A group starts when `itup' shares nothing with `rep', or shares at least one + * MAXALIGN quantum more with `prev' than with `rep'. The second case keeps a + * long run of tuples that share much among themselves from being locked to a + * short accidental prefix of the page's first tuple (e.g., just a leading + * fixed-width column). The rule looks only backwards and the new group is + * led by `itup', so no earlier tuple is ever regrouped and the estimate stays + * exact tuple by tuple. + */ +static bool +_bt_prefix_group_start(const BTPrefixAttr * attrs, int natts, + IndexTuple rep, IndexTuple prev, IndexTuple itup, + Size *shared) +{ + BTPrefixSplit split; + Size s_rep; + + if (rep == NULL) + { + _bt_prefix_walk(attrs, natts, itup, itup, &split); + *shared = _bt_prefix_shared(&split); + return true; + } + + _bt_prefix_walk(attrs, natts, rep, itup, &split); + s_rep = _bt_prefix_shared(&split); + if (s_rep == 0) + { + _bt_prefix_walk(attrs, natts, itup, itup, &split); + *shared = _bt_prefix_shared(&split); + return true; + } + + if (prev != NULL && prev != rep) + { + BTPrefixSplit psplit; + Size s_prev; + + _bt_prefix_walk(attrs, natts, prev, itup, &psplit); + s_prev = _bt_prefix_shared(&psplit); + if (s_prev >= s_rep + MAXIMUM_ALIGNOF) + { + _bt_prefix_walk(attrs, natts, itup, itup, &split); + *shared = _bt_prefix_shared(&split); + return true; + } + } + + *shared = s_rep; + return false; +} + +/* + * Running size estimate of a BTP_PREFIX page laid out from a sequence of plain + * tuples in key order, as _bt_prefix_form_page would lay it out (same + * grouping, same coded sizes). Used by CREATE INDEX to fill coded pages. + * The tuples passed to _bt_prefix_est_add must stay valid while the estimate + * is in use. + */ +void +_bt_prefix_est_add(BTPrefixPageEst *est, const BTPrefixAttr * attrs, + int natts, IndexTuple itup) +{ + Size plain = MAXALIGN(IndexTupleSize(itup)) + sizeof(ItemIdData); + Size shared; + + est->natts = natts; + if (_bt_prefix_group_start(attrs, natts, est->grouprep, est->prev, itup, + &shared)) + { + est->grouprep = itup; + est->ngroups++; + est->anchorsz += MAXALIGN(MAXALIGN(sizeof(BTPrefixAnchorDisk)) + + _bt_prefix_keysz(itup)); + } + est->lastcoded = _bt_prefix_coded_size(itup, shared) + + sizeof(ItemIdData); + est->maxcoded = Max(est->maxcoded, est->lastcoded - sizeof(ItemIdData)); + est->codedsz += est->lastcoded; + est->plainsz += plain; + est->maxplain = Max(est->maxplain, plain); + est->prev = itup; +} + +/* Bytes (items plus line pointers) the coded page would use */ +Size +_bt_prefix_est_coded(const BTPrefixPageEst *est) +{ + return _bt_prefix_diritem_size(est->natts, est->ngroups, est->anchorsz) + + sizeof(ItemIdData) + est->codedsz; +} + +/* The directory and each member must fit the IndexTuple size field. */ +bool +_bt_prefix_est_representable(const BTPrefixPageEst *est) +{ + return _bt_prefix_diritem_size(est->natts, est->ngroups, est->anchorsz) <= + INDEX_SIZE_MASK && + est->maxcoded <= INDEX_SIZE_MASK; +} + +/* + * Is a coded page worth having, given its coded and plain sizes? Demand a + * real saving: decoding costs CPU on every access, so a page that would save + * only a few bytes stays plain. + */ +bool +_bt_prefix_worthwhile(Size codedsz, Size plainsz) +{ + return codedsz * 16 <= plainsz * 15; +} + +/* + * _bt_prefix_build_layout + * Fill `attrs' (INDEX_MAX_KEYS entries) with the index's key-column + * layout and return the key count. + * + * The primary calls this from RelationGetDescr(index) at page-write time; the + * layout it returns is stored in the directory so decode can parse tuples + * page-only. + */ +int +_bt_prefix_build_layout(Relation index, BTPrefixAttr * attrs) +{ + TupleDesc tupdesc = RelationGetDescr(index); + int natts = IndexRelationGetNumberOfKeyAttributes(index); + + Assert(natts >= 1 && natts <= INDEX_MAX_KEYS); + for (int i = 0; i < natts; i++) + { + CompactAttribute *attr = TupleDescCompactAttr(tupdesc, i); + + attrs[i].attlen = attr->attlen; + attrs[i].attalignby = attr->attalignby; + attrs[i].flags = attr->attbyval ? BTPREFIX_ATTR_BYVAL : 0; + } + return natts; +} + +/* + * _bt_prefix_choose_groups + * Group plain tuples items[0..n-1], in key order, by + * _bt_prefix_group_start. + * + * Returns a palloc'd BTPrefixDir, or NULL when no two tuples share a group. + */ +static BTPrefixDir * +_bt_prefix_choose_groups(const BTPrefixAttr * attrs, int natts, + IndexTuple *items, int n) +{ + BTPrefixDir *dir; + int ngroups = 0; + + StaticAssertStmt(MaxIndexTuplesPerPage <= BTREE_PREFIX_MAXGROUPS, + "group number must fit in uint16"); + + if (n <= 1) + return NULL; + + dir = palloc(offsetof(BTPrefixDir, anchors) + sizeof(BTPrefixAnchor) * n); + for (int i = 0; i < n; i++) + { + IndexTuple rep = ngroups == 0 ? NULL : dir->anchors[ngroups - 1].rep; + IndexTuple prev = i == 0 ? NULL : items[i - 1]; + Size shared; + + if (_bt_prefix_group_start(attrs, natts, rep, prev, items[i], &shared)) + dir->anchors[ngroups++].rep = items[i]; + } + + if (ngroups >= n) + { + pfree(dir); + return NULL; /* every tuple its own group: nothing shared */ + } + + dir->ngroups = ngroups; + return dir; +} + +/* + * Serialize `dir' as a palloc'd directory item, setting *itemsz to its size. + * `attrs'/`natts' is the key-column layout stored in the header for page-only + * decode. The cached decoded sizes are left zero for _bt_prefix_recount. + */ +static IndexTuple +_bt_prefix_form_diritem(BTPrefixDir *dir, const BTPrefixAttr * attrs, int natts, + Size *itemsz) +{ + int ng = dir->ngroups; + Size total = _bt_prefix_diritem_size(natts, ng, 0); + Size *anchoroff = palloc(sizeof(Size) * ng); + char *buf; + IndexTuple item; + BTPrefixDirHdr *hdr; + uint16 *offarr; + + for (int g = 0; g < ng; g++) + { + Size repsz = _bt_prefix_keysz(dir->anchors[g].rep); + + anchoroff[g] = total; + total += MAXALIGN(MAXALIGN(sizeof(BTPrefixAnchorDisk)) + repsz); + } + + if (total > INDEX_SIZE_MASK) + elog(ERROR, "nbtree prefix directory too large (%zu bytes)", total); + + buf = palloc0(total); + item = (IndexTuple) buf; + ItemPointerSetInvalid(&item->t_tid); + item->t_info = (unsigned short) total; /* size only; no null/varwidth */ + + hdr = (BTPrefixDirHdr *) buf; + hdr->ngroups = (uint16) ng; + hdr->decodedsz = 0; + hdr->maxdecoded = 0; + hdr->natts = (uint16) natts; + for (int i = 0; i < natts; i++) + hdr->attrs[i] = attrs[i]; + offarr = _bt_prefix_anchoroff(hdr); + for (int g = 0; g < ng; g++) + offarr[g] = (uint16) anchoroff[g]; + + for (int g = 0; g < ng; g++) + { + BTPrefixAnchorDisk *ad = (BTPrefixAnchorDisk *) (buf + anchoroff[g]); + Size repsz = _bt_prefix_keysz(dir->anchors[g].rep); + IndexTuple rep; + + ad->repsz = (uint16) repsz; + /* store the key part only, as a plain non-posting tuple */ + rep = (IndexTuple) ((char *) ad + MAXALIGN(sizeof(BTPrefixAnchorDisk))); + memcpy(rep, dir->anchors[g].rep, repsz); + rep->t_info = (rep->t_info & ~(INDEX_SIZE_MASK | INDEX_ALT_TID_MASK)) | + repsz; + } + + pfree(anchoroff); + *itemsz = total; + return item; +} + +/* The directory item of a BTP_PREFIX page, unchecked. */ +static inline char * +_bt_prefix_diritem(Page page) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber off = BTPageGetPrefixOff(opaque); + + Assert(P_HASPREFIX(opaque)); + return (char *) PageGetItem(page, PageGetItemId(page, off)); +} + +/* + * Key-column layout stored in a coded page's directory, for re-coding against + * that page page-only (insert, recode). The directory holds exactly the + * layout the page was coded with, so a member re-coded with it decodes the + * same way. + */ +static inline const BTPrefixAttr * +_bt_prefix_page_layout(char *diritem, int *natts) +{ + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) diritem; + + *natts = hdr->natts; + return hdr->attrs; +} + +/* Pointer to anchor g's on-disk blob within the directory item. */ +static inline BTPrefixAnchorDisk * +_bt_prefix_anchor(char *diritem, int g) +{ + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) diritem; + + return (BTPrefixAnchorDisk *) (diritem + _bt_prefix_anchoroff(hdr)[g]); +} + +/* The representative IndexTuple inside an on-disk anchor blob. */ +static inline IndexTuple +_bt_prefix_anchor_rep(BTPrefixAnchorDisk *ad) +{ + return (IndexTuple) ((char *) ad + MAXALIGN(sizeof(BTPrefixAnchorDisk))); +} + +/* Report a malformed physical representation without interpreting its data. */ +pg_noreturn static void +_bt_prefix_corrupt(OffsetNumber offnum, const char *field) +{ + ereport(ERROR, + (errcode(ERRCODE_INDEX_CORRUPTED), + errmsg_internal("invalid prefix %s at offset %u", field, offnum))); +} + +/* Establish page bounds before using either line pointers or the opaque area. */ +static void +_bt_prefix_check_header(Page page) +{ + PageHeader phdr = (PageHeader) page; + BTPageOpaque opaque; + + if (phdr->pd_special != BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData)) || + phdr->pd_lower < SizeOfPageHeaderData || + phdr->pd_lower > phdr->pd_upper || + phdr->pd_upper > phdr->pd_special || + (phdr->pd_lower - SizeOfPageHeaderData) % sizeof(ItemIdData) != 0) + _bt_prefix_corrupt(InvalidOffsetNumber, "page header"); + + opaque = BTPageGetOpaque(page); + if (!P_HASPREFIX(opaque) || !P_ISLEAF(opaque) || P_IGNORE(opaque) || + P_ISMETA(opaque) || opaque->btpo_level != 0 || + PageGetMaxOffsetNumber(page) < P_FIRSTDATAKEY(opaque)) + _bt_prefix_corrupt(InvalidOffsetNumber, "page layout"); +} + +/* The caller has checked the page header, but not the line pointer. */ +static IndexTuple +_bt_prefix_checked_item(Page page, OffsetNumber offnum, Size minsize) +{ + ItemId itemid; + Size offset; + Size len; + IndexTuple itup; + + if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page)) + _bt_prefix_corrupt(offnum, "item offset"); + itemid = PageGetItemId(page, offnum); + offset = ItemIdGetOffset(itemid); + len = ItemIdGetLength(itemid); + if ((!ItemIdIsNormal(itemid) && !ItemIdIsDead(itemid)) || + offset != MAXALIGN(offset) || + offset < ((PageHeader) page)->pd_upper || + offset > ((PageHeader) page)->pd_special || + len > ((PageHeader) page)->pd_special - offset || len < minsize) + _bt_prefix_corrupt(offnum, "line pointer"); + itup = (IndexTuple) PageGetItem(page, itemid); + if (IndexTupleSize(itup) != len || len != MAXALIGN(len)) + _bt_prefix_corrupt(offnum, "tuple size"); + return itup; +} + +/* Check the directory header and offset array, without visiting any anchor. */ +static BTPrefixDirHdr * +_bt_prefix_checked_directory(Page page) +{ + OffsetNumber offnum = BTPageGetPrefixOff(BTPageGetOpaque(page)); + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) + _bt_prefix_checked_item(page, offnum, offsetof(BTPrefixDirHdr, attrs)); + Size len = IndexTupleSize(&hdr->header); + + if (hdr->header.t_info != len || + ItemPointerIsValid(&hdr->header.t_tid) || + ItemIdIsDead(PageGetItemId(page, offnum)) || + hdr->ngroups == 0 || hdr->ngroups > BTREE_PREFIX_MAXGROUPS || + hdr->natts > INDEX_MAX_KEYS || + _bt_prefix_diritem_size(hdr->natts, hdr->ngroups, 0) > len) + _bt_prefix_corrupt(offnum, "directory header"); + return hdr; +} + +/* Validate just the selected anchor; never follow an unchecked byte offset. */ +static IndexTuple +_bt_prefix_checked_anchor(BTPrefixDirHdr *hdr, int group, OffsetNumber offnum) +{ + Size len = IndexTupleSize(&hdr->header); + Size offset; + BTPrefixAnchorDisk *ad; + IndexTuple rep; + + if (group >= hdr->ngroups) + _bt_prefix_corrupt(offnum, "group number"); + offset = _bt_prefix_anchoroff(hdr)[group]; + if (offset != MAXALIGN(offset) || + offset < _bt_prefix_diritem_size(hdr->natts, hdr->ngroups, 0) || + offset > len || + MAXALIGN(sizeof(BTPrefixAnchorDisk)) + sizeof(IndexTupleData) > len - offset) + _bt_prefix_corrupt(offnum, "anchor offset"); + ad = (BTPrefixAnchorDisk *) ((char *) hdr + offset); + if (ad->repsz < sizeof(IndexTupleData) || + ad->repsz > len - offset - MAXALIGN(sizeof(BTPrefixAnchorDisk))) + _bt_prefix_corrupt(offnum, "anchor size"); + rep = _bt_prefix_anchor_rep(ad); + if (IndexTupleSize(rep) != ad->repsz || + ad->repsz != MAXALIGN(ad->repsz) || + (rep->t_info & INDEX_ALT_TID_MASK) != 0 || + ad->repsz < IndexInfoFindDataOffset(rep->t_info)) + _bt_prefix_corrupt(offnum, "anchor tuple header"); + return rep; +} + +/* Check every source and destination extent used by the decoder. */ +static Size +_bt_prefix_check_member(BTPrefixDirHdr *hdr, IndexTuple coded, + OffsetNumber offnum, IndexTuple *repp, + BTPrefixSplice *splice) +{ + BTPrefixCode *code = (BTPrefixCode *) ((char *) coded + sizeof(IndexTupleData)); + IndexTuple rep = _bt_prefix_checked_anchor(hdr, code->group, offnum); + Size keysz = code->orig_info & INDEX_SIZE_MASK; + Size hoff = IndexInfoFindDataOffset(code->orig_info); + Size rephoff = IndexInfoFindDataOffset(rep->t_info); + Size repdatalen = IndexTupleSize(rep) - rephoff; + Size lead_shared = code->lead_shared; + Size shared_len = code->shared_len; + Size bodysz; + Size plainsz = keysz; + Size codesz = IndexTupleSize(coded); + Size mhdr; + Size ahdr; + bool ok_m, + ok_a; + const char *codebody = (const char *) code + sizeof(BTPrefixCode); + Size bitmaplen = hoff - sizeof(IndexTupleData); + const uint8 *mbitmap = (code->orig_info & INDEX_NULL_MASK) != 0 ? + (const uint8 *) codebody : NULL; + const char *repdata = (const char *) rep + rephoff; + const char *residp; + Size residual; + + if ((code->orig_info & INDEX_ALT_TID_MASK) != 0 || + keysz < hoff || keysz != MAXALIGN(keysz) || + (coded->t_info & (INDEX_NULL_MASK | INDEX_VAR_MASK)) != 0 || + BTreeTupleIsPivot(coded)) + _bt_prefix_corrupt(offnum, "member header"); + + /* + * The shared span is the fully-shared leading columns (lead_shared, from + * the anchor's [0..D)) plus the divergent column's shared value bytes + * (shared_len). Both must lie within the member's data area and the + * anchor must carry the shared leading bytes. + */ + if (lead_shared > keysz - hoff || + shared_len > keysz - hoff - lead_shared || + lead_shared > repdatalen) + _bt_prefix_corrupt(offnum, "shared length"); + bodysz = MAXALIGN(sizeof(BTPrefixCode) + keysz - lead_shared - shared_len); + if (bodysz > codesz) + _bt_prefix_corrupt(offnum, "residual extent"); + residual = keysz - hoff - lead_shared - shared_len; + residp = codebody + bitmaplen; + + /* + * The divergent column's header stays private: the member's own copy + * leads its residual, the anchor's is skipped so the shared value bytes + * splice after it. Both prefixes (padding plus length header) are + * measured from the layout: the member's from its residual, the anchor's + * from its stored tuple, each walking the anchor's byte-identical [0..D) + * to reach the divergent column. Bound every splice extent against the + * member residual and the anchor's data area before decode copies. + */ + mhdr = _bt_prefix_divprefix(hdr->attrs, hdr->natts, repdata, mbitmap, + repdatalen, residp, residual, lead_shared, + &ok_m); + ahdr = _bt_prefix_divprefix(hdr->attrs, hdr->natts, repdata, + IndexTupleHasNulls(rep) ? + (const uint8 *) rep + sizeof(IndexTupleData) : + NULL, repdatalen, repdata + lead_shared, + repdatalen - lead_shared, lead_shared, &ok_a); + if (!ok_m || !ok_a || mhdr > residual || + lead_shared + ahdr + shared_len > repdatalen) + _bt_prefix_corrupt(offnum, "shared length"); + if (BTreeTupleIsPosting(coded)) + { + Size listsz = BTreeTupleGetNPosting(coded) * sizeof(ItemPointerData); + + if (BTreeTupleGetNPosting(coded) < 2 || + (ItemPointerGetOffsetNumberNoCheck(&coded->t_tid) & + BT_STATUS_OFFSET_MASK) != BT_IS_POSTING || + BTreeTupleGetPostingOffset(coded) != bodysz || + listsz > codesz - bodysz || MAXALIGN(bodysz + listsz) != codesz) + _bt_prefix_corrupt(offnum, "posting list extent"); + plainsz = MAXALIGN(keysz + listsz); + } + else if (bodysz != codesz) + _bt_prefix_corrupt(offnum, "residual extent"); + if (plainsz > INDEX_SIZE_MASK || plainsz > BLCKSZ) + _bt_prefix_corrupt(offnum, "decoded tuple size"); + if (repp != NULL) + *repp = rep; + if (splice != NULL) + { + splice->lead_shared = lead_shared; + splice->shared_len = shared_len; + splice->mhdr = mhdr; + splice->ahdr = ahdr; + splice->residual = residual; + } + return plainsz; +} + +/* + * _bt_prefix_check + * Validate a whole BTP_PREFIX page; ERROR if it is malformed. + * + * For amcheck and pageinspect, before they read the page's tuples. Unlike + * decode, this also visits unused anchors and checks the cached decoded sizes + * against the split-fit invariant (see _bt_prefix_split_needed). + */ +void +_bt_prefix_check(Page page) +{ + BTPageOpaque opaque; + BTPrefixDirHdr *hdr; + OffsetNumber diroff; + Size end; + Size total = 0; + Size maxitem = 0; + Size hikeysz = 0; + Size usable = BLCKSZ - SizeOfPageHeaderData - MAXALIGN(sizeof(BTPageOpaqueData)); + + _bt_prefix_check_header(page); + opaque = BTPageGetOpaque(page); + diroff = BTPageGetPrefixOff(opaque); + hdr = _bt_prefix_checked_directory(page); + end = _bt_prefix_diritem_size(hdr->natts, hdr->ngroups, 0); + for (int g = 0; g < hdr->ngroups; g++) + { + IndexTuple rep = _bt_prefix_checked_anchor(hdr, g, diroff); + + if (_bt_prefix_anchoroff(hdr)[g] != end) + _bt_prefix_corrupt(diroff, "anchor layout"); + end += MAXALIGN(sizeof(BTPrefixAnchorDisk)) + IndexTupleSize(rep); + } + if (end != IndexTupleSize(&hdr->header)) + _bt_prefix_corrupt(diroff, "directory size"); + for (OffsetNumber off = P_FIRSTDATAKEY(opaque); + off <= PageGetMaxOffsetNumber(page); off++) + { + IndexTuple coded = _bt_prefix_checked_item(page, off, + sizeof(IndexTupleData) + sizeof(BTPrefixCode)); + Size sz = _bt_prefix_check_member(hdr, coded, off, NULL, NULL) + sizeof(ItemIdData); + + total += sz; + maxitem = Max(maxitem, sz); + } + if (total != hdr->decodedsz || maxitem != hdr->maxdecoded) + _bt_prefix_corrupt(diroff, "directory decoded size"); + if (!P_RIGHTMOST(opaque)) + { + IndexTuple hikey = _bt_prefix_checked_item(page, P_HIKEY, sizeof(IndexTupleData)); + + hikeysz = IndexTupleSize(hikey) + sizeof(ItemIdData); + } + if (total + hikeysz + 2 * maxitem + MAXALIGN(sizeof(ItemPointerData)) > 2 * usable) + _bt_prefix_corrupt(diroff, "decoded split budget"); +} + +/* + * _bt_prefix_page_descriptor + * Copy coded page `page's stored key-column layout into `attrs' + * (INDEX_MAX_KEYS entries) and return its key count, or 0 if `page' is + * not a coded leaf. + * + * For WAL redo, which re-codes the left half of a split from the original + * page: a coded original carries the layout the primary used, so redo matches + * it page-only. Validates the directory header before reading. + */ +int +_bt_prefix_page_descriptor(Page page, BTPrefixAttr * attrs) +{ + BTPrefixDirHdr *hdr; + + if (!P_HASPREFIX(BTPageGetOpaque(page))) + return 0; + _bt_prefix_check_header(page); + hdr = _bt_prefix_checked_directory(page); + for (int i = 0; i < hdr->natts; i++) + attrs[i] = hdr->attrs[i]; + return hdr->natts; +} + +/* + * Code plain tuple `itup' against group `group', whose representative is + * `rep'. `attrs'/`natts' is the key-column layout used to decide where the + * two diverge (see _bt_prefix_walk); NULL falls back to v15 whole-data + * sharing. Returns a palloc'd coded tuple, or NULL if its size does not fit + * INDEX_SIZE_MASK. + * + * The member drops the fully-shared leading columns (D bytes) and the + * divergent column's shared value prefix (sv bytes), keeping its own + * divergent-column header. Its stored residual is the data area from D with + * the shared value bytes cut out of the middle: [divergent header][value + * bytes after the shared ones][later columns]. + */ +static IndexTuple +_bt_prefix_encode_against(const BTPrefixAttr * attrs, int natts, + IndexTuple rep, IndexTuple itup, int group) +{ + Size hoff = IndexInfoFindDataOffset(itup->t_info); + Size keysz = _bt_prefix_keysz(itup); + bool posting = BTreeTupleIsPosting(itup); + BTPrefixSplit split; + Size lead_shared; /* D: fully-shared leading columns */ + Size shared_len; /* sv: divergent column's shared value bytes */ + Size mhdr; /* divergent column's prefix in itup */ + Size residual; + Size bodysz; + Size codesz; + char *buf; + char *residp; + IndexTuple coded; + BTPrefixCode *code; + + _bt_prefix_walk(attrs, natts, rep, itup, &split); + lead_shared = split.lead_shared; + shared_len = split.shared_len; + mhdr = _bt_prefix_divhdr(attrs, natts, itup, lead_shared); + + residual = keysz - hoff - lead_shared - shared_len; + bodysz = MAXALIGN(sizeof(IndexTupleData) + sizeof(BTPrefixCode) + + (hoff - sizeof(IndexTupleData)) + residual); + codesz = bodysz; + if (posting) + codesz = MAXALIGN(bodysz + BTreeTupleGetNPosting(itup) * + sizeof(ItemPointerData)); + if (codesz > INDEX_SIZE_MASK) + return NULL; + + buf = palloc0(codesz); + coded = (IndexTuple) buf; + coded->t_tid = itup->t_tid; + coded->t_info = (unsigned short) codesz; + + code = (BTPrefixCode *) (buf + sizeof(IndexTupleData)); + code->group = (uint16) group; + code->lead_shared = (uint16) lead_shared; + code->shared_len = (uint16) shared_len; + /* flags and key-part size of the original; posting-ness is the coded's */ + code->orig_info = (itup->t_info & ~(INDEX_SIZE_MASK | INDEX_ALT_TID_MASK)) | + keysz; + + /* copy the original's null bitmap (bytes between header and data area) */ + memcpy(buf + sizeof(IndexTupleData) + sizeof(BTPrefixCode), + (char *) itup + sizeof(IndexTupleData), + hoff - sizeof(IndexTupleData)); + + /* + * Copy the residual. The fully-shared leading D bytes come from the + * anchor, so they are not stored. The member's own divergent header + * (mhdr bytes at D) stays, the next shared_len value bytes are dropped, + * and the rest of the data area follows. + */ + residp = buf + sizeof(IndexTupleData) + sizeof(BTPrefixCode) + + (hoff - sizeof(IndexTupleData)); + memcpy(residp, (char *) itup + hoff + lead_shared, mhdr); + memcpy(residp + mhdr, + (char *) itup + hoff + lead_shared + mhdr + shared_len, + residual - mhdr); + + /* + * A posting list stays uncoded, in the standard posting tuple layout, so + * code that only reads heap TIDs (VACUUM, LP_DEAD hinting, deletion, + * posting list splits) works on the coded tuple as is. + */ + if (posting) + { + int nhtids = BTreeTupleGetNPosting(itup); + + BTreeTupleSetPosting(coded, nhtids, bodysz); + memcpy(BTreeTupleGetPosting(coded), BTreeTupleGetPosting(itup), + nhtids * sizeof(ItemPointerData)); + } + + return coded; +} + +/* + * _bt_prefix_decode + * Decode the data item at `offnum' on BTP_PREFIX page `page' into `buf'. + * + * Returns a pointer into `buf'. Every extent the copy reads or writes is + * validated first, so a corrupt page raises ERROR rather than reading past + * the page or overrunning `buf'. + */ +IndexTuple +_bt_prefix_decode(Page page, OffsetNumber offnum, BTItemBuf *buf) +{ + IndexTuple coded; + BTPrefixDirHdr *hdr; + BTPrefixCode *code; + IndexTuple rep; + BTPrefixSplice splice; + Size rephoff; + Size hoff; + Size bitmaplen; + char *codebody; + char *residp; + char *out = buf->data; + IndexTuple plain = (IndexTuple) out; + Size keysz; + + _bt_prefix_check_header(page); + hdr = _bt_prefix_checked_directory(page); + coded = _bt_prefix_checked_item(page, offnum, + sizeof(IndexTupleData) + sizeof(BTPrefixCode)); + _bt_prefix_check_member(hdr, coded, offnum, &rep, &splice); + code = (BTPrefixCode *) ((char *) coded + sizeof(IndexTupleData)); + rephoff = IndexInfoFindDataOffset(rep->t_info); + hoff = IndexInfoFindDataOffset(code->orig_info); + bitmaplen = hoff - sizeof(IndexTupleData); + codebody = (char *) code + sizeof(BTPrefixCode); + residp = codebody + bitmaplen; + + /* key-part size from orig_info, not the coded size (padding, posting) */ + keysz = (code->orig_info & INDEX_SIZE_MASK); + + /* + * Reconstruct the data area from the offsets _bt_prefix_check_member + * validated. [0..D) is the fully-shared leading columns, spliced whole + * from the anchor. The divergent column's header stays private: the + * member's own prefix (mhdr) leads its residual, the anchor's (ahdr) is + * skipped so the shared value bytes come after it, then the member's + * remaining residual. A single varlena column makes D 0, reproducing the + * v16 layout exactly. + */ + plain->t_tid = coded->t_tid; + plain->t_info = code->orig_info; + memcpy(out + sizeof(IndexTupleData), codebody, bitmaplen); + /* fully-shared leading columns from the anchor */ + memcpy(out + hoff, (char *) rep + rephoff, splice.lead_shared); + /* member's own divergent-column prefix (alignment and length header) */ + memcpy(out + hoff + splice.lead_shared, residp, splice.mhdr); + /* shared value bytes from the anchor, after its divergent-column prefix */ + memcpy(out + hoff + splice.lead_shared + splice.mhdr, + (char *) rep + rephoff + splice.lead_shared + splice.ahdr, + splice.shared_len); + /* the member's remaining residual value bytes */ + memcpy(out + hoff + splice.lead_shared + splice.mhdr + splice.shared_len, + residp + splice.mhdr, splice.residual - splice.mhdr); + + if (BTreeTupleIsPosting(coded)) + { + int nhtids = BTreeTupleGetNPosting(coded); + Size listsz = nhtids * sizeof(ItemPointerData); + Size plainsz = MAXALIGN(keysz + listsz); + + Assert(plainsz <= BLCKSZ); + plain->t_info = (code->orig_info & ~INDEX_SIZE_MASK) | plainsz; + BTreeTupleSetPosting(plain, nhtids, keysz); + memcpy(out + keysz, BTreeTupleGetPosting(coded), listsz); + memset(out + keysz + listsz, 0, plainsz - keysz - listsz); + } + + return plain; +} + +/* + * _bt_prefix_form_page + * Lay out a BTP_PREFIX leaf from `hikey' and items[0..n-1]. + * + * `newpage' must be _bt_pageinit'd with its opaque area set; `hikey' is NULL + * on a rightmost page, and the items are plain and in key order. Returns + * false, leaving `newpage' unspecified, if coding does not pay off (unless + * `force'), the directory or a coded member exceeds INDEX_SIZE_MASK, or the + * coded items do not fit one page. The caller sets LSN and prune XID. + */ +bool +_bt_prefix_form_page(Page newpage, IndexTuple hikey, IndexTuple *items, int n, + const BTPrefixAttr * attrs, int natts, bool force) +{ + BTPrefixPageEst est; + BTPrefixDir *dir; + IndexTuple diritem; + Size diritemsz; + OffsetNumber newoff; + bool ok = true; + + if (n <= 0) + return false; + + /* Is it worth it? The estimate is exact: same grouping, same sizes. */ + memset(&est, 0, sizeof(est)); + for (int i = 0; i < n; i++) + _bt_prefix_est_add(&est, attrs, natts, items[i]); + if (!_bt_prefix_est_representable(&est) || + (!force && !_bt_prefix_worthwhile(_bt_prefix_est_coded(&est), + est.plainsz))) + return false; + + dir = _bt_prefix_choose_groups(attrs, natts, items, n); + if (dir == NULL) + { + Assert(!force || n == 1); + return false; /* nothing shared */ + } + + if (hikey && + PageAddItem(newpage, hikey, MAXALIGN(IndexTupleSize(hikey)), P_HIKEY, + false, false) == InvalidOffsetNumber) + elog(ERROR, "could not add high key during prefix compression"); + + diritem = _bt_prefix_form_diritem(dir, attrs, natts, &diritemsz); + if (PageAddItem(newpage, diritem, diritemsz, + BTPageGetPrefixOff(BTPageGetOpaque(newpage)), + false, false) == InvalidOffsetNumber) + ok = false; + newoff = OffsetNumberNext(BTPageGetPrefixOff(BTPageGetOpaque(newpage))); + + for (int i = 0, g = 0; ok && i < n; i++) + { + IndexTuple coded; + + while (g + 1 < dir->ngroups && items[i] == dir->anchors[g + 1].rep) + g++; + + coded = _bt_prefix_encode_against(attrs, natts, dir->anchors[g].rep, + items[i], g); + Assert(coded != NULL); + if (PageAddItem(newpage, coded, IndexTupleSize(coded), newoff, + false, false) == InvalidOffsetNumber) + ok = false; /* the coded items do not fit one page */ + newoff = OffsetNumberNext(newoff); + pfree(coded); + } + + pfree(diritem); + pfree(dir); + if (!ok) + return false; + + BTPageGetOpaque(newpage)->btpo_flags |= BTP_PREFIX; + _bt_prefix_recount(newpage); + +#ifdef USE_ASSERT_CHECKING + /* decode must reproduce every plain tuple byte for byte */ + for (int i = 0; i < n; i++) + { + BTItemBuf chk; + IndexTuple d = _bt_getitem(newpage, + P_FIRSTDATAKEY(BTPageGetOpaque(newpage)) + i, + &chk); + + Assert(IndexTupleSize(d) == IndexTupleSize(items[i]) && + memcmp(d, items[i], IndexTupleSize(d)) == 0); + } +#endif + + return true; +} + +/* + * _bt_prefix_compress_page + * Rewrite plain leaf `page' in BTP_PREFIX form, in place, if that pays + * off; otherwise leave it unchanged. + */ +void +_bt_prefix_compress_page(Relation index, Page page) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff, + maxoff; + int n; + IndexTuple *items; + IndexTuple hikey = NULL; + Page newpage; + + if (!_bt_prefix_enabled(index) || !P_ISLEAF(opaque) || P_HASPREFIX(opaque)) + return; + + minoff = P_FIRSTDATAKEY(opaque); + maxoff = PageGetMaxOffsetNumber(page); + if (maxoff < minoff) + return; /* empty page */ + n = maxoff - minoff + 1; + + if (!P_RIGHTMOST(opaque)) + hikey = (IndexTuple) PageGetItem(page, PageGetItemId(page, P_HIKEY)); + + items = palloc(sizeof(IndexTuple) * n); + for (int i = 0; i < n; i++) + items[i] = (IndexTuple) PageGetItem(page, + PageGetItemId(page, minoff + i)); + + /* Heap-allocated: this runs inside _bt_split, already two pages deep. */ + newpage = (Page) palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE, 0); + _bt_pageinit(newpage, BLCKSZ); + memcpy(BTPageGetOpaque(newpage), opaque, sizeof(BTPageOpaqueData)); + { + BTPrefixAttr attrs[INDEX_MAX_KEYS]; + int natts = _bt_prefix_build_layout(index, attrs); + + if (_bt_prefix_form_page(newpage, hikey, items, n, attrs, natts, false)) + { + PageSetLSN(newpage, PageGetLSN(page)); + ((PageHeader) newpage)->pd_prune_xid = + ((PageHeader) page)->pd_prune_xid; + memcpy(page, newpage, BLCKSZ); + } + } + pfree(newpage); + pfree(items); +} + +/* + * _bt_prefix_encode_insert + * Code plain tuple `itup' for insertion at `newitemoff' on BTP_PREFIX + * page `page'. + * + * The tuple joins the group of the item it displaces (or of the last item, + * when appended), sharing however much it happens to share, possibly nothing. + * The result is at most BTREE_PREFIX_CODE_OVERHEAD larger than `itup'. + * Returns a palloc'd coded tuple, or NULL when it exceeds INDEX_SIZE_MASK and + * the page must split. NB: pallocs, so call it before the critical section. + */ +IndexTuple +_bt_prefix_encode_insert(Page page, OffsetNumber newitemoff, IndexTuple itup) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + char *diritem = _bt_prefix_diritem(page); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + OffsetNumber neighbor; + IndexTuple ncoded; + BTPrefixCode *ncode; + BTPrefixAnchorDisk *ad; + IndexTuple rep; + int group; + int natts; + const BTPrefixAttr *attrs = _bt_prefix_page_layout(diritem, &natts); + + Assert(P_HASPREFIX(opaque)); + + if (newitemoff <= maxoff && newitemoff >= P_FIRSTDATAKEY(opaque)) + neighbor = newitemoff; + else if (maxoff >= P_FIRSTDATAKEY(opaque)) + neighbor = maxoff; + else + { + /* no data items: use group 0 */ + ad = _bt_prefix_anchor(diritem, 0); + return _bt_prefix_encode_against(attrs, natts, + _bt_prefix_anchor_rep(ad), itup, 0); + } + + ncoded = (IndexTuple) PageGetItem(page, PageGetItemId(page, neighbor)); + ncode = (BTPrefixCode *) ((char *) ncoded + sizeof(IndexTupleData)); + group = ncode->group; + ad = _bt_prefix_anchor(diritem, group); + rep = _bt_prefix_anchor_rep(ad); + + return _bt_prefix_encode_against(attrs, natts, rep, itup, group); +} + +/* + * _bt_prefix_recode + * Code plain tuple `itup' against the group of the item at `offnum' on + * BTP_PREFIX page `page', returning a palloc'd coded tuple. + * + * For a tuple with the same key as that item (a split or merged posting + * list), which therefore codes the same way. NB: pallocs, so call it before + * the critical section. + */ +IndexTuple +_bt_prefix_recode(Page page, OffsetNumber offnum, IndexTuple itup) +{ + char *diritem = _bt_prefix_diritem(page); + IndexTuple ncoded = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum)); + BTPrefixCode *ncode = (BTPrefixCode *) ((char *) ncoded + + sizeof(IndexTupleData)); + BTPrefixAnchorDisk *ad = _bt_prefix_anchor(diritem, ncode->group); + IndexTuple rep = _bt_prefix_anchor_rep(ad); + int natts; + const BTPrefixAttr *attrs = _bt_prefix_page_layout(diritem, &natts); + IndexTuple coded; + + coded = _bt_prefix_encode_against(attrs, natts, rep, itup, ncode->group); + if (coded == NULL) + elog(ERROR, "coded nbtree posting tuple too large"); + return coded; +} + +/* + * _bt_prefix_decode_copy + * Return a palloc'd decoded copy of the item at `offnum' on BTP_PREFIX + * page `page'. + * + * The BLCKSZ decode buffer lives in this frame, so hot-path callers need not + * reserve one on their own stack for a case that arises only on coded pages. + */ +IndexTuple +_bt_prefix_decode_copy(Page page, OffsetNumber offnum) +{ + BTItemBuf decbuf; + + return CopyIndexTuple(_bt_prefix_decode(page, offnum, &decbuf)); +} + +/* + * _bt_prefix_decode_items + * Decode every data item of BTP_PREFIX page `page'. + * + * Sets *items_out to a palloc'd array of palloc'd plain tuples and returns + * its length. *hikey gets a palloc'd copy of the high key and *hikeysz its + * line pointer length (NULL and 0 on a rightmost page). The caller frees all + * of it. + */ +int +_bt_prefix_decode_items(Page page, IndexTuple **items_out, + IndexTuple *hikey, Size *hikeysz) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff = P_FIRSTDATAKEY(opaque); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + int n = (maxoff >= minoff) ? (maxoff - minoff + 1) : 0; + IndexTuple *items = n ? palloc(sizeof(IndexTuple) * n) : NULL; + BTItemBuf decbuf; + int k = 0; + + if (!P_RIGHTMOST(opaque)) + { + ItemId hii = PageGetItemId(page, P_HIKEY); + + *hikey = CopyIndexTuple((IndexTuple) PageGetItem(page, hii)); + *hikeysz = ItemIdGetLength(hii); + } + else + { + *hikey = NULL; + *hikeysz = 0; + } + + for (OffsetNumber off = minoff; off <= maxoff; off = OffsetNumberNext(off)) + { + items[k++] = CopyIndexTuple(_bt_prefix_decode(page, off, &decbuf)); + } + *items_out = items; + return n; +} + +/* + * _bt_prefix_try_plain_page + * Write a plain copy of BTP_PREFIX page `page' into BLCKSZ buffer `out'. + * + * Returns `out', or NULL if the decoded content does not fit one page, in + * which case `out' is left partly written. + */ +Page +_bt_prefix_try_plain_page(Relation rel, Page page, Page out) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff = P_FIRSTDATAKEY(opaque); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + OffsetNumber newoff; + BTItemBuf decbuf; + + _bt_pageinit(out, BLCKSZ); + memcpy(BTPageGetOpaque(out), opaque, sizeof(BTPageOpaqueData)); + BTPageGetOpaque(out)->btpo_flags &= ~BTP_PREFIX; + + if (!P_RIGHTMOST(opaque)) + { + ItemId hii = PageGetItemId(page, P_HIKEY); + + if (PageAddItem(out, PageGetItem(page, hii), ItemIdGetLength(hii), + P_HIKEY, false, false) == InvalidOffsetNumber) + return NULL; + } + + newoff = P_FIRSTDATAKEY(BTPageGetOpaque(out)); + for (OffsetNumber off = minoff; off <= maxoff; off = OffsetNumberNext(off)) + { + IndexTuple pt = _bt_prefix_decode(page, off, &decbuf); + + if (PageAddItem(out, pt, IndexTupleSize(pt), newoff, false, false) == + InvalidOffsetNumber) + return NULL; /* decoded content exceeds a page */ + newoff = OffsetNumberNext(newoff); + } + + return out; +} + +/* + * MAXALIGN'd size of coded member `coded' once decoded, from its header alone. + * + * NB: the split-fit invariant (see _bt_prefix_split_needed) needs this to be + * the same unit _bt_prefix_findsplitloc and the CREATE INDEX estimate use, + * MAXALIGN(IndexTupleSize()) of the plain tuple. + */ +static inline Size +_bt_prefix_plain_size(IndexTuple coded) +{ + BTPrefixCode *code = (BTPrefixCode *) ((char *) coded + + sizeof(IndexTupleData)); + Size keysz = code->orig_info & INDEX_SIZE_MASK; + + if (BTreeTupleIsPosting(coded)) + return MAXALIGN(keysz + BTreeTupleGetNPosting(coded) * + sizeof(ItemPointerData)); + return MAXALIGN(keysz); +} + +/* + * _bt_prefix_split_needed + * Must inserting a plain tuple of (MAXALIGN'd) size `newitemsz' into + * BTP_PREFIX page `page' split it first? + * + * The split-fit guarantee. A coded page may hold more decoded content than a + * plain page, but its decoded items must always split into two plain pages. + * Each coded page keeps + * + * T + hikey + 2 * m + heap TID <= 2 * usable (*) + * + * where T is the decoded size of its data items (including line pointers) and + * m the largest. Under (*) a split of the page plus a new item x always has a + * legal point when x was admitted by this test, because admitting x requires + * (*) to hold with x counted in T and m. Proof: take the leftmost point whose + * right half (items plus the old high key) fits. The point before it did + * not, so the left items before it total less than T - (usable - hikey); + * adding one more item and the new high key (a truncated copy of firstright + * plus a heap TID) gives a left half under T - usable + hikey + 2m + heap TID, + * at most usable by (*). + * + * So insert splits a page before it would break (*). _bt_split's split then + * places the new item too: (*) with the new item counted is exactly what + * failed, but the page without it satisfied (*), and a page that a plain + * split would handle (decoded content at most one page) always has a legal + * point by the usual one-third-of-a-page item size rule; the remaining case + * (content between one and two pages, new item large) is handled by + * _bt_prefix_findsplitloc trying the split without the new item first. + */ +bool +_bt_prefix_split_needed(Page page, Size newitemsz) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) _bt_prefix_diritem(page); + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size newsz = MAXALIGN(newitemsz) + sizeof(ItemIdData); + Size total = hdr->decodedsz + newsz; + Size maxitem = Max((Size) hdr->maxdecoded, newsz); + Size hikeysz = 0; + + if (!P_RIGHTMOST(opaque)) + hikeysz = MAXALIGN(ItemIdGetLength(PageGetItemId(page, P_HIKEY))) + + sizeof(ItemIdData); + + return total + hikeysz + 2 * maxitem + MAXALIGN(sizeof(ItemPointerData)) > + 2 * usable; +} + +/* + * _bt_prefix_recount + * Recompute the directory's cached decoded sizes after a change to the + * page's data items (deletion, posting list update, a rebuilt page), or + * drop the directory if no data items remain. Page-only, so WAL redo + * calls it after replaying the same change and reproduces the page. + */ +void +_bt_prefix_recount(Page page) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff, + maxoff; + BTPrefixDirHdr *hdr; + Size total = 0, + maxitem = 0; + + if (!P_HASPREFIX(opaque)) + return; + + minoff = P_FIRSTDATAKEY(opaque); + maxoff = PageGetMaxOffsetNumber(page); + if (maxoff < minoff) + { + /* + * An emptied leaf holds only its high key (page deletion relies on + * that): drop the directory and become a plain page. + */ + PageIndexTupleDelete(page, BTPageGetPrefixOff(opaque)); + opaque->btpo_flags &= ~BTP_PREFIX; + return; + } + + for (OffsetNumber off = minoff; off <= maxoff; off = OffsetNumberNext(off)) + { + IndexTuple coded = (IndexTuple) PageGetItem(page, PageGetItemId(page, off)); + Size sz = _bt_prefix_plain_size(coded) + sizeof(ItemIdData); + + total += sz; + maxitem = Max(maxitem, sz); + } + Assert(total <= PG_UINT16_MAX); + hdr = (BTPrefixDirHdr *) _bt_prefix_diritem(page); + hdr->decodedsz = (uint16) total; + hdr->maxdecoded = (uint16) maxitem; +} + +/* + * _bt_prefix_note_insert + * Account for coded item `coded' just added to BTP_PREFIX page `page'. + * Page-only; insert redo calls it too. + */ +void +_bt_prefix_note_insert(Page page, IndexTuple coded) +{ + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) _bt_prefix_diritem(page); + Size sz = _bt_prefix_plain_size(coded) + sizeof(ItemIdData); + + Assert(hdr->decodedsz + sz <= PG_UINT16_MAX); + hdr->decodedsz += (uint16) sz; + hdr->maxdecoded = (uint16) Max((Size) hdr->maxdecoded, sz); +} + +/* + * _bt_prefix_findsplitloc + * Choose a split point for coded leaf `page' from its decoded items. + * + * ditems[] holds one plain tuple per data item. Returns firstrightoff and + * sets *newitemonleft, as _bt_findsplitloc does. With newitemoff valid the + * new item, of plain size newitemsz, is placed there, and the result is + * InvalidOffsetNumber if no point keeps both halves within a page. With + * newitemoff invalid only the existing items are split, and the split-fit + * invariant (see _bt_prefix_split_needed) guarantees a legal point. + * + * Each candidate is checked against the real sizes of both plain halves: the + * left half's new high key is charged as firstright plus a heap TID, as + * _bt_findsplitloc does, and the right half keeps the old high key. The most + * even legal point wins, except on a rightmost page, where points are ranked + * by leaf fillfactor as _bt_findsplitloc ranks them, so ascending inserts + * leave fillfactor-full left pages behind. + */ +OffsetNumber +_bt_prefix_findsplitloc(Relation rel, Page page, IndexTuple *ditems, + OffsetNumber newitemoff, Size newitemsz, + bool *newitemonleft) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber mn = P_FIRSTDATAKEY(opaque); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + bool hasnew = OffsetNumberIsValid(newitemoff); + int n = maxoff - mn + 1; /* existing items */ + int nall = n + (hasnew ? 1 : 0); + int newpos = hasnew ? newitemoff - mn : -1; + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size hikeysz = 0; + Size *sz = palloc(sizeof(Size) * nall); + Size total = 0, + acc = 0; + int best = -1; + Size bestdelta = SIZE_MAX; + + if (!P_RIGHTMOST(opaque)) + hikeysz = MAXALIGN(ItemIdGetLength(PageGetItemId(page, P_HIKEY))) + + sizeof(ItemIdData); + + /* sizes of the combined sequence, new item spliced in at newpos */ + for (int k = 0, i = 0; k < nall; k++) + { + if (k == newpos) + sz[k] = MAXALIGN(newitemsz) + sizeof(ItemIdData); + else + sz[k] = MAXALIGN(IndexTupleSize(ditems[i++])) + sizeof(ItemIdData); + total += sz[k]; + } + + /* split before position k: left = [0,k), right = [k,nall) */ + for (int k = 1; k < nall; k++) + { + Size left, + right; + + acc += sz[k - 1]; + left = acc + sz[k] + MAXALIGN(sizeof(ItemPointerData)); + right = (total - acc) + hikeysz; + if (left <= usable && right <= usable) + { + Size delta = left > right ? left - right : right - left; + + if (P_RIGHTMOST(opaque)) + { + double fillfactormult = BTGetFillFactor(rel) / 100.0; + int16 weighteddelta; + + weighteddelta = fillfactormult * (usable - left) - + (1.0 - fillfactormult) * (usable - right); + delta = abs(weighteddelta); + } + + if (delta < bestdelta) + { + bestdelta = delta; + best = k; + } + } + } + pfree(sz); + + /* + * With a new item there may be no legal point (the item is large and the + * page dense); the caller then splits the existing items alone. + */ + if (best < 0) + { + if (hasnew) + return InvalidOffsetNumber; + elog(ERROR, "could not find a legal split point for prefix-compressed page in index \"%s\"", + RelationGetRelationName(rel)); + } + + /* map combined position back to (firstrightoff, newitemonleft) */ + if (!hasnew || best <= newpos) + { + *newitemonleft = false; + return mn + best; + } + *newitemonleft = true; + return mn + best - 1; +} diff --git a/src/backend/access/nbtree/nbtreadpage.c b/src/backend/access/nbtree/nbtreadpage.c index 55722fd8791..eb5a83233a9 100644 --- a/src/backend/access/nbtree/nbtreadpage.c +++ b/src/backend/access/nbtree/nbtreadpage.c @@ -22,6 +22,7 @@ #include "access/relscan.h" #include "storage/predicate.h" #include "utils/datum.h" +#include "utils/memutils.h" #include "utils/rel.h" @@ -110,6 +111,27 @@ static bool _bt_verify_keys_with_arraykeys(IndexScanDesc scan); #endif +/* + * _bt_scan_skip_key -- can _bt_readpage skip decoding the current item? + * + * Decoding a coded item costs a copy, wasted when (a) this is not an + * index-only scan, so only the heap TID or posting list is needed, and coding + * leaves both in place; and (b) _bt_checkkeys would read no key attribute, + * because startikey has passed every scan key and there are no array keys + * (array-key advancement reads the key regardless of startikey). The caller + * then treats the item as a match and reads it raw. + * + * NB: the _bt_checkkeys call must be skipped, not just the decode. In + * assert-enabled builds it re-runs _bt_check_compare from ikey 0 to verify + * startikey, which would read the still-coded key. + */ +static inline bool +_bt_scan_skip_key(BTScanOpaque so, BTReadPageState *pstate, bool arrayKeys) +{ + return so->currTuples == NULL && !arrayKeys && + pstate->startikey >= so->numberOfKeys; +} + /* * _bt_readpage() -- Load data from current index page into so->currPos * @@ -141,6 +163,8 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, OffsetNumber minoff; OffsetNumber maxoff; BTReadPageState pstate; + BTItemBuf itupbuf; /* decode workspace for a loop's current item */ + BTItemBuf finalbuf; /* decode workspace for finaltup */ bool arrayKeys, ignore_killed_tuples = scan->ignore_killed_tuples; int itemIndex, @@ -156,6 +180,26 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, pstate.dir = so->currPos.dir = dir; so->currPos.nextTupleOffset = 0; + /* + * A prefix-compressed leaf can decode to up to two pages of tuples (see + * _bt_prefix_split_needed), more than the BLCKSZ index-only scan + * workspaces hold. Grow them the first time such a page is read. + */ + if (unlikely(P_HASPREFIX(opaque)) && so->currTuples && !so->bigTuples) + { + char *big; + + big = MemoryContextAlloc(GetMemoryChunkContext(so->currTuples), + 4 * BLCKSZ); + if (BTScanPosIsValid(so->markPos)) + memcpy(big + 2 * BLCKSZ, so->markTuples, + so->markPos.nextTupleOffset); + pfree(so->currTuples); + so->currTuples = big; + so->markTuples = big + 2 * BLCKSZ; + so->bigTuples = true; + } + /* either moreRight or moreLeft should be set now (may be unset later) */ Assert(ScanDirectionIsForward(dir) ? so->currPos.moreRight : so->currPos.moreLeft); @@ -252,12 +296,23 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, continue; } - itup = (IndexTuple) PageGetItem(page, iid); - Assert(!BTreeTupleIsPivot(itup)); + if (_bt_scan_skip_key(so, &pstate, arrayKeys)) + { + /* only the heap TID(s) are needed: read the item raw */ + itup = (IndexTuple) PageGetItem(page, iid); + Assert(!BTreeTupleIsPivot(itup)); + pstate.offnum = offnum; + passes_quals = true; + } + else + { + itup = _bt_getitem(page, offnum, &itupbuf); + Assert(!BTreeTupleIsPivot(itup)); - pstate.offnum = offnum; - passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, - itup, indnatts); + pstate.offnum = offnum; + passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, + itup, indnatts); + } /* * Check if we need to skip ahead to a later tuple (only possible @@ -353,9 +408,7 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, { if (minoff <= maxoff && !P_LEFTMOST(opaque)) { - ItemId iid = PageGetItemId(page, minoff); - - pstate.finaltup = (IndexTuple) PageGetItem(page, iid); + pstate.finaltup = _bt_getitem(page, minoff, &finalbuf); if (unlikely(so->scanBehind) && !_bt_scanbehind_checkkeys(scan, dir, pstate.finaltup)) @@ -415,19 +468,36 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, else tuple_alive = true; - itup = (IndexTuple) PageGetItem(page, iid); - Assert(!BTreeTupleIsPivot(itup)); - pstate.offnum = offnum; - if (arrayKeys && offnum == minoff && pstate.forcenonrequired) + if (_bt_scan_skip_key(so, &pstate, arrayKeys)) { - /* Reset arrays, per _bt_set_startikey contract */ - pstate.forcenonrequired = false; - pstate.startikey = 0; - _bt_start_array_keys(scan, dir); + /* only the heap TID(s) are needed: read the item raw */ + itup = (IndexTuple) PageGetItem(page, iid); + Assert(!BTreeTupleIsPivot(itup)); + passes_quals = true; + } + else + { + /* + * Reuse finaltup's decoded copy at minoff, so that + * _bt_advance_array_keys still recognizes it by pointer. + */ + if (offnum == minoff && pstate.finaltup) + itup = pstate.finaltup; + else + itup = _bt_getitem(page, offnum, &itupbuf); + Assert(!BTreeTupleIsPivot(itup)); + + if (arrayKeys && offnum == minoff && pstate.forcenonrequired) + { + /* Reset arrays, per _bt_set_startikey contract */ + pstate.forcenonrequired = false; + pstate.startikey = 0; + _bt_start_array_keys(scan, dir); + } + passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, + itup, indnatts); } - passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, - itup, indnatts); if (arrayKeys && so->scanBehind) { @@ -596,7 +666,8 @@ _bt_set_startikey(IndexScanDesc scan, BTReadPageState *pstate) BTScanOpaque so = (BTScanOpaque) scan->opaque; Relation rel = scan->indexRelation; TupleDesc tupdesc = RelationGetDescr(rel); - ItemId iid; + BTItemBuf firstbuf, + lastbuf; IndexTuple firsttup, lasttup; int startikey = 0, @@ -616,12 +687,10 @@ _bt_set_startikey(IndexScanDesc scan, BTReadPageState *pstate) return; /* minoff is an offset to the lowest non-pivot tuple on the page */ - iid = PageGetItemId(pstate->page, pstate->minoff); - firsttup = (IndexTuple) PageGetItem(pstate->page, iid); + firsttup = _bt_getitem(pstate->page, pstate->minoff, &firstbuf); /* maxoff is an offset to the highest non-pivot tuple on the page */ - iid = PageGetItemId(pstate->page, pstate->maxoff); - lasttup = (IndexTuple) PageGetItem(pstate->page, iid); + lasttup = _bt_getitem(pstate->page, pstate->maxoff, &lastbuf); /* Determine the first attribute whose values change on caller's page */ firstchangingattnum = _bt_keep_natts_fast(rel, firsttup, lasttup); @@ -2053,6 +2122,7 @@ _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate, ScanDirection dir = pstate->dir; OffsetNumber aheadoffnum; IndexTuple ahead; + BTItemBuf aheadbuf; Assert(!pstate->forcenonrequired); @@ -2088,8 +2158,7 @@ _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate, aheadoffnum = Max((int) pstate->minoff, (int) pstate->offnum - pstate->targetdistance); - ahead = (IndexTuple) PageGetItem(pstate->page, - PageGetItemId(pstate->page, aheadoffnum)); + ahead = _bt_getitem(pstate->page, aheadoffnum, &aheadbuf); if (_bt_tuple_before_array_skeys(scan, dir, ahead, tupdesc, tupnatts, false, 0, NULL)) { diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index ef9ed290cae..a3a8de477a2 100644 --- a/src/backend/access/nbtree/nbtree.c +++ b/src/backend/access/nbtree/nbtree.c @@ -379,6 +379,7 @@ btbeginscan(Relation rel, int nkeys, int norderbys) * scan->xs_itupdesc whether we'll need it or not, since that's so cheap. */ so->currTuples = so->markTuples = NULL; + so->bigTuples = false; scan->xs_itupdesc = RelationGetDescr(rel); diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c index 61f63251c6f..7eaf626e8f1 100644 --- a/src/backend/access/nbtree/nbtsearch.c +++ b/src/backend/access/nbtree/nbtsearch.c @@ -33,6 +33,11 @@ static Buffer _bt_moveright(Relation rel, Relation heaprel, BTScanInsert key, Buffer buf, bool forupdate, BTStack stack, int access); static OffsetNumber _bt_binsrch(Relation rel, BTScanInsert key, Buffer buf); +static int32 _bt_compare_coded(Relation rel, BTScanInsert key, Page page, + OffsetNumber offnum); +static inline int32 _bt_compare_tuple(Relation rel, BTScanInsert key, + Page page, OffsetNumber offnum, + IndexTuple itup); static int _bt_binsrch_posting(BTScanInsert key, Page page, OffsetNumber offnum); static inline void _bt_returnitem(IndexScanDesc scan, BTScanOpaque so); @@ -692,17 +697,54 @@ _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + + if (unlikely(P_HASPREFIX(opaque)) && offnum > BTPageGetPrefixOff(opaque)) + return _bt_compare_coded(rel, key, page, offnum); + + Assert(_bt_check_natts(rel, key->heapkeyspace, page, offnum)); + return _bt_compare_tuple(rel, key, page, offnum, + (IndexTuple) PageGetItem(page, + PageGetItemId(page, offnum))); +} + +/* + * _bt_compare_coded() -- _bt_compare() for a coded prefix-compressed leaf item. + * + * Kept out of line so that only these comparisons pay for the decode buffer, + * which is a whole BLCKSZ; _bt_compare() on a plain page uses no stack for it. + */ +static pg_noinline int32 +_bt_compare_coded(Relation rel, BTScanInsert key, Page page, + OffsetNumber offnum) +{ + BTItemBuf prefixbuf; + + /* Decode (and so validate) the member before assertions inspect it. */ + IndexTuple itup = _bt_prefix_decode(page, offnum, &prefixbuf); + + Assert(_bt_check_natts(rel, key->heapkeyspace, page, offnum)); + return _bt_compare_tuple(rel, key, page, offnum, itup); +} + +/* + * _bt_compare_tuple() -- body of _bt_compare(), given the item at offnum. + * + * itup is either the tuple on the page or its decoded copy. + */ +static inline int32 +_bt_compare_tuple(Relation rel, BTScanInsert key, Page page, + OffsetNumber offnum, IndexTuple itup) { TupleDesc itupdesc = RelationGetDescr(rel); BTPageOpaque opaque = BTPageGetOpaque(page); - IndexTuple itup; ItemPointer heapTid; ScanKey scankey; int ncmpkey; int ntupatts; int32 result; - Assert(_bt_check_natts(rel, key->heapkeyspace, page, offnum)); Assert(key->keysz <= IndexRelationGetNumberOfKeyAttributes(rel)); Assert(key->heapkeyspace || key->scantid == NULL); @@ -713,7 +755,6 @@ _bt_compare(Relation rel, if (!P_ISLEAF(opaque) && offnum == P_FIRSTDATAKEY(opaque)) return 1; - itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum)); ntupatts = BTreeTupleGetNAtts(itup, rel); /* diff --git a/src/backend/access/nbtree/nbtsort.c b/src/backend/access/nbtree/nbtsort.c index 756dfa3dcf4..58fe8828846 100644 --- a/src/backend/access/nbtree/nbtsort.c +++ b/src/backend/access/nbtree/nbtsort.c @@ -242,6 +242,17 @@ typedef struct BTPageState uint32 btps_level; /* tree level (0 = leaf) */ Size btps_full; /* "full" if less than this much free space */ struct BTPageState *btps_next; /* link to parent level, if any */ + + /* + * Leaf level of a prefix_compression build: tuples are collected here + * instead of on btps_buf, and laid out as a leaf, coded or plain, when + * the next tuple would overfill it. See _bt_buildadd_coded. + */ + IndexTuple *btps_items; /* pending leaf tuples, palloc'd copies */ + int btps_nitems; + int btps_maxitems; + BTPrefixPageEst btps_est; /* coded estimate of btps_items */ + Size btps_lastkey; /* worst-case high key from the last item */ } BTPageState; /* @@ -254,6 +265,9 @@ typedef struct BTWriteState BulkWriteState *bulkstate; BTScanInsert inskey; /* generic insertion scankey */ BlockNumber btws_pages_alloced; /* # pages allocated */ + BTPrefixAttr prefixattrs[INDEX_MAX_KEYS]; /* key-column layout for + * coding */ + int prefixnatts; /* key columns, 0 until set in _bt_load */ } BTWriteState; @@ -268,6 +282,10 @@ static void _bt_build_callback(Relation index, ItemPointer tid, Datum *values, static BulkWriteBuffer _bt_blnewpage(BTWriteState *wstate, uint32 level); static BTPageState *_bt_pagestate(BTWriteState *wstate, uint32 level); static void _bt_slideleft(Page rightmostpage); +static void _bt_buildadd_coded(BTWriteState *wstate, BTPageState *state, + IndexTuple itup, Size truncextra); +static void _bt_flush_coded(BTWriteState *wstate, BTPageState *state, + bool last); static void _bt_sortaddtup(Page page, Size itemsize, const IndexTupleData *itup, OffsetNumber itup_off, bool newfirstdataitem); @@ -567,6 +585,8 @@ _bt_leafbuild(BTSpool *btspool, BTSpool *btspool2) wstate.inskey = _bt_mkscankey(wstate.index, NULL); /* _bt_mkscankey() won't set allequalimage without metapage */ wstate.inskey->allequalimage = _bt_allequalimage(wstate.index, true); + /* key-column layout the coder stores on each coded leaf */ + wstate.prefixnatts = _bt_prefix_build_layout(wstate.index, wstate.prefixattrs); /* reserve the metapage */ wstate.btws_pages_alloced = BTREE_METAPAGE + 1; @@ -804,6 +824,12 @@ _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, */ CHECK_FOR_INTERRUPTS(); + if (state->btps_level == 0 && _bt_prefix_enabled(wstate->index)) + { + _bt_buildadd_coded(wstate, state, itup, truncextra); + return; + } + nbuf = state->btps_buf; npage = (Page) nbuf; nblkno = state->btps_blkno; @@ -1022,6 +1048,257 @@ _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, state->btps_lastoff = last_off; } +/* + * _bt_buildadd_coded -- add a leaf tuple to a prefix_compression index build. + * + * Leaf tuples are collected in state->btps_items with a running estimate of + * the page they would make when coded (BTPrefixPageEst). Before adding itup, + * the pending leaf is laid out and written if itup would push it past either + * limit: + * + * - the leaf fillfactor, applied to the coded (on-disk) size, so a coded + * leaf leaves the same insert headroom that a plain one does; and + * - the split-fit budget (see _bt_prefix_split_needed): the decoded items of + * a coded page must still split into two plain pages. + * + * A pending leaf that cannot be coded, or would not compress enough to be + * worthwhile, is laid out plain and capped at what a plain page holds, exactly + * as in a non-prefix build. + */ +static void +_bt_buildadd_coded(BTWriteState *wstate, BTPageState *state, IndexTuple itup, + Size truncextra) +{ + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size fillsz = usable - state->btps_full; + Size itupsz = MAXALIGN(IndexTupleSize(itup)); + BTPrefixPageEst est; + + CHECK_FOR_INTERRUPTS(); + + if (unlikely(itupsz > BTMaxItemSize)) + _bt_check_third_page(wstate->index, wstate->heap, true, + (Page) state->btps_buf, itup); + + if (state->btps_items == NULL) + { + state->btps_maxitems = 2 * MaxIndexTuplesPerPage; + state->btps_items = palloc_array(IndexTuple, state->btps_maxitems); + } + + /* + * Mirror _bt_buildadd's two tests, in terms of the leaf the pending + * tuples would make. A finished leaf keeps all pending tuples but the + * last, which moves to the next leaf and supplies the new high key (at + * most its key part plus a heap TID, stored plain). The soft limit + * finishes the leaf once it is fillfactor-full as it stands. The hard + * limit finishes it if admitting itup could leave it unable to hold its + * tuples and high key, or (coded) beyond the split-fit budget, or out of + * line pointers. Sizes are coded when coding is worthwhile and plain + * otherwise, so a build that does not compress fills leaves exactly as a + * plain one. + * + * Copy itup before estimating: the running estimate keeps a pointer to + * its group's anchor tuple, which may be this one, so it must point at + * the copy that is kept. + */ + itup = CopyIndexTuple(itup); + est = state->btps_est; + _bt_prefix_est_add(&est, wstate->prefixattrs, wstate->prefixnatts, itup); + + if (state->btps_nitems >= 2) + { + BTPrefixPageEst *pend = &state->btps_est; + Size lastplain = MAXALIGN(IndexTupleSize(state->btps_items[state->btps_nitems - 1])) + + sizeof(ItemIdData); + Size itupplain = itupsz + sizeof(ItemIdData); + Size itupkey = itupsz - truncextra + + MAXALIGN(sizeof(ItemPointerData)) + sizeof(ItemIdData); + Size leafnow, + leafwith; + bool full; + + if (_bt_prefix_est_representable(pend) && + _bt_prefix_worthwhile(_bt_prefix_est_coded(pend), pend->plainsz)) + leafnow = _bt_prefix_est_coded(pend) - pend->lastcoded + + state->btps_lastkey; + else + leafnow = pend->plainsz - lastplain + state->btps_lastkey; + full = leafnow > fillsz; + + if (!full) + { + if (_bt_prefix_est_representable(&est) && + _bt_prefix_worthwhile(_bt_prefix_est_coded(&est), est.plainsz)) + { + leafwith = _bt_prefix_est_coded(&est) - est.lastcoded + itupkey; + + /* + * The final leaf keeps the last item, including its posting + * list. + */ + full = est.plainsz - itupplain + Max(itupplain, itupkey) + + 2 * est.maxplain + MAXALIGN(sizeof(ItemPointerData)) > 2 * usable || + _bt_prefix_est_coded(&est) > usable; + } + else + { + leafwith = est.plainsz - itupplain + itupkey; + /* The whole set must also fit if this is the final leaf. */ + full = est.plainsz > usable; + } + full = full || leafwith > usable || + state->btps_nitems >= MaxIndexTuplesPerPage - 2; + } + + if (full) + { + /* itup starts the next leaf: its estimate starts over */ + _bt_flush_coded(wstate, state, false); + est = state->btps_est; + _bt_prefix_est_add(&est, wstate->prefixattrs, + wstate->prefixnatts, itup); + } + } + + if (state->btps_nitems >= state->btps_maxitems) + { + state->btps_maxitems *= 2; + state->btps_items = repalloc_array(state->btps_items, IndexTuple, + state->btps_maxitems); + } + state->btps_items[state->btps_nitems++] = itup; + state->btps_est = est; + state->btps_lastkey = itupsz - truncextra + + MAXALIGN(sizeof(ItemPointerData)) + sizeof(ItemIdData); +} + +/* + * _bt_flush_coded -- lay out and write the pending leaf of a coded build. + * + * All pending tuples but the last go on the leaf (the last one starts the next + * leaf and supplies the new high key, as in _bt_buildadd). When `last' the + * whole pending set makes the final, rightmost leaf, which is left in + * state->btps_buf for _bt_uppershutdown to write. + */ +static void +_bt_flush_coded(BTWriteState *wstate, BTPageState *state, bool last) +{ + Page page = (Page) state->btps_buf; + BTPageOpaque opaque = BTPageGetOpaque(page); + int nleaf = last ? state->btps_nitems : state->btps_nitems - 1; + IndexTuple firstright = last ? NULL : state->btps_items[nleaf]; + IndexTuple hikey = NULL; + BTPageOpaqueData saveopaque; + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size plainsz; + bool trycode; + BulkWriteBuffer nbuf = NULL; + BlockNumber nblkno = InvalidBlockNumber; + + Assert(nleaf >= 1); + + /* + * A finished leaf is not rightmost: link it to the next leaf before + * laying it out, since the layout (high key, directory offset) depends on + * that. + */ + if (!last) + { + nbuf = _bt_blnewpage(wstate, 0); + nblkno = wstate->btws_pages_alloced++; + opaque->btpo_next = nblkno; + BTPageGetOpaque((Page) nbuf)->btpo_prev = state->btps_blkno; + } + saveopaque = *opaque; + + if (!last) + hikey = _bt_truncate(wstate->index, state->btps_items[nleaf - 1], + firstright, wstate->inskey); + + /* + * Lay out the leaf: coded if worthwhile, else plain. The running + * estimate covers all pending tuples, so leaving out the last one can tip + * the worthwhile test; if the plain layout would then overflow a page, + * code it anyway (admission in _bt_buildadd_coded guaranteed the coded + * layout fits). When the estimate says coding does not pay and plain + * fits, the common case for an incompressible index, skip the coding + * attempt and its second pass over the tuples. + */ + plainsz = hikey ? MAXALIGN(IndexTupleSize(hikey)) + sizeof(ItemIdData) : 0; + for (int i = 0; i < nleaf; i++) + plainsz += MAXALIGN(IndexTupleSize(state->btps_items[i])) + + sizeof(ItemIdData); + trycode = plainsz > usable || + (_bt_prefix_est_representable(&state->btps_est) && + _bt_prefix_worthwhile(_bt_prefix_est_coded(&state->btps_est), + state->btps_est.plainsz)); + _bt_pageinit(page, BLCKSZ); + *BTPageGetOpaque(page) = saveopaque; + opaque = BTPageGetOpaque(page); + if (!trycode || + !_bt_prefix_form_page(page, hikey, state->btps_items, nleaf, + wstate->prefixattrs, wstate->prefixnatts, + plainsz > usable)) + { + OffsetNumber off = P_FIRSTKEY; + + if (plainsz > usable) + elog(ERROR, "could not lay out prefix-compressed leaf during build of index \"%s\"", + RelationGetRelationName(wstate->index)); + + _bt_pageinit(page, BLCKSZ); + *BTPageGetOpaque(page) = saveopaque; + opaque = BTPageGetOpaque(page); + if (hikey) + _bt_sortaddtup(page, IndexTupleSize(hikey), hikey, P_HIKEY, false); + else + off = P_HIKEY; /* rightmost: no high key */ + for (int i = 0; i < nleaf; i++, off = OffsetNumberNext(off)) + _bt_sortaddtup(page, MAXALIGN(IndexTupleSize(state->btps_items[i])), + state->btps_items[i], off, false); + } + + /* minus infinity low key for the leftmost leaf */ + if (state->btps_lowkey == NULL) + { + state->btps_lowkey = palloc0_object(IndexTupleData); + state->btps_lowkey->t_info = sizeof(IndexTupleData); + BTreeTupleSetNAtts(state->btps_lowkey, 0, false); + } + + if (!last) + { + /* link the finished leaf into its parent, using its low key */ + if (state->btps_next == NULL) + state->btps_next = _bt_pagestate(wstate, 1); + BTreeTupleSetDownLink(state->btps_lowkey, state->btps_blkno); + _bt_buildadd(wstate, state->btps_next, state->btps_lowkey, 0); + pfree(state->btps_lowkey); + state->btps_lowkey = hikey; /* the next leaf's low key */ + + _bt_blwritepage(wstate, state->btps_buf, state->btps_blkno); + state->btps_buf = nbuf; + state->btps_blkno = nblkno; + } + + /* keep only the carried-over first tuple of the next leaf */ + for (int i = 0; i < nleaf; i++) + pfree(state->btps_items[i]); + state->btps_nitems = 0; + memset(&state->btps_est, 0, sizeof(BTPrefixPageEst)); + if (!last) + { + state->btps_items[0] = firstright; + state->btps_nitems = 1; + _bt_prefix_est_add(&state->btps_est, wstate->prefixattrs, + wstate->prefixnatts, firstright); + /* btps_lastkey still describes firstright */ + } +} + /* * Finalize pending posting list tuple, and add it to the index. Final tuple * is based on saved base tuple, and saved list of heap TIDs. @@ -1071,6 +1348,10 @@ _bt_uppershutdown(BTWriteState *wstate, BTPageState *state) uint32 rootlevel = 0; BulkWriteBuffer metabuf; + /* lay out the final leaf of a prefix_compression build */ + if (state != NULL && state->btps_items != NULL) + _bt_flush_coded(wstate, state, true); + /* * Each iteration of this loop completes one more level of the tree. */ @@ -1114,7 +1395,8 @@ _bt_uppershutdown(BTWriteState *wstate, BTPageState *state) * This is the rightmost page, so the ItemId array needs to be slid * back one slot. Then we can dump out the page. */ - _bt_slideleft((Page) s->btps_buf); + if (s->btps_items == NULL) /* coded-build leaves are laid out exactly */ + _bt_slideleft((Page) s->btps_buf); _bt_blwritepage(wstate, s->btps_buf, s->btps_blkno); s->btps_buf = NULL; /* writepage took ownership of the buffer */ } diff --git a/src/backend/access/nbtree/nbtsplitloc.c b/src/backend/access/nbtree/nbtsplitloc.c index de9eca3c8b2..a6be84f1977 100644 --- a/src/backend/access/nbtree/nbtsplitloc.c +++ b/src/backend/access/nbtree/nbtsplitloc.c @@ -459,6 +459,13 @@ _bt_recsplitloc(FindSplitData *state, Size postingsz = 0; bool newitemisfirstright; + /* + * Reject an empty left half. A prefix representation limit can force a + * split of a sparse page, where the space checks below would accept one. + */ + if (olddataitemstoleft == 0 && !newitemonleft) + return; + /* Is the new item going to be split point's firstright tuple? */ newitemisfirstright = (firstrightoff == state->newitemoff && !newitemonleft); diff --git a/src/backend/access/nbtree/nbtutils.c b/src/backend/access/nbtree/nbtutils.c index 85c1b632522..5dc2b2f3050 100644 --- a/src/backend/access/nbtree/nbtutils.c +++ b/src/backend/access/nbtree/nbtutils.c @@ -602,7 +602,9 @@ btoptions(Datum reloptions, bool validate) {"vacuum_cleanup_index_scale_factor", RELOPT_TYPE_REAL, offsetof(BTOptions, vacuum_cleanup_index_scale_factor)}, {"deduplicate_items", RELOPT_TYPE_BOOL, - offsetof(BTOptions, deduplicate_items)} + offsetof(BTOptions, deduplicate_items)}, + {"prefix_compression", RELOPT_TYPE_BOOL, + offsetof(BTOptions, prefix_compression)} }; return (bytea *) build_reloptions(reloptions, validate, diff --git a/src/backend/access/nbtree/nbtxlog.c b/src/backend/access/nbtree/nbtxlog.c index dff7d286fc8..1f42adf0fff 100644 --- a/src/backend/access/nbtree/nbtxlog.c +++ b/src/backend/access/nbtree/nbtxlog.c @@ -186,6 +186,11 @@ btree_xlog_insert(bool isleaf, bool ismeta, bool posting, /* Simple retail insertion */ if (PageAddItem(page, datapos, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) elog(PANIC, "failed to add new item"); + /* the logged item is the coded one on a prefix leaf */ + if (isleaf && P_HASPREFIX(BTPageGetOpaque(page))) + _bt_prefix_note_insert(page, + (IndexTuple) PageGetItem(page, + PageGetItemId(page, xlrec->offnum))); } else { @@ -215,15 +220,45 @@ btree_xlog_insert(bool isleaf, bool ismeta, bool posting, /* Use mutable, aligned newitem copy in _bt_swap_posting() */ Assert(isleaf && postingoff > 0); newitem = CopyIndexTuple((IndexTuple) datapos); - nposting = _bt_swap_posting(newitem, oposting, postingoff); - /* Replace existing posting list with post-split version */ - memcpy(oposting, nposting, MAXALIGN(IndexTupleSize(nposting))); + if (P_HASPREFIX(BTPageGetOpaque(page))) + { + /* + * Coded leaf: repeat _bt_insertonpg's exact steps. Swap on + * the decoded posting list, then code both results against + * the page; coding needs no catalog access. + */ + BTItemBuf pbuf; + IndexTuple plainpost = CopyIndexTuple(_bt_getitem(page, + OffsetNumberPrev(xlrec->offnum), + &pbuf)); + IndexTuple codedpost; + IndexTuple codednew; + + nposting = _bt_swap_posting(newitem, plainpost, postingoff); + codedpost = _bt_prefix_recode(page, + OffsetNumberPrev(xlrec->offnum), + nposting); + Assert(IndexTupleSize(codedpost) == ItemIdGetLength(itemid)); + memcpy(oposting, codedpost, MAXALIGN(IndexTupleSize(codedpost))); + codednew = _bt_prefix_encode_insert(page, xlrec->offnum, newitem); + if (PageAddItem(page, codednew, MAXALIGN(IndexTupleSize(codednew)), + xlrec->offnum, false, false) == InvalidOffsetNumber) + elog(PANIC, "failed to add posting split new item"); + _bt_prefix_note_insert(page, codednew); + } + else + { + nposting = _bt_swap_posting(newitem, oposting, postingoff); + + /* Replace existing posting list with post-split version */ + memcpy(oposting, nposting, MAXALIGN(IndexTupleSize(nposting))); - /* Insert "final" new item (not orignewitem from WAL stream) */ - Assert(IndexTupleSize(newitem) == datalen); - if (PageAddItem(page, newitem, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) - elog(PANIC, "failed to add posting split new item"); + /* Insert "final" new item (not orignewitem from WAL stream) */ + Assert(IndexTupleSize(newitem) == datalen); + if (PageAddItem(page, newitem, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) + elog(PANIC, "failed to add posting split new item"); + } } PageSetLSN(page, lsn); @@ -280,7 +315,11 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) if (!isleaf) _bt_clear_incomplete_split(record, 3); - /* Reconstruct right (new) sibling page from scratch */ + /* + * Reconstruct right (new) sibling page from scratch. A coded right half + * was logged as its coded items, directory included, which + * _bt_restore_page lays out exactly as the primary did. + */ rbuf = XLogInitBufferForRedo(record, 1); datapos = XLogRecGetBlockData(record, 1, &datalen); rpage = BufferGetPage(rbuf); @@ -292,6 +331,8 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) ropaque->btpo_next = spagenumber; ropaque->btpo_level = xlrec->level; ropaque->btpo_flags = isleaf ? BTP_LEAF : 0; + if (xlrec->flags & XLH_SPLIT_RIGHT_CODED) + ropaque->btpo_flags |= BTP_PREFIX; ropaque->btpo_cycleid = 0; _bt_restore_page(rpage, datapos, datalen); @@ -320,7 +361,35 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) left_hikeysz = 0; Page leftpage; OffsetNumber leftoff, + firstdata, replacepostingoff = InvalidOffsetNumber; + IndexTuple *ditems = NULL; /* decoded items of a coded origpage */ + IndexTuple *litems; /* the left half's items, in order */ + int nlitems = 0; + + /* + * The original page's data items, as plain tuples. For a coded page + * (XLH_SPLIT_ORIG_CODED) the record's offsets are into the decoded + * sequence, which starts at the prefix directory's offset. + */ + if (xlrec->flags & XLH_SPLIT_ORIG_CODED) + { + IndexTuple dhikey; + Size dhikeysz; + + Assert(P_HASPREFIX(oopaque)); + (void) _bt_prefix_decode_items(origpage, &ditems, &dhikey, + &dhikeysz); + if (dhikey) + pfree(dhikey); + firstdata = BTPageGetPrefixOff(oopaque); + } + else + firstdata = P_FIRSTDATAKEY(oopaque); + +#define ORIG_ITEM(o) \ + (ditems ? ditems[(o) - firstdata] : \ + (IndexTuple) PageGetItem(origpage, PageGetItemId(origpage, (o)))) datapos = XLogRecGetBlockData(record, 0, &datalen); @@ -333,7 +402,6 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) if (xlrec->postingoff != 0) { - ItemId itemid; IndexTuple oposting; /* Posting list must be at offset number before new item's */ @@ -341,8 +409,7 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) /* Use mutable, aligned newitem copy in _bt_swap_posting() */ newitem = CopyIndexTuple(newitem); - itemid = PageGetItemId(origpage, replacepostingoff); - oposting = (IndexTuple) PageGetItem(origpage, itemid); + oposting = ORIG_ITEM(replacepostingoff); nposting = _bt_swap_posting(newitem, oposting, xlrec->postingoff); } @@ -360,64 +427,107 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) Assert(datalen == 0); - leftpage = PageGetTempPageCopySpecial(origpage); - - /* Add high key tuple from WAL record to temp page */ - leftoff = P_HIKEY; - if (PageAddItem(leftpage, left_hikey, left_hikeysz, P_HIKEY, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add high key to left page after split"); - leftoff = OffsetNumberNext(leftoff); - - for (off = P_FIRSTDATAKEY(oopaque); off < xlrec->firstrightoff; off++) + /* Collect the left half's items, in item number order */ + litems = palloc(sizeof(IndexTuple) * (MaxIndexTuplesPerPage * 2 + 1)); + for (off = firstdata; off < xlrec->firstrightoff; off++) { - ItemId itemid; - Size itemsz; - IndexTuple item; - /* Add replacement posting list when required */ if (off == replacepostingoff) { Assert(newitemonleft || xlrec->firstrightoff == xlrec->newitemoff); - if (PageAddItem(leftpage, nposting, MAXALIGN(IndexTupleSize(nposting)), leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add new posting list item to left page after split"); - leftoff = OffsetNumberNext(leftoff); + litems[nlitems++] = nposting; continue; /* don't insert oposting */ } /* add the new item if it was inserted on left page */ else if (newitemonleft && off == xlrec->newitemoff) - { - if (PageAddItem(leftpage, newitem, newitemsz, leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add new item to left page after split"); - leftoff = OffsetNumberNext(leftoff); - } + litems[nlitems++] = newitem; - itemid = PageGetItemId(origpage, off); - itemsz = ItemIdGetLength(itemid); - item = (IndexTuple) PageGetItem(origpage, itemid); - if (PageAddItem(leftpage, item, itemsz, leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add old item to left page after split"); - leftoff = OffsetNumberNext(leftoff); + litems[nlitems++] = ORIG_ITEM(off); } /* cope with possibility that newitem goes at the end */ if (newitemonleft && off == xlrec->newitemoff) - { - if (PageAddItem(leftpage, newitem, newitemsz, leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add new item to left page after split"); - leftoff = OffsetNumberNext(leftoff); - } + litems[nlitems++] = newitem; +#undef ORIG_ITEM - PageRestoreTempPage(leftpage, origpage); + /* + * The left half holds one item per original offset in [firstdata, + * firstrightoff), plus newitem when it landed on the left; a replaced + * posting list does not change the count. A mismatch means redo + * disagrees with the primary about the split. + */ + Assert(nlitems == (xlrec->firstrightoff - firstdata) + + (newitemonleft ? 1 : 0)); + + /* + * To retain the same physical order of the tuples that they had, we + * initialize a temporary empty page for the left page and add all the + * items to that in item number order. This mirrors how _bt_split() + * works. Retaining the same physical order makes WAL consistency + * checking possible. See also _bt_restore_page(), which does the + * same for the right page. + */ + leftpage = PageGetTempPageCopySpecial(origpage); - /* Fix opaque fields */ + /* Fix opaque fields (the layout of a coded page depends on them) */ + oopaque = BTPageGetOpaque(leftpage); oopaque->btpo_flags = BTP_INCOMPLETE_SPLIT; if (isleaf) oopaque->btpo_flags |= BTP_LEAF; oopaque->btpo_next = rightpagenumber; oopaque->btpo_cycleid = 0; + if (xlrec->flags & XLH_SPLIT_LEFT_CODED) + { + /* + * Lay out the coded left half as _bt_split did. The coding rule + * needs the index's key-column layout. A coded original carries + * it in its directory; a plain original cannot, so the primary + * logged it in the record (XLH_SPLIT_LEFT_DESC). Either way the + * layout reaches redo without the catalog. + */ + BTPrefixAttr prefixattrs[INDEX_MAX_KEYS]; + int prefixnatts = 0; + + if (xlrec->flags & XLH_SPLIT_LEFT_DESC) + { + char *d = (char *) xlrec + SizeOfBtreeSplit; + + prefixnatts = *(uint16 *) d; + memcpy(prefixattrs, d + sizeof(uint16), + sizeof(BTPrefixAttr) * prefixnatts); + } + else if (xlrec->flags & XLH_SPLIT_ORIG_CODED) + prefixnatts = _bt_prefix_page_descriptor(origpage, prefixattrs); + + if (!_bt_prefix_form_page(leftpage, left_hikey, litems, nlitems, + prefixnatts ? prefixattrs : NULL, + prefixnatts, true)) + elog(ERROR, "failed to lay out prefix-compressed left page after split"); + } + else + { + /* Add high key tuple from WAL record to temp page */ + if (PageAddItem(leftpage, left_hikey, left_hikeysz, P_HIKEY, false, false) == InvalidOffsetNumber) + elog(ERROR, "failed to add high key to left page after split"); + leftoff = OffsetNumberNext(P_HIKEY); + + for (int i = 0; i < nlitems; i++) + { + if (PageAddItem(leftpage, litems[i], + MAXALIGN(IndexTupleSize(litems[i])), leftoff, + false, false) == InvalidOffsetNumber) + elog(ERROR, "failed to add item to left page after split"); + leftoff = OffsetNumberNext(leftoff); + } + } + + /* btree_redo resets opCtx per record, freeing the decoded items */ + PageRestoreTempPage(leftpage, origpage); + pfree(litems); + PageSetLSN(origpage, lsn); MarkBufferDirty(buf); } @@ -468,6 +578,8 @@ btree_xlog_dedup(XLogReaderState *record) BTDedupState state; BTDedupInterval *intervals; Page newpage; + bool coded = P_HASPREFIX(opaque); + IndexTuple *ditems = NULL; state = palloc_object(BTDedupStateData); state->deduplicate = true; /* unused */ @@ -497,13 +609,33 @@ btree_xlog_dedup(XLogReaderState *record) elog(ERROR, "deduplication failed to add highkey"); } + /* + * A prefix-compressed page is deduplicated on decoded copies of its + * items and keeps its directory, as in _bt_dedup_pass. + */ + if (coded) + { + OffsetNumber prefixoff = BTPageGetPrefixOff(opaque); + ItemId diritemid = PageGetItemId(page, prefixoff); + IndexTuple dummyhikey; + Size dummyhikeysz; + + if (PageAddItem(newpage, PageGetItem(page, diritemid), + ItemIdGetLength(diritemid), prefixoff, + false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add prefix directory"); + (void) _bt_prefix_decode_items(page, &ditems, &dummyhikey, + &dummyhikeysz); + } + intervals = (BTDedupInterval *) ptr; for (offnum = minoff; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid = PageGetItemId(page, offnum); - IndexTuple itup = (IndexTuple) PageGetItem(page, itemid); + IndexTuple itup = coded ? ditems[offnum - minoff] : + (IndexTuple) PageGetItem(page, itemid); if (offnum == minoff) _bt_dedup_start_pending(state, itup, offnum); @@ -516,12 +648,21 @@ btree_xlog_dedup(XLogReaderState *record) } else { - _bt_dedup_finish_pending(newpage, state); + if (coded) + _bt_dedup_finish_pending_coded(page, newpage, state); + else + _bt_dedup_finish_pending(newpage, state); _bt_dedup_start_pending(state, itup, offnum); } } - _bt_dedup_finish_pending(newpage, state); + if (coded) + { + _bt_dedup_finish_pending_coded(page, newpage, state); + _bt_prefix_recount(newpage); + } + else + _bt_dedup_finish_pending(newpage, state); Assert(state->nintervals == xlrec->nintervals); Assert(memcmp(state->intervals, intervals, state->nintervals * sizeof(BTDedupInterval)) == 0); @@ -620,6 +761,7 @@ btree_xlog_vacuum(XLogReaderState *record) if (xlrec->ndeleted > 0) PageIndexMultiDelete(page, (OffsetNumber *) ptr, xlrec->ndeleted); + _bt_prefix_recount(page); /* * Clear the vacuum cycle ID, and mark the page as not containing any @@ -686,6 +828,7 @@ btree_xlog_delete(XLogReaderState *record) if (xlrec->ndeleted > 0) PageIndexMultiDelete(page, (OffsetNumber *) ptr, xlrec->ndeleted); + _bt_prefix_recount(page); /* * Do *not* clear the vacuum cycle ID, but do mark the page as not diff --git a/src/backend/access/rmgrdesc/nbtdesc.c b/src/backend/access/rmgrdesc/nbtdesc.c index 1d08f9957bd..fbe96890b22 100644 --- a/src/backend/access/rmgrdesc/nbtdesc.c +++ b/src/backend/access/rmgrdesc/nbtdesc.c @@ -46,6 +46,12 @@ btree_desc(StringInfo buf, XLogReaderState *record) appendStringInfo(buf, "level: %u, firstrightoff: %d, newitemoff: %d, postingoff: %d", xlrec->level, xlrec->firstrightoff, xlrec->newitemoff, xlrec->postingoff); + if (xlrec->flags != 0) + appendStringInfo(buf, ", prefix:%s%s%s%s", + (xlrec->flags & XLH_SPLIT_ORIG_CODED) ? " orig" : "", + (xlrec->flags & XLH_SPLIT_LEFT_CODED) ? " left" : "", + (xlrec->flags & XLH_SPLIT_RIGHT_CODED) ? " right" : "", + (xlrec->flags & XLH_SPLIT_LEFT_DESC) ? " leftdesc" : ""); break; } case XLOG_BTREE_DEDUP: diff --git a/src/include/access/nbtree.h b/src/include/access/nbtree.h index 3097e9bb1af..083eefab4e0 100644 --- a/src/include/access/nbtree.h +++ b/src/include/access/nbtree.h @@ -83,6 +83,8 @@ typedef BTPageOpaqueData *BTPageOpaque; #define BTP_HAS_GARBAGE (1 << 6) /* page has LP_DEAD tuples (deprecated) */ #define BTP_INCOMPLETE_SPLIT (1 << 7) /* right sibling's downlink is missing */ #define BTP_HAS_FULLXID (1 << 8) /* contains BTDeletedPageData */ +#define BTP_PREFIX (1 << 9) /* leaf keys coded against a page prefix + * (see nbtprefix.c) */ /* * The max allowed value of a cycle ID is a bit less than 64K. This is @@ -367,7 +369,66 @@ typedef struct BTVacState #define P_HIKEY ((OffsetNumber) 1) #define P_FIRSTKEY ((OffsetNumber) 2) -#define P_FIRSTDATAKEY(opaque) (P_RIGHTMOST(opaque) ? P_HIKEY : P_FIRSTKEY) + +/* + * Leaf key prefix compression (see nbtprefix.c for the code). + * + * A leaf of an index whose prefix_compression reloption is on may be flagged + * BTP_PREFIX. Its data items are organized in GROUPS of consecutive items; + * each group has an ANCHOR, a copy of the key part of the group's first item, + * and each member is stored "coded": without the data-area bytes it shares + * with the anchor. Sharing is by stored bytes, never by the opclass notion of + * equality, so it is sound for any column type (an index-only scan gets back + * exactly the bytes that were stored) and needs no equalimage support. Within + * a group every member shares the anchor's leading key columns whole, then + * diverges inside one column (the DIVERGENT column: a common value prefix, a + * differing full value, hence a differing varlena length header). Only that + * column's length header is kept with the member; the fully-shared leading + * columns and their headers share from the anchor as ordinary bytes. A single + * leading varlena column makes the divergent column the first column, so this + * reduces to sharing that column's value bytes and keeping its header private. + * Walking to the divergent column needs the key-column layout, which the + * directory carries (see BTPrefixDirHdr). + * + * Page layout. At BTPageGetPrefixOff(opaque) (right after the high key) is a + * single PREFIX DIRECTORY item that holds every group's anchor; the data items + * follow it, in key order, starting at P_FIRSTDATAKEY. One item before the + * data keeps P_FIRSTDATAKEY a function of the page flag alone, so neither + * BTPageOpaqueData nor the on-disk page header changes, and binary search over + * the data items is unaffected. The directory item is an IndexTupleData header + * (invalid t_tid; t_info = its size) followed by the group count, the cached + * decoded size of the page's data items (see _bt_prefix_split_needed), the + * key-column layout, the anchor offsets, and the anchors (BTPrefixDirHdr, + * BTPrefixAnchorDisk). + * + * Coded member. An IndexTupleData header whose t_tid is the member's own heap + * TID (or posting list metadata), a small code header (group, the fully-shared + * leading byte count, the divergent column's shared value byte count, the + * original's t_info), the original's null bitmap, the residual (the original's + * data-area bytes from the divergent column on, minus the shared value bytes) + * and, for a posting list tuple, its posting list in the standard layout. + * Code that reads only heap TIDs therefore works on coded items as is. + * Decoding splices the anchor's fully-shared leading columns, then the + * member's own divergent-column header, then the anchor's shared value bytes, + * then the member's remaining residual, reproducing the original tuple byte + * for byte. Coding and decoding use only the page and the tuple, never the + * catalog, so WAL redo repeats them. Pivots (high keys, downlinks) are never + * coded. + */ +#define BTREE_PREFIX_MAXGROUPS 0xFFFE /* group-id ceiling (uint16) */ + +/* + * Most bytes a coded member can take beyond its plain tuple (see the static + * assertion in nbtprefix.c). Insert reserves this on a prefix page so the + * coded PageAddItem cannot fail after the fit check. + */ +#define BTREE_PREFIX_CODE_OVERHEAD MAXALIGN(16) + +#define P_HASPREFIX(opaque) (((opaque)->btpo_flags & BTP_PREFIX) != 0) +#define BTPageGetPrefixOff(opaque) \ + (P_RIGHTMOST(opaque) ? P_HIKEY : P_FIRSTKEY) +#define P_FIRSTDATAKEY(opaque) \ + (BTPageGetPrefixOff(opaque) + (P_HASPREFIX(opaque) ? 1 : 0)) /* * Notes on B-Tree tuple format, and key and non-key attributes: @@ -676,6 +737,34 @@ BTreeTupleGetMaxHeapTID(IndexTuple itup) return &itup->t_tid; } +/* + * Workspace for _bt_getitem. Every read of a leaf data item that could be on + * a BTP_PREFIX page goes through _bt_getitem rather than PageGetItem, so + * decoding has one home. The returned tuple is valid until the workspace is + * reused or the page is unlocked. High keys, pivots, and items a caller + * changes in place are read with PageGetItem. + */ +typedef PGAlignedBlock BTItemBuf; + +extern IndexTuple _bt_prefix_decode(Page page, OffsetNumber offnum, BTItemBuf *buf); +extern IndexTuple _bt_prefix_decode_copy(Page page, OffsetNumber offnum); +extern void _bt_prefix_check(Page page); + +/* + * Return the data item at `offnum' on `page' as a plain IndexTuple, decoded + * into `buf' on a BTP_PREFIX page and the on-page tuple otherwise. Callers + * must not write through the result. + */ +static inline IndexTuple +_bt_getitem(Page page, OffsetNumber offnum, BTItemBuf *buf) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + + if (unlikely(P_HASPREFIX(opaque)) && offnum > BTPageGetPrefixOff(opaque)) + return _bt_prefix_decode(page, offnum, buf); + return (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum)); +} + /* * Operator strategy numbers for B-tree have been moved to access/stratnum.h, * because many places need to use them in ScanKeyInit() calls. @@ -1075,10 +1164,13 @@ typedef struct BTScanOpaqueData /* * If we are doing an index-only scan, these are the tuple storage * workspaces for the currPos and markPos respectively. Each is of size - * BLCKSZ, so it can hold as much as a full page's worth of tuples. + * BLCKSZ, so it can hold as much as a full page's worth of tuples, or 2 * + * BLCKSZ once bigTuples is set (a prefix-compressed leaf can decode to + * more than one page; see _bt_prefix_split_needed). */ char *currTuples; /* tuple storage for currPos */ char *markTuples; /* tuple storage for markPos */ + bool bigTuples; /* workspaces grown for prefix pages? */ /* * If the marked position is on the same page as current position, we @@ -1122,6 +1214,7 @@ typedef struct BTOptions int fillfactor; /* page fill factor in percent (0..100) */ float8 vacuum_cleanup_index_scale_factor; /* deprecated */ bool deduplicate_items; /* Try to deduplicate items? */ + bool prefix_compression; /* Code leaf keys against a page prefix? */ } BTOptions; #define BTGetFillFactor(relation) \ @@ -1203,6 +1296,8 @@ extern void _bt_dedup_start_pending(BTDedupState state, IndexTuple base, OffsetNumber baseoff); extern bool _bt_dedup_save_htid(BTDedupState state, IndexTuple itup); extern Size _bt_dedup_finish_pending(Page newpage, BTDedupState state); +extern void _bt_dedup_finish_pending_coded(Page page, Page newpage, + BTDedupState state); extern IndexTuple _bt_form_posting(IndexTuple base, const ItemPointerData *htids, int nhtids); extern void _bt_update_posting(BTVacuumPosting vacposting); @@ -1315,6 +1410,68 @@ extern void _bt_check_third_page(Relation rel, Relation heap, bool needheaptidspace, Page page, IndexTuple newtup); extern bool _bt_allequalimage(Relation rel, bool debugmessage); +/* + * prototypes for functions in nbtprefix.c + */ +extern bool _bt_prefix_enabled(Relation index); +extern IndexTuple _bt_prefix_encode_insert(Page page, + OffsetNumber newitemoff, IndexTuple itup); +extern void _bt_prefix_compress_page(Relation index, Page page); + +/* + * Per-key-attribute layout the coder needs to parse a tuple's data area + * without the catalog. _bt_prefix_build_layout fills a caller array of + * INDEX_MAX_KEYS of these from the index's descriptor and returns the key + * count; the same descriptor is stored on the page by _bt_prefix_form_page so + * decode stays page-only. + */ +typedef struct BTPrefixAttr +{ + int16 attlen; /* pg_attribute.attlen (-1 == varlena) */ + uint8 attalignby; /* alignment in bytes (1/2/4/8) */ + uint8 flags; /* bit0: pass-by-value */ +} BTPrefixAttr; + +extern int _bt_prefix_build_layout(Relation index, BTPrefixAttr * attrs); +extern int _bt_prefix_page_descriptor(Page page, BTPrefixAttr * attrs); + +/* Running estimate of a coded leaf, for filling pages during CREATE INDEX */ +typedef struct BTPrefixPageEst +{ + int ngroups; + int natts; /* key columns in the stored layout */ + IndexTuple grouprep; /* current group's representative */ + IndexTuple prev; /* previous tuple added (NULL at start) */ + Size anchorsz; /* directory anchor blobs so far */ + Size codedsz; /* coded items, plus line pointers */ + Size lastcoded; /* most recent item's share of codedsz */ + Size maxcoded; /* largest coded item, without line pointer */ + Size plainsz; /* plain items, plus line pointers */ + Size maxplain; /* largest plain item, plus line pointer */ +} BTPrefixPageEst; + +extern void _bt_prefix_est_add(BTPrefixPageEst *est, const BTPrefixAttr * attrs, + int natts, IndexTuple itup); +extern Size _bt_prefix_est_coded(const BTPrefixPageEst *est); +extern bool _bt_prefix_est_representable(const BTPrefixPageEst *est); +extern bool _bt_prefix_worthwhile(Size codedsz, Size plainsz); +extern bool _bt_prefix_form_page(Page newpage, IndexTuple hikey, + IndexTuple *items, int n, + const BTPrefixAttr * attrs, int natts, bool force); +extern IndexTuple _bt_prefix_recode(Page page, OffsetNumber offnum, + IndexTuple itup); +extern int _bt_prefix_decode_items(Page page, IndexTuple **items_out, + IndexTuple *hikey, Size *hikeysz); +extern Page _bt_prefix_try_plain_page(Relation rel, Page page, Page out); +extern bool _bt_prefix_split_needed(Page page, Size newitemsz); +extern OffsetNumber _bt_prefix_findsplitloc(Relation rel, Page page, + IndexTuple *ditems, + OffsetNumber newitemoff, + Size newitemsz, + bool *newitemonleft); +extern void _bt_prefix_recount(Page page); +extern void _bt_prefix_note_insert(Page page, IndexTuple coded); + /* * prototypes for functions in nbtvalidate.c */ diff --git a/src/include/access/nbtxlog.h b/src/include/access/nbtxlog.h index 3a78ec27fe8..0ee84e189b8 100644 --- a/src/include/access/nbtxlog.h +++ b/src/include/access/nbtxlog.h @@ -156,9 +156,31 @@ typedef struct xl_btree_split OffsetNumber firstrightoff; /* first origpage item on rightpage */ OffsetNumber newitemoff; /* new item's offset */ uint16 postingoff; /* offset inside orig posting tuple */ + uint8 flags; /* XLH_SPLIT_* prefix compression flags */ } xl_btree_split; -#define SizeOfBtreeSplit (offsetof(xl_btree_split, postingoff) + sizeof(uint16)) +#define SizeOfBtreeSplit (offsetof(xl_btree_split, flags) + sizeof(uint8)) + +/* + * xl_btree_split flags for prefix-compressed (BTP_PREFIX) leaves. When the + * original page was coded, firstrightoff and newitemoff are offsets into its + * decoded item sequence, which has no prefix directory, so data items start + * at BTPageGetPrefixOff; redo decodes the original page to rebuild the left + * half. Redo lays out a coded left half with _bt_prefix_form_page from those + * items, exactly as the primary did. A coded right half arrives as its coded + * items, directory included, and only needs the page flag set. + * + * Coding a left half needs the index's key-column layout to find a leading + * varlena header. Redo takes it from the original page's directory when the + * original was coded; when the original was plain, there is no such source, + * so the primary logs the layout after the fixed record (XLH_SPLIT_LEFT_DESC) + * as a uint16 natts followed by natts BTPrefixAttr. This keeps redo off the + * catalog without a full-page image. + */ +#define XLH_SPLIT_ORIG_CODED 0x01 +#define XLH_SPLIT_LEFT_CODED 0x02 +#define XLH_SPLIT_RIGHT_CODED 0x04 +#define XLH_SPLIT_LEFT_DESC 0x08 /* * When page is deduplicated, consecutive groups of tuples with equal keys are diff --git a/src/test/recovery/Makefile b/src/test/recovery/Makefile index e90e0b1ad4c..d766357f8c3 100644 --- a/src/test/recovery/Makefile +++ b/src/test/recovery/Makefile @@ -9,7 +9,9 @@ # #------------------------------------------------------------------------- -EXTRA_INSTALL=contrib/pg_prewarm \ +EXTRA_INSTALL=contrib/amcheck \ + contrib/pageinspect \ + contrib/pg_prewarm \ contrib/pg_stat_statements \ contrib/pg_visibility \ contrib/test_decoding \ diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index cb3df6ed895..c99040a161f 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -70,6 +70,7 @@ tests += { 't/059_remote_apply_status_interval.pl', 't/060_multixact_crashed_updater.pl', 't/061_recovery_target_prefetch.pl', + 't/062_nbtree_prefix.pl', ], }, } diff --git a/src/test/recovery/t/062_nbtree_prefix.pl b/src/test/recovery/t/062_nbtree_prefix.pl new file mode 100644 index 00000000000..509f634d8bb --- /dev/null +++ b/src/test/recovery/t/062_nbtree_prefix.pl @@ -0,0 +1,470 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Replay of prefix-compressed btree leaves on a streaming standby. +# +# Redo rebuilds coded leaves from the WAL record, not from a full-page image, +# for inserts, splits, deduplication, posting list splits, VACUUM, simple and +# bottom-up deletion, and page deletion. wal_consistency_checking makes any +# divergence from the primary's page fail replay. +# +# Queries test btpo_flags bits from nbtree.h: BTP_ROOT is 2, BTP_PREFIX is 512. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $primary = PostgreSQL::Test::Cluster->new('primary'); +$primary->init(allows_streaming => 1); +$primary->append_conf( + 'postgresql.conf', q{ +wal_consistency_checking = 'btree' +autovacuum = off +}); +$primary->start; + +# wal_consistency_checking logs a full-page image with every btree record, so +# the workload writes far more WAL than max_wal_size; a slot keeps the primary +# from recycling segments the standby has not received yet. +$primary->safe_psql('postgres', + "SELECT pg_create_physical_replication_slot('standby')"); +$primary->backup('backup'); + +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($primary, 'backup', has_streaming => 1); +$standby->append_conf('postgresql.conf', "primary_slot_name = 'standby'"); +$standby->start; + +$primary->safe_psql( + 'postgres', q{ +CREATE EXTENSION amcheck; +CREATE EXTENSION pageinspect; + +-- Distinct keys sharing a long prefix: coded inserts and splits, including +-- splits of pages whose decoded content exceeds one page. +CREATE TABLE pfx_url (u text COLLATE "C", id int); +CREATE INDEX pfx_url_u ON pfx_url (u) WITH (prefix_compression = on); +INSERT INTO pfx_url + SELECT 'https://example.com/path/to/resource/' || (hashint4(g) & x'7fffffff'::int), g + FROM generate_series(1, 30000) g; + +-- Bulk-built coded leaves, then inserts into them. +CREATE INDEX pfx_url_u_id ON pfx_url (u, id) WITH (prefix_compression = on); +INSERT INTO pfx_url + SELECT 'https://example.com/path/to/resource/' || g, -g + FROM generate_series(1, 10000) g; + +-- Two variable-length key columns: rows share the whole first column and a +-- long, length-varying prefix of the second, so coded leaves carry a nonzero +-- fully-shared leading span (lead_shared > 0). Replaying their inserts and +-- splits under wal_consistency_checking exercises the multi-column decode. +CREATE TABLE pfx_mc (a text COLLATE "C", b text COLLATE "C"); +CREATE INDEX pfx_mc_ab ON pfx_mc (a, b) WITH (prefix_compression = on); +INSERT INTO pfx_mc + SELECT 'https://example.com/tenant/' || lpad((g % 50)::text, 4, '0'), + '/path/segment/' || repeat('y', 64) || '/' || g + FROM generate_series(1, 20000) g; +INSERT INTO pfx_mc + SELECT 'https://example.com/tenant/' || lpad((g % 50)::text, 4, '0'), + '/path/segment/' || repeat('y', 64) || '/' || g + FROM generate_series(20001, 40000) g ORDER BY random(); + +-- Duplicates in random order: deduplication of coded pages, then posting +-- list splits on them. +CREATE TABLE pfx_dup (u text COLLATE "C", n int); +CREATE INDEX pfx_dup_u ON pfx_dup (u) WITH (prefix_compression = on); +INSERT INTO pfx_dup + SELECT 'https://example.com/path/to/resource/' || lpad((g % 300)::text, 8, '0'), g + FROM generate_series(1, 30000) g ORDER BY random(); +INSERT INTO pfx_dup + SELECT 'https://example.com/path/to/resource/' || lpad((g % 300)::text, 8, '0'), g + FROM generate_series(30001, 60000) g ORDER BY random(); + +-- VACUUM of coded pages (posting list updates and deletions), then page +-- deletion of emptied coded leaves. +DELETE FROM pfx_dup WHERE n % 3 = 0; +VACUUM pfx_dup; +DELETE FROM pfx_dup WHERE u < 'https://example.com/path/to/resource/00000150'; +VACUUM pfx_dup; + +-- Non-key updates: bottom-up deletion on coded pages. +CREATE TABLE pfx_upd (id int PRIMARY KEY, u text COLLATE "C", f int); +CREATE INDEX pfx_upd_u ON pfx_upd (u) WITH (prefix_compression = on); +INSERT INTO pfx_upd + SELECT g, 'https://example.com/x/' || lpad((g % 500)::text, 8, '0'), 0 + FROM generate_series(1, 20000) g; +UPDATE pfx_upd SET f = f + 1; +UPDATE pfx_upd SET f = f + 1; + +-- Unique checking with a nullable second key and an INCLUDE column. Equal +-- numeric values with different scales must retain their representations. +CREATE TABLE pfx_unique (u text COLLATE "C", n numeric, payload text, + f int DEFAULT 0); +INSERT INTO pfx_unique (u, n, payload) + SELECT 'https://example.com/unique/' || lpad(g::text, 8, '0'), + CASE WHEN g % 10 = 0 THEN NULL + WHEN g % 2 = 0 THEN 1.0 ELSE 1.00 END, + CASE WHEN g % 7 = 0 THEN NULL ELSE 'payload-' || g END + FROM generate_series(1, 2000) g; +CREATE UNIQUE INDEX pfx_unique_u ON pfx_unique (u, n) INCLUDE (payload) + NULLS NOT DISTINCT WITH (prefix_compression = on); +INSERT INTO pfx_unique (u, n, payload) + SELECT 'https://example.com/unique/' || lpad(g::text, 8, '0'), + CASE WHEN g % 10 = 0 THEN NULL + WHEN g % 2 = 0 THEN 1.0 ELSE 1.00 END, + CASE WHEN g % 7 = 0 THEN NULL ELSE 'payload-' || g END + FROM generate_series(2001, 4000) g; +VACUUM ANALYZE pfx_unique; +}); + +# Check the leaves containing both duplicate probe keys, not unrelated leaves +# that may be plain. Do this before updates can create HOT root redirects. +is( $primary->safe_psql( + 'postgres', q{ +SELECT count(DISTINCT u) = 2 + FROM generate_series(1, + (pg_relation_size('pfx_unique_u') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_unique_u', b) s, + LATERAL bt_page_items('pfx_unique_u', b) i, + pfx_unique t + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0 + AND i.itemoffset > CASE WHEN s.btpo_next = 0 THEN 1 ELSE 2 END + AND i.htid = t.ctid + AND t.u IN ('https://example.com/unique/00000002', + 'https://example.com/unique/00000010'); +}), + 't', + 'both unique duplicate probes target prefix-compressed leaves'); + +foreach my $duplicate ( + q{('https://example.com/unique/00000002', 1.000, 'duplicate')}, + q{('https://example.com/unique/00000010', NULL, 'duplicate')}) +{ + my ($ret, $stdout, $stderr) = $primary->psql('postgres', + "INSERT INTO pfx_unique (u, n, payload) VALUES $duplicate"); + is($ret, 3, 'compressed unique index rejects duplicate'); + like( + $stderr, + qr/duplicate key value violates unique constraint "pfx_unique_u"/, + 'duplicate rejected by compressed index'); +} + +$primary->safe_psql( + 'postgres', q{ +UPDATE pfx_unique SET f = f + 1; +UPDATE pfx_unique SET f = f + 1; +VACUUM ANALYZE pfx_unique; +}); + +$primary->wait_for_replay_catchup($standby); + +# The standby replayed everything (a consistency failure would have stopped +# it) and is still serving queries. +is($standby->safe_psql('postgres', 'SELECT 1'), '1', 'standby is alive'); + +my $query = q{ +SET enable_seqscan = off; +SET enable_bitmapscan = off; +SELECT count(*), md5(string_agg(u, '|' ORDER BY u)) FROM pfx_url; +SELECT count(*), md5(string_agg(u || n, '|' ORDER BY u, n)) FROM pfx_dup; +SELECT count(*) FROM pfx_upd WHERE u = 'https://example.com/x/00000007'; +SELECT count(*), md5(string_agg(a || E'\x1f' || b, '|' ORDER BY a, b)) + FROM pfx_mc; +}; +is( $standby->safe_psql('postgres', $query), + $primary->safe_psql('postgres', $query), + 'standby index scans match primary'); + +# Compare the decoded keys and INCLUDE values with an independent heap scan, +# including numeric scale (numeric equality alone would not detect its loss). +my $unique_query = q{ +SELECT count(*), md5(string_agg( + u || ':' || coalesce(n::text, '') || ':' || + coalesce(payload, ''), '|' ORDER BY u)) FROM pfx_unique; +}; +my $unique_expected = $primary->safe_psql( + 'postgres', + 'SET enable_indexscan = off; SET enable_indexonlyscan = off; ' + . 'SET enable_bitmapscan = off; SET enable_seqscan = on; ' + . $unique_query); +foreach my $node ($primary, $standby) +{ + my $ios = 'SET enable_seqscan = off; SET enable_bitmapscan = off; ' + . 'SET enable_indexonlyscan = on; '; + like( + $node->safe_psql('postgres', + $ios . 'EXPLAIN (COSTS OFF) ' . $unique_query), + qr/Index Only Scan using pfx_unique_u/, + 'unique index digest uses index-only scan'); + is($node->safe_psql('postgres', $ios . $unique_query), + $unique_expected, 'unique index preserves keys and INCLUDE values'); + is( $node->safe_psql( + 'postgres', $ios . q{ +SELECT n::text, payload FROM pfx_unique + WHERE u = ANY (ARRAY['https://example.com/unique/00000002', + 'https://example.com/unique/00000003', + 'https://example.com/unique/00002002']) + ORDER BY u; +SELECT payload FROM pfx_unique + WHERE u = ANY (ARRAY['https://example.com/unique/00000010', + 'https://example.com/unique/00002010']) + AND n IS NULL ORDER BY u; +}), + "1.0|payload-2\n1.00|payload-3\n1.0|\npayload-10\npayload-2010", + 'array probes and NULL keys on multicolumn unique index'); +} + +foreach my $idx (qw(pfx_url_u pfx_url_u_id pfx_dup_u pfx_upd_u pfx_unique_u + pfx_mc_ab)) +{ + is( $standby->safe_psql( + 'postgres', "SELECT bt_index_check('$idx', true)"), + '', + "amcheck on standby: $idx"); +} + +# The two-varlena-column index must have coded leaves that carry a nonzero +# fully-shared leading span; otherwise the replay above never exercised the +# multi-column decode path. +ok( $primary->safe_psql( + 'postgres', q{ +SELECT count(*) > 0 + FROM generate_series(1, + (pg_relation_size('pfx_mc_ab') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_mc_ab', b) s + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0; +}) eq 't', + 'multicolumn index has prefix-compressed leaves'); + +# Guard against a workload that never produced a coded leaf. +ok( $primary->safe_psql( + 'postgres', q{ +SELECT count(*) > 0 + FROM generate_series(1, + (pg_relation_size('pfx_url_u') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_url_u', b) s + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0; +}) eq 't', + 'index has prefix-compressed leaves'); + +# VACUUM removes the empty root directory on both primary and standby. +SKIP: +{ + skip 'large tuple insertion into empty root requires 32KB pages', 7 + unless $primary->safe_psql('postgres', 'SHOW block_size') == 32768; + + $primary->safe_psql( + 'postgres', q{ +CREATE TABLE pfx_empty (a smallint, b bytea); +ALTER TABLE pfx_empty ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO pfx_empty + SELECT 1, decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 3); +CREATE INDEX pfx_empty_idx ON pfx_empty (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +CHECKPOINT; +DELETE FROM pfx_empty; +VACUUM pfx_empty; +}); + is( $primary->safe_psql( + 'postgres', q{ +SELECT btpo_flags & 512 = 0 AND btpo_flags & 2 <> 0 + AND live_items = 0 AND dead_items = 0 + FROM bt_page_stats('pfx_empty_idx', 1); +}), + 't', 'vacuum removes the empty root directory before insertion'); + + $primary->safe_psql( + 'postgres', q{ +INSERT INTO pfx_empty VALUES (2, decode(repeat('cd', 8168), 'hex')); +VACUUM pfx_empty; +}); + $primary->wait_for_replay_catchup($standby); + foreach my $node ($primary, $standby) + { + is( $node->safe_psql('postgres', + "SELECT bt_index_check('pfx_empty_idx', true)"), + '', 'empty root insertion passes amcheck'); + my $settings = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + my $query = q{ +SELECT a, octet_length(b), b = decode(repeat('cd', 8168), 'hex') + FROM pfx_empty; +}; + like( + $node->safe_psql('postgres', + $settings . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using pfx_empty_idx/, + 'empty root insertion uses index-only scan'); + is($node->safe_psql('postgres', $settings . $query), + '2|8168|t', 'empty root insertion preserves indexed value'); + } +} + +# Deduplication merges keys that are equal under equalimage even when their +# stored bytes differ. Here the heap compresses equal keys with pglz first +# and lz4 later, and index tuples keep the inline-compressed datums, so +# posting lists built and split on coded leaves mix both representations. +# The index must still return the stored values, on the primary and after +# byte-checked replay on the standby. +SKIP: +{ + skip 'mixed compression methods require lz4', 7 + unless check_pg_config('^#define USE_LZ4 1$'); + + $primary->safe_psql( + 'postgres', q{ +CREATE TABLE pfx_img (id int, k text COLLATE "C") + WITH (autovacuum_enabled = off, fillfactor = 100); +ALTER TABLE pfx_img ALTER COLUMN k SET COMPRESSION pglz; +INSERT INTO pfx_img + SELECT g, 'https://example.com/path/to/resource/' || + lpad((g % 20)::text, 4, '0') || repeat('x', 3000) + FROM generate_series(1, 400) g; +CREATE INDEX pfx_img_k ON pfx_img (k) WITH (prefix_compression = on); +-- Free heap slots inside every posting list's TID range, so that the lz4 +-- reinserts split existing posting lists instead of only appending. +DELETE FROM pfx_img WHERE id BETWEEN 150 AND 250; +VACUUM pfx_img; +ALTER TABLE pfx_img ALTER COLUMN k SET COMPRESSION lz4; +INSERT INTO pfx_img + SELECT g, 'https://example.com/path/to/resource/' || + lpad((g % 20)::text, 4, '0') || repeat('x', 3000) + FROM generate_series(150, 800) g WHERE g NOT BETWEEN 251 AND 400; +VACUUM ANALYZE pfx_img; +}); + is( $primary->safe_psql( + 'postgres', q{ +SELECT count(*) > 0 + FROM (SELECT b, i.itemoffset + FROM generate_series(1, + (pg_relation_size('pfx_img_k') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_img_k', b) s, + LATERAL bt_page_items('pfx_img_k', b) i, + LATERAL unnest(i.tids) t(tid) + JOIN pfx_img h ON h.ctid = t.tid + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0 + GROUP BY 1, 2 + HAVING count(DISTINCT pg_column_compression(h.k)) = 2) m; +}), + 't', + 'coded posting lists merge pglz and lz4 representations'); + + $primary->wait_for_replay_catchup($standby); + my $query = q{SELECT count(*), md5(string_agg(k, '|' ORDER BY k)) + FROM pfx_img}; + my $expected = $primary->safe_psql('postgres', + 'SET enable_indexscan = off; SET enable_indexonlyscan = off; ' + . 'SET enable_bitmapscan = off; ' . $query); + foreach my $node ($primary, $standby) + { + is( $node->safe_psql('postgres', + "SELECT bt_index_check('pfx_img_k', true)"), + '', 'mixed-representation index passes amcheck'); + my $ios = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + like( + $node->safe_psql('postgres', $ios . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using pfx_img_k/, + 'mixed-representation digest uses index-only scan'); + is($node->safe_psql('postgres', $ios . $query), + $expected, 'mixed-representation index returns the heap values'); + } +} + +# A nondeterministic collation has no equalimage support, so deduplication +# stays off while prefix compression shares the identical bytes of keys that +# compare equal but are stored differently. Each case variant must come back +# unchanged, and uniqueness must still use the collation's equality. +SKIP: +{ + skip 'nondeterministic collations require ICU', 9 + unless check_pg_config('^#define USE_ICU 1$'); + + # ICU collations need a UTF8 database, whatever the cluster's default. + $primary->safe_psql('postgres', + "CREATE DATABASE pfx_icu ENCODING 'UTF8' LOCALE 'C' TEMPLATE template0" + ); + $primary->safe_psql( + 'pfx_icu', q{ +CREATE EXTENSION amcheck; +CREATE EXTENSION pageinspect; +CREATE COLLATION pfx_ci (provider = icu, locale = 'und-u-ks-level2', + deterministic = false); +CREATE TABLE pfx_nd (k text COLLATE pfx_ci) WITH (autovacuum_enabled = off); +INSERT INTO pfx_nd + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 5, '0') + || v + FROM generate_series(1, 1500) g, + unnest(ARRAY['/view', '/VIEW', '/View']) v; +CREATE INDEX pfx_nd_k ON pfx_nd (k) WITH (prefix_compression = on); +INSERT INTO pfx_nd + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 5, '0') + || '/vIeW' + FROM generate_series(1, 1500) g; +CREATE TABLE pfx_nd_u (k text COLLATE pfx_ci) WITH (autovacuum_enabled = off); +INSERT INTO pfx_nd_u + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 5, '0') + FROM generate_series(1, 3000) g; +CREATE UNIQUE INDEX pfx_nd_u_k ON pfx_nd_u (k) + WITH (prefix_compression = on); +VACUUM ANALYZE pfx_nd; +VACUUM ANALYZE pfx_nd_u; +}); + is( $primary->safe_psql( + 'pfx_icu', q{ +SELECT NOT m.allequalimage AND + bool_or(s.type = 'l' AND (s.btpo_flags & 512) <> 0) AND + NOT bool_or(i.tids IS NOT NULL) + FROM bt_metap('pfx_nd_k') m, + generate_series(1, + (pg_relation_size('pfx_nd_k') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_nd_k', b) s, + LATERAL bt_page_items('pfx_nd_k', b) i + GROUP BY m.allequalimage; +}), + 't', + 'nondeterministic index is coded without posting lists'); + + my ($ret, $stdout, $stderr) = $primary->psql('pfx_icu', + "INSERT INTO pfx_nd_u VALUES ('HTTPS://EXAMPLE.COM/PATH/TO/RESOURCE/01234')"); + is($ret, 3, 'case variant of an existing key is rejected'); + like( + $stderr, + qr/duplicate key value violates unique constraint "pfx_nd_u_k"/, + 'nondeterministic uniqueness is checked on coded leaves'); + + $primary->wait_for_replay_catchup($standby); + my $query = q{SELECT count(*), md5(string_agg(k, '|' ORDER BY k COLLATE "C")) + FROM pfx_nd}; + my $expected = $primary->safe_psql('pfx_icu', + 'SET enable_indexscan = off; SET enable_indexonlyscan = off; ' + . 'SET enable_bitmapscan = off; ' . $query); + my $ios = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + foreach my $node ($primary, $standby) + { + is( $node->safe_psql('pfx_icu', + "SELECT bt_index_check('pfx_nd_k', true)"), + '', 'nondeterministic index passes amcheck'); + is($node->safe_psql('pfx_icu', $ios . $query), + $expected, 'nondeterministic index returns every variant unchanged'); + } + like( + $primary->safe_psql('pfx_icu', $ios . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using pfx_nd_k/, + 'nondeterministic digest uses index-only scan'); + is( $standby->safe_psql( + 'pfx_icu', $ios . q{ +SELECT string_agg(k, ',' ORDER BY k COLLATE "C") FROM pfx_nd + WHERE k = 'https://example.com/path/to/resource/00042/view'; +}), + 'https://example.com/path/to/resource/00042/VIEW,' + . 'https://example.com/path/to/resource/00042/View,' + . 'https://example.com/path/to/resource/00042/vIeW,' + . 'https://example.com/path/to/resource/00042/view', + 'equality probe finds all case variants'); +} + +done_testing(); diff --git a/src/test/regress/expected/btree_index.out b/src/test/regress/expected/btree_index.out index 7c53d598649..6e18bf328ff 100644 --- a/src/test/regress/expected/btree_index.out +++ b/src/test/regress/expected/btree_index.out @@ -891,3 +891,358 @@ ALTER INDEX btree_part_idx ALTER COLUMN id SET (n_distinct=100); ERROR: ALTER action ALTER COLUMN ... SET cannot be performed on relation "btree_part_idx" DETAIL: This operation is not supported for partitioned indexes. DROP TABLE btree_part; +-- +-- Leaf key prefix compression (prefix_compression reloption). +-- +-- Forced scans of a prefix-compressed index must return what the heap or the +-- inserted literals return, after build, retail inserts and splits, and +-- VACUUM. The keys share a long prefix, sit around 127 bytes (where the +-- varlena header grows from 1 to 4 bytes, so neighbors share only a +-- header-length prefix), exceed a group's anchor, share nothing, or are NULL. +-- The C collation keeps the output platform-independent. +-- +CREATE TABLE btree_prefix (u text COLLATE "C"); +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO btree_prefix + SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n; +INSERT INTO btree_prefix VALUES + (repeat('a', 125)), (repeat('a', 126)), (repeat('a', 127)), (repeat('a', 300)), + ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX btree_prefix_on ON btree_prefix (u) WITH (prefix_compression = on); +-- The queries below must read the index, not fall back to the heap. +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT u FROM btree_prefix WHERE u = 'https://example.com/path/to/resource/00012345'; + QUERY PLAN +--------------------------------------------------------------------------- + Index Only Scan using btree_prefix_on on btree_prefix + Index Cond: (u = 'https://example.com/path/to/resource/00012345'::text) +(2 rows) + +-- The recorded output is the oracle for these scans. +SELECT count(*) FROM btree_prefix + WHERE u = 'https://example.com/path/to/resource/00012345'; + count +------- + 1 +(1 row) + +SELECT count(*) FROM btree_prefix + WHERE u BETWEEN 'https://example.com/path/to/resource/00000100' + AND 'https://example.com/path/to/resource/00000900'; + count +------- + 801 +(1 row) + +SELECT u FROM btree_prefix + WHERE u > 'https://example.com/path/to/resource/00019996' ORDER BY u DESC; + u +----------------------------------------------- + zzz-no-shared-prefix + https://example.com/path/to/resource/00019999 + https://example.com/path/to/resource/00019998 + https://example.com/path/to/resource/00019997 +(4 rows) + +-- Boundary and oversized keys round-trip to their exact stored values. +SELECT u FROM btree_prefix WHERE u LIKE 'aaaa%' ORDER BY u; + u +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +(10 rows) + +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 300); + count +------- + 1 +(1 row) + +SELECT count(*) FROM btree_prefix WHERE u IS NULL; + count +------- + 1 +(1 row) + +-- Compare an index-only scan with the inserted literals. The plan shows the +-- keys come from decoded index tuples, not the heap. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; + QUERY PLAN +------------------------------------------------------------- + Aggregate + -> Index Only Scan using btree_prefix_on on btree_prefix + Index Cond: (u IS NOT NULL) +(3 rows) + +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) + FROM btree_prefix WHERE u IS NOT NULL) = + md5(string_agg(x, '|' ORDER BY x)) AS ios_ok + FROM ( + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') AS x + FROM generate_series(1, 20000) g + UNION ALL SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n + UNION ALL SELECT v FROM (VALUES (repeat('a',125)),(repeat('a',126)), + (repeat('a',127)),(repeat('a',300)), + ('zzz-no-shared-prefix')) t(v) + ) oracle; + ios_ok +-------- + t +(1 row) + +INSERT INTO btree_prefix + SELECT 'https://example.com/other/' || lpad(g::text, 8, '0') + FROM generate_series(1, 10000) g; +-- Delete only part of the URL range, so the boundary keys survive for later +-- checks. +DELETE FROM btree_prefix + WHERE u >= 'https://example.com/path/to/resource/00000000' + AND u < 'https://example.com/path/to/resource/00005000'; +VACUUM btree_prefix; +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 5000)::text, 8, '0') + FROM generate_series(1, 5000) g; +-- The index-only digest must equal the digest of a sequential heap scan. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; + QUERY PLAN +------------------------------------------------------------- + Aggregate + -> Index Only Scan using btree_prefix_on on btree_prefix + Index Cond: (u IS NOT NULL) +(3 rows) + +SELECT md5(string_agg(u, '|' ORDER BY u)) AS ios_digest + FROM btree_prefix WHERE u IS NOT NULL \gset +SET enable_indexscan = off; +SET enable_seqscan = on; +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; + QUERY PLAN +--------------------------------------- + Aggregate + -> Sort + Sort Key: u COLLATE "C" + -> Seq Scan on btree_prefix + Filter: (u IS NOT NULL) +(5 rows) + +SELECT :'ios_digest' = + (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL) + AS post_churn_ok; + post_churn_ok +--------------- + t +(1 row) + +RESET enable_indexscan; +RESET enable_seqscan; +RESET enable_bitmapscan; +-- The reloption round-trips and can be toggled without a rewrite. +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; + reloptions +------------------------- + {prefix_compression=on} +(1 row) + +ALTER INDEX btree_prefix_on SET (prefix_compression = off); +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; + reloptions +-------------------------- + {prefix_compression=off} +(1 row) + +-- Reading back with the option off still returns correct rows: existing +-- BTP_PREFIX leaves keep their coded form and decode on the page flag. +SET enable_seqscan = off; +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 126); + count +------- + 1 +(1 row) + +RESET enable_seqscan; +-- Verify scans of a fixed-width key with prefix compression enabled. +CREATE INDEX btree_prefix_int ON btree_prefix ((length(u))) WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT length(u) FROM btree_prefix WHERE length(u) = 300; + QUERY PLAN +--------------------------------------------------- + Index Scan using btree_prefix_int on btree_prefix + Index Cond: (length(u) = 300) +(2 rows) + +SELECT length(u) FROM btree_prefix WHERE length(u) = 300; + length +-------- + 300 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix; +-- +-- Bottom-up index deletion on prefix-compressed pages. +-- +-- Non-key UPDATEs make "logically unchanged" index inserts, so full coded +-- leaves get a bottom-up deletion pass before they split. What the pass can +-- remove depends on timing, so only the index contents are checked. +-- +CREATE TABLE btree_prefix_bu (id int PRIMARY KEY, u text COLLATE "C", filler text); +INSERT INTO btree_prefix_bu + SELECT g, 'https://example.com/path/' || lpad((g % 500)::text, 8, '0'), repeat('x', 40) + FROM generate_series(1, 4000) g; +CREATE INDEX btree_prefix_bu_u ON btree_prefix_bu (u) WITH (prefix_compression = on); +UPDATE btree_prefix_bu SET filler = repeat('y', 40); +UPDATE btree_prefix_bu SET filler = repeat('z', 40); +UPDATE btree_prefix_bu SET filler = repeat('w', 40); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_bu; + QUERY PLAN +------------------------------------------------------------ + Index Only Scan using btree_prefix_bu_u on btree_prefix_bu +(1 row) + +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_bu) = + md5(string_agg(x, '|' ORDER BY x)) AS bottomup_ok + FROM (SELECT 'https://example.com/path/' || lpad((g % 500)::text, 8, '0') AS x + FROM generate_series(1, 4000) g) oracle; + bottomup_ok +------------- + t +(1 row) + +SELECT count(*) FROM btree_prefix_bu + WHERE u = 'https://example.com/path/' || lpad('7', 8, '0'); + count +------- + 8 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_bu; +-- A final coded leaf must fit all posting tuples, not just the layout with +-- the last posting tuple replaced by a high key. +CREATE TABLE btree_prefix_post (u text COLLATE "C"); +INSERT INTO btree_prefix_post + SELECT repeat('x', 119) FROM generate_series(1, 1356); +CREATE INDEX btree_prefix_post_u ON btree_prefix_post (u) + WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +SELECT count(*) FROM btree_prefix_post WHERE u = repeat('x', 119); + count +------- + 1356 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_post; +-- +-- Runtime deduplication on prefix-compressed leaves. Retail inserts of +-- duplicates fill coded leaves, which deduplicate and re-code before they +-- split. +-- +CREATE TABLE btree_prefix_dd (u text COLLATE "C"); +CREATE INDEX btree_prefix_dd_u ON btree_prefix_dd (u) WITH (prefix_compression = on); +INSERT INTO btree_prefix_dd + SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') + FROM generate_series(1, 40000) g; +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_dd; + QUERY PLAN +------------------------------------------------------------ + Index Only Scan using btree_prefix_dd_u on btree_prefix_dd +(1 row) + +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_dd) = + md5(string_agg(x, '|' ORDER BY x)) AS runtime_dedup_ok + FROM (SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') AS x + FROM generate_series(1, 40000) g) oracle; + runtime_dedup_ok +------------------ + t +(1 row) + +SELECT count(*) FROM btree_prefix_dd + WHERE u = 'https://example.com/path/to/resource/' || lpad('42', 8, '0'); + count +------- + 200 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_dd; +-- +-- Compression actually happens, both when an index is built and when it grows +-- by insertion: a prefix-compressed index on keys with a long shared prefix +-- is much smaller than a plain one. +-- +CREATE TABLE btree_prefix_sz (u text COLLATE "C"); +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +CREATE INDEX btree_prefix_sz_on ON btree_prefix_sz (u) WITH (prefix_compression = on); +CREATE INDEX btree_prefix_sz_off ON btree_prefix_sz (u); +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS build_compresses; + build_compresses +------------------ + t +(1 row) + +TRUNCATE btree_prefix_sz; +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(((g * 7919) % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS insert_compresses; + insert_compresses +------------------- + t +(1 row) + +DROP TABLE btree_prefix_sz; +-- +-- Multiple prefix groups per page. When a leaf's first tuple shares only a +-- short prefix (here the leading int column) with a long run of tuples that +-- share much more among themselves, the run must form its own group rather +-- than stay anchored to that first tuple. Without per-page grouping this case +-- does not compress at all. +-- +CREATE TABLE btree_prefix_grp (tenant int4, u text COLLATE "C"); +INSERT INTO btree_prefix_grp VALUES (1001, 'a'); +INSERT INTO btree_prefix_grp + SELECT 1001, 'https://shop.example.com/pay/' || lpad(g::text, 6, '0') + FROM generate_series(1, 150 * current_setting('block_size')::integer / 8192) g; +CREATE INDEX btree_prefix_grp_on ON btree_prefix_grp (tenant, u) + WITH (prefix_compression = on); +CREATE INDEX btree_prefix_grp_off ON btree_prefix_grp (tenant, u); +SELECT pg_relation_size('btree_prefix_grp_on') < + pg_relation_size('btree_prefix_grp_off') AS groups_compress; + groups_compress +----------------- + t +(1 row) + +DROP TABLE btree_prefix_grp; diff --git a/src/test/regress/sql/btree_index.sql b/src/test/regress/sql/btree_index.sql index 6990d7818da..e516b8d6c84 100644 --- a/src/test/regress/sql/btree_index.sql +++ b/src/test/regress/sql/btree_index.sql @@ -520,3 +520,213 @@ CREATE TABLE btree_part (id int4) PARTITION BY RANGE (id); CREATE INDEX btree_part_idx ON btree_part(id); ALTER INDEX btree_part_idx ALTER COLUMN id SET (n_distinct=100); DROP TABLE btree_part; + +-- +-- Leaf key prefix compression (prefix_compression reloption). +-- +-- Forced scans of a prefix-compressed index must return what the heap or the +-- inserted literals return, after build, retail inserts and splits, and +-- VACUUM. The keys share a long prefix, sit around 127 bytes (where the +-- varlena header grows from 1 to 4 bytes, so neighbors share only a +-- header-length prefix), exceed a group's anchor, share nothing, or are NULL. +-- The C collation keeps the output platform-independent. +-- +CREATE TABLE btree_prefix (u text COLLATE "C"); +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO btree_prefix + SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n; +INSERT INTO btree_prefix VALUES + (repeat('a', 125)), (repeat('a', 126)), (repeat('a', 127)), (repeat('a', 300)), + ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX btree_prefix_on ON btree_prefix (u) WITH (prefix_compression = on); + +-- The queries below must read the index, not fall back to the heap. +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT u FROM btree_prefix WHERE u = 'https://example.com/path/to/resource/00012345'; + +-- The recorded output is the oracle for these scans. +SELECT count(*) FROM btree_prefix + WHERE u = 'https://example.com/path/to/resource/00012345'; +SELECT count(*) FROM btree_prefix + WHERE u BETWEEN 'https://example.com/path/to/resource/00000100' + AND 'https://example.com/path/to/resource/00000900'; +SELECT u FROM btree_prefix + WHERE u > 'https://example.com/path/to/resource/00019996' ORDER BY u DESC; +-- Boundary and oversized keys round-trip to their exact stored values. +SELECT u FROM btree_prefix WHERE u LIKE 'aaaa%' ORDER BY u; +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 300); +SELECT count(*) FROM btree_prefix WHERE u IS NULL; + +-- Compare an index-only scan with the inserted literals. The plan shows the +-- keys come from decoded index tuples, not the heap. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) + FROM btree_prefix WHERE u IS NOT NULL) = + md5(string_agg(x, '|' ORDER BY x)) AS ios_ok + FROM ( + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') AS x + FROM generate_series(1, 20000) g + UNION ALL SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n + UNION ALL SELECT v FROM (VALUES (repeat('a',125)),(repeat('a',126)), + (repeat('a',127)),(repeat('a',300)), + ('zzz-no-shared-prefix')) t(v) + ) oracle; + +INSERT INTO btree_prefix + SELECT 'https://example.com/other/' || lpad(g::text, 8, '0') + FROM generate_series(1, 10000) g; +-- Delete only part of the URL range, so the boundary keys survive for later +-- checks. +DELETE FROM btree_prefix + WHERE u >= 'https://example.com/path/to/resource/00000000' + AND u < 'https://example.com/path/to/resource/00005000'; +VACUUM btree_prefix; +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 5000)::text, 8, '0') + FROM generate_series(1, 5000) g; +-- The index-only digest must equal the digest of a sequential heap scan. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; +SELECT md5(string_agg(u, '|' ORDER BY u)) AS ios_digest + FROM btree_prefix WHERE u IS NOT NULL \gset +SET enable_indexscan = off; +SET enable_seqscan = on; +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; +SELECT :'ios_digest' = + (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL) + AS post_churn_ok; +RESET enable_indexscan; +RESET enable_seqscan; +RESET enable_bitmapscan; + +-- The reloption round-trips and can be toggled without a rewrite. +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; +ALTER INDEX btree_prefix_on SET (prefix_compression = off); +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; +-- Reading back with the option off still returns correct rows: existing +-- BTP_PREFIX leaves keep their coded form and decode on the page flag. +SET enable_seqscan = off; +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 126); +RESET enable_seqscan; + +-- Verify scans of a fixed-width key with prefix compression enabled. +CREATE INDEX btree_prefix_int ON btree_prefix ((length(u))) WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT length(u) FROM btree_prefix WHERE length(u) = 300; +SELECT length(u) FROM btree_prefix WHERE length(u) = 300; +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix; + +-- +-- Bottom-up index deletion on prefix-compressed pages. +-- +-- Non-key UPDATEs make "logically unchanged" index inserts, so full coded +-- leaves get a bottom-up deletion pass before they split. What the pass can +-- remove depends on timing, so only the index contents are checked. +-- +CREATE TABLE btree_prefix_bu (id int PRIMARY KEY, u text COLLATE "C", filler text); +INSERT INTO btree_prefix_bu + SELECT g, 'https://example.com/path/' || lpad((g % 500)::text, 8, '0'), repeat('x', 40) + FROM generate_series(1, 4000) g; +CREATE INDEX btree_prefix_bu_u ON btree_prefix_bu (u) WITH (prefix_compression = on); +UPDATE btree_prefix_bu SET filler = repeat('y', 40); +UPDATE btree_prefix_bu SET filler = repeat('z', 40); +UPDATE btree_prefix_bu SET filler = repeat('w', 40); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_bu; +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_bu) = + md5(string_agg(x, '|' ORDER BY x)) AS bottomup_ok + FROM (SELECT 'https://example.com/path/' || lpad((g % 500)::text, 8, '0') AS x + FROM generate_series(1, 4000) g) oracle; +SELECT count(*) FROM btree_prefix_bu + WHERE u = 'https://example.com/path/' || lpad('7', 8, '0'); +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_bu; + +-- A final coded leaf must fit all posting tuples, not just the layout with +-- the last posting tuple replaced by a high key. +CREATE TABLE btree_prefix_post (u text COLLATE "C"); +INSERT INTO btree_prefix_post + SELECT repeat('x', 119) FROM generate_series(1, 1356); +CREATE INDEX btree_prefix_post_u ON btree_prefix_post (u) + WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +SELECT count(*) FROM btree_prefix_post WHERE u = repeat('x', 119); +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_post; + +-- +-- Runtime deduplication on prefix-compressed leaves. Retail inserts of +-- duplicates fill coded leaves, which deduplicate and re-code before they +-- split. +-- +CREATE TABLE btree_prefix_dd (u text COLLATE "C"); +CREATE INDEX btree_prefix_dd_u ON btree_prefix_dd (u) WITH (prefix_compression = on); +INSERT INTO btree_prefix_dd + SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') + FROM generate_series(1, 40000) g; +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_dd; +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_dd) = + md5(string_agg(x, '|' ORDER BY x)) AS runtime_dedup_ok + FROM (SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') AS x + FROM generate_series(1, 40000) g) oracle; +SELECT count(*) FROM btree_prefix_dd + WHERE u = 'https://example.com/path/to/resource/' || lpad('42', 8, '0'); +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_dd; + +-- +-- Compression actually happens, both when an index is built and when it grows +-- by insertion: a prefix-compressed index on keys with a long shared prefix +-- is much smaller than a plain one. +-- +CREATE TABLE btree_prefix_sz (u text COLLATE "C"); +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +CREATE INDEX btree_prefix_sz_on ON btree_prefix_sz (u) WITH (prefix_compression = on); +CREATE INDEX btree_prefix_sz_off ON btree_prefix_sz (u); +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS build_compresses; +TRUNCATE btree_prefix_sz; +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(((g * 7919) % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS insert_compresses; +DROP TABLE btree_prefix_sz; + +-- +-- Multiple prefix groups per page. When a leaf's first tuple shares only a +-- short prefix (here the leading int column) with a long run of tuples that +-- share much more among themselves, the run must form its own group rather +-- than stay anchored to that first tuple. Without per-page grouping this case +-- does not compress at all. +-- +CREATE TABLE btree_prefix_grp (tenant int4, u text COLLATE "C"); +INSERT INTO btree_prefix_grp VALUES (1001, 'a'); +INSERT INTO btree_prefix_grp + SELECT 1001, 'https://shop.example.com/pay/' || lpad(g::text, 6, '0') + FROM generate_series(1, 150 * current_setting('block_size')::integer / 8192) g; +CREATE INDEX btree_prefix_grp_on ON btree_prefix_grp (tenant, u) + WITH (prefix_compression = on); +CREATE INDEX btree_prefix_grp_off ON btree_prefix_grp (tenant, u); +SELECT pg_relation_size('btree_prefix_grp_on') < + pg_relation_size('btree_prefix_grp_off') AS groups_compress; +DROP TABLE btree_prefix_grp; diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb469266..66719e9ff34 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -215,6 +215,7 @@ BTDeletedPageData BTIndexStat BTInsertState BTInsertStateData +BTItemBuf BTLeader BTMetaPageData BTOneVacInfo @@ -226,6 +227,14 @@ BTPageStat BTPageState BTParallelScanDesc BTPendingFSM +BTPrefixAnchor +BTPrefixAnchorDisk +BTPrefixCode +BTPrefixDir +BTPrefixDirHdr +BTPrefixPageEst +BTPrefixSplice +BTPrefixSplit BTReadPageState BTScanInsert BTScanInsertData base-commit: 31878ccc2cd5642a5d2a1a39dedb79e9a18c8a07 -- 2.56.0