agora inbox for pgsql-hackers@postgresql.org  
help / color / mirror / Atom feed
Confine vacuum skip logic to lazy_scan_skip
81+ messages / 15 participants
[nested] [flat]

* Confine vacuum skip logic to lazy_scan_skip
@ 2023-12-31 18:28 Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2023-12-31 18:28 UTC (permalink / raw)
  To: pgsql-hackers; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>

Hi,

I've written a patch set for vacuum to use the streaming read interface
proposed in [1]. Making lazy_scan_heap() async-friendly required a bit
of refactoring of lazy_scan_heap() and lazy_scan_skip(). I needed to
confine all of the skipping logic -- previously spread across
lazy_scan_heap() and lazy_scan_skip() -- to lazy_scan_skip(). All of the
patches doing this and other preparation for vacuum to use the streaming
read API can be applied on top of master. The attached patch set does
this.

There are a few comments that still need to be updated. I also noticed I
needed to reorder and combine a couple of the commits. I wanted to
register this for the january commitfest, so I didn't quite have time
for the finishing touches.

- Melanie

[1] https://www.postgresql.org/message-id/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2...

Attachments:

  [text/x-patch] v1-0001-lazy_scan_skip-remove-unnecessary-local-var-rel_p.patch (1.6K, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/2-v1-0001-lazy_scan_skip-remove-unnecessary-local-var-rel_p.patch)
  download | inline diff:
From 9cd579d6a20aef2aeeab6ef50d72e779d75bf7cd Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:18:40 -0500
Subject: [PATCH v1 1/7] lazy_scan_skip remove unnecessary local var rel_pages

lazy_scan_skip() only uses vacrel->rel_pages twice, so there seems to be
no reason to save it in a local variable, rel_pages.
---
 src/backend/access/heap/vacuumlazy.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3b9299b8924..c4e0c077694 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1302,13 +1302,12 @@ static BlockNumber
 lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
+	BlockNumber next_unskippable_block = next_block,
 				nskippable_blocks = 0;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	while (next_unskippable_block < vacrel->rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
@@ -1331,7 +1330,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		 *
 		 * Implement this by always treating the last block as unsafe to skip.
 		 */
-		if (next_unskippable_block == rel_pages - 1)
+		if (next_unskippable_block == vacrel->rel_pages - 1)
 			break;
 
 		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-- 
2.37.2



  [text/x-patch] v1-0002-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.6K, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/3-v1-0002-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From 314dd9038593610583e4fe60ab62e0d46ea3be86 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v1 2/7] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index c4e0c077694..3b28ea2cdb5 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1302,8 +1302,7 @@ static BlockNumber
 lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
-	BlockNumber next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+	BlockNumber next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1360,7 +1359,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1373,7 +1371,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.37.2



  [text/x-patch] v1-0003-Add-lazy_scan_skip-unskippable-state.patch (9.6K, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/4-v1-0003-Add-lazy_scan_skip-unskippable-state.patch)
  download | inline diff:
From 67043818003faa9cf3cdf10e6fdc6cbf6f8eee4c Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v1 3/7] Add lazy_scan_skip unskippable state

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce the struct, VacSkipState, which will maintain the variables
needed to skip ranges less than SKIP_PAGES_THRESHOLD.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 105 ++++++++++++++++-----------
 src/tools/pgindent/typedefs.list     |   1 +
 2 files changed, 64 insertions(+), 42 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3b28ea2cdb5..6f9c2446c56 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -238,13 +238,24 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+/*
+ * Parameters maintained by lazy_scan_skip() to manage skipping ranges of pages
+ * greater than SKIP_PAGES_THRESHOLD.
+ */
+typedef struct VacSkipState
+{
+	/* Next unskippable block */
+	BlockNumber next_unskippable_block;
+	/* Next unskippable block's visibility status */
+	bool		next_unskippable_allvis;
+	/* Whether or not skippable blocks should be skipped */
+	bool		skipping_current_range;
+} VacSkipState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+						   BlockNumber next_block, Buffer *vmbuffer);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -826,12 +837,10 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
+	VacSkipState vacskip;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -846,9 +855,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, &vacskip, 0, &vmbuffer);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -856,26 +863,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		all_visible_according_to_vm;
 		LVPagePruneState prunestate;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacskip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacskip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, &vacskip, blkno + 1, &vmbuffer);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacskip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacskip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -1280,15 +1284,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in vacskip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
+ *
+ * The block number and visibility status of the next unskippable block are set
+ * in vacskip->next_unskippable_block and next_unskippable_allvis.
+ * vacskip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1298,24 +1321,24 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+			   BlockNumber next_block, Buffer *vmbuffer)
 {
-	BlockNumber next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
-	while (next_unskippable_block < vacrel->rel_pages)
+	vacskip->next_unskippable_block = next_block;
+	vacskip->next_unskippable_allvis = true;
+	while (vacskip->next_unskippable_block < vacrel->rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
+													   vacskip->next_unskippable_block,
 													   vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacskip->next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1329,14 +1352,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		 *
 		 * Implement this by always treating the last block as unsafe to skip.
 		 */
-		if (next_unskippable_block == vacrel->rel_pages - 1)
+		if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
 			break;
 
 		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacskip->next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1358,7 +1381,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		}
 
 		vacuum_delay_point();
-		next_unskippable_block++;
+		vacskip->next_unskippable_block++;
 	}
 
 	/*
@@ -1371,16 +1394,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacskip->next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacskip->skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacskip->skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index e37ef9aa76d..bd008e1699b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2955,6 +2955,7 @@ VacOptValue
 VacuumParams
 VacuumRelation
 VacuumStmt
+VacSkipState
 ValidIOData
 ValidateIndexState
 ValuesScan
-- 
2.37.2



  [text/x-patch] v1-0004-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (13.4K, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/5-v1-0004-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 387db30b7e06f450dc7f60494751f78e00d43272 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v1 4/7] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and eventually
AIO), refactor vacuum's logic for skipping blocks such that it is entirely
confined to lazy_scan_skip(). This turns lazy_scan_skip() and the VacSkipState
it uses into an iterator which yields blocks to lazy_scan_heap(). Such a
structure is conducive to an async interface.

By always calling lazy_scan_skip() -- instead of only when we have reached the
next unskippable block, we no longer need the skipping_current_range variable.
lazy_scan_heap() no longer needs to manage the skipped range -- checking if we
reached the end in order to then call lazy_scan_skip(). And lazy_scan_skip()
can derive the visibility status of a block from whether or not we are in a
skippable range -- that is, whether or not the next_block is equal to the next
unskippable block.

ci-os-only:
---
 src/backend/access/heap/vacuumlazy.c | 230 ++++++++++++++-------------
 1 file changed, 117 insertions(+), 113 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 6f9c2446c56..5070c3fe744 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,14 +248,13 @@ typedef struct VacSkipState
 	BlockNumber next_unskippable_block;
 	/* Next unskippable block's visibility status */
 	bool		next_unskippable_allvis;
-	/* Whether or not skippable blocks should be skipped */
-	bool		skipping_current_range;
 } VacSkipState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
-						   BlockNumber next_block, Buffer *vmbuffer);
+static BlockNumber lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+								  BlockNumber blkno, Buffer *vmbuffer,
+								  bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -836,9 +835,12 @@ static void
 lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
-	VacSkipState vacskip;
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
+	VacSkipState vacskip = {.next_unskippable_block = InvalidBlockNumber};
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
@@ -854,37 +856,17 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, &vacskip, 0, &vmbuffer);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		LVPagePruneState prunestate;
 
-		if (blkno == vacskip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacskip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, &vacskip, blkno + 1, &vmbuffer);
-
-			Assert(vacskip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacskip.skipping_current_range)
-				continue;
+		blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
+									&vmbuffer, &all_visible_according_to_vm);
 
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
+		if (blkno == InvalidBlockNumber)
+			break;
 
 		vacrel->scanned_pages++;
 
@@ -1281,20 +1263,13 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
- *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in vacskip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *	lazy_scan_skip() -- get next block for vacuum to process
  *
- * vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * lazy_scan_skip() returns the next block that needs to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1304,14 +1279,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in vacskip->next_unskippable_block and next_unskippable_allvis.
- * vacskip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacskip->next_unskippable_block and next_unskippable_allvis. The caller
+ * should not concern itself with anything in vacskip. This is only used by
+ * lazy_scan_skip() to keep track of this state across invocations.
+ *
+ * lazy_scan_skip() returns the next block for vacuum to process and sets its
+ * visibility status in the output parameter, all_visible_according_to_vm.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1321,87 +1308,104 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
+static BlockNumber
 lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
-			   BlockNumber next_block, Buffer *vmbuffer)
+			   BlockNumber next_block, Buffer *vmbuffer,
+			   bool *all_visible_according_to_vm)
 {
 	bool		skipsallvis = false;
 
-	vacskip->next_unskippable_block = next_block;
-	vacskip->next_unskippable_allvis = true;
-	while (vacskip->next_unskippable_block < vacrel->rel_pages)
-	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   vacskip->next_unskippable_block,
-													   vmbuffer);
+	if (next_block >= vacrel->rel_pages)
+		return InvalidBlockNumber;
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	if (vacskip->next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacskip->next_unskippable_block)
+	{
+		while (++vacskip->next_unskippable_block < vacrel->rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacskip->next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   vacskip->next_unskippable_block,
+														   vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
-			break;
+			vacskip->next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacskip->next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacskip->next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacskip->next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		vacskip->next_unskippable_block++;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacskip->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacskip->next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
 	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacskip->next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacskip->skipping_current_range = false;
+	if (next_block == vacskip->next_unskippable_block)
+		*all_visible_according_to_vm = vacskip->next_unskippable_allvis;
 	else
-	{
-		vacskip->skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	return next_block;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v1-0005-VacSkipState-saves-reference-to-LVRelState.patch (4.9K, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/6-v1-0005-VacSkipState-saves-reference-to-LVRelState.patch)
  download | inline diff:
From 2fdb5fc93e8db3f885fc270a6742b8bd4c399aab Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 09:47:18 -0500
Subject: [PATCH v1 5/7] VacSkipState saves reference to LVRelState

The streaming read interface can only give pgsr_next callbacks access to
two pieces of private data. As such, move a reference to the LVRelState
into the VacSkipState.
---
 src/backend/access/heap/vacuumlazy.c | 36 ++++++++++++++++------------
 1 file changed, 21 insertions(+), 15 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 5070c3fe744..67020c2a807 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,11 +248,13 @@ typedef struct VacSkipState
 	BlockNumber next_unskippable_block;
 	/* Next unskippable block's visibility status */
 	bool		next_unskippable_allvis;
+	/* reference to whole relation vac state */
+	LVRelState *vacrel;
 } VacSkipState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+static BlockNumber lazy_scan_skip(VacSkipState *vacskip,
 								  BlockNumber blkno, Buffer *vmbuffer,
 								  bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
@@ -840,7 +842,10 @@ lazy_scan_heap(LVRelState *vacrel)
 
 	/* relies on InvalidBlockNumber overflowing to 0 */
 	BlockNumber blkno = InvalidBlockNumber;
-	VacSkipState vacskip = {.next_unskippable_block = InvalidBlockNumber};
+	VacSkipState vacskip = {
+		.next_unskippable_block = InvalidBlockNumber,
+		.vacrel = vacrel
+	};
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
@@ -862,8 +867,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Page		page;
 		LVPagePruneState prunestate;
 
-		blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
-									&vmbuffer, &all_visible_according_to_vm);
+		blkno = lazy_scan_skip(&vacskip, blkno + 1,
+							   &vmbuffer, &all_visible_according_to_vm);
 
 		if (blkno == InvalidBlockNumber)
 			break;
@@ -1290,9 +1295,10 @@ lazy_scan_heap(LVRelState *vacrel)
  * lazy_scan_skip() returns the next block for vacuum to process and sets its
  * visibility status in the output parameter, all_visible_according_to_vm.
  *
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ * vacskip->vacrel is an in/out parameter here; vacuum options and information
+ * about the relation are read and vacrel->skippedallvis is set to ensure we
+ * don't advance relfrozenxid when we have skipped vacuuming all visible
+ * blocks.
  *
  * vmbuffer will contain the block from the VM containing visibility
  * information for the next unskippable heap block. We may end up needed a
@@ -1309,21 +1315,21 @@ lazy_scan_heap(LVRelState *vacrel)
  * choice to skip such a range is actually made, making everything safe.)
  */
 static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+lazy_scan_skip(VacSkipState *vacskip,
 			   BlockNumber next_block, Buffer *vmbuffer,
 			   bool *all_visible_according_to_vm)
 {
 	bool		skipsallvis = false;
 
-	if (next_block >= vacrel->rel_pages)
+	if (next_block >= vacskip->vacrel->rel_pages)
 		return InvalidBlockNumber;
 
 	if (vacskip->next_unskippable_block == InvalidBlockNumber ||
 		next_block > vacskip->next_unskippable_block)
 	{
-		while (++vacskip->next_unskippable_block < vacrel->rel_pages)
+		while (++vacskip->next_unskippable_block < vacskip->vacrel->rel_pages)
 		{
-			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+			uint8		mapbits = visibilitymap_get_status(vacskip->vacrel->rel,
 														   vacskip->next_unskippable_block,
 														   vmbuffer);
 
@@ -1347,11 +1353,11 @@ lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
 			 * Implement this by always treating the last block as unsafe to
 			 * skip.
 			 */
-			if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
+			if (vacskip->next_unskippable_block == vacskip->vacrel->rel_pages - 1)
 				break;
 
 			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-			if (!vacrel->skipwithvm)
+			if (!vacskip->vacrel->skipwithvm)
 			{
 				/* Caller shouldn't rely on all_visible_according_to_vm */
 				vacskip->next_unskippable_allvis = false;
@@ -1366,7 +1372,7 @@ lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
 			 */
 			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
 			{
-				if (vacrel->aggressive)
+				if (vacskip->vacrel->aggressive)
 					break;
 
 				/*
@@ -1396,7 +1402,7 @@ lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
 		{
 			next_block = vacskip->next_unskippable_block;
 			if (skipsallvis)
-				vacrel->skippedallvis = true;
+				vacskip->vacrel->skippedallvis = true;
 		}
 	}
 
-- 
2.37.2



  [text/x-patch] v1-0006-VacSkipState-store-next-unskippable-block-vmbuffe.patch (6.8K, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/7-v1-0006-VacSkipState-store-next-unskippable-block-vmbuffe.patch)
  download | inline diff:
From a9d0592b7a54686968c4872323f5e45b809379c2 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 11:20:07 -0500
Subject: [PATCH v1 6/7] VacSkipState store next unskippable block vmbuffer

This fits nicely with the other state in VacSkipState.
---
 src/backend/access/heap/vacuumlazy.c | 47 ++++++++++++++++------------
 1 file changed, 27 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 67020c2a807..49d16fcf039 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,6 +248,8 @@ typedef struct VacSkipState
 	BlockNumber next_unskippable_block;
 	/* Next unskippable block's visibility status */
 	bool		next_unskippable_allvis;
+	/* Next unskippable block's vmbuffer */
+	Buffer		vmbuffer;
 	/* reference to whole relation vac state */
 	LVRelState *vacrel;
 } VacSkipState;
@@ -255,7 +257,7 @@ typedef struct VacSkipState
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
 static BlockNumber lazy_scan_skip(VacSkipState *vacskip,
-								  BlockNumber blkno, Buffer *vmbuffer,
+								  BlockNumber blkno,
 								  bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -844,10 +846,10 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber blkno = InvalidBlockNumber;
 	VacSkipState vacskip = {
 		.next_unskippable_block = InvalidBlockNumber,
+		.vmbuffer = InvalidBuffer,
 		.vacrel = vacrel
 	};
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -868,7 +870,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		LVPagePruneState prunestate;
 
 		blkno = lazy_scan_skip(&vacskip, blkno + 1,
-							   &vmbuffer, &all_visible_according_to_vm);
+							   &all_visible_according_to_vm);
 
 		if (blkno == InvalidBlockNumber)
 			break;
@@ -909,10 +911,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacskip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacskip.vmbuffer);
+				vacskip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -937,7 +939,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacskip.vmbuffer);
 
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
@@ -957,7 +959,7 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/* Check for new or empty pages before lazy_scan_noprune call */
 			if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, true,
-									   vmbuffer))
+									   vacskip.vmbuffer))
 			{
 				/* Processed as new/empty page (lock and pin released) */
 				continue;
@@ -995,7 +997,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		}
 
 		/* Check for new or empty pages before lazy_scan_prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, false, vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, false,
+								   vacskip.vmbuffer))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -1032,7 +1035,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			{
 				Size		freespace;
 
-				lazy_vacuum_heap_page(vacrel, blkno, buf, 0, vmbuffer);
+				lazy_vacuum_heap_page(vacrel, blkno, buf, 0, vacskip.vmbuffer);
 
 				/* Forget the LP_DEAD items that we just vacuumed */
 				dead_items->num_items = 0;
@@ -1111,7 +1114,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			PageSetAllVisible(page);
 			MarkBufferDirty(buf);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, prunestate.visibility_cutoff_xid,
+							  vacskip.vmbuffer, prunestate.visibility_cutoff_xid,
 							  flags);
 		}
 
@@ -1122,11 +1125,12 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * with buffer lock before concluding that the VM is corrupt.
 		 */
 		else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-				 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+				 visibilitymap_get_status(vacrel->rel,
+										  blkno, &vacskip.vmbuffer) != 0)
 		{
 			elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 				 vacrel->relname, blkno);
-			visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+			visibilitymap_clear(vacrel->rel, blkno, vacskip.vmbuffer,
 								VISIBILITYMAP_VALID_BITS);
 		}
 
@@ -1151,7 +1155,7 @@ lazy_scan_heap(LVRelState *vacrel)
 				 vacrel->relname, blkno);
 			PageClearAllVisible(page);
 			MarkBufferDirty(buf);
-			visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+			visibilitymap_clear(vacrel->rel, blkno, vacskip.vmbuffer,
 								VISIBILITYMAP_VALID_BITS);
 		}
 
@@ -1162,7 +1166,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		else if (all_visible_according_to_vm && prunestate.all_visible &&
 				 prunestate.all_frozen &&
-				 !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+				 !VM_ALL_FROZEN(vacrel->rel, blkno, &vacskip.vmbuffer))
 		{
 			/*
 			 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1184,7 +1188,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			 */
 			Assert(!TransactionIdIsValid(prunestate.visibility_cutoff_xid));
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacskip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE |
 							  VISIBILITYMAP_ALL_FROZEN);
 		}
@@ -1226,8 +1230,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacskip.vmbuffer))
+	{
+		ReleaseBuffer(vacskip.vmbuffer);
+		vacskip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1316,7 +1323,7 @@ lazy_scan_heap(LVRelState *vacrel)
  */
 static BlockNumber
 lazy_scan_skip(VacSkipState *vacskip,
-			   BlockNumber next_block, Buffer *vmbuffer,
+			   BlockNumber next_block,
 			   bool *all_visible_according_to_vm)
 {
 	bool		skipsallvis = false;
@@ -1331,7 +1338,7 @@ lazy_scan_skip(VacSkipState *vacskip,
 		{
 			uint8		mapbits = visibilitymap_get_status(vacskip->vacrel->rel,
 														   vacskip->next_unskippable_block,
-														   vmbuffer);
+														   &vacskip->vmbuffer);
 
 			vacskip->next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-- 
2.37.2



  [text/x-patch] v1-0007-Remove-unneeded-vacuum_delay_point-from-lazy_scan.patch (918B, ../../CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA@mail.gmail.com/8-v1-0007-Remove-unneeded-vacuum_delay_point-from-lazy_scan.patch)
  download | inline diff:
From b1fe24867172da232456b7e452178bf8adbf0538 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v1 7/7] Remove unneeded vacuum_delay_point from lazy_scan_skip

lazy_scan_skip() does relatively little work, so there is no need to
call vacuum_delay_point(). A future commit will call lazy_scan_skip()
from a callback, and we would like to avoid calling vacuum_delay_point()
in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 49d16fcf039..fc32610397b 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1389,8 +1389,6 @@ lazy_scan_skip(VacSkipState *vacskip,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		/*
-- 
2.37.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-01-02 17:36 ` Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-01-02 17:36 UTC (permalink / raw)
  To: pgsql-hackers; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; Nazir Bilal Yavuz <byavuz81@gmail.com>

On Sun, Dec 31, 2023 at 1:28 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> There are a few comments that still need to be updated. I also noticed I
> needed to reorder and combine a couple of the commits. I wanted to
> register this for the january commitfest, so I didn't quite have time
> for the finishing touches.

I've updated this patch set to remove a commit that didn't make sense
on its own and do various other cleanup.

- Melanie

Attachments:

  [text/x-patch] v2-0004-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (13.3K, ../../CAAKRu_aK68L=YbMf4rtksxk-kz4dnmMZmjJwohjVf0FTSpgXdw@mail.gmail.com/2-v2-0004-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 335faad5948b2bec3b83c2db809bb9161d373dcb Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v2 4/6] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and eventually
AIO), refactor vacuum's logic for skipping blocks such that it is entirely
confined to lazy_scan_skip(). This turns lazy_scan_skip() and the VacSkipState
it uses into an iterator which yields blocks to lazy_scan_heap(). Such a
structure is conducive to an async interface.

By always calling lazy_scan_skip() -- instead of only when we have reached the
next unskippable block, we no longer need the skipping_current_range variable.
lazy_scan_heap() no longer needs to manage the skipped range -- checking if we
reached the end in order to then call lazy_scan_skip(). And lazy_scan_skip()
can derive the visibility status of a block from whether or not we are in a
skippable range -- that is, whether or not the next_block is equal to the next
unskippable block.
---
 src/backend/access/heap/vacuumlazy.c | 233 ++++++++++++++-------------
 1 file changed, 120 insertions(+), 113 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index e3827a5e4d3..42da4ac64f8 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -250,14 +250,13 @@ typedef struct VacSkipState
 	Buffer		vmbuffer;
 	/* Next unskippable block's visibility status */
 	bool		next_unskippable_allvis;
-	/* Whether or not skippable blocks should be skipped */
-	bool		skipping_current_range;
 } VacSkipState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
-						   BlockNumber next_block);
+static BlockNumber lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+								  BlockNumber blkno,
+								  bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -838,9 +837,15 @@ static void
 lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
-	VacSkipState vacskip = {.vmbuffer = InvalidBuffer};
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
+	VacSkipState vacskip = {
+		.next_unskippable_block = InvalidBlockNumber,
+		.vmbuffer = InvalidBuffer
+	};
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -855,37 +860,17 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, &vacskip, 0);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		LVPagePruneState prunestate;
 
-		if (blkno == vacskip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacskip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, &vacskip, blkno + 1);
-
-			Assert(vacskip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacskip.skipping_current_range)
-				continue;
+		blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
+							   &all_visible_according_to_vm);
 
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
+		if (blkno == InvalidBlockNumber)
+			break;
 
 		vacrel->scanned_pages++;
 
@@ -1287,20 +1272,13 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
- *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in vacskip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *	lazy_scan_skip() -- get next block for vacuum to process
  *
- * vacskip->vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * lazy_scan_skip() returns the next block that needs to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1310,14 +1288,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in vacskip->next_unskippable_block and next_unskippable_allvis.
- * vacskip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacskip->next_unskippable_block and next_unskippable_allvis. The caller
+ * should not concern itself with anything in vacskip. This is only used by
+ * lazy_scan_skip() to keep track of this state across invocations.
+ *
+ * lazy_scan_skip() returns the next block for vacuum to process and sets its
+ * visibility status in the output parameter, all_visible_according_to_vm.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * vacskip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1327,87 +1317,104 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
+static BlockNumber
 lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
-			   BlockNumber next_block)
+			   BlockNumber next_block,
+			   bool *all_visible_according_to_vm)
 {
 	bool		skipsallvis = false;
 
-	vacskip->next_unskippable_block = next_block;
-	vacskip->next_unskippable_allvis = true;
-	while (vacskip->next_unskippable_block < vacrel->rel_pages)
-	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   vacskip->next_unskippable_block,
-													   &vacskip->vmbuffer);
+	if (next_block >= vacrel->rel_pages)
+		return InvalidBlockNumber;
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	if (vacskip->next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacskip->next_unskippable_block)
+	{
+		while (++vacskip->next_unskippable_block < vacrel->rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacskip->next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   vacskip->next_unskippable_block,
+														   &vacskip->vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
-			break;
+			vacskip->next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacskip->next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacskip->next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacskip->next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		vacskip->next_unskippable_block++;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacskip->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacskip->next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
 	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacskip->next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacskip->skipping_current_range = false;
+	if (next_block == vacskip->next_unskippable_block)
+		*all_visible_according_to_vm = vacskip->next_unskippable_allvis;
 	else
-	{
-		vacskip->skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	return next_block;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v2-0003-Add-lazy_scan_skip-unskippable-state.patch (13.9K, ../../CAAKRu_aK68L=YbMf4rtksxk-kz4dnmMZmjJwohjVf0FTSpgXdw@mail.gmail.com/3-v2-0003-Add-lazy_scan_skip-unskippable-state.patch)
  download | inline diff:
From eea3c207eeaf7c390096dcb48fc062d81d6d7cc3 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v2 3/6] Add lazy_scan_skip unskippable state

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce the struct, VacSkipState, which will maintain the variables
needed to skip ranges less than SKIP_PAGES_THRESHOLD.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 145 ++++++++++++++++-----------
 src/tools/pgindent/typedefs.list     |   1 +
 2 files changed, 87 insertions(+), 59 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3b28ea2cdb5..e3827a5e4d3 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -238,13 +238,26 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+/*
+ * Parameters maintained by lazy_scan_skip() to manage skipping ranges of pages
+ * greater than SKIP_PAGES_THRESHOLD.
+ */
+typedef struct VacSkipState
+{
+	/* Next unskippable block */
+	BlockNumber next_unskippable_block;
+	/* Buffer containing next unskippable block's visibility info */
+	Buffer		vmbuffer;
+	/* Next unskippable block's visibility status */
+	bool		next_unskippable_allvis;
+	/* Whether or not skippable blocks should be skipped */
+	bool		skipping_current_range;
+} VacSkipState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+						   BlockNumber next_block);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -826,12 +839,9 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
+	VacSkipState vacskip = {.vmbuffer = InvalidBuffer};
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -846,9 +856,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, &vacskip, 0);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -856,26 +864,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		all_visible_according_to_vm;
 		LVPagePruneState prunestate;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacskip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacskip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, &vacskip, blkno + 1);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacskip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacskip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -918,10 +923,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacskip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacskip.vmbuffer);
+				vacskip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -946,7 +951,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacskip.vmbuffer);
 
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
@@ -966,7 +971,7 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/* Check for new or empty pages before lazy_scan_noprune call */
 			if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, true,
-									   vmbuffer))
+									   vacskip.vmbuffer))
 			{
 				/* Processed as new/empty page (lock and pin released) */
 				continue;
@@ -1004,7 +1009,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		}
 
 		/* Check for new or empty pages before lazy_scan_prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, false, vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, false,
+								   vacskip.vmbuffer))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -1041,7 +1047,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			{
 				Size		freespace;
 
-				lazy_vacuum_heap_page(vacrel, blkno, buf, 0, vmbuffer);
+				lazy_vacuum_heap_page(vacrel, blkno, buf, 0, vacskip.vmbuffer);
 
 				/* Forget the LP_DEAD items that we just vacuumed */
 				dead_items->num_items = 0;
@@ -1120,7 +1126,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			PageSetAllVisible(page);
 			MarkBufferDirty(buf);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, prunestate.visibility_cutoff_xid,
+							  vacskip.vmbuffer, prunestate.visibility_cutoff_xid,
 							  flags);
 		}
 
@@ -1131,11 +1137,12 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * with buffer lock before concluding that the VM is corrupt.
 		 */
 		else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-				 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+				 visibilitymap_get_status(vacrel->rel, blkno,
+										  &vacskip.vmbuffer) != 0)
 		{
 			elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 				 vacrel->relname, blkno);
-			visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+			visibilitymap_clear(vacrel->rel, blkno, vacskip.vmbuffer,
 								VISIBILITYMAP_VALID_BITS);
 		}
 
@@ -1160,7 +1167,7 @@ lazy_scan_heap(LVRelState *vacrel)
 				 vacrel->relname, blkno);
 			PageClearAllVisible(page);
 			MarkBufferDirty(buf);
-			visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+			visibilitymap_clear(vacrel->rel, blkno, vacskip.vmbuffer,
 								VISIBILITYMAP_VALID_BITS);
 		}
 
@@ -1171,7 +1178,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		else if (all_visible_according_to_vm && prunestate.all_visible &&
 				 prunestate.all_frozen &&
-				 !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+				 !VM_ALL_FROZEN(vacrel->rel, blkno, &vacskip.vmbuffer))
 		{
 			/*
 			 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1193,7 +1200,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			 */
 			Assert(!TransactionIdIsValid(prunestate.visibility_cutoff_xid));
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacskip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE |
 							  VISIBILITYMAP_ALL_FROZEN);
 		}
@@ -1235,8 +1242,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacskip.vmbuffer))
+	{
+		ReleaseBuffer(vacskip.vmbuffer);
+		vacskip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1280,15 +1290,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in vacskip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * vacskip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
+ *
+ * The block number and visibility status of the next unskippable block are set
+ * in vacskip->next_unskippable_block and next_unskippable_allvis.
+ * vacskip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1298,24 +1327,24 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+			   BlockNumber next_block)
 {
-	BlockNumber next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
-	while (next_unskippable_block < vacrel->rel_pages)
+	vacskip->next_unskippable_block = next_block;
+	vacskip->next_unskippable_allvis = true;
+	while (vacskip->next_unskippable_block < vacrel->rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   vmbuffer);
+													   vacskip->next_unskippable_block,
+													   &vacskip->vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacskip->next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1329,14 +1358,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		 *
 		 * Implement this by always treating the last block as unsafe to skip.
 		 */
-		if (next_unskippable_block == vacrel->rel_pages - 1)
+		if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
 			break;
 
 		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacskip->next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1358,7 +1387,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		}
 
 		vacuum_delay_point();
-		next_unskippable_block++;
+		vacskip->next_unskippable_block++;
 	}
 
 	/*
@@ -1371,16 +1400,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacskip->next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacskip->skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacskip->skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index e37ef9aa76d..bd008e1699b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2955,6 +2955,7 @@ VacOptValue
 VacuumParams
 VacuumRelation
 VacuumStmt
+VacSkipState
 ValidIOData
 ValidateIndexState
 ValuesScan
-- 
2.37.2



  [text/x-patch] v2-0001-lazy_scan_skip-remove-unnecessary-local-var-rel_p.patch (1.6K, ../../CAAKRu_aK68L=YbMf4rtksxk-kz4dnmMZmjJwohjVf0FTSpgXdw@mail.gmail.com/4-v2-0001-lazy_scan_skip-remove-unnecessary-local-var-rel_p.patch)
  download | inline diff:
From 9cd579d6a20aef2aeeab6ef50d72e779d75bf7cd Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:18:40 -0500
Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages

lazy_scan_skip() only uses vacrel->rel_pages twice, so there seems to be
no reason to save it in a local variable, rel_pages.
---
 src/backend/access/heap/vacuumlazy.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3b9299b8924..c4e0c077694 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1302,13 +1302,12 @@ static BlockNumber
 lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
+	BlockNumber next_unskippable_block = next_block,
 				nskippable_blocks = 0;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	while (next_unskippable_block < vacrel->rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
@@ -1331,7 +1330,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		 *
 		 * Implement this by always treating the last block as unsafe to skip.
 		 */
-		if (next_unskippable_block == rel_pages - 1)
+		if (next_unskippable_block == vacrel->rel_pages - 1)
 			break;
 
 		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-- 
2.37.2



  [text/x-patch] v2-0002-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.6K, ../../CAAKRu_aK68L=YbMf4rtksxk-kz4dnmMZmjJwohjVf0FTSpgXdw@mail.gmail.com/5-v2-0002-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From 314dd9038593610583e4fe60ab62e0d46ea3be86 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index c4e0c077694..3b28ea2cdb5 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1302,8 +1302,7 @@ static BlockNumber
 lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
-	BlockNumber next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+	BlockNumber next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1360,7 +1359,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1373,7 +1371,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.37.2



  [text/x-patch] v2-0005-VacSkipState-saves-reference-to-LVRelState.patch (5.1K, ../../CAAKRu_aK68L=YbMf4rtksxk-kz4dnmMZmjJwohjVf0FTSpgXdw@mail.gmail.com/6-v2-0005-VacSkipState-saves-reference-to-LVRelState.patch)
  download | inline diff:
From b6603e35147c4bbe3337280222e6243524b0110e Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 09:47:18 -0500
Subject: [PATCH v2 5/6] VacSkipState saves reference to LVRelState

The streaming read interface can only give pgsr_next callbacks access to
two pieces of private data. As such, move a reference to the LVRelState
into the VacSkipState.

This is a separate commit (as opposed to as part of the commit
introducing VacSkipState) because it is required for using the streaming
read interface but not a natural change on its own. VacSkipState is per
block and the LVRelState is referenced for the whole relation vacuum.
---
 src/backend/access/heap/vacuumlazy.c | 35 +++++++++++++++-------------
 1 file changed, 19 insertions(+), 16 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 42da4ac64f8..1b64b9988de 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -250,11 +250,13 @@ typedef struct VacSkipState
 	Buffer		vmbuffer;
 	/* Next unskippable block's visibility status */
 	bool		next_unskippable_allvis;
+	/* reference to whole relation vac state */
+	LVRelState *vacrel;
 } VacSkipState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
+static BlockNumber lazy_scan_skip(VacSkipState *vacskip,
 								  BlockNumber blkno,
 								  bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
@@ -844,7 +846,8 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber blkno = InvalidBlockNumber;
 	VacSkipState vacskip = {
 		.next_unskippable_block = InvalidBlockNumber,
-		.vmbuffer = InvalidBuffer
+		.vmbuffer = InvalidBuffer,
+		.vacrel = vacrel
 	};
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
@@ -866,7 +869,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		Page		page;
 		LVPagePruneState prunestate;
 
-		blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
+		blkno = lazy_scan_skip(&vacskip, blkno + 1,
 							   &all_visible_according_to_vm);
 
 		if (blkno == InvalidBlockNumber)
@@ -1299,9 +1302,10 @@ lazy_scan_heap(LVRelState *vacrel)
  * lazy_scan_skip() returns the next block for vacuum to process and sets its
  * visibility status in the output parameter, all_visible_according_to_vm.
  *
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ * vacskip->vacrel is an in/out parameter here; vacuum options and information
+ * about the relation are read and vacrel->skippedallvis is set to ensure we
+ * don't advance relfrozenxid when we have skipped vacuuming all visible
+ * blocks.
  *
  * vacskip->vmbuffer will contain the block from the VM containing visibility
  * information for the next unskippable heap block. We may end up needed a
@@ -1318,21 +1322,20 @@ lazy_scan_heap(LVRelState *vacrel)
  * choice to skip such a range is actually made, making everything safe.)
  */
 static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
-			   BlockNumber next_block,
-			   bool *all_visible_according_to_vm)
+lazy_scan_skip(VacSkipState *vacskip,
+			   BlockNumber next_block, bool *all_visible_according_to_vm)
 {
 	bool		skipsallvis = false;
 
-	if (next_block >= vacrel->rel_pages)
+	if (next_block >= vacskip->vacrel->rel_pages)
 		return InvalidBlockNumber;
 
 	if (vacskip->next_unskippable_block == InvalidBlockNumber ||
 		next_block > vacskip->next_unskippable_block)
 	{
-		while (++vacskip->next_unskippable_block < vacrel->rel_pages)
+		while (++vacskip->next_unskippable_block < vacskip->vacrel->rel_pages)
 		{
-			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+			uint8		mapbits = visibilitymap_get_status(vacskip->vacrel->rel,
 														   vacskip->next_unskippable_block,
 														   &vacskip->vmbuffer);
 
@@ -1356,11 +1359,11 @@ lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
 			 * Implement this by always treating the last block as unsafe to
 			 * skip.
 			 */
-			if (vacskip->next_unskippable_block == vacrel->rel_pages - 1)
+			if (vacskip->next_unskippable_block == vacskip->vacrel->rel_pages - 1)
 				break;
 
 			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-			if (!vacrel->skipwithvm)
+			if (!vacskip->vacrel->skipwithvm)
 			{
 				/* Caller shouldn't rely on all_visible_according_to_vm */
 				vacskip->next_unskippable_allvis = false;
@@ -1375,7 +1378,7 @@ lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
 			 */
 			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
 			{
-				if (vacrel->aggressive)
+				if (vacskip->vacrel->aggressive)
 					break;
 
 				/*
@@ -1405,7 +1408,7 @@ lazy_scan_skip(LVRelState *vacrel, VacSkipState *vacskip,
 		{
 			next_block = vacskip->next_unskippable_block;
 			if (skipsallvis)
-				vacrel->skippedallvis = true;
+				vacskip->vacrel->skippedallvis = true;
 		}
 	}
 
-- 
2.37.2



  [text/x-patch] v2-0006-Remove-unneeded-vacuum_delay_point-from-lazy_scan.patch (918B, ../../CAAKRu_aK68L=YbMf4rtksxk-kz4dnmMZmjJwohjVf0FTSpgXdw@mail.gmail.com/7-v2-0006-Remove-unneeded-vacuum_delay_point-from-lazy_scan.patch)
  download | inline diff:
From aa948b99c09f2fdf9a10deac78bcb880e09366ec Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v2 6/6] Remove unneeded vacuum_delay_point from lazy_scan_skip

lazy_scan_skip() does relatively little work, so there is no need to
call vacuum_delay_point(). A future commit will call lazy_scan_skip()
from a callback, and we would like to avoid calling vacuum_delay_point()
in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1b64b9988de..1329da95254 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1388,8 +1388,6 @@ lazy_scan_skip(VacSkipState *vacskip,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		/*
-- 
2.37.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-01-04 20:23   ` Andres Freund <andres@anarazel.de>
  2024-01-04 23:25     ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Andres Freund @ 2024-01-04 20:23 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>

Hi,

On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
> Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
> Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
>  nskippable_blocks

I think these may lead to worse code - the compiler has to reload
vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
can't guarantee that they're not changed within one of the external functions
called in the loop body.

> Subject: [PATCH v2 3/6] Add lazy_scan_skip unskippable state
> 
> Future commits will remove all skipping logic from lazy_scan_heap() and
> confine it to lazy_scan_skip(). To make those commits more clear, first
> introduce the struct, VacSkipState, which will maintain the variables
> needed to skip ranges less than SKIP_PAGES_THRESHOLD.

Why not add this to LVRelState, possibly as a struct embedded within it?


> From 335faad5948b2bec3b83c2db809bb9161d373dcb Mon Sep 17 00:00:00 2001
> From: Melanie Plageman <melanieplageman@gmail.com>
> Date: Sat, 30 Dec 2023 16:59:27 -0500
> Subject: [PATCH v2 4/6] Confine vacuum skip logic to lazy_scan_skip
> 
> In preparation for vacuum to use the streaming read interface (and eventually
> AIO), refactor vacuum's logic for skipping blocks such that it is entirely
> confined to lazy_scan_skip(). This turns lazy_scan_skip() and the VacSkipState
> it uses into an iterator which yields blocks to lazy_scan_heap(). Such a
> structure is conducive to an async interface.

And it's cleaner - I find the current code extremely hard to reason about.


> By always calling lazy_scan_skip() -- instead of only when we have reached the
> next unskippable block, we no longer need the skipping_current_range variable.
> lazy_scan_heap() no longer needs to manage the skipped range -- checking if we
> reached the end in order to then call lazy_scan_skip(). And lazy_scan_skip()
> can derive the visibility status of a block from whether or not we are in a
> skippable range -- that is, whether or not the next_block is equal to the next
> unskippable block.

I wonder if it should be renamed as part of this - the name is somewhat
confusing now (and perhaps before)? lazy_scan_get_next_block() or such?


> +	while (true)
>  	{
>  		Buffer		buf;
>  		Page		page;
> -		bool		all_visible_according_to_vm;
>  		LVPagePruneState prunestate;
>  
> -		if (blkno == vacskip.next_unskippable_block)
> -		{
> -			/*
> -			 * Can't skip this page safely.  Must scan the page.  But
> -			 * determine the next skippable range after the page first.
> -			 */
> -			all_visible_according_to_vm = vacskip.next_unskippable_allvis;
> -			lazy_scan_skip(vacrel, &vacskip, blkno + 1);
> -
> -			Assert(vacskip.next_unskippable_block >= blkno + 1);
> -		}
> -		else
> -		{
> -			/* Last page always scanned (may need to set nonempty_pages) */
> -			Assert(blkno < rel_pages - 1);
> -
> -			if (vacskip.skipping_current_range)
> -				continue;
> +		blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
> +							   &all_visible_according_to_vm);
>  
> -			/* Current range is too small to skip -- just scan the page */
> -			all_visible_according_to_vm = true;
> -		}
> +		if (blkno == InvalidBlockNumber)
> +			break;
>  
>  		vacrel->scanned_pages++;
>

I don't like that we still do determination about the next block outside of
lazy_scan_skip() and have duplicated exit conditions between lazy_scan_skip()
and lazy_scan_heap().

I'd probably change the interface to something like

while (lazy_scan_get_next_block(vacrel, &blkno))
{
...
}


> From b6603e35147c4bbe3337280222e6243524b0110e Mon Sep 17 00:00:00 2001
> From: Melanie Plageman <melanieplageman@gmail.com>
> Date: Sun, 31 Dec 2023 09:47:18 -0500
> Subject: [PATCH v2 5/6] VacSkipState saves reference to LVRelState
> 
> The streaming read interface can only give pgsr_next callbacks access to
> two pieces of private data. As such, move a reference to the LVRelState
> into the VacSkipState.
> 
> This is a separate commit (as opposed to as part of the commit
> introducing VacSkipState) because it is required for using the streaming
> read interface but not a natural change on its own. VacSkipState is per
> block and the LVRelState is referenced for the whole relation vacuum.

I'd do it the other way round, i.e. either embed VacSkipState ino LVRelState
or point to it from VacSkipState.

LVRelState is already tied to the iteration state, so I don't think there's a
reason not to do so.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
@ 2024-01-04 23:25     ` Jim Nasby <jim.nasby@gmail.com>
  2024-01-05 10:51       ` Re: Confine vacuum skip logic to lazy_scan_skip Nazir Bilal Yavuz <byavuz81@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Jim Nasby @ 2024-01-04 23:25 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; Melanie Plageman <melanieplageman@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <div class="moz-cite-prefix">On 1/4/24 2:23 PM, Andres Freund wrote:<br>
    </div>
    <blockquote type="cite"
      cite="mid:20240104202309.77h5llrambkl5a3m@awork3.anarazel.de">
      <pre><pre class="moz-quote-pre" wrap="">On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
</pre><blockquote type="cite" style="color: #007cff;"><pre
      class="moz-quote-pre" wrap="">Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
 nskippable_blocks
</pre></blockquote><pre class="moz-quote-pre" wrap="">I think these may lead to worse code - the compiler has to reload
vacrel-&gt;rel_pages/next_unskippable_block for every loop iteration, because it
can't guarantee that they're not changed within one of the external functions
called in the loop body.</pre></pre>
    </blockquote>
    <p>Admittedly I'm not up to speed on recent vacuum changes, but I
      have to wonder if the concept of skipping should go away in the
      context of vector IO? Instead of thinking about "we can skip this
      range of blocks", why not maintain a list of "here's the next X
      number of blocks that we need to vacuum"?<br>
    </p>
    <pre class="moz-signature" cols="72">-- 
Jim Nasby, Data Architect, Austin TX</pre>
  </body>
</html>





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-04 23:25     ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
@ 2024-01-05 10:51       ` Nazir Bilal Yavuz <byavuz81@gmail.com>
  2024-01-11 23:50         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Nazir Bilal Yavuz @ 2024-01-05 10:51 UTC (permalink / raw)
  To: Jim Nasby <jim.nasby@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Melanie Plageman <melanieplageman@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>

Hi,

On Fri, 5 Jan 2024 at 02:25, Jim Nasby <jim.nasby@gmail.com> wrote:
>
> On 1/4/24 2:23 PM, Andres Freund wrote:
>
> On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
>
> Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
> Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
>  nskippable_blocks
>
> I think these may lead to worse code - the compiler has to reload
> vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
> can't guarantee that they're not changed within one of the external functions
> called in the loop body.
>
> Admittedly I'm not up to speed on recent vacuum changes, but I have to wonder if the concept of skipping should go away in the context of vector IO? Instead of thinking about "we can skip this range of blocks", why not maintain a list of "here's the next X number of blocks that we need to vacuum"?

Sorry if I misunderstood. AFAIU, with the help of the vectored IO;
"the next X number of blocks that need to be vacuumed" will be
prefetched by calculating the unskippable blocks ( using the
lazy_scan_skip() function ) and the X will be determined by Postgres
itself. Do you have something different in your mind?

-- 
Regards,
Nazir Bilal Yavuz
Microsoft





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-04 23:25     ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
  2024-01-05 10:51       ` Re: Confine vacuum skip logic to lazy_scan_skip Nazir Bilal Yavuz <byavuz81@gmail.com>
@ 2024-01-11 23:50         ` Melanie Plageman <melanieplageman@gmail.com>
  2024-01-12 19:02           ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-01-11 23:50 UTC (permalink / raw)
  To: Nazir Bilal Yavuz <byavuz81@gmail.com>; +Cc: Jim Nasby <jim.nasby@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>

On Fri, Jan 5, 2024 at 5:51 AM Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:
>
> On Fri, 5 Jan 2024 at 02:25, Jim Nasby <jim.nasby@gmail.com> wrote:
> >
> > On 1/4/24 2:23 PM, Andres Freund wrote:
> >
> > On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
> >
> > Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
> > Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
> >  nskippable_blocks
> >
> > I think these may lead to worse code - the compiler has to reload
> > vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
> > can't guarantee that they're not changed within one of the external functions
> > called in the loop body.
> >
> > Admittedly I'm not up to speed on recent vacuum changes, but I have to wonder if the concept of skipping should go away in the context of vector IO? Instead of thinking about "we can skip this range of blocks", why not maintain a list of "here's the next X number of blocks that we need to vacuum"?
>
> Sorry if I misunderstood. AFAIU, with the help of the vectored IO;
> "the next X number of blocks that need to be vacuumed" will be
> prefetched by calculating the unskippable blocks ( using the
> lazy_scan_skip() function ) and the X will be determined by Postgres
> itself. Do you have something different in your mind?

I think you are both right. As we gain more control of readahead from
within Postgres, we will likely want to revisit this heuristic as it
may not serve us anymore. But the streaming read interface/vectored
I/O is also not a drop-in replacement for it. To change anything and
ensure there is no regression, we will probably have to do
cross-platform benchmarking, though.

That being said, I would absolutely love to get rid of the skippable
ranges because I find them very error-prone and confusing. Hopefully
now that the skipping logic is isolated to a single function, it will
be easier not to trip over it when working on lazy_scan_heap().

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-04 23:25     ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
  2024-01-05 10:51       ` Re: Confine vacuum skip logic to lazy_scan_skip Nazir Bilal Yavuz <byavuz81@gmail.com>
  2024-01-11 23:50         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-01-12 19:02           ` Jim Nasby <jim.nasby@gmail.com>
  2024-01-12 19:09             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Jim Nasby @ 2024-01-12 19:02 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>

On 1/11/24 5:50 PM, Melanie Plageman wrote:
> On Fri, Jan 5, 2024 at 5:51 AM Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:
>>
>> On Fri, 5 Jan 2024 at 02:25, Jim Nasby <jim.nasby@gmail.com> wrote:
>>>
>>> On 1/4/24 2:23 PM, Andres Freund wrote:
>>>
>>> On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
>>>
>>> Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
>>> Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
>>>   nskippable_blocks
>>>
>>> I think these may lead to worse code - the compiler has to reload
>>> vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
>>> can't guarantee that they're not changed within one of the external functions
>>> called in the loop body.
>>>
>>> Admittedly I'm not up to speed on recent vacuum changes, but I have to wonder if the concept of skipping should go away in the context of vector IO? Instead of thinking about "we can skip this range of blocks", why not maintain a list of "here's the next X number of blocks that we need to vacuum"?
>>
>> Sorry if I misunderstood. AFAIU, with the help of the vectored IO;
>> "the next X number of blocks that need to be vacuumed" will be
>> prefetched by calculating the unskippable blocks ( using the
>> lazy_scan_skip() function ) and the X will be determined by Postgres
>> itself. Do you have something different in your mind?
> 
> I think you are both right. As we gain more control of readahead from
> within Postgres, we will likely want to revisit this heuristic as it
> may not serve us anymore. But the streaming read interface/vectored
> I/O is also not a drop-in replacement for it. To change anything and
> ensure there is no regression, we will probably have to do
> cross-platform benchmarking, though.
> 
> That being said, I would absolutely love to get rid of the skippable
> ranges because I find them very error-prone and confusing. Hopefully
> now that the skipping logic is isolated to a single function, it will
> be easier not to trip over it when working on lazy_scan_heap().

Yeah, arguably it's just a matter of semantics, but IMO it's a lot 
clearer to simply think in terms of "here's the next blocks we know we 
want to vacuum" instead of "we vacuum everything, but sometimes we skip 
some blocks".
-- 
Jim Nasby, Data Architect, Austin TX






^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-04 23:25     ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
  2024-01-05 10:51       ` Re: Confine vacuum skip logic to lazy_scan_skip Nazir Bilal Yavuz <byavuz81@gmail.com>
  2024-01-11 23:50         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-12 19:02           ` Re: Confine vacuum skip logic to lazy_scan_skip Jim Nasby <jim.nasby@gmail.com>
@ 2024-01-12 19:09             ` Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-01-12 19:09 UTC (permalink / raw)
  To: Jim Nasby <jim.nasby@gmail.com>; +Cc: Nazir Bilal Yavuz <byavuz81@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>

On Fri, Jan 12, 2024 at 2:02 PM Jim Nasby <jim.nasby@gmail.com> wrote:
>
> On 1/11/24 5:50 PM, Melanie Plageman wrote:
> > On Fri, Jan 5, 2024 at 5:51 AM Nazir Bilal Yavuz <byavuz81@gmail.com> wrote:
> >>
> >> On Fri, 5 Jan 2024 at 02:25, Jim Nasby <jim.nasby@gmail.com> wrote:
> >>>
> >>> On 1/4/24 2:23 PM, Andres Freund wrote:
> >>>
> >>> On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
> >>>
> >>> Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
> >>> Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
> >>>   nskippable_blocks
> >>>
> >>> I think these may lead to worse code - the compiler has to reload
> >>> vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
> >>> can't guarantee that they're not changed within one of the external functions
> >>> called in the loop body.
> >>>
> >>> Admittedly I'm not up to speed on recent vacuum changes, but I have to wonder if the concept of skipping should go away in the context of vector IO? Instead of thinking about "we can skip this range of blocks", why not maintain a list of "here's the next X number of blocks that we need to vacuum"?
> >>
> >> Sorry if I misunderstood. AFAIU, with the help of the vectored IO;
> >> "the next X number of blocks that need to be vacuumed" will be
> >> prefetched by calculating the unskippable blocks ( using the
> >> lazy_scan_skip() function ) and the X will be determined by Postgres
> >> itself. Do you have something different in your mind?
> >
> > I think you are both right. As we gain more control of readahead from
> > within Postgres, we will likely want to revisit this heuristic as it
> > may not serve us anymore. But the streaming read interface/vectored
> > I/O is also not a drop-in replacement for it. To change anything and
> > ensure there is no regression, we will probably have to do
> > cross-platform benchmarking, though.
> >
> > That being said, I would absolutely love to get rid of the skippable
> > ranges because I find them very error-prone and confusing. Hopefully
> > now that the skipping logic is isolated to a single function, it will
> > be easier not to trip over it when working on lazy_scan_heap().
>
> Yeah, arguably it's just a matter of semantics, but IMO it's a lot
> clearer to simply think in terms of "here's the next blocks we know we
> want to vacuum" instead of "we vacuum everything, but sometimes we skip
> some blocks".

Even "we vacuum some stuff, but sometimes we skip some blocks" would
be okay. What we have now is "we vacuum some stuff, but sometimes we
skip some blocks, but only if we would skip enough blocks, and, when
we decide to do that we can't go back and actually get visibility
information for those blocks we skipped because we are too cheap"

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
@ 2024-01-11 23:41     ` Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-01-11 23:41 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>

v3 attached

On Thu, Jan 4, 2024 at 3:23 PM Andres Freund <andres@anarazel.de> wrote:
>
> Hi,
>
> On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
> > Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
> > Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
> >  nskippable_blocks
>
> I think these may lead to worse code - the compiler has to reload
> vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
> can't guarantee that they're not changed within one of the external functions
> called in the loop body.

I buy that for 0001 but 0002 is still using local variables.
nskippable_blocks was just another variable to keep track of even
though we could already get that info from local variables
next_unskippable_block and next_block.

In light of this comment, I've refactored 0003/0004 (0002 and 0003 in
this version [v3]) to use local variables in the loop as well. I had
started using the members of the VacSkipState which I introduced.

> > Subject: [PATCH v2 3/6] Add lazy_scan_skip unskippable state
> >
> > Future commits will remove all skipping logic from lazy_scan_heap() and
> > confine it to lazy_scan_skip(). To make those commits more clear, first
> > introduce the struct, VacSkipState, which will maintain the variables
> > needed to skip ranges less than SKIP_PAGES_THRESHOLD.
>
> Why not add this to LVRelState, possibly as a struct embedded within it?

Done in attached.

> > From 335faad5948b2bec3b83c2db809bb9161d373dcb Mon Sep 17 00:00:00 2001
> > From: Melanie Plageman <melanieplageman@gmail.com>
> > Date: Sat, 30 Dec 2023 16:59:27 -0500
> > Subject: [PATCH v2 4/6] Confine vacuum skip logic to lazy_scan_skip
>
> > By always calling lazy_scan_skip() -- instead of only when we have reached the
> > next unskippable block, we no longer need the skipping_current_range variable.
> > lazy_scan_heap() no longer needs to manage the skipped range -- checking if we
> > reached the end in order to then call lazy_scan_skip(). And lazy_scan_skip()
> > can derive the visibility status of a block from whether or not we are in a
> > skippable range -- that is, whether or not the next_block is equal to the next
> > unskippable block.
>
> I wonder if it should be renamed as part of this - the name is somewhat
> confusing now (and perhaps before)? lazy_scan_get_next_block() or such?

Why stop there! I've removed lazy and called it
heap_vac_scan_get_next_block() -- a little long, but...

> > +     while (true)
> >       {
> >               Buffer          buf;
> >               Page            page;
> > -             bool            all_visible_according_to_vm;
> >               LVPagePruneState prunestate;
> >
> > -             if (blkno == vacskip.next_unskippable_block)
> > -             {
> > -                     /*
> > -                      * Can't skip this page safely.  Must scan the page.  But
> > -                      * determine the next skippable range after the page first.
> > -                      */
> > -                     all_visible_according_to_vm = vacskip.next_unskippable_allvis;
> > -                     lazy_scan_skip(vacrel, &vacskip, blkno + 1);
> > -
> > -                     Assert(vacskip.next_unskippable_block >= blkno + 1);
> > -             }
> > -             else
> > -             {
> > -                     /* Last page always scanned (may need to set nonempty_pages) */
> > -                     Assert(blkno < rel_pages - 1);
> > -
> > -                     if (vacskip.skipping_current_range)
> > -                             continue;
> > +             blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
> > +                                                        &all_visible_according_to_vm);
> >
> > -                     /* Current range is too small to skip -- just scan the page */
> > -                     all_visible_according_to_vm = true;
> > -             }
> > +             if (blkno == InvalidBlockNumber)
> > +                     break;
> >
> >               vacrel->scanned_pages++;
> >
>
> I don't like that we still do determination about the next block outside of
> lazy_scan_skip() and have duplicated exit conditions between lazy_scan_skip()
> and lazy_scan_heap().
>
> I'd probably change the interface to something like
>
> while (lazy_scan_get_next_block(vacrel, &blkno))
> {
> ...
> }

I've done this. I do now find the parameter names a bit confusing.
There is next_block (which is the "next block in line" and is an input
parameter) and blkno, which is an output parameter with the next block
that should actually be processed. Maybe it's okay?

> > From b6603e35147c4bbe3337280222e6243524b0110e Mon Sep 17 00:00:00 2001
> > From: Melanie Plageman <melanieplageman@gmail.com>
> > Date: Sun, 31 Dec 2023 09:47:18 -0500
> > Subject: [PATCH v2 5/6] VacSkipState saves reference to LVRelState
> >
> > The streaming read interface can only give pgsr_next callbacks access to
> > two pieces of private data. As such, move a reference to the LVRelState
> > into the VacSkipState.
> >
> > This is a separate commit (as opposed to as part of the commit
> > introducing VacSkipState) because it is required for using the streaming
> > read interface but not a natural change on its own. VacSkipState is per
> > block and the LVRelState is referenced for the whole relation vacuum.
>
> I'd do it the other way round, i.e. either embed VacSkipState ino LVRelState
> or point to it from VacSkipState.
>
> LVRelState is already tied to the iteration state, so I don't think there's a
> reason not to do so.

Done, and, as such, this patch is dropped from the set.

- Melane

Attachments:

  [text/x-patch] v3-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.0K, ../../CAAKRu_b9kbXeK05_jTqBayhsRNeruyWHD6i8RPWoVtGxSV4D9g@mail.gmail.com/2-v3-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From 2ac56028b7379a5f40680801eb0e188ca512bd7f Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v3 4/4] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 77d35f1974d..a6cb96409b9 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1384,8 +1384,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		vacrel->skip.next_unskippable_block = next_unskippable_block;
-- 
2.37.2



  [text/x-patch] v3-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch (13.6K, ../../CAAKRu_b9kbXeK05_jTqBayhsRNeruyWHD6i8RPWoVtGxSV4D9g@mail.gmail.com/3-v3-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch)
  download | inline diff:
From 57b18a83ea998dd27ecaac9c04e503089813cf6c Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v3 2/4] Add lazy_scan_skip unskippable state to LVRelState

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce add a struct to LVRelState containing variables needed to skip
ranges less than SKIP_PAGES_THRESHOLD.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 139 ++++++++++++++++-----------
 1 file changed, 84 insertions(+), 55 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 22ba16b6718..cab2bbb9629 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -210,6 +210,22 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/*
+	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
+	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 */
+	struct
+	{
+		/* Next unskippable block */
+		BlockNumber next_unskippable_block;
+		/* Buffer containing next unskippable block's visibility info */
+		Buffer		vmbuffer;
+		/* Next unskippable block's visibility status */
+		bool		next_unskippable_allvis;
+		/* Whether or not skippable blocks should be skipped */
+		bool		skipping_current_range;
+	}			skip;
 } LVRelState;
 
 /*
@@ -237,13 +253,9 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
-
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -825,12 +837,8 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -844,10 +852,9 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.vmbuffer = InvalidBuffer;
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, 0);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -855,26 +862,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		all_visible_according_to_vm;
 		LVPagePruneState prunestate;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacrel->skip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, blkno + 1);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacrel->skip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -917,10 +921,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacrel->skip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacrel->skip.vmbuffer);
+				vacrel->skip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -945,7 +949,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
@@ -964,7 +968,7 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/* Check for new or empty pages before lazy_scan_noprune call */
 			if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, true,
-									   vmbuffer))
+									   vacrel->skip.vmbuffer))
 			{
 				/* Processed as new/empty page (lock and pin released) */
 				continue;
@@ -1003,7 +1007,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		}
 
 		/* Check for new or empty pages before lazy_scan_prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, false, vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, false,
+								   vacrel->skip.vmbuffer))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -1037,7 +1042,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			{
 				Size		freespace;
 
-				lazy_vacuum_heap_page(vacrel, blkno, buf, 0, vmbuffer);
+				lazy_vacuum_heap_page(vacrel, blkno, buf, 0, vacrel->skip.vmbuffer);
 
 				/* Forget the LP_DEAD items that we just vacuumed */
 				dead_items->num_items = 0;
@@ -1116,7 +1121,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			PageSetAllVisible(page);
 			MarkBufferDirty(buf);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, prunestate.visibility_cutoff_xid,
+							  vacrel->skip.vmbuffer, prunestate.visibility_cutoff_xid,
 							  flags);
 		}
 
@@ -1127,11 +1132,12 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * with buffer lock before concluding that the VM is corrupt.
 		 */
 		else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-				 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+				 visibilitymap_get_status(vacrel->rel, blkno,
+										  &vacrel->skip.vmbuffer) != 0)
 		{
 			elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 				 vacrel->relname, blkno);
-			visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+			visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 								VISIBILITYMAP_VALID_BITS);
 		}
 
@@ -1156,7 +1162,7 @@ lazy_scan_heap(LVRelState *vacrel)
 				 vacrel->relname, blkno);
 			PageClearAllVisible(page);
 			MarkBufferDirty(buf);
-			visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+			visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 								VISIBILITYMAP_VALID_BITS);
 		}
 
@@ -1167,7 +1173,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		else if (all_visible_according_to_vm && prunestate.all_visible &&
 				 prunestate.all_frozen &&
-				 !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+				 !VM_ALL_FROZEN(vacrel->rel, blkno, &vacrel->skip.vmbuffer))
 		{
 			/*
 			 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1189,7 +1195,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			 */
 			Assert(!TransactionIdIsValid(prunestate.visibility_cutoff_xid));
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacrel->skip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE |
 							  VISIBILITYMAP_ALL_FROZEN);
 		}
@@ -1231,8 +1237,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacrel->skip.vmbuffer))
+	{
+		ReleaseBuffer(vacrel->skip.vmbuffer);
+		vacrel->skip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1276,15 +1285,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in skip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
+ *
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * The block number and visibility status of the next unskippable block are set
+ * in skip->next_unskippable_block and next_unskippable_allvis.
+ * skip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1294,25 +1322,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
 {
+	/* Use local variables for better optimized loop code */
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_unskippable_block = next_block;
+
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
+	vacrel->skip.next_unskippable_allvis = true;
 	while (next_unskippable_block < rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
-													   vmbuffer);
+													   &vacrel->skip.vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1333,7 +1362,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1358,6 +1387,8 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		next_unskippable_block++;
 	}
 
+	vacrel->skip.next_unskippable_block = next_unskippable_block;
+
 	/*
 	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
 	 * pages.  Since we're reading sequentially, the OS should be doing
@@ -1368,16 +1399,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacrel->skip.skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacrel->skip.skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v3-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (15.1K, ../../CAAKRu_b9kbXeK05_jTqBayhsRNeruyWHD6i8RPWoVtGxSV4D9g@mail.gmail.com/4-v3-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 5d4f6b74e35491be52a5cc32e4e56f8584ce127e Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v3 3/4] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and
eventually AIO), refactor vacuum's logic for skipping blocks such that
it is entirely confined to lazy_scan_skip(). This turns lazy_scan_skip()
and the skip state in LVRelState it uses into an iterator which yields
blocks to lazy_scan_heap(). Such a structure is conducive to an async
interface. While we are at it, rename lazy_scan_skip() to
heap_vac_scan_get_next_block(), which now more accurately describes it.

By always calling heap_vac_scan_get_next_block() -- instead of only when
we have reached the next unskippable block, we no longer need the
skipping_current_range variable. lazy_scan_heap() no longer needs to
manage the skipped range -- checking if we reached the end in order to
then call heap_vac_scan_get_next_block(). And
heap_vac_scan_get_next_block() can derive the visibility status of a
block from whether or not we are in a skippable range -- that is,
whether or not the next_block is equal to the next unskippable block.
---
 src/backend/access/heap/vacuumlazy.c | 258 ++++++++++++++-------------
 1 file changed, 134 insertions(+), 124 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index cab2bbb9629..77d35f1974d 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -212,8 +212,8 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
-	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 * Parameters maintained by heap_vac_scan_get_next_block() to manage
+	 * skipping ranges of pages greater than SKIP_PAGES_THRESHOLD.
 	 */
 	struct
 	{
@@ -255,7 +255,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
+static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+										 BlockNumber *blkno,
+										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -835,9 +837,15 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
+	Page		page;
+	LVPagePruneState prunestate;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -852,39 +860,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, 0);
-	for (blkno = 0; blkno < rel_pages; blkno++)
-	{
-		Buffer		buf;
-		Page		page;
-		bool		all_visible_according_to_vm;
-		LVPagePruneState prunestate;
-
-		if (blkno == vacrel->skip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, blkno + 1);
-
-			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacrel->skip.skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
 
+	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
+										&blkno, &all_visible_according_to_vm))
+	{
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1093,7 +1074,8 @@ lazy_scan_heap(LVRelState *vacrel)
 
 		/*
 		 * Handle setting visibility map bit based on information from the VM
-		 * (as of last lazy_scan_skip() call), and from prunestate
+		 * (as of last heap_vac_scan_get_next_block() call), and from
+		 * prunestate
 		 */
 		if (!all_visible_according_to_vm && prunestate.all_visible)
 		{
@@ -1128,8 +1110,9 @@ lazy_scan_heap(LVRelState *vacrel)
 		/*
 		 * As of PostgreSQL 9.2, the visibility map bit should never be set if
 		 * the page-level bit is clear.  However, it's possible that the bit
-		 * got cleared after lazy_scan_skip() was called, so we must recheck
-		 * with buffer lock before concluding that the VM is corrupt.
+		 * got cleared after heap_vac_scan_get_next_block() was called, so we
+		 * must recheck with buffer lock before concluding that the VM is
+		 * corrupt.
 		 */
 		else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
 				 visibilitymap_get_status(vacrel->rel, blkno,
@@ -1282,20 +1265,14 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
+ *	heap_vac_scan_get_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in skip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
- *
- * skip->vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * heap_vac_scan_get_next_block() sets blkno to next block that actually needs
+ * to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1305,14 +1282,25 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in skip->next_unskippable_block and next_unskippable_allvis.
- * skip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacrel->skip->next_unskippable_block and next_unskippable_allvis.
+ *
+ * The block number and visibility status of the next block to process are set
+ * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
+ * returns false if there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1322,91 +1310,113 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
-lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
+static bool
+heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
-	/* Use local variables for better optimized loop code */
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block;
-
 	bool		skipsallvis = false;
 
-	vacrel->skip.next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	if (next_block >= vacrel->rel_pages)
 	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   &vacrel->skip.vmbuffer);
+		*blkno = InvalidBlockNumber;
+		return false;
+	}
+
+	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->skip.next_unskippable_block)
+	{
+		/* Use local variables for better optimized loop code */
+		BlockNumber rel_pages = vacrel->rel_pages;
+		BlockNumber next_unskippable_block = vacrel->skip.next_unskippable_block;
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+		while (++next_unskippable_block < rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   &vacrel->skip.vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacrel->skip.next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacrel->skip.next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-	}
+		vacrel->skip.next_unskippable_block = next_unskippable_block;
 
-	vacrel->skip.next_unskippable_block = next_unskippable_block;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->skip.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->skip.next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
+	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacrel->skip.skipping_current_range = false;
+	if (next_block == vacrel->skip.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
 	else
-	{
-		vacrel->skip.skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	*blkno = next_block;
+	return true;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v3-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.7K, ../../CAAKRu_b9kbXeK05_jTqBayhsRNeruyWHD6i8RPWoVtGxSV4D9g@mail.gmail.com/5-v3-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From e0bc1eb3b5c1a2dfda0f54eae98278ad21a05be8 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v3 1/4] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index b63cad1335f..22ba16b6718 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1299,8 +1299,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+				next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1357,7 +1356,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1370,7 +1368,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.37.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-01-26 13:28       ` vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: vignesh C @ 2024-01-26 13:28 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>

On Fri, 12 Jan 2024 at 05:12, Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> v3 attached
>
> On Thu, Jan 4, 2024 at 3:23 PM Andres Freund <andres@anarazel.de> wrote:
> >
> > Hi,
> >
> > On 2024-01-02 12:36:18 -0500, Melanie Plageman wrote:
> > > Subject: [PATCH v2 1/6] lazy_scan_skip remove unnecessary local var rel_pages
> > > Subject: [PATCH v2 2/6] lazy_scan_skip remove unneeded local var
> > >  nskippable_blocks
> >
> > I think these may lead to worse code - the compiler has to reload
> > vacrel->rel_pages/next_unskippable_block for every loop iteration, because it
> > can't guarantee that they're not changed within one of the external functions
> > called in the loop body.
>
> I buy that for 0001 but 0002 is still using local variables.
> nskippable_blocks was just another variable to keep track of even
> though we could already get that info from local variables
> next_unskippable_block and next_block.
>
> In light of this comment, I've refactored 0003/0004 (0002 and 0003 in
> this version [v3]) to use local variables in the loop as well. I had
> started using the members of the VacSkipState which I introduced.
>
> > > Subject: [PATCH v2 3/6] Add lazy_scan_skip unskippable state
> > >
> > > Future commits will remove all skipping logic from lazy_scan_heap() and
> > > confine it to lazy_scan_skip(). To make those commits more clear, first
> > > introduce the struct, VacSkipState, which will maintain the variables
> > > needed to skip ranges less than SKIP_PAGES_THRESHOLD.
> >
> > Why not add this to LVRelState, possibly as a struct embedded within it?
>
> Done in attached.
>
> > > From 335faad5948b2bec3b83c2db809bb9161d373dcb Mon Sep 17 00:00:00 2001
> > > From: Melanie Plageman <melanieplageman@gmail.com>
> > > Date: Sat, 30 Dec 2023 16:59:27 -0500
> > > Subject: [PATCH v2 4/6] Confine vacuum skip logic to lazy_scan_skip
> >
> > > By always calling lazy_scan_skip() -- instead of only when we have reached the
> > > next unskippable block, we no longer need the skipping_current_range variable.
> > > lazy_scan_heap() no longer needs to manage the skipped range -- checking if we
> > > reached the end in order to then call lazy_scan_skip(). And lazy_scan_skip()
> > > can derive the visibility status of a block from whether or not we are in a
> > > skippable range -- that is, whether or not the next_block is equal to the next
> > > unskippable block.
> >
> > I wonder if it should be renamed as part of this - the name is somewhat
> > confusing now (and perhaps before)? lazy_scan_get_next_block() or such?
>
> Why stop there! I've removed lazy and called it
> heap_vac_scan_get_next_block() -- a little long, but...
>
> > > +     while (true)
> > >       {
> > >               Buffer          buf;
> > >               Page            page;
> > > -             bool            all_visible_according_to_vm;
> > >               LVPagePruneState prunestate;
> > >
> > > -             if (blkno == vacskip.next_unskippable_block)
> > > -             {
> > > -                     /*
> > > -                      * Can't skip this page safely.  Must scan the page.  But
> > > -                      * determine the next skippable range after the page first.
> > > -                      */
> > > -                     all_visible_according_to_vm = vacskip.next_unskippable_allvis;
> > > -                     lazy_scan_skip(vacrel, &vacskip, blkno + 1);
> > > -
> > > -                     Assert(vacskip.next_unskippable_block >= blkno + 1);
> > > -             }
> > > -             else
> > > -             {
> > > -                     /* Last page always scanned (may need to set nonempty_pages) */
> > > -                     Assert(blkno < rel_pages - 1);
> > > -
> > > -                     if (vacskip.skipping_current_range)
> > > -                             continue;
> > > +             blkno = lazy_scan_skip(vacrel, &vacskip, blkno + 1,
> > > +                                                        &all_visible_according_to_vm);
> > >
> > > -                     /* Current range is too small to skip -- just scan the page */
> > > -                     all_visible_according_to_vm = true;
> > > -             }
> > > +             if (blkno == InvalidBlockNumber)
> > > +                     break;
> > >
> > >               vacrel->scanned_pages++;
> > >
> >
> > I don't like that we still do determination about the next block outside of
> > lazy_scan_skip() and have duplicated exit conditions between lazy_scan_skip()
> > and lazy_scan_heap().
> >
> > I'd probably change the interface to something like
> >
> > while (lazy_scan_get_next_block(vacrel, &blkno))
> > {
> > ...
> > }
>
> I've done this. I do now find the parameter names a bit confusing.
> There is next_block (which is the "next block in line" and is an input
> parameter) and blkno, which is an output parameter with the next block
> that should actually be processed. Maybe it's okay?
>
> > > From b6603e35147c4bbe3337280222e6243524b0110e Mon Sep 17 00:00:00 2001
> > > From: Melanie Plageman <melanieplageman@gmail.com>
> > > Date: Sun, 31 Dec 2023 09:47:18 -0500
> > > Subject: [PATCH v2 5/6] VacSkipState saves reference to LVRelState
> > >
> > > The streaming read interface can only give pgsr_next callbacks access to
> > > two pieces of private data. As such, move a reference to the LVRelState
> > > into the VacSkipState.
> > >
> > > This is a separate commit (as opposed to as part of the commit
> > > introducing VacSkipState) because it is required for using the streaming
> > > read interface but not a natural change on its own. VacSkipState is per
> > > block and the LVRelState is referenced for the whole relation vacuum.
> >
> > I'd do it the other way round, i.e. either embed VacSkipState ino LVRelState
> > or point to it from VacSkipState.
> >
> > LVRelState is already tied to the iteration state, so I don't think there's a
> > reason not to do so.
>
> Done, and, as such, this patch is dropped from the set.

CFBot shows that the patch does not apply anymore as in [1]:
=== applying patch
./v3-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch
patching file src/backend/access/heap/vacuumlazy.c
...
Hunk #10 FAILED at 1042.
Hunk #11 FAILED at 1121.
Hunk #12 FAILED at 1132.
Hunk #13 FAILED at 1161.
Hunk #14 FAILED at 1172.
Hunk #15 FAILED at 1194.
...
6 out of 21 hunks FAILED -- saving rejects to file
src/backend/access/heap/vacuumlazy.c.rej

Please post an updated version for the same.

[1] - http://cfbot.cputube.org/patch_46_4755.log

Regards,
Vignesh





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
@ 2024-01-30 01:18         ` Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-01-30 01:18 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>

On Fri, Jan 26, 2024 at 8:28 AM vignesh C <vignesh21@gmail.com> wrote:
>
> CFBot shows that the patch does not apply anymore as in [1]:
> === applying patch
> ./v3-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch
> patching file src/backend/access/heap/vacuumlazy.c
> ...
> Hunk #10 FAILED at 1042.
> Hunk #11 FAILED at 1121.
> Hunk #12 FAILED at 1132.
> Hunk #13 FAILED at 1161.
> Hunk #14 FAILED at 1172.
> Hunk #15 FAILED at 1194.
> ...
> 6 out of 21 hunks FAILED -- saving rejects to file
> src/backend/access/heap/vacuumlazy.c.rej
>
> Please post an updated version for the same.
>
> [1] - http://cfbot.cputube.org/patch_46_4755.log

Fixed in attached rebased v4

- Melanie

Attachments:

  [text/x-patch] v4-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.0K, ../../CAAKRu_ZuYsf4MNGzm7_KvG0SKsu-EtYRhFHy2x3q0heX8KLMTg@mail.gmail.com/2-v4-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From b71fbf1e9abea4689b57d9439ecdcc4387e91195 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v4 4/4] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index e5988262611..ea270941379 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1190,8 +1190,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		vacrel->skip.next_unskippable_block = next_unskippable_block;
-- 
2.37.2



  [text/x-patch] v4-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (14.0K, ../../CAAKRu_ZuYsf4MNGzm7_KvG0SKsu-EtYRhFHy2x3q0heX8KLMTg@mail.gmail.com/3-v4-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 5b39165dde6e60ed214bc988eeb58fb9d357030c Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v4 3/4] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and
eventually AIO), refactor vacuum's logic for skipping blocks such that
it is entirely confined to lazy_scan_skip(). This turns lazy_scan_skip()
and the skip state in LVRelState it uses into an iterator which yields
blocks to lazy_scan_heap(). Such a structure is conducive to an async
interface. While we are at it, rename lazy_scan_skip() to
heap_vac_scan_get_next_block(), which now more accurately describes it.

By always calling heap_vac_scan_get_next_block() -- instead of only when
we have reached the next unskippable block, we no longer need the
skipping_current_range variable. lazy_scan_heap() no longer needs to
manage the skipped range -- checking if we reached the end in order to
then call heap_vac_scan_get_next_block(). And
heap_vac_scan_get_next_block() can derive the visibility status of a
block from whether or not we are in a skippable range -- that is,
whether or not the next_block is equal to the next unskippable block.
---
 src/backend/access/heap/vacuumlazy.c | 243 ++++++++++++++-------------
 1 file changed, 126 insertions(+), 117 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 077164896fb..e5988262611 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -212,8 +212,8 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
-	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 * Parameters maintained by heap_vac_scan_get_next_block() to manage
+	 * skipping ranges of pages greater than SKIP_PAGES_THRESHOLD.
 	 */
 	struct
 	{
@@ -238,7 +238,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
+static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+										 BlockNumber *blkno,
+										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock);
@@ -820,8 +822,11 @@ static void
 lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -836,40 +841,17 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, 0);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+
+	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
+										&blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == vacrel->skip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, blkno + 1);
-
-			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacrel->skip.skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1089,20 +1071,14 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
- *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in skip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *	heap_vac_scan_get_next_block() -- get next block for vacuum to process
  *
- * skip->vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * heap_vac_scan_get_next_block() sets blkno to next block that actually needs
+ * to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1112,14 +1088,25 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in skip->next_unskippable_block and next_unskippable_allvis.
- * skip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacrel->skip->next_unskippable_block and next_unskippable_allvis.
+ *
+ * The block number and visibility status of the next block to process are set
+ * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
+ * returns false if there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1129,91 +1116,113 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
-lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
+static bool
+heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
-	/* Use local variables for better optimized loop code */
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block;
-
 	bool		skipsallvis = false;
 
-	vacrel->skip.next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	if (next_block >= vacrel->rel_pages)
 	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   &vacrel->skip.vmbuffer);
+		*blkno = InvalidBlockNumber;
+		return false;
+	}
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->skip.next_unskippable_block)
+	{
+		/* Use local variables for better optimized loop code */
+		BlockNumber rel_pages = vacrel->rel_pages;
+		BlockNumber next_unskippable_block = vacrel->skip.next_unskippable_block;
+
+		while (++next_unskippable_block < rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   &vacrel->skip.vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacrel->skip.next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacrel->skip.next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-	}
+		vacrel->skip.next_unskippable_block = next_unskippable_block;
 
-	vacrel->skip.next_unskippable_block = next_unskippable_block;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->skip.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->skip.next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
+	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacrel->skip.skipping_current_range = false;
+	if (next_block == vacrel->skip.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
 	else
-	{
-		vacrel->skip.skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	*blkno = next_block;
+	return true;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v4-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.7K, ../../CAAKRu_ZuYsf4MNGzm7_KvG0SKsu-EtYRhFHy2x3q0heX8KLMTg@mail.gmail.com/4-v4-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From ab6d37e74daba17ff845f7399ec734f751127156 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v4 1/4] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index fa56480808b..e21c1124f5c 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1109,8 +1109,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+				next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1167,7 +1166,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1180,7 +1178,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.37.2



  [text/x-patch] v4-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch (15.8K, ../../CAAKRu_ZuYsf4MNGzm7_KvG0SKsu-EtYRhFHy2x3q0heX8KLMTg@mail.gmail.com/5-v4-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch)
  download | inline diff:
From 9e949d6e6f6e6d63b246c70fc88ba1d79ea5eeb6 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v4 2/4] Add lazy_scan_skip unskippable state to LVRelState

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce add a struct to LVRelState containing variables needed to skip
ranges less than SKIP_PAGES_THRESHOLD.

lazy_scan_prune() and lazy_scan_new_or_empty() can now access the
buffer containing the relevant block of the visibility map through the
LVRelState.skip, so it no longer needs to be a separate function
parameter.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 154 ++++++++++++++++-----------
 1 file changed, 90 insertions(+), 64 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index e21c1124f5c..077164896fb 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -210,6 +210,22 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/*
+	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
+	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 */
+	struct
+	{
+		/* Next unskippable block */
+		BlockNumber next_unskippable_block;
+		/* Buffer containing next unskippable block's visibility info */
+		Buffer		vmbuffer;
+		/* Next unskippable block's visibility status */
+		bool		next_unskippable_allvis;
+		/* Whether or not skippable blocks should be skipped */
+		bool		skipping_current_range;
+	}			skip;
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -220,19 +236,15 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
-
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
-								   bool sharelock, Buffer vmbuffer);
+								   bool sharelock);
 static void lazy_scan_prune(LVRelState *vacrel, Buffer buf,
 							BlockNumber blkno, Page page,
-							Buffer vmbuffer, bool all_visible_according_to_vm,
+							bool all_visible_according_to_vm,
 							bool *has_lpdead_items);
 static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 							  BlockNumber blkno, Page page,
@@ -809,12 +821,8 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -828,10 +836,9 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.vmbuffer = InvalidBuffer;
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, 0);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -840,26 +847,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacrel->skip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, blkno + 1);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacrel->skip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -902,10 +906,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacrel->skip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacrel->skip.vmbuffer);
+				vacrel->skip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -930,7 +934,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
 		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
 								 vacrel->bstrategy);
@@ -948,8 +952,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			LockBuffer(buf, BUFFER_LOCK_SHARE);
 
 		/* Check for new or empty pages before lazy_scan_[no]prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
-								   vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -991,7 +994,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1041,8 +1044,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacrel->skip.vmbuffer))
+	{
+		ReleaseBuffer(vacrel->skip.vmbuffer);
+		vacrel->skip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1086,15 +1092,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in skip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
+ *
+ * The block number and visibility status of the next unskippable block are set
+ * in skip->next_unskippable_block and next_unskippable_allvis.
+ * skip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1104,25 +1129,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
 {
+	/* Use local variables for better optimized loop code */
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_unskippable_block = next_block;
+
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
+	vacrel->skip.next_unskippable_allvis = true;
 	while (next_unskippable_block < rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
-													   vmbuffer);
+													   &vacrel->skip.vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1143,7 +1169,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1168,6 +1194,8 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		next_unskippable_block++;
 	}
 
+	vacrel->skip.next_unskippable_block = next_unskippable_block;
+
 	/*
 	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
 	 * pages.  Since we're reading sequentially, the OS should be doing
@@ -1178,16 +1206,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacrel->skip.skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacrel->skip.skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
@@ -1220,7 +1246,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
  */
 static bool
 lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
-					   Page page, bool sharelock, Buffer vmbuffer)
+					   Page page, bool sharelock)
 {
 	Size		freespace;
 
@@ -1306,7 +1332,7 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
 
 			PageSetAllVisible(page);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacrel->skip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
 			END_CRIT_SECTION();
 		}
@@ -1342,10 +1368,11 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
  * any tuple that becomes dead after the call to heap_page_prune() can't need to
  * be frozen, because it was visible to another session when vacuum started.
  *
- * vmbuffer is the buffer containing the VM block with visibility information
- * for the heap block, blkno. all_visible_according_to_vm is the saved
- * visibility status of the heap block looked up earlier by the caller. We
- * won't rely entirely on this status, as it may be out of date.
+ * vacrel->skipstate.vmbuffer is the buffer containing the VM block with
+ * visibility information for the heap block, blkno.
+ * all_visible_according_to_vm is the saved visibility status of the heap block
+ * looked up earlier by the caller. We won't rely entirely on this status, as
+ * it may be out of date.
  *
  * *has_lpdead_items is set to true or false depending on whether, upon return
  * from this function, any LP_DEAD items are still present on the page.
@@ -1355,7 +1382,6 @@ lazy_scan_prune(LVRelState *vacrel,
 				Buffer buf,
 				BlockNumber blkno,
 				Page page,
-				Buffer vmbuffer,
 				bool all_visible_according_to_vm,
 				bool *has_lpdead_items)
 {
@@ -1789,7 +1815,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		PageSetAllVisible(page);
 		MarkBufferDirty(buf);
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, visibility_cutoff_xid,
+						  vacrel->skip.vmbuffer, visibility_cutoff_xid,
 						  flags);
 	}
 
@@ -1800,11 +1826,11 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+			 visibilitymap_get_status(vacrel->rel, blkno, &vacrel->skip.vmbuffer) != 0)
 	{
 		elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 			 vacrel->relname, blkno);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1828,7 +1854,7 @@ lazy_scan_prune(LVRelState *vacrel,
 			 vacrel->relname, blkno);
 		PageClearAllVisible(page);
 		MarkBufferDirty(buf);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1838,7 +1864,7 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * true, so we must check both all_visible and all_frozen.
 	 */
 	else if (all_visible_according_to_vm && all_visible &&
-			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vacrel->skip.vmbuffer))
 	{
 		/*
 		 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1860,7 +1886,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		 */
 		Assert(!TransactionIdIsValid(visibility_cutoff_xid));
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, InvalidTransactionId,
+						  vacrel->skip.vmbuffer, InvalidTransactionId,
 						  VISIBILITYMAP_ALL_VISIBLE |
 						  VISIBILITYMAP_ALL_FROZEN);
 	}
-- 
2.37.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-02-27 19:47           ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-02-27 19:47 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Mon, Jan 29, 2024 at 8:18 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Fri, Jan 26, 2024 at 8:28 AM vignesh C <vignesh21@gmail.com> wrote:
> >
> > CFBot shows that the patch does not apply anymore as in [1]:
> > === applying patch
> > ./v3-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch
> > patching file src/backend/access/heap/vacuumlazy.c
> > ...
> > Hunk #10 FAILED at 1042.
> > Hunk #11 FAILED at 1121.
> > Hunk #12 FAILED at 1132.
> > Hunk #13 FAILED at 1161.
> > Hunk #14 FAILED at 1172.
> > Hunk #15 FAILED at 1194.
> > ...
> > 6 out of 21 hunks FAILED -- saving rejects to file
> > src/backend/access/heap/vacuumlazy.c.rej
> >
> > Please post an updated version for the same.
> >
> > [1] - http://cfbot.cputube.org/patch_46_4755.log
>
> Fixed in attached rebased v4

In light of Thomas' update to the streaming read API [1], I have
rebased and updated this patch set.

The attached v5 has some simplifications when compared to v4 but takes
largely the same approach.

0001-0004 are refactoring
0005 is the streaming read code not yet in master
0006 is the vacuum streaming read user for vacuum's first pass
0007 is the vacuum streaming read user for vacuum's second pass

- Melanie

[1] https://www.postgresql.org/message-id/CA%2BhUKGJtLyxcAEvLhVUhgD4fMQkOu3PDaj8Qb9SR_UsmzgsBpQ%40mail.g...

Attachments:

  [text/x-patch] v5-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.0K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/2-v5-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From a153a50da9bcdeff408a1fe183ee2226570aadc9 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v5 4/7] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index e5988262611..ea270941379 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1190,8 +1190,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		vacrel->skip.next_unskippable_block = next_unskippable_block;
-- 
2.37.2



  [text/x-patch] v5-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.7K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/3-v5-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From 958e254aa12779c3a9f457a5751ba85931e23201 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v5 1/7] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index fa56480808b..e21c1124f5c 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1109,8 +1109,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+				next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1167,7 +1166,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1180,7 +1178,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.37.2



  [text/x-patch] v5-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (14.0K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/4-v5-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From e9a3b596fab396d3e5b4ac5a66bc80762667c885 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v5 3/7] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and
eventually AIO), refactor vacuum's logic for skipping blocks such that
it is entirely confined to lazy_scan_skip(). This turns lazy_scan_skip()
and the skip state in LVRelState it uses into an iterator which yields
blocks to lazy_scan_heap(). Such a structure is conducive to an async
interface. While we are at it, rename lazy_scan_skip() to
heap_vac_scan_get_next_block(), which now more accurately describes it.

By always calling heap_vac_scan_get_next_block() -- instead of only when
we have reached the next unskippable block, we no longer need the
skipping_current_range variable. lazy_scan_heap() no longer needs to
manage the skipped range -- checking if we reached the end in order to
then call heap_vac_scan_get_next_block(). And
heap_vac_scan_get_next_block() can derive the visibility status of a
block from whether or not we are in a skippable range -- that is,
whether or not the next_block is equal to the next unskippable block.
---
 src/backend/access/heap/vacuumlazy.c | 243 ++++++++++++++-------------
 1 file changed, 126 insertions(+), 117 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 077164896fb..e5988262611 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -212,8 +212,8 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
-	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 * Parameters maintained by heap_vac_scan_get_next_block() to manage
+	 * skipping ranges of pages greater than SKIP_PAGES_THRESHOLD.
 	 */
 	struct
 	{
@@ -238,7 +238,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
+static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+										 BlockNumber *blkno,
+										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock);
@@ -820,8 +822,11 @@ static void
 lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -836,40 +841,17 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, 0);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+
+	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
+										&blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == vacrel->skip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, blkno + 1);
-
-			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacrel->skip.skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1089,20 +1071,14 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
- *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in skip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *	heap_vac_scan_get_next_block() -- get next block for vacuum to process
  *
- * skip->vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * heap_vac_scan_get_next_block() sets blkno to next block that actually needs
+ * to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1112,14 +1088,25 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in skip->next_unskippable_block and next_unskippable_allvis.
- * skip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacrel->skip->next_unskippable_block and next_unskippable_allvis.
+ *
+ * The block number and visibility status of the next block to process are set
+ * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
+ * returns false if there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1129,91 +1116,113 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
-lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
+static bool
+heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
-	/* Use local variables for better optimized loop code */
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block;
-
 	bool		skipsallvis = false;
 
-	vacrel->skip.next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	if (next_block >= vacrel->rel_pages)
 	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   &vacrel->skip.vmbuffer);
+		*blkno = InvalidBlockNumber;
+		return false;
+	}
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->skip.next_unskippable_block)
+	{
+		/* Use local variables for better optimized loop code */
+		BlockNumber rel_pages = vacrel->rel_pages;
+		BlockNumber next_unskippable_block = vacrel->skip.next_unskippable_block;
+
+		while (++next_unskippable_block < rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   &vacrel->skip.vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacrel->skip.next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacrel->skip.next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-	}
+		vacrel->skip.next_unskippable_block = next_unskippable_block;
 
-	vacrel->skip.next_unskippable_block = next_unskippable_block;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->skip.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->skip.next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
+	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacrel->skip.skipping_current_range = false;
+	if (next_block == vacrel->skip.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
 	else
-	{
-		vacrel->skip.skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	*blkno = next_block;
+	return true;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v5-0005-Streaming-Read-API.patch (56.9K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/5-v5-0005-Streaming-Read-API.patch)
  download | inline diff:
From 1f10bf10a02502a9521d8ce8130d1964315da30c Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Mon, 26 Feb 2024 23:48:31 +1300
Subject: [PATCH v5 5/7] Streaming Read API

---
 contrib/pg_prewarm/pg_prewarm.c          |  40 +-
 src/backend/storage/Makefile             |   2 +-
 src/backend/storage/aio/Makefile         |  14 +
 src/backend/storage/aio/meson.build      |   5 +
 src/backend/storage/aio/streaming_read.c | 612 ++++++++++++++++++++++
 src/backend/storage/buffer/bufmgr.c      | 641 ++++++++++++++++-------
 src/backend/storage/buffer/localbuf.c    |  14 +-
 src/backend/storage/meson.build          |   1 +
 src/include/storage/bufmgr.h             |  45 ++
 src/include/storage/streaming_read.h     |  52 ++
 src/tools/pgindent/typedefs.list         |   3 +
 11 files changed, 1218 insertions(+), 211 deletions(-)
 create mode 100644 src/backend/storage/aio/Makefile
 create mode 100644 src/backend/storage/aio/meson.build
 create mode 100644 src/backend/storage/aio/streaming_read.c
 create mode 100644 src/include/storage/streaming_read.h

diff --git a/contrib/pg_prewarm/pg_prewarm.c b/contrib/pg_prewarm/pg_prewarm.c
index 8541e4d6e46..1cc84bcb0c2 100644
--- a/contrib/pg_prewarm/pg_prewarm.c
+++ b/contrib/pg_prewarm/pg_prewarm.c
@@ -20,6 +20,7 @@
 #include "miscadmin.h"
 #include "storage/bufmgr.h"
 #include "storage/smgr.h"
+#include "storage/streaming_read.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
 #include "utils/lsyscache.h"
@@ -38,6 +39,25 @@ typedef enum
 
 static PGIOAlignedBlock blockbuffer;
 
+struct pg_prewarm_streaming_read_private
+{
+	BlockNumber blocknum;
+	int64		last_block;
+};
+
+static BlockNumber
+pg_prewarm_streaming_read_next(PgStreamingRead *pgsr,
+							   void *pgsr_private,
+							   void *per_buffer_data)
+{
+	struct pg_prewarm_streaming_read_private *p = pgsr_private;
+
+	if (p->blocknum <= p->last_block)
+		return p->blocknum++;
+
+	return InvalidBlockNumber;
+}
+
 /*
  * pg_prewarm(regclass, mode text, fork text,
  *			  first_block int8, last_block int8)
@@ -183,18 +203,36 @@ pg_prewarm(PG_FUNCTION_ARGS)
 	}
 	else if (ptype == PREWARM_BUFFER)
 	{
+		struct pg_prewarm_streaming_read_private p;
+		PgStreamingRead *pgsr;
+
 		/*
 		 * In buffer mode, we actually pull the data into shared_buffers.
 		 */
+
+		/* Set up the private state for our streaming buffer read callback. */
+		p.blocknum = first_block;
+		p.last_block = last_block;
+
+		pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_FULL,
+											  &p,
+											  0,
+											  NULL,
+											  BMR_REL(rel),
+											  forkNumber,
+											  pg_prewarm_streaming_read_next);
+
 		for (block = first_block; block <= last_block; ++block)
 		{
 			Buffer		buf;
 
 			CHECK_FOR_INTERRUPTS();
-			buf = ReadBufferExtended(rel, forkNumber, block, RBM_NORMAL, NULL);
+			buf = pg_streaming_read_buffer_get_next(pgsr, NULL);
 			ReleaseBuffer(buf);
 			++blocks_done;
 		}
+		Assert(pg_streaming_read_buffer_get_next(pgsr, NULL) == InvalidBuffer);
+		pg_streaming_read_free(pgsr);
 	}
 
 	/* Close relation, release lock. */
diff --git a/src/backend/storage/Makefile b/src/backend/storage/Makefile
index 8376cdfca20..eec03f6f2b4 100644
--- a/src/backend/storage/Makefile
+++ b/src/backend/storage/Makefile
@@ -8,6 +8,6 @@ subdir = src/backend/storage
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
-SUBDIRS     = buffer file freespace ipc large_object lmgr page smgr sync
+SUBDIRS     = aio buffer file freespace ipc large_object lmgr page smgr sync
 
 include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/Makefile b/src/backend/storage/aio/Makefile
new file mode 100644
index 00000000000..bcab44c802f
--- /dev/null
+++ b/src/backend/storage/aio/Makefile
@@ -0,0 +1,14 @@
+#
+# Makefile for storage/aio
+#
+# src/backend/storage/aio/Makefile
+#
+
+subdir = src/backend/storage/aio
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+
+OBJS = \
+	streaming_read.o
+
+include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/meson.build b/src/backend/storage/aio/meson.build
new file mode 100644
index 00000000000..39aef2a84a2
--- /dev/null
+++ b/src/backend/storage/aio/meson.build
@@ -0,0 +1,5 @@
+# Copyright (c) 2024, PostgreSQL Global Development Group
+
+backend_sources += files(
+  'streaming_read.c',
+)
diff --git a/src/backend/storage/aio/streaming_read.c b/src/backend/storage/aio/streaming_read.c
new file mode 100644
index 00000000000..71f2c4a70b6
--- /dev/null
+++ b/src/backend/storage/aio/streaming_read.c
@@ -0,0 +1,612 @@
+#include "postgres.h"
+
+#include "storage/streaming_read.h"
+#include "utils/rel.h"
+
+/*
+ * Element type for PgStreamingRead's circular array of block ranges.
+ */
+typedef struct PgStreamingReadRange
+{
+	bool		need_wait;
+	bool		advice_issued;
+	BlockNumber blocknum;
+	int			nblocks;
+	int			per_buffer_data_index;
+	Buffer		buffers[MAX_BUFFERS_PER_TRANSFER];
+	ReadBuffersOperation operation;
+} PgStreamingReadRange;
+
+/*
+ * Streaming read object.
+ */
+struct PgStreamingRead
+{
+	int			max_ios;
+	int			ios_in_progress;
+	int			max_pinned_buffers;
+	int			pinned_buffers;
+	int			pinned_buffers_trigger;
+	int			next_tail_buffer;
+	int			ramp_up_pin_limit;
+	int			ramp_up_pin_stall;
+	bool		finished;
+	bool		advice_enabled;
+	void	   *pgsr_private;
+	PgStreamingReadBufferCB callback;
+
+	BufferAccessStrategy strategy;
+	BufferManagerRelation bmr;
+	ForkNumber	forknum;
+
+	/* Sometimes we need to buffer one block for flow control. */
+	BlockNumber unget_blocknum;
+	void	   *unget_per_buffer_data;
+
+	/* Next expected block, for detecting sequential access. */
+	BlockNumber seq_blocknum;
+
+	/* Space for optional per-buffer private data. */
+	size_t		per_buffer_data_size;
+	void	   *per_buffer_data;
+
+	/* Circular buffer of ranges. */
+	int			size;
+	int			head;
+	int			tail;
+	PgStreamingReadRange ranges[FLEXIBLE_ARRAY_MEMBER];
+};
+
+static PgStreamingRead *
+pg_streaming_read_buffer_alloc_internal(int flags,
+										void *pgsr_private,
+										size_t per_buffer_data_size,
+										BufferAccessStrategy strategy)
+{
+	PgStreamingRead *pgsr;
+	int			size;
+	int			max_ios;
+	uint32		max_pinned_buffers;
+
+
+	/*
+	 * Decide how many assumed I/Os we will allow to run concurrently.  That
+	 * is, advice to the kernel to tell it that we will soon read.  This
+	 * number also affects how far we look ahead for opportunities to start
+	 * more I/Os.
+	 */
+	if (flags & PGSR_FLAG_MAINTENANCE)
+		max_ios = maintenance_io_concurrency;
+	else
+		max_ios = effective_io_concurrency;
+
+	/*
+	 * The desired level of I/O concurrency controls how far ahead we are
+	 * willing to look ahead.  We also clamp it to at least
+	 * MAX_BUFFER_PER_TRANFER so that we can have a chance to build up a full
+	 * sized read, even when max_ios is zero.
+	 */
+	max_pinned_buffers = Max(max_ios * 4, MAX_BUFFERS_PER_TRANSFER);
+
+	/*
+	 * The *_io_concurrency GUCs might be set to 0, but we want to allow at
+	 * least one, to keep our gating logic simple.
+	 */
+	max_ios = Max(max_ios, 1);
+
+	/*
+	 * Don't allow this backend to pin too many buffers.  For now we'll apply
+	 * the limit for the shared buffer pool and the local buffer pool, without
+	 * worrying which it is.
+	 */
+	LimitAdditionalPins(&max_pinned_buffers);
+	LimitAdditionalLocalPins(&max_pinned_buffers);
+	Assert(max_pinned_buffers > 0);
+
+	/*
+	 * pgsr->ranges is a circular buffer.  When it is empty, head == tail.
+	 * When it is full, there is an empty element between head and tail.  Head
+	 * can also be empty (nblocks == 0), therefore we need two extra elements
+	 * for non-occupied ranges, on top of max_pinned_buffers to allow for the
+	 * maxmimum possible number of occupied ranges of the smallest possible
+	 * size of one.
+	 */
+	size = max_pinned_buffers + 2;
+
+	pgsr = (PgStreamingRead *)
+		palloc0(offsetof(PgStreamingRead, ranges) +
+				sizeof(pgsr->ranges[0]) * size);
+
+	pgsr->max_ios = max_ios;
+	pgsr->per_buffer_data_size = per_buffer_data_size;
+	pgsr->max_pinned_buffers = max_pinned_buffers;
+	pgsr->pgsr_private = pgsr_private;
+	pgsr->strategy = strategy;
+	pgsr->size = size;
+
+	pgsr->unget_blocknum = InvalidBlockNumber;
+
+#ifdef USE_PREFETCH
+
+	/*
+	 * This system supports prefetching advice.  As long as direct I/O isn't
+	 * enabled, and the caller hasn't promised sequential access, we can use
+	 * it.
+	 */
+	if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
+		(flags & PGSR_FLAG_SEQUENTIAL) == 0)
+		pgsr->advice_enabled = true;
+#endif
+
+	/*
+	 * We start off building small ranges, but double that quickly, for the
+	 * benefit of users that don't know how far ahead they'll read.  This can
+	 * be disabled by users that already know they'll read all the way.
+	 */
+	if (flags & PGSR_FLAG_FULL)
+		pgsr->ramp_up_pin_limit = INT_MAX;
+	else
+		pgsr->ramp_up_pin_limit = 1;
+
+	/*
+	 * We want to avoid creating ranges that are smaller than they could be
+	 * just because we hit max_pinned_buffers.  We only look ahead when the
+	 * number of pinned buffers falls below this trigger number, or put
+	 * another way, we stop looking ahead when we wouldn't be able to build a
+	 * "full sized" range.
+	 */
+	pgsr->pinned_buffers_trigger =
+		Max(1, (int) max_pinned_buffers - MAX_BUFFERS_PER_TRANSFER);
+
+	/* Space for the callback to store extra data along with each block. */
+	if (per_buffer_data_size)
+		pgsr->per_buffer_data = palloc(per_buffer_data_size * max_pinned_buffers);
+
+	return pgsr;
+}
+
+/*
+ * Create a new streaming read object that can be used to perform the
+ * equivalent of a series of ReadBuffer() calls for one fork of one relation.
+ * Internally, it generates larger vectored reads where possible by looking
+ * ahead.
+ */
+PgStreamingRead *
+pg_streaming_read_buffer_alloc(int flags,
+							   void *pgsr_private,
+							   size_t per_buffer_data_size,
+							   BufferAccessStrategy strategy,
+							   BufferManagerRelation bmr,
+							   ForkNumber forknum,
+							   PgStreamingReadBufferCB next_block_cb)
+{
+	PgStreamingRead *result;
+
+	result = pg_streaming_read_buffer_alloc_internal(flags,
+													 pgsr_private,
+													 per_buffer_data_size,
+													 strategy);
+	result->callback = next_block_cb;
+	result->bmr = bmr;
+	result->forknum = forknum;
+
+	return result;
+}
+
+/*
+ * Find the per-buffer data index for the Nth block of a range.
+ */
+static int
+get_per_buffer_data_index(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	int			result;
+
+	/*
+	 * Find slot in the circular buffer of per-buffer data, without using the
+	 * expensive % operator.
+	 */
+	result = range->per_buffer_data_index + n;
+	if (result >= pgsr->max_pinned_buffers)
+		result -= pgsr->max_pinned_buffers;
+	Assert(result == (range->per_buffer_data_index + n) % pgsr->max_pinned_buffers);
+
+	return result;
+}
+
+/*
+ * Return a pointer to the per-buffer data by index.
+ */
+static void *
+get_per_buffer_data_by_index(PgStreamingRead *pgsr, int per_buffer_data_index)
+{
+	return (char *) pgsr->per_buffer_data +
+		pgsr->per_buffer_data_size * per_buffer_data_index;
+}
+
+/*
+ * Return a pointer to the per-buffer data for the Nth block of a range.
+ */
+static void *
+get_per_buffer_data(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	return get_per_buffer_data_by_index(pgsr,
+										get_per_buffer_data_index(pgsr,
+																  range,
+																  n));
+}
+
+/*
+ * Start reading the head range, and create a new head range.  The new head
+ * range is returned.  It may not be empty, if StartReadBuffers() couldn't
+ * start the entire range; in that case the returned range contains the
+ * remaining portion of the range.
+ */
+static PgStreamingReadRange *
+pg_streaming_read_start_head_range(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *head_range;
+	PgStreamingReadRange *new_head_range;
+	int			nblocks_pinned;
+	int			flags;
+
+	/* Caller should make sure we never exceed max_ios. */
+	Assert(pgsr->ios_in_progress < pgsr->max_ios);
+
+	/* Should only call if the head range has some blocks to read. */
+	head_range = &pgsr->ranges[pgsr->head];
+	Assert(head_range->nblocks > 0);
+
+	/*
+	 * If advice hasn't been suppressed, and this system supports it, this
+	 * isn't a strictly sequential pattern, then we'll issue advice.
+	 */
+	if (pgsr->advice_enabled && head_range->blocknum != pgsr->seq_blocknum)
+		flags = READ_BUFFERS_ISSUE_ADVICE;
+	else
+		flags = 0;
+
+
+	/* Start reading as many blocks as we can from the head range. */
+	nblocks_pinned = head_range->nblocks;
+	head_range->need_wait =
+		StartReadBuffers(pgsr->bmr,
+						 head_range->buffers,
+						 pgsr->forknum,
+						 head_range->blocknum,
+						 &nblocks_pinned,
+						 pgsr->strategy,
+						 flags,
+						 &head_range->operation);
+
+	/* Did that start an I/O? */
+	if (head_range->need_wait && (flags & READ_BUFFERS_ISSUE_ADVICE))
+	{
+		head_range->advice_issued = true;
+		pgsr->ios_in_progress++;
+		Assert(pgsr->ios_in_progress <= pgsr->max_ios);
+	}
+
+	/*
+	 * StartReadBuffers() might have pinned fewer blocks than we asked it to,
+	 * but always at least one.
+	 */
+	Assert(nblocks_pinned <= head_range->nblocks);
+	Assert(nblocks_pinned >= 1);
+	pgsr->pinned_buffers += nblocks_pinned;
+
+	/*
+	 * Remember where the next block would be after that, so we can detect
+	 * sequential access next time.
+	 */
+	pgsr->seq_blocknum = head_range->blocknum + nblocks_pinned;
+
+	/*
+	 * Create a new head range.  There must be space, because we have enough
+	 * elements for every range to hold just one block, up to the pin limit.
+	 */
+	Assert(pgsr->size > pgsr->max_pinned_buffers);
+	Assert((pgsr->head + 1) % pgsr->size != pgsr->tail);
+	if (++pgsr->head == pgsr->size)
+		pgsr->head = 0;
+	new_head_range = &pgsr->ranges[pgsr->head];
+	new_head_range->nblocks = 0;
+	new_head_range->advice_issued = false;
+
+	/*
+	 * If we didn't manage to start the whole read above, we split the range,
+	 * moving the remainder into the new head range.
+	 */
+	if (nblocks_pinned < head_range->nblocks)
+	{
+		int			nblocks_remaining = head_range->nblocks - nblocks_pinned;
+
+		head_range->nblocks = nblocks_pinned;
+
+		new_head_range->blocknum = head_range->blocknum + nblocks_pinned;
+		new_head_range->nblocks = nblocks_remaining;
+	}
+
+	/* The new range has per-buffer data starting after the previous range. */
+	new_head_range->per_buffer_data_index =
+		get_per_buffer_data_index(pgsr, head_range, nblocks_pinned);
+
+	return new_head_range;
+}
+
+/*
+ * Ask the callback which block it would like us to read next, with a small
+ * buffer in front to allow pg_streaming_unget_block() to work.
+ */
+static BlockNumber
+pg_streaming_get_block(PgStreamingRead *pgsr, void *per_buffer_data)
+{
+	BlockNumber result;
+
+	if (unlikely(pgsr->unget_blocknum != InvalidBlockNumber))
+	{
+		/*
+		 * If we had to unget a block, now it is time to return that one
+		 * again.
+		 */
+		result = pgsr->unget_blocknum;
+		pgsr->unget_blocknum = InvalidBlockNumber;
+
+		/*
+		 * The same per_buffer_data element must have been used, and still
+		 * contains whatever data the callback wrote into it.  So we just
+		 * sanity-check that we were called with the value that
+		 * pg_streaming_unget_block() pushed back.
+		 */
+		Assert(per_buffer_data == pgsr->unget_per_buffer_data);
+	}
+	else
+	{
+		/* Use the installed callback directly. */
+		result = pgsr->callback(pgsr, pgsr->pgsr_private, per_buffer_data);
+	}
+
+	return result;
+}
+
+/*
+ * In order to deal with short reads in StartReadBuffers(), we sometimes need
+ * to defer handling of a block until later.  This *must* be called with the
+ * last value returned by pg_streaming_get_block().
+ */
+static void
+pg_streaming_unget_block(PgStreamingRead *pgsr, BlockNumber blocknum, void *per_buffer_data)
+{
+	Assert(pgsr->unget_blocknum == InvalidBlockNumber);
+	pgsr->unget_blocknum = blocknum;
+	pgsr->unget_per_buffer_data = per_buffer_data;
+}
+
+static void
+pg_streaming_read_look_ahead(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *range;
+
+	/*
+	 * If we're still ramping up, we may have to stall to wait for buffers to
+	 * be consumed first before we do any more prefetching.
+	 */
+	if (pgsr->ramp_up_pin_stall > 0)
+	{
+		Assert(pgsr->pinned_buffers > 0);
+		return;
+	}
+
+	/*
+	 * If we're finished or can't start more I/O, then don't look ahead.
+	 */
+	if (pgsr->finished || pgsr->ios_in_progress == pgsr->max_ios)
+		return;
+
+	/*
+	 * We'll also wait until the number of pinned buffers falls below our
+	 * trigger level, so that we have the chance to create a full range.
+	 */
+	if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+		return;
+
+	do
+	{
+		BlockNumber blocknum;
+		void	   *per_buffer_data;
+
+		/* Do we have a full-sized range? */
+		range = &pgsr->ranges[pgsr->head];
+		if (range->nblocks == lengthof(range->buffers))
+		{
+			/* Start as much of it as we can. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/* If we're now at the I/O limit, stop here. */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+				return;
+
+			/*
+			 * If we couldn't form a full range, then stop here to avoid
+			 * creating small I/O.
+			 */
+			if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+				return;
+
+			/*
+			 * That might have only been partially started, but always
+			 * processes at least one so that'll do for now.
+			 */
+			Assert(range->nblocks < lengthof(range->buffers));
+		}
+
+		/* Find per-buffer data slot for the next block. */
+		per_buffer_data = get_per_buffer_data(pgsr, range, range->nblocks);
+
+		/* Find out which block the callback wants to read next. */
+		blocknum = pg_streaming_get_block(pgsr, per_buffer_data);
+		if (blocknum == InvalidBlockNumber)
+		{
+			/* End of stream. */
+			pgsr->finished = true;
+			break;
+		}
+
+		/*
+		 * Is there a head range that we cannot extend, because the requested
+		 * block is not consecutive?
+		 */
+		if (range->nblocks > 0 &&
+			range->blocknum + range->nblocks != blocknum)
+		{
+			/* Yes.  Start it, so we can begin building a new one. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * It's possible that it was only partially started, and we have a
+			 * new range with the remainder.  Keep starting I/Os until we get
+			 * it all out of the way, or we hit the I/O limit.
+			 */
+			while (range->nblocks > 0 && pgsr->ios_in_progress < pgsr->max_ios)
+				range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * We have to 'unget' the block returned by the callback if we
+			 * don't have enough I/O capacity left to start something.
+			 */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+			{
+				pg_streaming_unget_block(pgsr, blocknum, per_buffer_data);
+				return;
+			}
+		}
+
+		/* If we have a new, empty range, initialize the start block. */
+		if (range->nblocks == 0)
+		{
+			range->blocknum = blocknum;
+		}
+
+		/* This block extends the range by one. */
+		Assert(range->blocknum + range->nblocks == blocknum);
+		range->nblocks++;
+
+	} while (pgsr->pinned_buffers + range->nblocks < pgsr->max_pinned_buffers &&
+			 pgsr->pinned_buffers + range->nblocks < pgsr->ramp_up_pin_limit);
+
+	/* If we've hit the ramp-up limit, insert a stall. */
+	if (pgsr->pinned_buffers + range->nblocks >= pgsr->ramp_up_pin_limit)
+	{
+		/* Can't get here if an earlier stall hasn't finished. */
+		Assert(pgsr->ramp_up_pin_stall == 0);
+		/* Don't do any more prefetching until these buffers are consumed. */
+		pgsr->ramp_up_pin_stall = pgsr->ramp_up_pin_limit;
+		/* Double it.  It will soon be out of the way. */
+		pgsr->ramp_up_pin_limit *= 2;
+	}
+
+	/* Start as much as we can. */
+	while (range->nblocks > 0)
+	{
+		range = pg_streaming_read_start_head_range(pgsr);
+		if (pgsr->ios_in_progress == pgsr->max_ios)
+			break;
+	}
+}
+
+Buffer
+pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_data)
+{
+	pg_streaming_read_look_ahead(pgsr);
+
+	/* See if we have one buffer to return. */
+	while (pgsr->tail != pgsr->head)
+	{
+		PgStreamingReadRange *tail_range;
+
+		tail_range = &pgsr->ranges[pgsr->tail];
+
+		/*
+		 * Do we need to perform an I/O before returning the buffers from this
+		 * range?
+		 */
+		if (tail_range->need_wait)
+		{
+			WaitReadBuffers(&tail_range->operation);
+			tail_range->need_wait = false;
+
+			/*
+			 * We don't really know if the kernel generated a physical I/O
+			 * when we issued advice, let alone when it finished, but it has
+			 * certainly finished now because we've performed the read.
+			 */
+			if (tail_range->advice_issued)
+			{
+				Assert(pgsr->ios_in_progress > 0);
+				pgsr->ios_in_progress--;
+			}
+		}
+
+		/* Are there more buffers available in this range? */
+		if (pgsr->next_tail_buffer < tail_range->nblocks)
+		{
+			int			buffer_index;
+			Buffer		buffer;
+
+			buffer_index = pgsr->next_tail_buffer++;
+			buffer = tail_range->buffers[buffer_index];
+
+			Assert(BufferIsValid(buffer));
+
+			/* We are giving away ownership of this pinned buffer. */
+			Assert(pgsr->pinned_buffers > 0);
+			pgsr->pinned_buffers--;
+
+			if (pgsr->ramp_up_pin_stall > 0)
+				pgsr->ramp_up_pin_stall--;
+
+			if (per_buffer_data)
+				*per_buffer_data = get_per_buffer_data(pgsr, tail_range, buffer_index);
+
+			return buffer;
+		}
+
+		/* Advance tail to next range, if there is one. */
+		if (++pgsr->tail == pgsr->size)
+			pgsr->tail = 0;
+		pgsr->next_tail_buffer = 0;
+
+		/*
+		 * If tail crashed into head, and head is not empty, then it is time
+		 * to start that range.
+		 */
+		if (pgsr->tail == pgsr->head &&
+			pgsr->ranges[pgsr->head].nblocks > 0)
+			pg_streaming_read_start_head_range(pgsr);
+	}
+
+	Assert(pgsr->pinned_buffers == 0);
+
+	return InvalidBuffer;
+}
+
+void
+pg_streaming_read_free(PgStreamingRead *pgsr)
+{
+	Buffer		buffer;
+
+	/* Stop looking ahead. */
+	pgsr->finished = true;
+
+	/* Unpin anything that wasn't consumed. */
+	while ((buffer = pg_streaming_read_buffer_get_next(pgsr, NULL)) != InvalidBuffer)
+		ReleaseBuffer(buffer);
+
+	Assert(pgsr->pinned_buffers == 0);
+	Assert(pgsr->ios_in_progress == 0);
+
+	/* Release memory. */
+	if (pgsr->per_buffer_data)
+		pfree(pgsr->per_buffer_data);
+
+	pfree(pgsr);
+}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index bdf89bbc4dc..3b1b0ad99df 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -19,6 +19,11 @@
  *		and pin it so that no one can destroy it while this process
  *		is using it.
  *
+ * StartReadBuffers() -- as above, but for multiple contiguous blocks in
+ *		two steps.
+ *
+ * WaitReadBuffers() -- second step of StartReadBuffers().
+ *
  * ReleaseBuffer() -- unpin a buffer
  *
  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
@@ -472,10 +477,9 @@ ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
 )
 
 
-static Buffer ReadBuffer_common(SMgrRelation smgr, char relpersistence,
+static Buffer ReadBuffer_common(BufferManagerRelation bmr,
 								ForkNumber forkNum, BlockNumber blockNum,
-								ReadBufferMode mode, BufferAccessStrategy strategy,
-								bool *hit);
+								ReadBufferMode mode, BufferAccessStrategy strategy);
 static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
 										   ForkNumber fork,
 										   BufferAccessStrategy strategy,
@@ -501,7 +505,7 @@ static uint32 WaitBufHdrUnlocked(BufferDesc *buf);
 static int	SyncOneBuffer(int buf_id, bool skip_recently_used,
 						  WritebackContext *wb_context);
 static void WaitIO(BufferDesc *buf);
-static bool StartBufferIO(BufferDesc *buf, bool forInput);
+static bool StartBufferIO(BufferDesc *buf, bool forInput, bool nowait);
 static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
 							  uint32 set_flag_bits, bool forget_owner);
 static void AbortBufferIO(Buffer buffer);
@@ -782,7 +786,6 @@ Buffer
 ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				   ReadBufferMode mode, BufferAccessStrategy strategy)
 {
-	bool		hit;
 	Buffer		buf;
 
 	/*
@@ -795,15 +798,9 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("cannot access temporary tables of other sessions")));
 
-	/*
-	 * Read the buffer, and update pgstat counters to reflect a cache hit or
-	 * miss.
-	 */
-	pgstat_count_buffer_read(reln);
-	buf = ReadBuffer_common(RelationGetSmgr(reln), reln->rd_rel->relpersistence,
-							forkNum, blockNum, mode, strategy, &hit);
-	if (hit)
-		pgstat_count_buffer_hit(reln);
+	buf = ReadBuffer_common(BMR_REL(reln),
+							forkNum, blockNum, mode, strategy);
+
 	return buf;
 }
 
@@ -823,13 +820,12 @@ ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
 						  BlockNumber blockNum, ReadBufferMode mode,
 						  BufferAccessStrategy strategy, bool permanent)
 {
-	bool		hit;
-
 	SMgrRelation smgr = smgropen(rlocator, InvalidBackendId);
 
-	return ReadBuffer_common(smgr, permanent ? RELPERSISTENCE_PERMANENT :
-							 RELPERSISTENCE_UNLOGGED, forkNum, blockNum,
-							 mode, strategy, &hit);
+	return ReadBuffer_common(BMR_SMGR(smgr, permanent ? RELPERSISTENCE_PERMANENT :
+									  RELPERSISTENCE_UNLOGGED),
+							 forkNum, blockNum,
+							 mode, strategy);
 }
 
 /*
@@ -995,35 +991,68 @@ ExtendBufferedRelTo(BufferManagerRelation bmr,
 	 */
 	if (buffer == InvalidBuffer)
 	{
-		bool		hit;
-
 		Assert(extended_by == 0);
-		buffer = ReadBuffer_common(bmr.smgr, bmr.relpersistence,
-								   fork, extend_to - 1, mode, strategy,
-								   &hit);
+		buffer = ReadBuffer_common(bmr, fork, extend_to - 1, mode, strategy);
 	}
 
 	return buffer;
 }
 
+/*
+ * Zero a buffer and lock it, as part of the implementation of
+ * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK.  The buffer must be already
+ * pinned.  It does not have to be valid, but it is valid and locked on
+ * return.
+ */
+static void
+ZeroBuffer(Buffer buffer, ReadBufferMode mode)
+{
+	BufferDesc *bufHdr;
+	uint32		buf_state;
+
+	Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
+
+	if (BufferIsLocal(buffer))
+		bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+	else
+	{
+		bufHdr = GetBufferDescriptor(buffer - 1);
+		if (mode == RBM_ZERO_AND_LOCK)
+			LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
+		else
+			LockBufferForCleanup(buffer);
+	}
+
+	memset(BufferGetPage(buffer), 0, BLCKSZ);
+
+	if (BufferIsLocal(buffer))
+	{
+		buf_state = pg_atomic_read_u32(&bufHdr->state);
+		buf_state |= BM_VALID;
+		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+	}
+	else
+	{
+		buf_state = LockBufHdr(bufHdr);
+		buf_state |= BM_VALID;
+		UnlockBufHdr(bufHdr, buf_state);
+	}
+}
+
 /*
  * ReadBuffer_common -- common logic for all ReadBuffer variants
  *
  * *hit is set to true if the request was satisfied from shared buffer cache.
  */
 static Buffer
-ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
+ReadBuffer_common(BufferManagerRelation bmr, ForkNumber forkNum,
 				  BlockNumber blockNum, ReadBufferMode mode,
-				  BufferAccessStrategy strategy, bool *hit)
+				  BufferAccessStrategy strategy)
 {
-	BufferDesc *bufHdr;
-	Block		bufBlock;
-	bool		found;
-	IOContext	io_context;
-	IOObject	io_object;
-	bool		isLocalBuf = SmgrIsTemp(smgr);
-
-	*hit = false;
+	ReadBuffersOperation operation;
+	Buffer		buffer;
+	int			nblocks;
+	int			flags;
 
 	/*
 	 * Backward compatibility path, most code should use ExtendBufferedRel()
@@ -1042,181 +1071,404 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
 			flags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_SMGR(smgr, relpersistence),
-								 forkNum, strategy, flags);
+		return ExtendBufferedRel(bmr, forkNum, strategy, flags);
 	}
 
-	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
-									   smgr->smgr_rlocator.locator.spcOid,
-									   smgr->smgr_rlocator.locator.dbOid,
-									   smgr->smgr_rlocator.locator.relNumber,
-									   smgr->smgr_rlocator.backend);
+	nblocks = 1;
+	if (mode == RBM_ZERO_ON_ERROR)
+		flags = READ_BUFFERS_ZERO_ON_ERROR;
+	else
+		flags = 0;
+	if (StartReadBuffers(bmr,
+						 &buffer,
+						 forkNum,
+						 blockNum,
+						 &nblocks,
+						 strategy,
+						 flags,
+						 &operation))
+		WaitReadBuffers(&operation);
+	Assert(nblocks == 1);		/* single block can't be short */
+
+	if (mode == RBM_ZERO_AND_CLEANUP_LOCK || mode == RBM_ZERO_AND_LOCK)
+		ZeroBuffer(buffer, mode);
+
+	return buffer;
+}
+
+static Buffer
+PrepareReadBuffer(BufferManagerRelation bmr,
+				  ForkNumber forkNum,
+				  BlockNumber blockNum,
+				  BufferAccessStrategy strategy,
+				  bool *foundPtr)
+{
+	BufferDesc *bufHdr;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	Assert(blockNum != P_NEW);
 
+	Assert(bmr.smgr);
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/*
-		 * We do not use a BufferAccessStrategy for I/O of temporary tables.
-		 * However, in some cases, the "strategy" may not be NULL, so we can't
-		 * rely on IOContextForStrategy() to set the right IOContext for us.
-		 * This may happen in cases like CREATE TEMPORARY TABLE AS...
-		 */
 		io_context = IOCONTEXT_NORMAL;
 		io_object = IOOBJECT_TEMP_RELATION;
-		bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, &found);
-		if (found)
-			pgBufferUsage.local_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.local_blks_read++;
 	}
 	else
 	{
-		/*
-		 * lookup the buffer.  IO_IN_PROGRESS is set if the requested block is
-		 * not currently in memory.
-		 */
 		io_context = IOContextForStrategy(strategy);
 		io_object = IOOBJECT_RELATION;
-		bufHdr = BufferAlloc(smgr, relpersistence, forkNum, blockNum,
-							 strategy, &found, io_context);
-		if (found)
-			pgBufferUsage.shared_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.shared_blks_read++;
 	}
 
-	/* At this point we do NOT hold any locks. */
+	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
+									   bmr.smgr->smgr_rlocator.locator.spcOid,
+									   bmr.smgr->smgr_rlocator.locator.dbOid,
+									   bmr.smgr->smgr_rlocator.locator.relNumber,
+									   bmr.smgr->smgr_rlocator.backend);
 
-	/* if it was already in the buffer pool, we're done */
-	if (found)
+	ResourceOwnerEnlarge(CurrentResourceOwner);
+	if (isLocalBuf)
+	{
+		bufHdr = LocalBufferAlloc(bmr.smgr, forkNum, blockNum, foundPtr);
+		if (*foundPtr)
+			pgBufferUsage.local_blks_hit++;
+	}
+	else
+	{
+		bufHdr = BufferAlloc(bmr.smgr, bmr.relpersistence, forkNum, blockNum,
+							 strategy, foundPtr, io_context);
+		if (*foundPtr)
+			pgBufferUsage.shared_blks_hit++;
+	}
+	if (bmr.rel)
+	{
+		/*
+		 * While pgBufferUsage's "read" counter isn't bumped unless we reach
+		 * WaitReadBuffers() (so, not for hits, and not for buffers that are
+		 * zeroed instead), the per-relation stats always count them.
+		 */
+		pgstat_count_buffer_read(bmr.rel);
+		if (*foundPtr)
+			pgstat_count_buffer_hit(bmr.rel);
+	}
+	if (*foundPtr)
 	{
-		/* Just need to update stats before we exit */
-		*hit = true;
 		VacuumPageHit++;
 		pgstat_count_io_op(io_object, io_context, IOOP_HIT);
-
 		if (VacuumCostActive)
 			VacuumCostBalance += VacuumCostPageHit;
 
 		TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-										  smgr->smgr_rlocator.locator.spcOid,
-										  smgr->smgr_rlocator.locator.dbOid,
-										  smgr->smgr_rlocator.locator.relNumber,
-										  smgr->smgr_rlocator.backend,
-										  found);
+										  bmr.smgr->smgr_rlocator.locator.spcOid,
+										  bmr.smgr->smgr_rlocator.locator.dbOid,
+										  bmr.smgr->smgr_rlocator.locator.relNumber,
+										  bmr.smgr->smgr_rlocator.backend,
+										  true);
+	}
 
-		/*
-		 * In RBM_ZERO_AND_LOCK mode the caller expects the page to be locked
-		 * on return.
-		 */
-		if (!isLocalBuf)
-		{
-			if (mode == RBM_ZERO_AND_LOCK)
-				LWLockAcquire(BufferDescriptorGetContentLock(bufHdr),
-							  LW_EXCLUSIVE);
-			else if (mode == RBM_ZERO_AND_CLEANUP_LOCK)
-				LockBufferForCleanup(BufferDescriptorGetBuffer(bufHdr));
-		}
+	return BufferDescriptorGetBuffer(bufHdr);
+}
 
-		return BufferDescriptorGetBuffer(bufHdr);
+/*
+ * Begin reading a range of blocks beginning at blockNum and extending for
+ * *nblocks.  On return, up to *nblocks pinned buffers holding those blocks
+ * are written into the buffers array, and *nblocks is updated to contain the
+ * actual number, which may be fewer than requested.
+ *
+ * If false is returned, no I/O is necessary and WaitReadBuffers() is not
+ * necessary.  If true is returned, one I/O has been started, and
+ * WaitReadBuffers() must be called with the same operation object before the
+ * buffers are accessed.  Along with the operation object, the caller-supplied
+ * array of buffers must remain valid until WaitReadBuffers() is called.
+ *
+ * Currently the I/O is only started with optional operating system advice,
+ * and the real I/O happens in WaitReadBuffers().  In future work, true I/O
+ * could be initiated here.
+ */
+bool
+StartReadBuffers(BufferManagerRelation bmr,
+				 Buffer *buffers,
+				 ForkNumber forkNum,
+				 BlockNumber blockNum,
+				 int *nblocks,
+				 BufferAccessStrategy strategy,
+				 int flags,
+				 ReadBuffersOperation *operation)
+{
+	int			actual_nblocks = *nblocks;
+
+	if (bmr.rel)
+	{
+		bmr.smgr = RelationGetSmgr(bmr.rel);
+		bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
 	}
 
-	/*
-	 * if we have gotten to this point, we have allocated a buffer for the
-	 * page but its contents are not yet valid.  IO_IN_PROGRESS is set for it,
-	 * if it's a shared buffer.
-	 */
-	Assert(!(pg_atomic_read_u32(&bufHdr->state) & BM_VALID));	/* spinlock not needed */
+	operation->bmr = bmr;
+	operation->forknum = forkNum;
+	operation->blocknum = blockNum;
+	operation->buffers = buffers;
+	operation->nblocks = actual_nblocks;
+	operation->strategy = strategy;
+	operation->flags = flags;
 
-	bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
+	operation->io_buffers_len = 0;
 
-	/*
-	 * Read in the page, unless the caller intends to overwrite it and just
-	 * wants us to allocate a buffer.
-	 */
-	if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-		MemSet((char *) bufBlock, 0, BLCKSZ);
-	else
+	for (int i = 0; i < actual_nblocks; ++i)
 	{
-		instr_time	io_start = pgstat_prepare_io_time(track_io_timing);
+		bool		found;
 
-		smgrread(smgr, forkNum, blockNum, bufBlock);
+		buffers[i] = PrepareReadBuffer(bmr,
+									   forkNum,
+									   blockNum + i,
+									   strategy,
+									   &found);
 
-		pgstat_count_io_op_time(io_object, io_context,
-								IOOP_READ, io_start, 1);
+		if (found)
+		{
+			/*
+			 * Terminate the read as soon as we get a hit.  It could be a
+			 * single buffer hit, or it could be a hit that follows a readable
+			 * range.  We don't want to create more than one readable range,
+			 * so we stop here.
+			 */
+			actual_nblocks = operation->nblocks = *nblocks = i + 1;
+		}
+		else
+		{
+			/* Extend the readable range to cover this block. */
+			operation->io_buffers_len++;
+		}
+	}
 
-		/* check for garbage data */
-		if (!PageIsVerifiedExtended((Page) bufBlock, blockNum,
-									PIV_LOG_WARNING | PIV_REPORT_STAT))
+	if (operation->io_buffers_len > 0)
+	{
+		if (flags & READ_BUFFERS_ISSUE_ADVICE)
 		{
-			if (mode == RBM_ZERO_ON_ERROR || zero_damaged_pages)
-			{
-				ereport(WARNING,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s; zeroing out page",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
-				MemSet((char *) bufBlock, 0, BLCKSZ);
-			}
-			else
-				ereport(ERROR,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
+			/*
+			 * In theory we should only do this if PrepareReadBuffers() had to
+			 * allocate new buffers above.  That way, if two calls to
+			 * StartReadBuffers() were made for the same blocks before
+			 * WaitReadBuffers(), only the first would issue the advice.
+			 * That'd be a better simulation of true asynchronous I/O, which
+			 * would only start the I/O once, but isn't done here for
+			 * simplicity.  Note also that the following call might actually
+			 * issue two advice calls if we cross a segment boundary; in a
+			 * true asynchronous version we might choose to process only one
+			 * real I/O at a time in that case.
+			 */
+			smgrprefetch(bmr.smgr, forkNum, blockNum, operation->io_buffers_len);
 		}
+
+		/* Indicate that WaitReadBuffers() should be called. */
+		return true;
 	}
+	else
+	{
+		return false;
+	}
+}
 
-	/*
-	 * In RBM_ZERO_AND_LOCK / RBM_ZERO_AND_CLEANUP_LOCK mode, grab the buffer
-	 * content lock before marking the page as valid, to make sure that no
-	 * other backend sees the zeroed page before the caller has had a chance
-	 * to initialize it.
-	 *
-	 * Since no-one else can be looking at the page contents yet, there is no
-	 * difference between an exclusive lock and a cleanup-strength lock. (Note
-	 * that we cannot use LockBuffer() or LockBufferForCleanup() here, because
-	 * they assert that the buffer is already valid.)
-	 */
-	if ((mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK) &&
-		!isLocalBuf)
+static inline bool
+WaitReadBuffersCanStartIO(Buffer buffer, bool nowait)
+{
+	if (BufferIsLocal(buffer))
 	{
-		LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_EXCLUSIVE);
+		BufferDesc *bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+
+		return (pg_atomic_read_u32(&bufHdr->state) & BM_VALID) == 0;
 	}
+	else
+		return StartBufferIO(GetBufferDescriptor(buffer - 1), true, nowait);
+}
+
+void
+WaitReadBuffers(ReadBuffersOperation *operation)
+{
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	int			nblocks;
+	BlockNumber blocknum;
+	ForkNumber	forknum;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	/*
+	 * Currently operations are only allowed to include a read of some range,
+	 * with an optional extra buffer that is already pinned at the end.  So
+	 * nblocks can be at most one more than io_buffers_len.
+	 */
+	Assert((operation->nblocks == operation->io_buffers_len) ||
+		   (operation->nblocks == operation->io_buffers_len + 1));
 
+	/* Find the range of the physical read we need to perform. */
+	nblocks = operation->io_buffers_len;
+	if (nblocks == 0)
+		return;					/* nothing to do */
+
+	buffers = &operation->buffers[0];
+	blocknum = operation->blocknum;
+	forknum = operation->forknum;
+	bmr = operation->bmr;
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/* Only need to adjust flags */
-		uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
-
-		buf_state |= BM_VALID;
-		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+		io_context = IOCONTEXT_NORMAL;
+		io_object = IOOBJECT_TEMP_RELATION;
 	}
 	else
 	{
-		/* Set BM_VALID, terminate IO, and wake up any waiters */
-		TerminateBufferIO(bufHdr, false, BM_VALID, true);
+		io_context = IOContextForStrategy(operation->strategy);
+		io_object = IOOBJECT_RELATION;
 	}
 
-	VacuumPageMiss++;
-	if (VacuumCostActive)
-		VacuumCostBalance += VacuumCostPageMiss;
+	/*
+	 * We count all these blocks as read by this backend.  This is traditional
+	 * behavior, but might turn out to be not true if we find that someone
+	 * else has beaten us and completed the read of some of these blocks.  In
+	 * that case the system globally double-counts, but we traditionally don't
+	 * count this as a "hit", and we don't have a separate counter for "miss,
+	 * but another backend completed the read".
+	 */
+	if (isLocalBuf)
+		pgBufferUsage.local_blks_read += nblocks;
+	else
+		pgBufferUsage.shared_blks_read += nblocks;
 
-	TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-									  smgr->smgr_rlocator.locator.spcOid,
-									  smgr->smgr_rlocator.locator.dbOid,
-									  smgr->smgr_rlocator.locator.relNumber,
-									  smgr->smgr_rlocator.backend,
-									  found);
+	for (int i = 0; i < nblocks; ++i)
+	{
+		int			io_buffers_len;
+		Buffer		io_buffers[MAX_BUFFERS_PER_TRANSFER];
+		void	   *io_pages[MAX_BUFFERS_PER_TRANSFER];
+		instr_time	io_start;
+		BlockNumber io_first_block;
 
-	return BufferDescriptorGetBuffer(bufHdr);
+		/*
+		 * Skip this block if someone else has already completed it.  If an
+		 * I/O is already in progress in another backend, this will wait for
+		 * the outcome: either done, or something went wrong and we will
+		 * retry.
+		 */
+		if (!WaitReadBuffersCanStartIO(buffers[i], false))
+		{
+			/*
+			 * Report this as a 'hit' for this backend, even though it must
+			 * have started out as a miss in PrepareReadBuffer().
+			 */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, blocknum + i,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  true);
+			continue;
+		}
+
+		/* We found a buffer that we need to read in. */
+		io_buffers[0] = buffers[i];
+		io_pages[0] = BufferGetBlock(buffers[i]);
+		io_first_block = blocknum + i;
+		io_buffers_len = 1;
+
+		/*
+		 * How many neighboring-on-disk blocks can we can scatter-read into
+		 * other buffers at the same time?  In this case we don't wait if we
+		 * see an I/O already in progress.  We already hold BM_IO_IN_PROGRESS
+		 * for the head block, so we should get on with that I/O as soon as
+		 * possible.  We'll come back to this block again, above.
+		 */
+		while ((i + 1) < nblocks &&
+			   WaitReadBuffersCanStartIO(buffers[i + 1], true))
+		{
+			/* Must be consecutive block numbers. */
+			Assert(BufferGetBlockNumber(buffers[i + 1]) ==
+				   BufferGetBlockNumber(buffers[i]) + 1);
+
+			io_buffers[io_buffers_len] = buffers[++i];
+			io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
+		}
+
+		io_start = pgstat_prepare_io_time(track_io_timing);
+		smgrreadv(bmr.smgr, forknum, io_first_block, io_pages, io_buffers_len);
+		pgstat_count_io_op_time(io_object, io_context, IOOP_READ, io_start,
+								io_buffers_len);
+
+		/* Verify each block we read, and terminate the I/O. */
+		for (int j = 0; j < io_buffers_len; ++j)
+		{
+			BufferDesc *bufHdr;
+			Block		bufBlock;
+
+			if (isLocalBuf)
+			{
+				bufHdr = GetLocalBufferDescriptor(-io_buffers[j] - 1);
+				bufBlock = LocalBufHdrGetBlock(bufHdr);
+			}
+			else
+			{
+				bufHdr = GetBufferDescriptor(io_buffers[j] - 1);
+				bufBlock = BufHdrGetBlock(bufHdr);
+			}
+
+			/* check for garbage data */
+			if (!PageIsVerifiedExtended((Page) bufBlock, io_first_block + j,
+										PIV_LOG_WARNING | PIV_REPORT_STAT))
+			{
+				if ((operation->flags & READ_BUFFERS_ZERO_ON_ERROR) || zero_damaged_pages)
+				{
+					ereport(WARNING,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s; zeroing out page",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+					memset(bufBlock, 0, BLCKSZ);
+				}
+				else
+					ereport(ERROR,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+			}
+
+			/* Terminate I/O and set BM_VALID. */
+			if (isLocalBuf)
+			{
+				uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
+
+				buf_state |= BM_VALID;
+				pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+			}
+			else
+			{
+				/* Set BM_VALID, terminate IO, and wake up any waiters */
+				TerminateBufferIO(bufHdr, false, BM_VALID, true);
+			}
+
+			/* Report I/Os as completing individually. */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, io_first_block + j,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  false);
+		}
+
+		VacuumPageMiss += io_buffers_len;
+		if (VacuumCostActive)
+			VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
+	}
 }
 
 /*
- * BufferAlloc -- subroutine for ReadBuffer.  Handles lookup of a shared
- *		buffer.  If no buffer exists already, selects a replacement
- *		victim and evicts the old page, but does NOT read in new page.
+ * BufferAlloc -- subroutine for StartReadBuffers.  Handles lookup of a shared
+ *		buffer.  If no buffer exists already, selects a replacement victim and
+ *		evicts the old page, but does NOT read in new page.
  *
  * "strategy" can be a buffer replacement strategy object, or NULL for
  * the default strategy.  The selected buffer's usage_count is advanced when
@@ -1224,11 +1476,7 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
  *
  * The returned buffer is pinned and is already marked as holding the
  * desired page.  If it already did have the desired page, *foundPtr is
- * set true.  Otherwise, *foundPtr is set false and the buffer is marked
- * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.
- *
- * *foundPtr is actually redundant with the buffer's BM_VALID flag, but
- * we keep it for simplicity in ReadBuffer.
+ * set true.  Otherwise, *foundPtr is set false.
  *
  * io_context is passed as an output parameter to avoid calling
  * IOContextForStrategy() when there is a shared buffers hit and no IO
@@ -1287,19 +1535,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(buf, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return buf;
@@ -1364,19 +1603,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(existing_buf_hdr, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return existing_buf_hdr;
@@ -1408,15 +1638,9 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 	LWLockRelease(newPartitionLock);
 
 	/*
-	 * Buffer contents are currently invalid.  Try to obtain the right to
-	 * start I/O.  If StartBufferIO returns false, then someone else managed
-	 * to read it before we did, so there's nothing left for BufferAlloc() to
-	 * do.
+	 * Buffer contents are currently invalid.
 	 */
-	if (StartBufferIO(victim_buf_hdr, true))
-		*foundPtr = false;
-	else
-		*foundPtr = true;
+	*foundPtr = false;
 
 	return victim_buf_hdr;
 }
@@ -1770,7 +1994,7 @@ again:
  * pessimistic, but outside of toy-sized shared_buffers it should allow
  * sufficient pins.
  */
-static void
+void
 LimitAdditionalPins(uint32 *additional_pins)
 {
 	uint32		max_backends;
@@ -2035,7 +2259,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 
 				buf_state &= ~BM_VALID;
 				UnlockBufHdr(existing_hdr, buf_state);
-			} while (!StartBufferIO(existing_hdr, true));
+			} while (!StartBufferIO(existing_hdr, true, false));
 		}
 		else
 		{
@@ -2058,7 +2282,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 			LWLockRelease(partition_lock);
 
 			/* XXX: could combine the locked operations in it with the above */
-			StartBufferIO(victim_buf_hdr, true);
+			StartBufferIO(victim_buf_hdr, true, false);
 		}
 	}
 
@@ -2373,7 +2597,12 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 	else
 	{
 		/*
-		 * If we previously pinned the buffer, it must surely be valid.
+		 * If we previously pinned the buffer, it is likely to be valid, but
+		 * it may not be if StartReadBuffers() was called and
+		 * WaitReadBuffers() hasn't been called yet.  We'll check by loading
+		 * the flags without locking.  This is racy, but it's OK to return
+		 * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
+		 * it'll see that it's now valid.
 		 *
 		 * Note: We deliberately avoid a Valgrind client request here.
 		 * Individual access methods can optionally superimpose buffer page
@@ -2382,7 +2611,7 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 		 * that the buffer page is legitimately non-accessible here.  We
 		 * cannot meddle with that.
 		 */
-		result = true;
+		result = (pg_atomic_read_u32(&buf->state) & BM_VALID) != 0;
 	}
 
 	ref->refcount++;
@@ -3450,7 +3679,7 @@ FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
 	 * someone else flushed the buffer before we could, so we need not do
 	 * anything.
 	 */
-	if (!StartBufferIO(buf, false))
+	if (!StartBufferIO(buf, false, false))
 		return;
 
 	/* Setup error traceback support for ereport() */
@@ -5185,9 +5414,15 @@ WaitIO(BufferDesc *buf)
  *
  * Returns true if we successfully marked the buffer as I/O busy,
  * false if someone else already did the work.
+ *
+ * If nowait is true, then we don't wait for an I/O to be finished by another
+ * backend.  In that case, false indicates either that the I/O was already
+ * finished, or is still in progress.  This is useful for callers that want to
+ * find out if they can perform the I/O as part of a larger operation, without
+ * waiting for the answer or distinguishing the reasons why not.
  */
 static bool
-StartBufferIO(BufferDesc *buf, bool forInput)
+StartBufferIO(BufferDesc *buf, bool forInput, bool nowait)
 {
 	uint32		buf_state;
 
@@ -5200,6 +5435,8 @@ StartBufferIO(BufferDesc *buf, bool forInput)
 		if (!(buf_state & BM_IO_IN_PROGRESS))
 			break;
 		UnlockBufHdr(buf, buf_state);
+		if (nowait)
+			return false;
 		WaitIO(buf);
 	}
 
diff --git a/src/backend/storage/buffer/localbuf.c b/src/backend/storage/buffer/localbuf.c
index 1f02fed250e..6956d4e5b49 100644
--- a/src/backend/storage/buffer/localbuf.c
+++ b/src/backend/storage/buffer/localbuf.c
@@ -109,10 +109,9 @@ PrefetchLocalBuffer(SMgrRelation smgr, ForkNumber forkNum,
  * LocalBufferAlloc -
  *	  Find or create a local buffer for the given page of the given relation.
  *
- * API is similar to bufmgr.c's BufferAlloc, except that we do not need
- * to do any locking since this is all local.   Also, IO_IN_PROGRESS
- * does not get set.  Lastly, we support only default access strategy
- * (hence, usage_count is always advanced).
+ * API is similar to bufmgr.c's BufferAlloc, except that we do not need to do
+ * any locking since this is all local.  We support only default access
+ * strategy (hence, usage_count is always advanced).
  */
 BufferDesc *
 LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum,
@@ -288,7 +287,7 @@ GetLocalVictimBuffer(void)
 }
 
 /* see LimitAdditionalPins() */
-static void
+void
 LimitAdditionalLocalPins(uint32 *additional_pins)
 {
 	uint32		max_pins;
@@ -298,9 +297,10 @@ LimitAdditionalLocalPins(uint32 *additional_pins)
 
 	/*
 	 * In contrast to LimitAdditionalPins() other backends don't play a role
-	 * here. We can allow up to NLocBuffer pins in total.
+	 * here. We can allow up to NLocBuffer pins in total, but it might not be
+	 * initialized yet so read num_temp_buffers.
 	 */
-	max_pins = (NLocBuffer - NLocalPinnedBuffers);
+	max_pins = (num_temp_buffers - NLocalPinnedBuffers);
 
 	if (*additional_pins >= max_pins)
 		*additional_pins = max_pins;
diff --git a/src/backend/storage/meson.build b/src/backend/storage/meson.build
index 40345bdca27..739d13293fb 100644
--- a/src/backend/storage/meson.build
+++ b/src/backend/storage/meson.build
@@ -1,5 +1,6 @@
 # Copyright (c) 2022-2024, PostgreSQL Global Development Group
 
+subdir('aio')
 subdir('buffer')
 subdir('file')
 subdir('freespace')
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index d51d46d3353..b57f71f97e3 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -14,6 +14,7 @@
 #ifndef BUFMGR_H
 #define BUFMGR_H
 
+#include "port/pg_iovec.h"
 #include "storage/block.h"
 #include "storage/buf.h"
 #include "storage/bufpage.h"
@@ -158,6 +159,11 @@ extern PGDLLIMPORT int32 *LocalRefCount;
 #define BUFFER_LOCK_SHARE		1
 #define BUFFER_LOCK_EXCLUSIVE	2
 
+/*
+ * Maximum number of buffers for multi-buffer I/O functions.  This is set to
+ * allow 128kB transfers, unless BLCKSZ and IOV_MAX imply a a smaller maximum.
+ */
+#define MAX_BUFFERS_PER_TRANSFER Min(PG_IOV_MAX, (128 * 1024) / BLCKSZ)
 
 /*
  * prototypes for functions in bufmgr.c
@@ -177,6 +183,42 @@ extern Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator,
 										ForkNumber forkNum, BlockNumber blockNum,
 										ReadBufferMode mode, BufferAccessStrategy strategy,
 										bool permanent);
+
+#define READ_BUFFERS_ZERO_ON_ERROR 0x01
+#define READ_BUFFERS_ISSUE_ADVICE 0x02
+
+/*
+ * Private state used by StartReadBuffers() and WaitReadBuffers().  Declared
+ * in public header only to allow inclusion in other structs, but contents
+ * should not be accessed.
+ */
+struct ReadBuffersOperation
+{
+	/* Parameters passed in to StartReadBuffers(). */
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	ForkNumber	forknum;
+	BlockNumber blocknum;
+	int			nblocks;
+	BufferAccessStrategy strategy;
+	int			flags;
+
+	/* Range of buffers, if we need to perform a read. */
+	int			io_buffers_len;
+};
+
+typedef struct ReadBuffersOperation ReadBuffersOperation;
+
+extern bool StartReadBuffers(BufferManagerRelation bmr,
+							 Buffer *buffers,
+							 ForkNumber forknum,
+							 BlockNumber blocknum,
+							 int *nblocks,
+							 BufferAccessStrategy strategy,
+							 int flags,
+							 ReadBuffersOperation *operation);
+extern void WaitReadBuffers(ReadBuffersOperation *operation);
+
 extern void ReleaseBuffer(Buffer buffer);
 extern void UnlockReleaseBuffer(Buffer buffer);
 extern bool BufferIsExclusiveLocked(Buffer buffer);
@@ -250,6 +292,9 @@ extern bool HoldingBufferPinThatDelaysRecovery(void);
 
 extern bool BgBufferSync(struct WritebackContext *wb_context);
 
+extern void LimitAdditionalPins(uint32 *additional_pins);
+extern void LimitAdditionalLocalPins(uint32 *additional_pins);
+
 /* in buf_init.c */
 extern void InitBufferPool(void);
 extern Size BufferShmemSize(void);
diff --git a/src/include/storage/streaming_read.h b/src/include/storage/streaming_read.h
new file mode 100644
index 00000000000..c4d3892bb26
--- /dev/null
+++ b/src/include/storage/streaming_read.h
@@ -0,0 +1,52 @@
+#ifndef STREAMING_READ_H
+#define STREAMING_READ_H
+
+#include "storage/bufmgr.h"
+#include "storage/fd.h"
+#include "storage/smgr.h"
+
+/* Default tuning, reasonable for many users. */
+#define PGSR_FLAG_DEFAULT 0x00
+
+/*
+ * I/O streams that are performing maintenance work on behalf of potentially
+ * many users.
+ */
+#define PGSR_FLAG_MAINTENANCE 0x01
+
+/*
+ * We usually avoid issuing prefetch advice automatically when sequential
+ * access is detected, but this flag explicitly disables it, for cases that
+ * might not be correctly detected.  Explicit advice is known to perform worse
+ * than letting the kernel (at least Linux) detect sequential access.
+ */
+#define PGSR_FLAG_SEQUENTIAL 0x02
+
+/*
+ * We usually ramp up from smaller reads to larger ones, to support users who
+ * don't know if it's worth reading lots of buffers yet.  This flag disables
+ * that, declaring ahead of time that we'll be reading all available buffers.
+ */
+#define PGSR_FLAG_FULL 0x04
+
+struct PgStreamingRead;
+typedef struct PgStreamingRead PgStreamingRead;
+
+/* Callback that returns the next block number to read. */
+typedef BlockNumber (*PgStreamingReadBufferCB) (PgStreamingRead *pgsr,
+												void *pgsr_private,
+												void *per_buffer_private);
+
+extern PgStreamingRead *pg_streaming_read_buffer_alloc(int flags,
+													   void *pgsr_private,
+													   size_t per_buffer_private_size,
+													   BufferAccessStrategy strategy,
+													   BufferManagerRelation bmr,
+													   ForkNumber forknum,
+													   PgStreamingReadBufferCB next_block_cb);
+
+extern void pg_streaming_read_prefetch(PgStreamingRead *pgsr);
+extern Buffer pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_private);
+extern void pg_streaming_read_free(PgStreamingRead *pgsr);
+
+#endif
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index fc8b15d0cf2..cfb58cf4836 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2097,6 +2097,8 @@ PgStat_TableCounts
 PgStat_TableStatus
 PgStat_TableXactStatus
 PgStat_WalStats
+PgStreamingRead
+PgStreamingReadRange
 PgXmlErrorContext
 PgXmlStrictness
 Pg_finfo_record
@@ -2267,6 +2269,7 @@ ReInitializeDSMForeignScan_function
 ReScanForeignScan_function
 ReadBufPtrType
 ReadBufferMode
+ReadBuffersOperation
 ReadBytePtrType
 ReadExtraTocPtrType
 ReadFunc
-- 
2.37.2



  [text/x-patch] v5-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch (15.8K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/6-v5-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch)
  download | inline diff:
From 1bcc771d1b6baeb70b50a071a9274842051d6365 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v5 2/7] Add lazy_scan_skip unskippable state to LVRelState

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce add a struct to LVRelState containing variables needed to skip
ranges less than SKIP_PAGES_THRESHOLD.

lazy_scan_prune() and lazy_scan_new_or_empty() can now access the
buffer containing the relevant block of the visibility map through the
LVRelState.skip, so it no longer needs to be a separate function
parameter.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 154 ++++++++++++++++-----------
 1 file changed, 90 insertions(+), 64 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index e21c1124f5c..077164896fb 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -210,6 +210,22 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/*
+	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
+	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 */
+	struct
+	{
+		/* Next unskippable block */
+		BlockNumber next_unskippable_block;
+		/* Buffer containing next unskippable block's visibility info */
+		Buffer		vmbuffer;
+		/* Next unskippable block's visibility status */
+		bool		next_unskippable_allvis;
+		/* Whether or not skippable blocks should be skipped */
+		bool		skipping_current_range;
+	}			skip;
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -220,19 +236,15 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
-
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
-								   bool sharelock, Buffer vmbuffer);
+								   bool sharelock);
 static void lazy_scan_prune(LVRelState *vacrel, Buffer buf,
 							BlockNumber blkno, Page page,
-							Buffer vmbuffer, bool all_visible_according_to_vm,
+							bool all_visible_according_to_vm,
 							bool *has_lpdead_items);
 static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 							  BlockNumber blkno, Page page,
@@ -809,12 +821,8 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -828,10 +836,9 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.vmbuffer = InvalidBuffer;
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, 0);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -840,26 +847,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacrel->skip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, blkno + 1);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacrel->skip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -902,10 +906,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacrel->skip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacrel->skip.vmbuffer);
+				vacrel->skip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -930,7 +934,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
 		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
 								 vacrel->bstrategy);
@@ -948,8 +952,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			LockBuffer(buf, BUFFER_LOCK_SHARE);
 
 		/* Check for new or empty pages before lazy_scan_[no]prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
-								   vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -991,7 +994,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1041,8 +1044,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacrel->skip.vmbuffer))
+	{
+		ReleaseBuffer(vacrel->skip.vmbuffer);
+		vacrel->skip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1086,15 +1092,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in skip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
+ *
+ * The block number and visibility status of the next unskippable block are set
+ * in skip->next_unskippable_block and next_unskippable_allvis.
+ * skip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1104,25 +1129,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
 {
+	/* Use local variables for better optimized loop code */
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_unskippable_block = next_block;
+
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
+	vacrel->skip.next_unskippable_allvis = true;
 	while (next_unskippable_block < rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
-													   vmbuffer);
+													   &vacrel->skip.vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1143,7 +1169,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1168,6 +1194,8 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		next_unskippable_block++;
 	}
 
+	vacrel->skip.next_unskippable_block = next_unskippable_block;
+
 	/*
 	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
 	 * pages.  Since we're reading sequentially, the OS should be doing
@@ -1178,16 +1206,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacrel->skip.skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacrel->skip.skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
@@ -1220,7 +1246,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
  */
 static bool
 lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
-					   Page page, bool sharelock, Buffer vmbuffer)
+					   Page page, bool sharelock)
 {
 	Size		freespace;
 
@@ -1306,7 +1332,7 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
 
 			PageSetAllVisible(page);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacrel->skip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
 			END_CRIT_SECTION();
 		}
@@ -1342,10 +1368,11 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
  * any tuple that becomes dead after the call to heap_page_prune() can't need to
  * be frozen, because it was visible to another session when vacuum started.
  *
- * vmbuffer is the buffer containing the VM block with visibility information
- * for the heap block, blkno. all_visible_according_to_vm is the saved
- * visibility status of the heap block looked up earlier by the caller. We
- * won't rely entirely on this status, as it may be out of date.
+ * vacrel->skipstate.vmbuffer is the buffer containing the VM block with
+ * visibility information for the heap block, blkno.
+ * all_visible_according_to_vm is the saved visibility status of the heap block
+ * looked up earlier by the caller. We won't rely entirely on this status, as
+ * it may be out of date.
  *
  * *has_lpdead_items is set to true or false depending on whether, upon return
  * from this function, any LP_DEAD items are still present on the page.
@@ -1355,7 +1382,6 @@ lazy_scan_prune(LVRelState *vacrel,
 				Buffer buf,
 				BlockNumber blkno,
 				Page page,
-				Buffer vmbuffer,
 				bool all_visible_according_to_vm,
 				bool *has_lpdead_items)
 {
@@ -1789,7 +1815,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		PageSetAllVisible(page);
 		MarkBufferDirty(buf);
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, visibility_cutoff_xid,
+						  vacrel->skip.vmbuffer, visibility_cutoff_xid,
 						  flags);
 	}
 
@@ -1800,11 +1826,11 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+			 visibilitymap_get_status(vacrel->rel, blkno, &vacrel->skip.vmbuffer) != 0)
 	{
 		elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 			 vacrel->relname, blkno);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1828,7 +1854,7 @@ lazy_scan_prune(LVRelState *vacrel,
 			 vacrel->relname, blkno);
 		PageClearAllVisible(page);
 		MarkBufferDirty(buf);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1838,7 +1864,7 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * true, so we must check both all_visible and all_frozen.
 	 */
 	else if (all_visible_according_to_vm && all_visible &&
-			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vacrel->skip.vmbuffer))
 	{
 		/*
 		 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1860,7 +1886,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		 */
 		Assert(!TransactionIdIsValid(visibility_cutoff_xid));
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, InvalidTransactionId,
+						  vacrel->skip.vmbuffer, InvalidTransactionId,
 						  VISIBILITYMAP_ALL_VISIBLE |
 						  VISIBILITYMAP_ALL_FROZEN);
 	}
-- 
2.37.2



  [text/x-patch] v5-0006-Vacuum-first-pass-uses-Streaming-Read-interface.patch (8.3K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/7-v5-0006-Vacuum-first-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From f7e49269cf4e5ef0d2ef3ba0be42351bc1030ddb Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 11:29:02 -0500
Subject: [PATCH v5 6/7] Vacuum first pass uses Streaming Read interface

Now vacuum's first pass, which HOT prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by implementing a
streaming read callback which invokes heap_vac_scan_get_next_block().
---
 src/backend/access/heap/vacuumlazy.c | 79 +++++++++++++++++++++-------
 1 file changed, 59 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index ea270941379..96150834614 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -59,6 +59,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/streaming_read.h"
 #include "tcop/tcopprot.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
@@ -174,7 +175,12 @@ typedef struct LVRelState
 	char	   *relnamespace;
 	char	   *relname;
 	char	   *indname;		/* Current index name */
-	BlockNumber blkno;			/* used only for heap operations */
+
+	/*
+	 * The current block being processed by vacuum. Used only for heap
+	 * operations. Primarily for error reporting and logging.
+	 */
+	BlockNumber blkno;
 	OffsetNumber offnum;		/* used only for heap operations */
 	VacErrPhase phase;
 	bool		verbose;		/* VACUUM VERBOSE? */
@@ -195,6 +201,12 @@ typedef struct LVRelState
 	BlockNumber missed_dead_pages;	/* # pages with missed dead tuples */
 	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
 
+	/*
+	 * The most recent block submitted in the streaming read callback by the
+	 * first vacuum pass.
+	 */
+	BlockNumber blkno_prefetch;
+
 	/* Statistics output by us, for table */
 	double		new_rel_tuples; /* new estimated total # of tuples */
 	double		new_live_tuples;	/* new estimated total # of live tuples */
@@ -238,7 +250,7 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+static void heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 										 BlockNumber *blkno,
 										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
@@ -422,6 +434,9 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 	vacrel->nonempty_pages = 0;
 	/* dead_items_alloc allocates vacrel->dead_items later on */
 
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	vacrel->blkno_prefetch = InvalidBlockNumber;
+
 	/* Allocate/initialize output statistics state */
 	vacrel->new_rel_tuples = 0;
 	vacrel->new_live_tuples = 0;
@@ -782,6 +797,22 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 	}
 }
 
+static BlockNumber
+vacuum_scan_pgsr_next(PgStreamingRead *pgsr,
+					  void *pgsr_private, void *per_buffer_data)
+{
+	LVRelState *vacrel = pgsr_private;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
+
+	vacrel->blkno_prefetch++;
+
+	heap_vac_scan_get_next_block(vacrel,
+								 vacrel->blkno_prefetch, &vacrel->blkno_prefetch,
+								 all_visible_according_to_vm);
+
+	return vacrel->blkno_prefetch;
+}
+
 /*
  *	lazy_scan_heap() -- workhorse function for VACUUM
  *
@@ -821,12 +852,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm;
 
-	/* relies on InvalidBlockNumber overflowing to 0 */
-	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -834,6 +864,11 @@ lazy_scan_heap(LVRelState *vacrel)
 		PROGRESS_VACUUM_MAX_DEAD_TUPLES
 	};
 	int64		initprog_val[3];
+	PgStreamingRead *pgsr;
+
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(bool), vacrel->bstrategy, BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM, vacuum_scan_pgsr_next);
 
 	/* Report that we're scanning the heap, advertising total # of blocks */
 	initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
@@ -844,13 +879,19 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
-										&blkno, &all_visible_according_to_vm))
+	while (BufferIsValid(buf =
+						 pg_streaming_read_buffer_get_next(pgsr, (void **) &all_visible_according_to_vm)))
 	{
-		Buffer		buf;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
+		BlockNumber blkno;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		CheckBufferIsPinnedOnce(buf);
+
+		page = BufferGetPage(buf);
 
 		vacrel->scanned_pages++;
 
@@ -918,9 +959,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
 
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
@@ -976,7 +1014,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							all_visible_according_to_vm,
+							*all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1033,7 +1071,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, vacrel->rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1048,6 +1086,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	pg_streaming_read_free(pgsr);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1059,11 +1099,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (vacrel->rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, vacrel->rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, vacrel->rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1096,7 +1136,7 @@ lazy_scan_heap(LVRelState *vacrel)
  *
  * The block number and visibility status of the next block to process are set
  * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
- * returns false if there are no further blocks to process.
+ * sets blkno to InvalidBlockNumber if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here; vacuum options and information about the
  * relation are read and vacrel->skippedallvis is set to ensure we don't
@@ -1116,7 +1156,7 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static bool
+static void
 heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
@@ -1125,7 +1165,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 	if (next_block >= vacrel->rel_pages)
 	{
 		*blkno = InvalidBlockNumber;
-		return false;
+		return;
 	}
 
 	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
@@ -1220,7 +1260,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 		*all_visible_according_to_vm = true;
 
 	*blkno = next_block;
-	return true;
 }
 
 /*
-- 
2.37.2



  [text/x-patch] v5-0007-Vacuum-second-pass-uses-Streaming-Read-interface.patch (8.2K, ../../CAAKRu_bQgf4e9OveCQX++zTEJLKbZbqLeapA7SNkNuMjxcCO1w@mail.gmail.com/8-v5-0007-Vacuum-second-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From 4aa8c614440ac384459b07f803194bd08fbca554 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 27 Feb 2024 14:35:36 -0500
Subject: [PATCH v5 7/7] Vacuum second pass uses Streaming Read interface

Now vacuum's second pass, which removes dead items referring to dead
tuples catalogued in the first pass, uses the streaming read API by
implementing a streaming read callback which returns the next block
containing previously catalogued dead items. A new struct,
VacReapBlkState, is introduced to provide the caller with the starting
and ending indexes of dead items to vacuum.
---
 src/backend/access/heap/vacuumlazy.c | 106 +++++++++++++++++++++------
 src/tools/pgindent/typedefs.list     |   1 +
 2 files changed, 83 insertions(+), 24 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 96150834614..99514fa960c 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -207,6 +207,12 @@ typedef struct LVRelState
 	 */
 	BlockNumber blkno_prefetch;
 
+	/*
+	 * The index of the next TID in dead_items to reap during the second
+	 * vacuum pass.
+	 */
+	int			idx_prefetch;
+
 	/* Statistics output by us, for table */
 	double		new_rel_tuples; /* new estimated total # of tuples */
 	double		new_live_tuples;	/* new estimated total # of live tuples */
@@ -248,6 +254,21 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+/*
+ * State set up in streaming read callback during vacuum's second pass which
+ * removes dead items referring to dead tuples cataloged in the first pass
+ */
+typedef struct VacReapBlkState
+{
+	/*
+	 * The indexes of the TIDs of the first and last dead tuples in a single
+	 * block in the currently vacuumed relation. The callback will set these
+	 * up prior to adding this block to the stream.
+	 */
+	int			start_idx;
+	int			end_idx;
+} VacReapBlkState;
+
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
@@ -266,8 +287,9 @@ static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 static void lazy_vacuum(LVRelState *vacrel);
 static bool lazy_vacuum_all_indexes(LVRelState *vacrel);
 static void lazy_vacuum_heap_rel(LVRelState *vacrel);
-static int	lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
-								  Buffer buffer, int index, Buffer vmbuffer);
+static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+								  Buffer buffer, Buffer vmbuffer,
+								  VacReapBlkState *rbstate);
 static bool lazy_check_wraparound_failsafe(LVRelState *vacrel);
 static void lazy_cleanup_all_indexes(LVRelState *vacrel);
 static IndexBulkDeleteResult *lazy_vacuum_one_index(Relation indrel,
@@ -2407,6 +2429,37 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_pgsr_next(PgStreamingRead *pgsr,
+						 void *pgsr_private,
+						 void *per_buffer_data)
+{
+	BlockNumber blkno;
+	LVRelState *vacrel = pgsr_private;
+	VacReapBlkState *rbstate = per_buffer_data;
+
+	VacDeadItems *dead_items = vacrel->dead_items;
+
+	if (vacrel->idx_prefetch == dead_items->num_items)
+		return InvalidBlockNumber;
+
+	blkno = ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+	rbstate->start_idx = vacrel->idx_prefetch;
+
+	for (; vacrel->idx_prefetch < dead_items->num_items; vacrel->idx_prefetch++)
+	{
+		BlockNumber curblkno =
+			ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+
+		if (blkno != curblkno)
+			break;				/* past end of tuples for this block */
+	}
+
+	rbstate->end_idx = vacrel->idx_prefetch;
+
+	return blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2428,7 +2481,9 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
-	int			index = 0;
+	Buffer		buf;
+	PgStreamingRead *pgsr;
+	VacReapBlkState *rbstate;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2446,17 +2501,21 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 VACUUM_ERRCB_PHASE_VACUUM_HEAP,
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
-	while (index < vacrel->dead_items->num_items)
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(VacReapBlkState), vacrel->bstrategy, BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM, vacuum_reap_lp_pgsr_next);
+
+	while (BufferIsValid(buf =
+						 pg_streaming_read_buffer_get_next(pgsr,
+														   (void **) &rbstate)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 
 		vacuum_delay_point();
 
-		blkno = ItemPointerGetBlockNumber(&vacrel->dead_items->items[index]);
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		/*
 		 * Pin the visibility map page in case we need to mark the page
@@ -2466,10 +2525,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
-		index = lazy_vacuum_heap_page(vacrel, blkno, buf, index, vmbuffer);
+		lazy_vacuum_heap_page(vacrel, blkno, buf, vmbuffer, rbstate);
 
 		/* Now that we've vacuumed the page, record its available space */
 		page = BufferGetPage(buf);
@@ -2490,9 +2547,11 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 	 */
 	Assert(index > 0);
 	Assert(vacrel->num_index_scans > 1 ||
-		   (index == vacrel->lpdead_items &&
+		   (rbstate->end_idx == vacrel->lpdead_items &&
 			vacuumed_pages == vacrel->lpdead_item_pages));
 
+	pg_streaming_read_free(pgsr);
+
 	ereport(DEBUG2,
 			(errmsg("table \"%s\": removed %lld dead item identifiers in %u pages",
 					vacrel->relname, (long long) index, vacuumed_pages)));
@@ -2509,13 +2568,12 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
  * cleanup lock is also acceptable).  vmbuffer must be valid and already have
  * a pin on blkno's visibility map page.
  *
- * index is an offset into the vacrel->dead_items array for the first listed
- * LP_DEAD item on the page.  The return value is the first index immediately
- * after all LP_DEAD items for the same page in the array.
+ * Given a block and dead items recorded during the first pass, set those items
+ * dead and truncate the line pointer array. Update the VM as appropriate.
  */
-static int
-lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
-					  int index, Buffer vmbuffer)
+static void
+lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+					  Buffer buffer, Buffer vmbuffer, VacReapBlkState *rbstate)
 {
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Page		page = BufferGetPage(buffer);
@@ -2536,16 +2594,17 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	START_CRIT_SECTION();
 
-	for (; index < dead_items->num_items; index++)
+	for (int i = rbstate->start_idx; i < rbstate->end_idx; i++)
 	{
-		BlockNumber tblk;
 		OffsetNumber toff;
+		ItemPointer dead_item;
 		ItemId		itemid;
 
-		tblk = ItemPointerGetBlockNumber(&dead_items->items[index]);
-		if (tblk != blkno)
-			break;				/* past end of tuples for this block */
-		toff = ItemPointerGetOffsetNumber(&dead_items->items[index]);
+		dead_item = &dead_items->items[i];
+
+		Assert(ItemPointerGetBlockNumber(dead_item) == blkno);
+
+		toff = ItemPointerGetOffsetNumber(dead_item);
 		itemid = PageGetItemId(page, toff);
 
 		Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
@@ -2615,7 +2674,6 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
-	return index;
 }
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index cfb58cf4836..af055d5c037 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2972,6 +2972,7 @@ VacOptValue
 VacuumParams
 VacuumRelation
 VacuumStmt
+VacReapBlkState
 ValidIOData
 ValidateIndexState
 ValuesScan
-- 
2.37.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-06 19:55             ` Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Heikki Linnakangas @ 2024-03-06 19:55 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On 27/02/2024 21:47, Melanie Plageman wrote:
> The attached v5 has some simplifications when compared to v4 but takes
> largely the same approach.
> 
> 0001-0004 are refactoring

I'm looking at just these 0001-0004 patches for now. I like those 
changes a lot for the sake of readablity even without any of the later 
patches.

I made some further changes. I kept them as separate commits for easier 
review, see the commit messages for details. Any thoughts on those changes?

I feel heap_vac_scan_get_next_block() function could use some love. 
Maybe just some rewording of the comments, or maybe some other 
refactoring; not sure. But I'm pretty happy with the function signature 
and how it's called.

BTW, do we have tests that would fail if we botched up 
heap_vac_scan_get_next_block() so that it would skip pages incorrectly, 
for example? Not asking you to write them for this patch, but I'm just 
wondering.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments:

  [text/x-patch] v6-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.7K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/2-v6-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From 6e0258c3e31e85526475f46b2e14cbbcbb861909 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v6 1/9] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8b320c3f89a..1dc6cc8e4db 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1103,8 +1103,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+				next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1161,7 +1160,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1174,7 +1172,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.39.2



  [text/x-patch] v6-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch (15.8K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/3-v6-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch)
  download | inline diff:
From 258bce44e3275bc628bf984892797eecaebf0404 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v6 2/9] Add lazy_scan_skip unskippable state to LVRelState

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce add a struct to LVRelState containing variables needed to skip
ranges less than SKIP_PAGES_THRESHOLD.

lazy_scan_prune() and lazy_scan_new_or_empty() can now access the
buffer containing the relevant block of the visibility map through the
LVRelState.skip, so it no longer needs to be a separate function
parameter.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 154 ++++++++++++++++-----------
 1 file changed, 90 insertions(+), 64 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1dc6cc8e4db..0ddb986bc03 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -204,6 +204,22 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/*
+	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
+	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 */
+	struct
+	{
+		/* Next unskippable block */
+		BlockNumber next_unskippable_block;
+		/* Buffer containing next unskippable block's visibility info */
+		Buffer		vmbuffer;
+		/* Next unskippable block's visibility status */
+		bool		next_unskippable_allvis;
+		/* Whether or not skippable blocks should be skipped */
+		bool		skipping_current_range;
+	}			skip;
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -214,19 +230,15 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
-
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
-								   bool sharelock, Buffer vmbuffer);
+								   bool sharelock);
 static void lazy_scan_prune(LVRelState *vacrel, Buffer buf,
 							BlockNumber blkno, Page page,
-							Buffer vmbuffer, bool all_visible_according_to_vm,
+							bool all_visible_according_to_vm,
 							bool *has_lpdead_items);
 static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 							  BlockNumber blkno, Page page,
@@ -803,12 +815,8 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -822,10 +830,9 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.vmbuffer = InvalidBuffer;
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, 0);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -834,26 +841,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacrel->skip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, blkno + 1);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacrel->skip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -896,10 +900,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacrel->skip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacrel->skip.vmbuffer);
+				vacrel->skip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -924,7 +928,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
 		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
 								 vacrel->bstrategy);
@@ -942,8 +946,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			LockBuffer(buf, BUFFER_LOCK_SHARE);
 
 		/* Check for new or empty pages before lazy_scan_[no]prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
-								   vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -985,7 +988,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1035,8 +1038,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacrel->skip.vmbuffer))
+	{
+		ReleaseBuffer(vacrel->skip.vmbuffer);
+		vacrel->skip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1080,15 +1086,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in skip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
+ *
+ * The block number and visibility status of the next unskippable block are set
+ * in skip->next_unskippable_block and next_unskippable_allvis.
+ * skip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1098,25 +1123,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
 {
+	/* Use local variables for better optimized loop code */
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_unskippable_block = next_block;
+
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
+	vacrel->skip.next_unskippable_allvis = true;
 	while (next_unskippable_block < rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
-													   vmbuffer);
+													   &vacrel->skip.vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1137,7 +1163,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1162,6 +1188,8 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		next_unskippable_block++;
 	}
 
+	vacrel->skip.next_unskippable_block = next_unskippable_block;
+
 	/*
 	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
 	 * pages.  Since we're reading sequentially, the OS should be doing
@@ -1172,16 +1200,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacrel->skip.skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacrel->skip.skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
@@ -1214,7 +1240,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
  */
 static bool
 lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
-					   Page page, bool sharelock, Buffer vmbuffer)
+					   Page page, bool sharelock)
 {
 	Size		freespace;
 
@@ -1300,7 +1326,7 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
 
 			PageSetAllVisible(page);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacrel->skip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
 			END_CRIT_SECTION();
 		}
@@ -1336,10 +1362,11 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
  * any tuple that becomes dead after the call to heap_page_prune() can't need to
  * be frozen, because it was visible to another session when vacuum started.
  *
- * vmbuffer is the buffer containing the VM block with visibility information
- * for the heap block, blkno. all_visible_according_to_vm is the saved
- * visibility status of the heap block looked up earlier by the caller. We
- * won't rely entirely on this status, as it may be out of date.
+ * vacrel->skipstate.vmbuffer is the buffer containing the VM block with
+ * visibility information for the heap block, blkno.
+ * all_visible_according_to_vm is the saved visibility status of the heap block
+ * looked up earlier by the caller. We won't rely entirely on this status, as
+ * it may be out of date.
  *
  * *has_lpdead_items is set to true or false depending on whether, upon return
  * from this function, any LP_DEAD items are still present on the page.
@@ -1349,7 +1376,6 @@ lazy_scan_prune(LVRelState *vacrel,
 				Buffer buf,
 				BlockNumber blkno,
 				Page page,
-				Buffer vmbuffer,
 				bool all_visible_according_to_vm,
 				bool *has_lpdead_items)
 {
@@ -1783,7 +1809,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		PageSetAllVisible(page);
 		MarkBufferDirty(buf);
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, visibility_cutoff_xid,
+						  vacrel->skip.vmbuffer, visibility_cutoff_xid,
 						  flags);
 	}
 
@@ -1794,11 +1820,11 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+			 visibilitymap_get_status(vacrel->rel, blkno, &vacrel->skip.vmbuffer) != 0)
 	{
 		elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 			 vacrel->relname, blkno);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1822,7 +1848,7 @@ lazy_scan_prune(LVRelState *vacrel,
 			 vacrel->relname, blkno);
 		PageClearAllVisible(page);
 		MarkBufferDirty(buf);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1832,7 +1858,7 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * true, so we must check both all_visible and all_frozen.
 	 */
 	else if (all_visible_according_to_vm && all_visible &&
-			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vacrel->skip.vmbuffer))
 	{
 		/*
 		 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1854,7 +1880,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		 */
 		Assert(!TransactionIdIsValid(visibility_cutoff_xid));
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, InvalidTransactionId,
+						  vacrel->skip.vmbuffer, InvalidTransactionId,
 						  VISIBILITYMAP_ALL_VISIBLE |
 						  VISIBILITYMAP_ALL_FROZEN);
 	}
-- 
2.39.2



  [text/x-patch] v6-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (14.0K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/4-v6-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 6b2b0313ecf5a8f35a3fbab9e3ba817a5cff2c73 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v6 3/9] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and
eventually AIO), refactor vacuum's logic for skipping blocks such that
it is entirely confined to lazy_scan_skip(). This turns lazy_scan_skip()
and the skip state in LVRelState it uses into an iterator which yields
blocks to lazy_scan_heap(). Such a structure is conducive to an async
interface. While we are at it, rename lazy_scan_skip() to
heap_vac_scan_get_next_block(), which now more accurately describes it.

By always calling heap_vac_scan_get_next_block() -- instead of only when
we have reached the next unskippable block, we no longer need the
skipping_current_range variable. lazy_scan_heap() no longer needs to
manage the skipped range -- checking if we reached the end in order to
then call heap_vac_scan_get_next_block(). And
heap_vac_scan_get_next_block() can derive the visibility status of a
block from whether or not we are in a skippable range -- that is,
whether or not the next_block is equal to the next unskippable block.
---
 src/backend/access/heap/vacuumlazy.c | 243 ++++++++++++++-------------
 1 file changed, 126 insertions(+), 117 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 0ddb986bc03..99d160335e1 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -206,8 +206,8 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
-	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 * Parameters maintained by heap_vac_scan_get_next_block() to manage
+	 * skipping ranges of pages greater than SKIP_PAGES_THRESHOLD.
 	 */
 	struct
 	{
@@ -232,7 +232,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
+static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+										 BlockNumber *blkno,
+										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock);
@@ -814,8 +816,11 @@ static void
 lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -830,40 +835,17 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, 0);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+
+	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
+										&blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == vacrel->skip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, blkno + 1);
-
-			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacrel->skip.skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1083,20 +1065,14 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
- *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in skip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *	heap_vac_scan_get_next_block() -- get next block for vacuum to process
  *
- * skip->vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * heap_vac_scan_get_next_block() sets blkno to next block that actually needs
+ * to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1106,14 +1082,25 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in skip->next_unskippable_block and next_unskippable_allvis.
- * skip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacrel->skip->next_unskippable_block and next_unskippable_allvis.
+ *
+ * The block number and visibility status of the next block to process are set
+ * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
+ * returns false if there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1123,91 +1110,113 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
-lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
+static bool
+heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
-	/* Use local variables for better optimized loop code */
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block;
-
 	bool		skipsallvis = false;
 
-	vacrel->skip.next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	if (next_block >= vacrel->rel_pages)
 	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   &vacrel->skip.vmbuffer);
+		*blkno = InvalidBlockNumber;
+		return false;
+	}
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->skip.next_unskippable_block)
+	{
+		/* Use local variables for better optimized loop code */
+		BlockNumber rel_pages = vacrel->rel_pages;
+		BlockNumber next_unskippable_block = vacrel->skip.next_unskippable_block;
+
+		while (++next_unskippable_block < rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   &vacrel->skip.vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacrel->skip.next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacrel->skip.next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-	}
+		vacrel->skip.next_unskippable_block = next_unskippable_block;
 
-	vacrel->skip.next_unskippable_block = next_unskippable_block;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->skip.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->skip.next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
+	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacrel->skip.skipping_current_range = false;
+	if (next_block == vacrel->skip.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
 	else
-	{
-		vacrel->skip.skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	*blkno = next_block;
+	return true;
 }
 
 /*
-- 
2.39.2



  [text/x-patch] v6-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.0K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/5-v6-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From 026af3d4b19feabea8ed78795c64b3278fa93d7f Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v6 4/9] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 99d160335e1..65d257aab83 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1184,8 +1184,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		vacrel->skip.next_unskippable_block = next_unskippable_block;
-- 
2.39.2



  [text/x-patch] v6-0005-Remove-unused-skipping_current_range-field.patch (812B, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/6-v6-0005-Remove-unused-skipping_current_range-field.patch)
  download | inline diff:
From b4047b941182af0643838fde056c298d5cc3ae32 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 6 Mar 2024 20:13:42 +0200
Subject: [PATCH v6 5/9] Remove unused 'skipping_current_range' field

---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 65d257aab83..51391870bf3 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -217,8 +217,6 @@ typedef struct LVRelState
 		Buffer		vmbuffer;
 		/* Next unskippable block's visibility status */
 		bool		next_unskippable_allvis;
-		/* Whether or not skippable blocks should be skipped */
-		bool		skipping_current_range;
 	}			skip;
 } LVRelState;
 
-- 
2.39.2



  [text/x-patch] v6-0006-Move-vmbuffer-back-to-a-local-varible-in-lazy_sca.patch (10.4K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/7-v6-0006-Move-vmbuffer-back-to-a-local-varible-in-lazy_sca.patch)
  download | inline diff:
From 27e431e8dc69bbf09d831cb1cf2903d16f177d74 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 6 Mar 2024 20:58:57 +0200
Subject: [PATCH v6 6/9] Move vmbuffer back to a local varible in
 lazy_scan_heap()

It felt confusing that we passed around the current block, 'blkno', as
an argument to lazy_scan_new_or_empty() and lazy_scan_prune(), but
'vmbuffer' was accessed directly in the 'scan_state'.

It was also a bit vague, when exactly 'vmbuffer' was valid. Calling
heap_vac_scan_get_next_block() set it, sometimes, to a buffer that
might or might not contain the VM bit for 'blkno'. But other
functions, like lazy_scan_prune(), assumed it to contain the correct
buffer. That was fixed up visibilitymap_pin(). But clearly it was not
"owned" by heap_vac_scan_get_next_block(), like the other 'scan_state'
fields.

I moved it back to a local variable, like it was. Maybe there would be
even better ways to handle it, but at least this is not worse than
what we have in master currently.
---
 src/backend/access/heap/vacuumlazy.c | 72 +++++++++++++---------------
 1 file changed, 33 insertions(+), 39 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 51391870bf3..3f1661cea61 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -213,8 +213,6 @@ typedef struct LVRelState
 	{
 		/* Next unskippable block */
 		BlockNumber next_unskippable_block;
-		/* Buffer containing next unskippable block's visibility info */
-		Buffer		vmbuffer;
 		/* Next unskippable block's visibility status */
 		bool		next_unskippable_allvis;
 	}			skip;
@@ -232,13 +230,14 @@ typedef struct LVSavedErrInfo
 static void lazy_scan_heap(LVRelState *vacrel);
 static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 										 BlockNumber *blkno,
-										 bool *all_visible_according_to_vm);
+										 bool *all_visible_according_to_vm,
+										 Buffer *vmbuffer);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
-								   bool sharelock);
+								   bool sharelock, Buffer vmbuffer);
 static void lazy_scan_prune(LVRelState *vacrel, Buffer buf,
 							BlockNumber blkno, Page page,
-							bool all_visible_according_to_vm,
+							Buffer vmbuffer, bool all_visible_according_to_vm,
 							bool *has_lpdead_items);
 static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 							  BlockNumber blkno, Page page,
@@ -815,11 +814,10 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
-
-	/* relies on InvalidBlockNumber overflowing to 0 */
-	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
+	BlockNumber blkno;
+	bool		all_visible_according_to_vm;
+	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -834,10 +832,9 @@ lazy_scan_heap(LVRelState *vacrel)
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
 	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
-	vacrel->skip.vmbuffer = InvalidBuffer;
 
 	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
-										&blkno, &all_visible_according_to_vm))
+										&blkno, &all_visible_according_to_vm, &vmbuffer))
 	{
 		Buffer		buf;
 		Page		page;
@@ -880,10 +877,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vacrel->skip.vmbuffer))
+			if (BufferIsValid(vmbuffer))
 			{
-				ReleaseBuffer(vacrel->skip.vmbuffer);
-				vacrel->skip.vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vmbuffer);
+				vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -908,7 +905,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
 								 vacrel->bstrategy);
@@ -926,7 +923,8 @@ lazy_scan_heap(LVRelState *vacrel)
 			LockBuffer(buf, BUFFER_LOCK_SHARE);
 
 		/* Check for new or empty pages before lazy_scan_[no]prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
+								   vmbuffer))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -968,7 +966,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							all_visible_according_to_vm,
+							vmbuffer, all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1018,11 +1016,8 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vacrel->skip.vmbuffer))
-	{
-		ReleaseBuffer(vacrel->skip.vmbuffer);
-		vacrel->skip.vmbuffer = InvalidBuffer;
-	}
+	if (BufferIsValid(vmbuffer))
+		ReleaseBuffer(vmbuffer);
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1094,7 +1089,7 @@ lazy_scan_heap(LVRelState *vacrel)
  * relation are read and vacrel->skippedallvis is set to ensure we don't
  * advance relfrozenxid when we have skipped vacuuming all visible blocks.
  *
- * skip->vmbuffer will contain the block from the VM containing visibility
+ * vmbuffer will contain the block from the VM containing visibility
  * information for the next unskippable heap block. We may end up needed a
  * different block from the VM (if we decide not to skip a skippable block).
  * This is okay; visibilitymap_pin() will take care of this while processing
@@ -1110,7 +1105,7 @@ lazy_scan_heap(LVRelState *vacrel)
  */
 static bool
 heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
-							 BlockNumber *blkno, bool *all_visible_according_to_vm)
+							 BlockNumber *blkno, bool *all_visible_according_to_vm, Buffer *vmbuffer)
 {
 	bool		skipsallvis = false;
 
@@ -1131,7 +1126,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 		{
 			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 														   next_unskippable_block,
-														   &vacrel->skip.vmbuffer);
+														   vmbuffer);
 
 			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
@@ -1245,7 +1240,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
  */
 static bool
 lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
-					   Page page, bool sharelock)
+					   Page page, bool sharelock, Buffer vmbuffer)
 {
 	Size		freespace;
 
@@ -1331,7 +1326,7 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
 
 			PageSetAllVisible(page);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vacrel->skip.vmbuffer, InvalidTransactionId,
+							  vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
 			END_CRIT_SECTION();
 		}
@@ -1367,11 +1362,10 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
  * any tuple that becomes dead after the call to heap_page_prune() can't need to
  * be frozen, because it was visible to another session when vacuum started.
  *
- * vacrel->skipstate.vmbuffer is the buffer containing the VM block with
- * visibility information for the heap block, blkno.
- * all_visible_according_to_vm is the saved visibility status of the heap block
- * looked up earlier by the caller. We won't rely entirely on this status, as
- * it may be out of date.
+ * vmbuffer is the buffer containing the VM block with visibility information
+ * for the heap block, blkno. all_visible_according_to_vm is the saved
+ * visibility status of the heap block looked up earlier by the caller. We
+ * won't rely entirely on this status, as it may be out of date.
  *
  * *has_lpdead_items is set to true or false depending on whether, upon return
  * from this function, any LP_DEAD items are still present on the page.
@@ -1381,6 +1375,7 @@ lazy_scan_prune(LVRelState *vacrel,
 				Buffer buf,
 				BlockNumber blkno,
 				Page page,
+				Buffer vmbuffer,
 				bool all_visible_according_to_vm,
 				bool *has_lpdead_items)
 {
@@ -1814,8 +1809,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		PageSetAllVisible(page);
 		MarkBufferDirty(buf);
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vacrel->skip.vmbuffer, visibility_cutoff_xid,
-						  flags);
+						  vmbuffer, visibility_cutoff_xid, flags);
 	}
 
 	/*
@@ -1825,11 +1819,11 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-			 visibilitymap_get_status(vacrel->rel, blkno, &vacrel->skip.vmbuffer) != 0)
+			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
 	{
 		elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 			 vacrel->relname, blkno);
-		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1853,7 +1847,7 @@ lazy_scan_prune(LVRelState *vacrel,
 			 vacrel->relname, blkno);
 		PageClearAllVisible(page);
 		MarkBufferDirty(buf);
-		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1863,7 +1857,7 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * true, so we must check both all_visible and all_frozen.
 	 */
 	else if (all_visible_according_to_vm && all_visible &&
-			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vacrel->skip.vmbuffer))
+			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
 	{
 		/*
 		 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1885,7 +1879,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		 */
 		Assert(!TransactionIdIsValid(visibility_cutoff_xid));
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vacrel->skip.vmbuffer, InvalidTransactionId,
+						  vmbuffer, InvalidTransactionId,
 						  VISIBILITYMAP_ALL_VISIBLE |
 						  VISIBILITYMAP_ALL_FROZEN);
 	}
-- 
2.39.2



  [text/x-patch] v6-0007-Rename-skip_state.patch (5.0K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/8-v6-0007-Rename-skip_state.patch)
  download | inline diff:
From 519e26a01b6e6974f9e0edb94b00756af053f7ee Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 6 Mar 2024 20:27:57 +0200
Subject: [PATCH v6 7/9] Rename skip_state

I don't want to emphasize the "skipping" part. Rather, it's the state
onwed by the heap_vac_scan_get_next_block() function
---
 src/backend/access/heap/vacuumlazy.c | 32 ++++++++++++++--------------
 1 file changed, 16 insertions(+), 16 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3f1661cea61..17e06065f7e 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -206,8 +206,8 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by heap_vac_scan_get_next_block() to manage
-	 * skipping ranges of pages greater than SKIP_PAGES_THRESHOLD.
+	 * State maintained by heap_vac_scan_get_next_block() to manage skipping
+	 * ranges of pages greater than SKIP_PAGES_THRESHOLD.
 	 */
 	struct
 	{
@@ -215,7 +215,7 @@ typedef struct LVRelState
 		BlockNumber next_unskippable_block;
 		/* Next unskippable block's visibility status */
 		bool		next_unskippable_allvis;
-	}			skip;
+	}			get_next_block_state;
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -831,7 +831,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
+	vacrel->get_next_block_state.next_unskippable_block = InvalidBlockNumber;
 
 	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
 										&blkno, &all_visible_according_to_vm, &vmbuffer))
@@ -1079,7 +1079,7 @@ lazy_scan_heap(LVRelState *vacrel)
  * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in vacrel->skip->next_unskippable_block and next_unskippable_allvis.
+ * in vacrel->scan_sate->next_unskippable_block and next_unskippable_allvis.
  *
  * The block number and visibility status of the next block to process are set
  * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
@@ -1115,12 +1115,12 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 		return false;
 	}
 
-	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
-		next_block > vacrel->skip.next_unskippable_block)
+	if (vacrel->get_next_block_state.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->get_next_block_state.next_unskippable_block)
 	{
 		/* Use local variables for better optimized loop code */
 		BlockNumber rel_pages = vacrel->rel_pages;
-		BlockNumber next_unskippable_block = vacrel->skip.next_unskippable_block;
+		BlockNumber next_unskippable_block = vacrel->get_next_block_state.next_unskippable_block;
 
 		while (++next_unskippable_block < rel_pages)
 		{
@@ -1128,9 +1128,9 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 														   next_unskippable_block,
 														   vmbuffer);
 
-			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
+			vacrel->get_next_block_state.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-			if (!vacrel->skip.next_unskippable_allvis)
+			if (!vacrel->get_next_block_state.next_unskippable_allvis)
 			{
 				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
 				break;
@@ -1155,7 +1155,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 			if (!vacrel->skipwithvm)
 			{
 				/* Caller shouldn't rely on all_visible_according_to_vm */
-				vacrel->skip.next_unskippable_allvis = false;
+				vacrel->get_next_block_state.next_unskippable_allvis = false;
 				break;
 			}
 
@@ -1179,7 +1179,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 			}
 		}
 
-		vacrel->skip.next_unskippable_block = next_unskippable_block;
+		vacrel->get_next_block_state.next_unskippable_block = next_unskippable_block;
 
 		/*
 		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
@@ -1193,16 +1193,16 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 		 * pages then skipping makes updating relfrozenxid unsafe, which is a
 		 * real downside.
 		 */
-		if (vacrel->skip.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		if (vacrel->get_next_block_state.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
 		{
-			next_block = vacrel->skip.next_unskippable_block;
+			next_block = vacrel->get_next_block_state.next_unskippable_block;
 			if (skipsallvis)
 				vacrel->skippedallvis = true;
 		}
 	}
 
-	if (next_block == vacrel->skip.next_unskippable_block)
-		*all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
+	if (next_block == vacrel->get_next_block_state.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->get_next_block_state.next_unskippable_allvis;
 	else
 		*all_visible_according_to_vm = true;
 
-- 
2.39.2



  [text/x-patch] v6-0008-Track-current_block-in-the-skip-state.patch (4.2K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/9-v6-0008-Track-current_block-in-the-skip-state.patch)
  download | inline diff:
From 6dfae936a29e2d3479273f8ab47778a596258b16 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 6 Mar 2024 21:03:19 +0200
Subject: [PATCH v6 8/9] Track 'current_block' in the skip state

The caller was expected to always pass last blk + 1. It's not clear if
the next_unskippable block accounting would work correctly if you
passed something else. So rather than expecting the caller to do that,
have heap_vac_scan_get_next_block() keep track of the last returned
block itself, in the 'skip' state.

This is largely redundant with the LVRelState->blkno field. But that
one is currently only used for error reporting, so it feels best to
give heap_vac_scan_get_next_block() its own field that it owns.
---
 src/backend/access/heap/vacuumlazy.c | 27 +++++++++++++++------------
 1 file changed, 15 insertions(+), 12 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 17e06065f7e..535d70b71c3 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -211,6 +211,8 @@ typedef struct LVRelState
 	 */
 	struct
 	{
+		BlockNumber current_block;
+
 		/* Next unskippable block */
 		BlockNumber next_unskippable_block;
 		/* Next unskippable block's visibility status */
@@ -228,7 +230,7 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+static bool heap_vac_scan_get_next_block(LVRelState *vacrel,
 										 BlockNumber *blkno,
 										 bool *all_visible_according_to_vm,
 										 Buffer *vmbuffer);
@@ -831,10 +833,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	/* initialize for first heap_vac_scan_get_next_block() call */
+	vacrel->get_next_block_state.current_block = InvalidBlockNumber;
 	vacrel->get_next_block_state.next_unskippable_block = InvalidBlockNumber;
 
-	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
-										&blkno, &all_visible_according_to_vm, &vmbuffer))
+	while (heap_vac_scan_get_next_block(vacrel, &blkno, &all_visible_according_to_vm, &vmbuffer))
 	{
 		Buffer		buf;
 		Page		page;
@@ -1061,11 +1064,9 @@ lazy_scan_heap(LVRelState *vacrel)
  *	heap_vac_scan_get_next_block() -- get next block for vacuum to process
  *
  * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum, using the visibility map, vacuum options, and various
- * thresholds to skip blocks which do not need to be processed. Caller passes
- * next_block, the next block in line. This block may end up being skipped.
- * heap_vac_scan_get_next_block() sets blkno to next block that actually needs
- * to be processed.
+ * prune and vacuum.  We use the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed, and set blkno
+ * to next block that actually needs to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1104,14 +1105,16 @@ lazy_scan_heap(LVRelState *vacrel)
  * choice to skip such a range is actually made, making everything safe.)
  */
 static bool
-heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
-							 BlockNumber *blkno, bool *all_visible_according_to_vm, Buffer *vmbuffer)
+heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber *blkno,
+							 bool *all_visible_according_to_vm, Buffer *vmbuffer)
 {
+	/* Relies on InvalidBlockNumber + 1 == 0 */
+	BlockNumber next_block = vacrel->get_next_block_state.current_block + 1;
 	bool		skipsallvis = false;
 
 	if (next_block >= vacrel->rel_pages)
 	{
-		*blkno = InvalidBlockNumber;
+		vacrel->get_next_block_state.current_block = *blkno = InvalidBlockNumber;
 		return false;
 	}
 
@@ -1206,7 +1209,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 	else
 		*all_visible_according_to_vm = true;
 
-	*blkno = next_block;
+	vacrel->get_next_block_state.current_block = *blkno = next_block;
 	return true;
 }
 
-- 
2.39.2



  [text/x-patch] v6-0009-Comment-whitespace-cleanup.patch (4.3K, ../../1eeccf12-d5d1-4b7e-b88b-7342410129d7@iki.fi/10-v6-0009-Comment-whitespace-cleanup.patch)
  download | inline diff:
From 619556cad4aad68d1711c12b962e9002e56d8db2 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 6 Mar 2024 21:35:11 +0200
Subject: [PATCH v6 9/9] Comment & whitespace cleanup

I moved some of the paragraphs to inside the
heap_vac_scan_get_next_block() function. I found the explanation in
the function comment at the old place like too much detail. Someone
looking at the function signature and how to call it would not care
about all the details of what can or cannot be skipped.

The new place isn't great either, but will do for now
---
 src/backend/access/heap/vacuumlazy.c | 41 ++++++++++++++++------------
 1 file changed, 23 insertions(+), 18 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 535d70b71c3..b8a2dcfbbac 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -228,6 +228,7 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
 static bool heap_vac_scan_get_next_block(LVRelState *vacrel,
@@ -1068,30 +1069,17 @@ lazy_scan_heap(LVRelState *vacrel)
  * thresholds to skip blocks which do not need to be processed, and set blkno
  * to next block that actually needs to be processed.
  *
- * A block is unskippable if it is not all visible according to the visibility
- * map. It is also unskippable if it is the last block in the relation, if the
- * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
- * vacuum.
- *
- * Even if a block is skippable, we may choose not to skip it if the range of
- * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
- * consequence, we must keep track of the next truly unskippable block and its
- * visibility status separate from the next block lazy_scan_heap() should
- * process (and its visibility status).
- *
- * The block number and visibility status of the next unskippable block are set
- * in vacrel->scan_sate->next_unskippable_block and next_unskippable_allvis.
- *
- * The block number and visibility status of the next block to process are set
- * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
- * returns false if there are no further blocks to process.
+ * The block number and visibility status of the next block to process are
+ * returned in blkno and all_visible_according_to_vm.
+ * heap_vac_scan_get_next_block() returns false if there are no further blocks
+ * to process.
  *
  * vacrel is an in/out parameter here; vacuum options and information about the
  * relation are read and vacrel->skippedallvis is set to ensure we don't
  * advance relfrozenxid when we have skipped vacuuming all visible blocks.
  *
  * vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
+ * information for the next unskippable heap block.  We may end up needing a
  * different block from the VM (if we decide not to skip a skippable block).
  * This is okay; visibilitymap_pin() will take care of this while processing
  * the block.
@@ -1125,6 +1113,23 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		BlockNumber rel_pages = vacrel->rel_pages;
 		BlockNumber next_unskippable_block = vacrel->get_next_block_state.next_unskippable_block;
 
+		/*
+		 * A block is unskippable if it is not all visible according to the
+		 * visibility map.  It is also unskippable if it is the last block in
+		 * the relation, if the vacuum is an aggressive vacuum, or if
+		 * DISABLE_PAGE_SKIPPING was passed to vacuum.
+		 *
+		 * Even if a block is skippable, we may choose not to skip it if the
+		 * range of skippable blocks is too small (below
+		 * SKIP_PAGES_THRESHOLD).  As a consequence, we must keep track of the
+		 * next truly unskippable block and its visibility status separate
+		 * from the next block lazy_scan_heap() should process (and its
+		 * visibility status).
+		 *
+		 * The block number and visibility status of the next unskippable
+		 * block are set in vacrel->scan_sate->next_unskippable_block and
+		 * next_unskippable_allvis.
+		 */
 		while (++next_unskippable_block < rel_pages)
 		{
 			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-- 
2.39.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
@ 2024-03-07 03:00               ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-07 03:00 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Wed, Mar 06, 2024 at 09:55:21PM +0200, Heikki Linnakangas wrote:
> On 27/02/2024 21:47, Melanie Plageman wrote:
> > The attached v5 has some simplifications when compared to v4 but takes
> > largely the same approach.
> > 
> > 0001-0004 are refactoring
> 
> I'm looking at just these 0001-0004 patches for now. I like those changes a
> lot for the sake of readablity even without any of the later patches.

Thanks! And thanks so much for the review!

I've done a small performance experiment comparing a branch with all of
the patches applied (your v6 0001-0009) with master. I made an 11 GB
table that has 1,394,328 blocks. For setup, I vacuumed it to update the
VM and made sure it was entirely in shared buffers. All of this was to
make sure all of the blocks would be skipped and we spend the majority
of the time spinning through the lazy_scan_heap() code. Then I ran
vacuum again (the actual test). I saw vacuum go from 13 ms to 10 ms
with the patches applied.

I think I need to do some profiling to see if the difference is actually
due to our code changes, but I thought I would share preliminary
results.

> I made some further changes. I kept them as separate commits for easier
> review, see the commit messages for details. Any thoughts on those changes?

I've given some inline feedback on most of the extra patches you added.
Short answer is they all seem fine to me except I have a reservations
about 0008 because of the number of blkno variables flying around. I
didn't have a chance to rebase these into my existing changes today, so
either I will do it tomorrow or, if you are feeling like you're on a
roll and want to do it, that also works!

> I feel heap_vac_scan_get_next_block() function could use some love. Maybe
> just some rewording of the comments, or maybe some other refactoring; not
> sure. But I'm pretty happy with the function signature and how it's called.

I was wondering if we should remove the "get" and just go with
heap_vac_scan_next_block(). I didn't do that originally because I didn't
want to imply that the next block was literally the sequentially next
block, but I think maybe I was overthinking it.

Another idea is to call it heap_scan_vac_next_block() and then the order
of the words is more like the table AM functions that get the next block
(e.g. heapam_scan_bitmap_next_block()). Though maybe we don't want it to
be too similar to those since this isn't a table AM callback.

As for other refactoring and other rewording of comments and such, I
will take a pass at this tomorrow.

> BTW, do we have tests that would fail if we botched up
> heap_vac_scan_get_next_block() so that it would skip pages incorrectly, for
> example? Not asking you to write them for this patch, but I'm just
> wondering.

So, while developing this, when I messed up and skipped blocks I
shouldn't, vacuum would error out with the "found xmin from before
relfrozenxid" error -- which would cause random tests to fail. I know
that's not a correctly failing test of this code. I think there might be
some tests in the verify_heapam tests that could/do test this kind of
thing but I don't remember them failing for me during development -- so
I didn't spend much time looking at them.

I would also sometimes get freespace or VM tests that would fail because
those blocks that are incorrectly skipped were meant to be reflected in
the FSM or VM in those tests.

All of that is to say, perhaps we should write a more targeted test?

When I was writing the code, I added logging of skipped blocks and then
came up with different scenarios and ran them on master and with the
patch and diffed the logs.

> From b4047b941182af0643838fde056c298d5cc3ae32 Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Wed, 6 Mar 2024 20:13:42 +0200
> Subject: [PATCH v6 5/9] Remove unused 'skipping_current_range' field
> 
> ---
>  src/backend/access/heap/vacuumlazy.c | 2 --
>  1 file changed, 2 deletions(-)
> 
> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
> index 65d257aab83..51391870bf3 100644
> --- a/src/backend/access/heap/vacuumlazy.c
> +++ b/src/backend/access/heap/vacuumlazy.c
> @@ -217,8 +217,6 @@ typedef struct LVRelState
>  		Buffer		vmbuffer;
>  		/* Next unskippable block's visibility status */
>  		bool		next_unskippable_allvis;
> -		/* Whether or not skippable blocks should be skipped */
> -		bool		skipping_current_range;
>  	}			skip;
>  } LVRelState;
>  
> -- 
> 2.39.2
> 

Oops! I thought I removed this. I must have forgotten

> From 27e431e8dc69bbf09d831cb1cf2903d16f177d74 Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Wed, 6 Mar 2024 20:58:57 +0200
> Subject: [PATCH v6 6/9] Move vmbuffer back to a local varible in
>  lazy_scan_heap()
> 
> It felt confusing that we passed around the current block, 'blkno', as
> an argument to lazy_scan_new_or_empty() and lazy_scan_prune(), but
> 'vmbuffer' was accessed directly in the 'scan_state'.
> 
> It was also a bit vague, when exactly 'vmbuffer' was valid. Calling
> heap_vac_scan_get_next_block() set it, sometimes, to a buffer that
> might or might not contain the VM bit for 'blkno'. But other
> functions, like lazy_scan_prune(), assumed it to contain the correct
> buffer. That was fixed up visibilitymap_pin(). But clearly it was not
> "owned" by heap_vac_scan_get_next_block(), like the other 'scan_state'
> fields.
> 
> I moved it back to a local variable, like it was. Maybe there would be
> even better ways to handle it, but at least this is not worse than
> what we have in master currently.

I'm fine with this. I did it the way I did (grouping it with the
"next_unskippable_block" in the skip struct), because I think that this
vmbuffer is always the buffer containing the VM bit for the next
unskippable block -- which sometimes is the block returned by
heap_vac_scan_get_next_block() and sometimes isn't.

I agree it might be best as a local variable but perhaps we could retain
the comment about it being the block of the VM containing the bit for the
next unskippable block. (Honestly, the whole thing is very confusing).

> From 519e26a01b6e6974f9e0edb94b00756af053f7ee Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Wed, 6 Mar 2024 20:27:57 +0200
> Subject: [PATCH v6 7/9] Rename skip_state
> 
> I don't want to emphasize the "skipping" part. Rather, it's the state
> onwed by the heap_vac_scan_get_next_block() function

This makes sense to me. Skipping should be private details of vacuum's
get_next_block functionality. Though the name is a bit long. Maybe we
don't need the "get" and "state" parts (it is already in a struct with
state in the name)?

> From 6dfae936a29e2d3479273f8ab47778a596258b16 Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Wed, 6 Mar 2024 21:03:19 +0200
> Subject: [PATCH v6 8/9] Track 'current_block' in the skip state
> 
> The caller was expected to always pass last blk + 1. It's not clear if
> the next_unskippable block accounting would work correctly if you
> passed something else. So rather than expecting the caller to do that,
> have heap_vac_scan_get_next_block() keep track of the last returned
> block itself, in the 'skip' state.
> 
> This is largely redundant with the LVRelState->blkno field. But that
> one is currently only used for error reporting, so it feels best to
> give heap_vac_scan_get_next_block() its own field that it owns.

I understand and agree with you that relying on blkno + 1 is bad and we
should make the "next_block" state keep track of the current block.

Though, I now find it easy to confuse
lvrelstate->get_next_block_state->current_block, lvrelstate->blkno and
the local variable blkno in lazy_scan_heap(). I think it is a naming
thing and not that we shouldn't have all three. I'll think more about it
in the morning.

> From 619556cad4aad68d1711c12b962e9002e56d8db2 Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Wed, 6 Mar 2024 21:35:11 +0200
> Subject: [PATCH v6 9/9] Comment & whitespace cleanup
> 
> I moved some of the paragraphs to inside the
> heap_vac_scan_get_next_block() function. I found the explanation in
> the function comment at the old place like too much detail. Someone
> looking at the function signature and how to call it would not care
> about all the details of what can or cannot be skipped.

LGTM.

Thanks again.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-08 00:46                 ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 2 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 00:46 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
> On Wed, Mar 06, 2024 at 09:55:21PM +0200, Heikki Linnakangas wrote:
> > I made some further changes. I kept them as separate commits for easier
> > review, see the commit messages for details. Any thoughts on those changes?
> 
> I've given some inline feedback on most of the extra patches you added.
> Short answer is they all seem fine to me except I have a reservations
> about 0008 because of the number of blkno variables flying around. I
> didn't have a chance to rebase these into my existing changes today, so
> either I will do it tomorrow or, if you are feeling like you're on a
> roll and want to do it, that also works!

Attached v7 contains all of the changes that you suggested plus some
additional cleanups here and there.

> > I feel heap_vac_scan_get_next_block() function could use some love. Maybe
> > just some rewording of the comments, or maybe some other refactoring; not
> > sure. But I'm pretty happy with the function signature and how it's called.

I've cleaned up the comments on heap_vac_scan_next_block() in the first
couple patches (not so much in the streaming read user). Let me know if
it addresses your feelings or if I should look for other things I could
change.

I will say that now all of the variable names are *very* long. I didn't
want to remove the "state" from LVRelState->next_block_state. (In fact, I
kind of miss the "get". But I had to draw the line somewhere.) I think
without "state" in the name, next_block sounds too much like a function.

Any ideas for shortening the names of next_block_state and its members
or are you fine with them?

> I was wondering if we should remove the "get" and just go with
> heap_vac_scan_next_block(). I didn't do that originally because I didn't
> want to imply that the next block was literally the sequentially next
> block, but I think maybe I was overthinking it.
> 
> Another idea is to call it heap_scan_vac_next_block() and then the order
> of the words is more like the table AM functions that get the next block
> (e.g. heapam_scan_bitmap_next_block()). Though maybe we don't want it to
> be too similar to those since this isn't a table AM callback.

I've done a version of this.

> > From 27e431e8dc69bbf09d831cb1cf2903d16f177d74 Mon Sep 17 00:00:00 2001
> > From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> > Date: Wed, 6 Mar 2024 20:58:57 +0200
> > Subject: [PATCH v6 6/9] Move vmbuffer back to a local varible in
> >  lazy_scan_heap()
> > 
> > It felt confusing that we passed around the current block, 'blkno', as
> > an argument to lazy_scan_new_or_empty() and lazy_scan_prune(), but
> > 'vmbuffer' was accessed directly in the 'scan_state'.
> > 
> > It was also a bit vague, when exactly 'vmbuffer' was valid. Calling
> > heap_vac_scan_get_next_block() set it, sometimes, to a buffer that
> > might or might not contain the VM bit for 'blkno'. But other
> > functions, like lazy_scan_prune(), assumed it to contain the correct
> > buffer. That was fixed up visibilitymap_pin(). But clearly it was not
> > "owned" by heap_vac_scan_get_next_block(), like the other 'scan_state'
> > fields.
> > 
> > I moved it back to a local variable, like it was. Maybe there would be
> > even better ways to handle it, but at least this is not worse than
> > what we have in master currently.
> 
> I'm fine with this. I did it the way I did (grouping it with the
> "next_unskippable_block" in the skip struct), because I think that this
> vmbuffer is always the buffer containing the VM bit for the next
> unskippable block -- which sometimes is the block returned by
> heap_vac_scan_get_next_block() and sometimes isn't.
> 
> I agree it might be best as a local variable but perhaps we could retain
> the comment about it being the block of the VM containing the bit for the
> next unskippable block. (Honestly, the whole thing is very confusing).

In 0001-0004 I've stuck with only having the local variable vmbuffer in
lazy_scan_heap().

In 0006 (introducing pass 1 vacuum streaming read user) I added a
vmbuffer back to the next_block_state (while also keeping the local
variable vmbuffer in lazy_scan_heap()). The vmbuffer in lazy_scan_heap()
contains the block of the VM containing visi information for the next
unskippable block or for the current block if its visi information
happens to be in the same block of the VM as either 1) the next
unskippable block or 2) the most recently processed heap block.

Streaming read vacuum separates this visibility check in
heap_vac_scan_next_block() from the main loop of lazy_scan_heap(), so we
can't just use a local variable anymore. Now the local variable vmbuffer
in lazy_scan_heap() will only already contain the block with the visi
information for the to-be-processed block if it happens to be in the
same VM block as the most recently processed heap block. That means
potentially more VM fetches.

However, by adding a vmbuffer to next_block_state, the callback may be
able to avoid extra VM fetches from one invocation to the next.

Note that next_block->current_block in the streaming read vacuum context
is actually the prefetch block.


- Melanie

Attachments:

  [text/x-diff] v7-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch (1.7K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/2-v7-0001-lazy_scan_skip-remove-unneeded-local-var-nskippab.patch)
  download | inline diff:
From 5018cf4a882d48bc424301400cb40aa7a36955b1 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v7 1/7] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8b320c3f89a..1dc6cc8e4db 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1103,8 +1103,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+				next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1161,7 +1160,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1174,7 +1172,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.40.1

  [text/x-diff] v7-0002-Add-lazy_scan_skip-next-block-state-to-LVRelState.patch (10.7K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/3-v7-0002-Add-lazy_scan_skip-next-block-state-to-LVRelState.patch)
  download | inline diff:
From 4d49028df51550af931f70c21a920a22ff09ba48 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v7 2/7] Add lazy_scan_skip next block state to LVRelState

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce a struct to LVRelState containing members tracking the current
block and the information needed to determine whether or not to skip
ranges less than SKIP_PAGES_THRESHOLD.

While we are at it, expand the comments in lazy_scan_skip(), including
descriptions of the role and expectations of its function parameters and
more detail on when skippable blocks are not skipped.

Discussion: https://postgr.es/m/flat/CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 124 ++++++++++++++++++---------
 1 file changed, 84 insertions(+), 40 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1dc6cc8e4db..accc6303fa2 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -204,6 +204,22 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/*
+	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
+	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 */
+	struct
+	{
+		/* The last block lazy_scan_skip() returned and vacuum processed */
+		BlockNumber current_block;
+		/* Next unskippable block */
+		BlockNumber next_unskippable_block;
+		/* Next unskippable block's visibility status */
+		bool		next_unskippable_allvis;
+		/* Whether or not skippable blocks should be skipped */
+		bool		skipping_current_range;
+	}			next_block_state;
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -214,13 +230,9 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
-
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -803,12 +815,9 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -822,10 +831,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	/* Initialize for first lazy_scan_skip() call */
+	vacrel->next_block_state.current_block = InvalidBlockNumber;
+	vacrel->next_block_state.next_unskippable_block = InvalidBlockNumber;
+
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, &vmbuffer);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -834,26 +845,21 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacrel->next_block_state.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
-
-			Assert(next_unskippable_block >= blkno + 1);
+			all_visible_according_to_vm = vacrel->next_block_state.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, &vmbuffer);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacrel->next_block_state.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -1036,7 +1042,10 @@ lazy_scan_heap(LVRelState *vacrel)
 
 	vacrel->blkno = InvalidBlockNumber;
 	if (BufferIsValid(vmbuffer))
+	{
 		ReleaseBuffer(vmbuffer);
+		vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1080,15 +1089,20 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read, members of vacrel->next_block_state are read and set as
+ * bookeeping for this function, and vacrel->skippedallvis is set to ensure we
+ * don't advance relfrozenxid when we have skipped vacuuming all-visible
+ * blocks.
+ *
+ * vmbuffer is an output parameter which, upon return, will contain the block
+ * from the VM containing visibility information for the next unskippable heap
+ * block. If we decide not to skip this heap block, the caller is responsible
+ * for fetching the correct VM block into vmbuffer before using it. This is
+ * okay as providing it as an output parameter is an optimization, not a
+ * requirement.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1098,15 +1112,38 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer)
 {
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block;
+	/* Use local variables for better optimized loop code */
+	BlockNumber rel_pages = vacrel->rel_pages;
+	/* Relies on InvalidBlockNumber + 1 == 0 */
+	BlockNumber next_block = vacrel->next_block_state.current_block + 1;
+	BlockNumber next_unskippable_block = next_block;
+
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
+	vacrel->next_block_state.next_unskippable_allvis = true;
+
+	/*
+	 * A block is unskippable if it is not all visible according to the
+	 * visibility map. It is also unskippable if it is the last block in the
+	 * relation, if the vacuum is an aggressive vacuum, or if
+	 * DISABLE_PAGE_SKIPPING was passed to vacuum.
+	 *
+	 * Even if a block is skippable, we may choose not to skip it if the range
+	 * of skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+	 * consequence, we must keep track of the next truly unskippable block and
+	 * its visibility status along with whether or not we are skipping the
+	 * current range of skippable blocks. This can be used to derive the next
+	 * block lazy_scan_heap() must process and its visibility status.
+	 *
+	 * The block number and visibility status of the next unskippable block
+	 * are set in next_block_state->next_unskippable_block and
+	 * next_unskippable_allvis. next_block_state->skipping_current_range
+	 * indicates to the caller whether or not it is processing a skippable
+	 * (and thus all-visible) block.
+	 */
 	while (next_unskippable_block < rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
@@ -1116,7 +1153,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacrel->next_block_state.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1137,7 +1174,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacrel->next_block_state.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1162,6 +1199,10 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		next_unskippable_block++;
 	}
 
+	Assert(vacrel->next_block_state.next_unskippable_block >=
+		   vacrel->next_block_state.current_block);
+	vacrel->next_block_state.next_unskippable_block = next_unskippable_block;
+
 	/*
 	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
 	 * pages.  Since we're reading sequentially, the OS should be doing
@@ -1172,16 +1213,19 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacrel->next_block_state.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacrel->next_block_state.skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacrel->next_block_state.skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
 
-	return next_unskippable_block;
+	if (next_unskippable_block >= rel_pages)
+		next_block = InvalidBlockNumber;
+
+	vacrel->next_block_state.current_block = next_block;
 }
 
 /*
-- 
2.40.1

  [text/x-diff] v7-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (14.2K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/4-v7-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 991c5a7ed46cc5dee36352194058ffb06a4e8670 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v7 3/7] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface [1] (and
eventually AIO), refactor vacuum's logic for skipping blocks such that
it is entirely confined to lazy_scan_skip(). This turns lazy_scan_skip()
and its next block state in LVRelState into an iterator which yields
blocks to lazy_scan_heap(). Such a structure is conducive to an async
interface. While we are at it, rename lazy_scan_skip() to
heap_vac_scan_next_block(), which now more accurately describes it.

By always calling heap_vac_scan_next_block(), instead of only when we
have reached the next unskippable block, we no longer need the
skipping_current_range variable. Furthermore, lazy_scan_heap() no longer
needs to manage the skipped range by checking if we reached the end in
order to then call heap_vac_scan_next_block(). And
heap_vac_scan_next_block() can derive the visibility status of a block
from whether or not we are in a skippable range; that is, if the next
block is equal to the next unskippable block, then the block isn't all
visible, otherwise it is.

[1] https://postgr.es/m/flat/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com

Discussion: https://postgr.es/m/flat/CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 228 ++++++++++++++-------------
 1 file changed, 115 insertions(+), 113 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index accc6303fa2..8d715caccc1 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -206,19 +206,20 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
-	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 * Parameters maintained by heap_vac_scan_next_block() to manage getting
+	 * the next block for vacuum to process.
 	 */
 	struct
 	{
-		/* The last block lazy_scan_skip() returned and vacuum processed */
+		/*
+		 * The last block heap_vac_scan_next_block() returned and vacuum
+		 * processed
+		 */
 		BlockNumber current_block;
 		/* Next unskippable block */
 		BlockNumber next_unskippable_block;
 		/* Next unskippable block's visibility status */
 		bool		next_unskippable_allvis;
-		/* Whether or not skippable blocks should be skipped */
-		bool		skipping_current_range;
 	}			next_block_state;
 } LVRelState;
 
@@ -232,7 +233,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer);
+static bool heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
+									 BlockNumber *blkno,
+									 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -816,6 +819,8 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
@@ -831,41 +836,18 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	/* Initialize for first lazy_scan_skip() call */
+	/* Initialize for first heap_vac_scan_next_block() call */
 	vacrel->next_block_state.current_block = InvalidBlockNumber;
 	vacrel->next_block_state.next_unskippable_block = InvalidBlockNumber;
 
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, &vmbuffer);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+	while (heap_vac_scan_next_block(vacrel, &vmbuffer,
+									&blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == vacrel->next_block_state.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacrel->next_block_state.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, &vmbuffer);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacrel->next_block_state.skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1086,10 +1068,16 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
+ *	heap_vac_scan_next_block() -- get next block for vacuum to process
+ *
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed and set blkno to
+ * the next block that actually needs to be processed.
  *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.
+ * The block number and visibility status of the next block to process are set
+ * in blkno and all_visible_according_to_vm. heap_vac_scan_next_block()
+ * returns false if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here; vacuum options and information about the
  * relation are read, members of vacrel->next_block_state are read and set as
@@ -1112,19 +1100,14 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer)
+static bool
+heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
+						 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
-	/* Use local variables for better optimized loop code */
-	BlockNumber rel_pages = vacrel->rel_pages;
 	/* Relies on InvalidBlockNumber + 1 == 0 */
 	BlockNumber next_block = vacrel->next_block_state.current_block + 1;
-	BlockNumber next_unskippable_block = next_block;
-
 	bool		skipsallvis = false;
 
-	vacrel->next_block_state.next_unskippable_allvis = true;
-
 	/*
 	 * A block is unskippable if it is not all visible according to the
 	 * visibility map. It is also unskippable if it is the last block in the
@@ -1144,88 +1127,107 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer)
 	 * indicates to the caller whether or not it is processing a skippable
 	 * (and thus all-visible) block.
 	 */
-	while (next_unskippable_block < rel_pages)
+	if (next_block >= vacrel->rel_pages)
 	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   vmbuffer);
+		vacrel->next_block_state.current_block = *blkno = InvalidBlockNumber;
+		return false;
+	}
+
+	if (vacrel->next_block_state.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->next_block_state.next_unskippable_block)
+	{
+		/* Use local variables for better optimized loop code */
+		BlockNumber rel_pages = vacrel->rel_pages;
+		BlockNumber next_unskippable_block = vacrel->next_block_state.next_unskippable_block;
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+		while (++next_unskippable_block < rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacrel->next_block_state.next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+			vacrel->next_block_state.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacrel->next_block_state.next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacrel->next_block_state.next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacrel->next_block_state.next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
-		}
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-	}
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
 
-	Assert(vacrel->next_block_state.next_unskippable_block >=
-		   vacrel->next_block_state.current_block);
-	vacrel->next_block_state.next_unskippable_block = next_unskippable_block;
+			vacuum_delay_point();
+		}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacrel->next_block_state.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacrel->next_block_state.skipping_current_range = false;
-	else
-	{
-		vacrel->next_block_state.skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
+		vacrel->next_block_state.next_unskippable_block = next_unskippable_block;
+
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->next_block_state.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->next_block_state.next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
 	}
 
-	if (next_unskippable_block >= rel_pages)
-		next_block = InvalidBlockNumber;
+	if (next_block == vacrel->next_block_state.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->next_block_state.next_unskippable_allvis;
+	else
+		*all_visible_according_to_vm = true;
 
-	vacrel->next_block_state.current_block = next_block;
+	vacrel->next_block_state.current_block = *blkno = next_block;
+	return true;
 }
 
 /*
@@ -1798,8 +1800,8 @@ lazy_scan_prune(LVRelState *vacrel,
 
 	/*
 	 * Handle setting visibility map bit based on information from the VM (as
-	 * of last lazy_scan_skip() call), and from all_visible and all_frozen
-	 * variables
+	 * of last heap_vac_scan_next_block() call), and from all_visible and
+	 * all_frozen variables
 	 */
 	if (!all_visible_according_to_vm && all_visible)
 	{
@@ -1834,8 +1836,8 @@ lazy_scan_prune(LVRelState *vacrel,
 	/*
 	 * As of PostgreSQL 9.2, the visibility map bit should never be set if the
 	 * page-level bit is clear.  However, it's possible that the bit got
-	 * cleared after lazy_scan_skip() was called, so we must recheck with
-	 * buffer lock before concluding that the VM is corrupt.
+	 * cleared after heap_vac_scan_next_block() was called, so we must recheck
+	 * with buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
 			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
-- 
2.40.1

  [text/x-diff] v7-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.0K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/5-v7-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From 01be526bfb450d795dca7cabe3cd97687ef60156 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v7 4/7] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8d715caccc1..d2c8f27fc57 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1195,8 +1195,6 @@ heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		vacrel->next_block_state.next_unskippable_block = next_unskippable_block;
-- 
2.40.1

  [text/x-diff] v7-0005-Streaming-Read-API.patch (54.8K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/6-v7-0005-Streaming-Read-API.patch)
  download | inline diff:
From 4143bef6230138d85772f76a3129433f40d4195d Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 6 Mar 2024 14:46:08 -0500
Subject: [PATCH v7 5/7] Streaming Read API

---
 src/backend/storage/Makefile             |   2 +-
 src/backend/storage/aio/Makefile         |  14 +
 src/backend/storage/aio/meson.build      |   5 +
 src/backend/storage/aio/streaming_read.c | 612 ++++++++++++++++++++++
 src/backend/storage/buffer/bufmgr.c      | 641 ++++++++++++++++-------
 src/backend/storage/buffer/localbuf.c    |  14 +-
 src/backend/storage/meson.build          |   1 +
 src/include/storage/bufmgr.h             |  45 ++
 src/include/storage/streaming_read.h     |  52 ++
 src/tools/pgindent/typedefs.list         |   3 +
 10 files changed, 1179 insertions(+), 210 deletions(-)
 create mode 100644 src/backend/storage/aio/Makefile
 create mode 100644 src/backend/storage/aio/meson.build
 create mode 100644 src/backend/storage/aio/streaming_read.c
 create mode 100644 src/include/storage/streaming_read.h

diff --git a/src/backend/storage/Makefile b/src/backend/storage/Makefile
index 8376cdfca20..eec03f6f2b4 100644
--- a/src/backend/storage/Makefile
+++ b/src/backend/storage/Makefile
@@ -8,6 +8,6 @@ subdir = src/backend/storage
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
-SUBDIRS     = buffer file freespace ipc large_object lmgr page smgr sync
+SUBDIRS     = aio buffer file freespace ipc large_object lmgr page smgr sync
 
 include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/Makefile b/src/backend/storage/aio/Makefile
new file mode 100644
index 00000000000..bcab44c802f
--- /dev/null
+++ b/src/backend/storage/aio/Makefile
@@ -0,0 +1,14 @@
+#
+# Makefile for storage/aio
+#
+# src/backend/storage/aio/Makefile
+#
+
+subdir = src/backend/storage/aio
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+
+OBJS = \
+	streaming_read.o
+
+include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/meson.build b/src/backend/storage/aio/meson.build
new file mode 100644
index 00000000000..39aef2a84a2
--- /dev/null
+++ b/src/backend/storage/aio/meson.build
@@ -0,0 +1,5 @@
+# Copyright (c) 2024, PostgreSQL Global Development Group
+
+backend_sources += files(
+  'streaming_read.c',
+)
diff --git a/src/backend/storage/aio/streaming_read.c b/src/backend/storage/aio/streaming_read.c
new file mode 100644
index 00000000000..71f2c4a70b6
--- /dev/null
+++ b/src/backend/storage/aio/streaming_read.c
@@ -0,0 +1,612 @@
+#include "postgres.h"
+
+#include "storage/streaming_read.h"
+#include "utils/rel.h"
+
+/*
+ * Element type for PgStreamingRead's circular array of block ranges.
+ */
+typedef struct PgStreamingReadRange
+{
+	bool		need_wait;
+	bool		advice_issued;
+	BlockNumber blocknum;
+	int			nblocks;
+	int			per_buffer_data_index;
+	Buffer		buffers[MAX_BUFFERS_PER_TRANSFER];
+	ReadBuffersOperation operation;
+} PgStreamingReadRange;
+
+/*
+ * Streaming read object.
+ */
+struct PgStreamingRead
+{
+	int			max_ios;
+	int			ios_in_progress;
+	int			max_pinned_buffers;
+	int			pinned_buffers;
+	int			pinned_buffers_trigger;
+	int			next_tail_buffer;
+	int			ramp_up_pin_limit;
+	int			ramp_up_pin_stall;
+	bool		finished;
+	bool		advice_enabled;
+	void	   *pgsr_private;
+	PgStreamingReadBufferCB callback;
+
+	BufferAccessStrategy strategy;
+	BufferManagerRelation bmr;
+	ForkNumber	forknum;
+
+	/* Sometimes we need to buffer one block for flow control. */
+	BlockNumber unget_blocknum;
+	void	   *unget_per_buffer_data;
+
+	/* Next expected block, for detecting sequential access. */
+	BlockNumber seq_blocknum;
+
+	/* Space for optional per-buffer private data. */
+	size_t		per_buffer_data_size;
+	void	   *per_buffer_data;
+
+	/* Circular buffer of ranges. */
+	int			size;
+	int			head;
+	int			tail;
+	PgStreamingReadRange ranges[FLEXIBLE_ARRAY_MEMBER];
+};
+
+static PgStreamingRead *
+pg_streaming_read_buffer_alloc_internal(int flags,
+										void *pgsr_private,
+										size_t per_buffer_data_size,
+										BufferAccessStrategy strategy)
+{
+	PgStreamingRead *pgsr;
+	int			size;
+	int			max_ios;
+	uint32		max_pinned_buffers;
+
+
+	/*
+	 * Decide how many assumed I/Os we will allow to run concurrently.  That
+	 * is, advice to the kernel to tell it that we will soon read.  This
+	 * number also affects how far we look ahead for opportunities to start
+	 * more I/Os.
+	 */
+	if (flags & PGSR_FLAG_MAINTENANCE)
+		max_ios = maintenance_io_concurrency;
+	else
+		max_ios = effective_io_concurrency;
+
+	/*
+	 * The desired level of I/O concurrency controls how far ahead we are
+	 * willing to look ahead.  We also clamp it to at least
+	 * MAX_BUFFER_PER_TRANFER so that we can have a chance to build up a full
+	 * sized read, even when max_ios is zero.
+	 */
+	max_pinned_buffers = Max(max_ios * 4, MAX_BUFFERS_PER_TRANSFER);
+
+	/*
+	 * The *_io_concurrency GUCs might be set to 0, but we want to allow at
+	 * least one, to keep our gating logic simple.
+	 */
+	max_ios = Max(max_ios, 1);
+
+	/*
+	 * Don't allow this backend to pin too many buffers.  For now we'll apply
+	 * the limit for the shared buffer pool and the local buffer pool, without
+	 * worrying which it is.
+	 */
+	LimitAdditionalPins(&max_pinned_buffers);
+	LimitAdditionalLocalPins(&max_pinned_buffers);
+	Assert(max_pinned_buffers > 0);
+
+	/*
+	 * pgsr->ranges is a circular buffer.  When it is empty, head == tail.
+	 * When it is full, there is an empty element between head and tail.  Head
+	 * can also be empty (nblocks == 0), therefore we need two extra elements
+	 * for non-occupied ranges, on top of max_pinned_buffers to allow for the
+	 * maxmimum possible number of occupied ranges of the smallest possible
+	 * size of one.
+	 */
+	size = max_pinned_buffers + 2;
+
+	pgsr = (PgStreamingRead *)
+		palloc0(offsetof(PgStreamingRead, ranges) +
+				sizeof(pgsr->ranges[0]) * size);
+
+	pgsr->max_ios = max_ios;
+	pgsr->per_buffer_data_size = per_buffer_data_size;
+	pgsr->max_pinned_buffers = max_pinned_buffers;
+	pgsr->pgsr_private = pgsr_private;
+	pgsr->strategy = strategy;
+	pgsr->size = size;
+
+	pgsr->unget_blocknum = InvalidBlockNumber;
+
+#ifdef USE_PREFETCH
+
+	/*
+	 * This system supports prefetching advice.  As long as direct I/O isn't
+	 * enabled, and the caller hasn't promised sequential access, we can use
+	 * it.
+	 */
+	if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
+		(flags & PGSR_FLAG_SEQUENTIAL) == 0)
+		pgsr->advice_enabled = true;
+#endif
+
+	/*
+	 * We start off building small ranges, but double that quickly, for the
+	 * benefit of users that don't know how far ahead they'll read.  This can
+	 * be disabled by users that already know they'll read all the way.
+	 */
+	if (flags & PGSR_FLAG_FULL)
+		pgsr->ramp_up_pin_limit = INT_MAX;
+	else
+		pgsr->ramp_up_pin_limit = 1;
+
+	/*
+	 * We want to avoid creating ranges that are smaller than they could be
+	 * just because we hit max_pinned_buffers.  We only look ahead when the
+	 * number of pinned buffers falls below this trigger number, or put
+	 * another way, we stop looking ahead when we wouldn't be able to build a
+	 * "full sized" range.
+	 */
+	pgsr->pinned_buffers_trigger =
+		Max(1, (int) max_pinned_buffers - MAX_BUFFERS_PER_TRANSFER);
+
+	/* Space for the callback to store extra data along with each block. */
+	if (per_buffer_data_size)
+		pgsr->per_buffer_data = palloc(per_buffer_data_size * max_pinned_buffers);
+
+	return pgsr;
+}
+
+/*
+ * Create a new streaming read object that can be used to perform the
+ * equivalent of a series of ReadBuffer() calls for one fork of one relation.
+ * Internally, it generates larger vectored reads where possible by looking
+ * ahead.
+ */
+PgStreamingRead *
+pg_streaming_read_buffer_alloc(int flags,
+							   void *pgsr_private,
+							   size_t per_buffer_data_size,
+							   BufferAccessStrategy strategy,
+							   BufferManagerRelation bmr,
+							   ForkNumber forknum,
+							   PgStreamingReadBufferCB next_block_cb)
+{
+	PgStreamingRead *result;
+
+	result = pg_streaming_read_buffer_alloc_internal(flags,
+													 pgsr_private,
+													 per_buffer_data_size,
+													 strategy);
+	result->callback = next_block_cb;
+	result->bmr = bmr;
+	result->forknum = forknum;
+
+	return result;
+}
+
+/*
+ * Find the per-buffer data index for the Nth block of a range.
+ */
+static int
+get_per_buffer_data_index(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	int			result;
+
+	/*
+	 * Find slot in the circular buffer of per-buffer data, without using the
+	 * expensive % operator.
+	 */
+	result = range->per_buffer_data_index + n;
+	if (result >= pgsr->max_pinned_buffers)
+		result -= pgsr->max_pinned_buffers;
+	Assert(result == (range->per_buffer_data_index + n) % pgsr->max_pinned_buffers);
+
+	return result;
+}
+
+/*
+ * Return a pointer to the per-buffer data by index.
+ */
+static void *
+get_per_buffer_data_by_index(PgStreamingRead *pgsr, int per_buffer_data_index)
+{
+	return (char *) pgsr->per_buffer_data +
+		pgsr->per_buffer_data_size * per_buffer_data_index;
+}
+
+/*
+ * Return a pointer to the per-buffer data for the Nth block of a range.
+ */
+static void *
+get_per_buffer_data(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	return get_per_buffer_data_by_index(pgsr,
+										get_per_buffer_data_index(pgsr,
+																  range,
+																  n));
+}
+
+/*
+ * Start reading the head range, and create a new head range.  The new head
+ * range is returned.  It may not be empty, if StartReadBuffers() couldn't
+ * start the entire range; in that case the returned range contains the
+ * remaining portion of the range.
+ */
+static PgStreamingReadRange *
+pg_streaming_read_start_head_range(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *head_range;
+	PgStreamingReadRange *new_head_range;
+	int			nblocks_pinned;
+	int			flags;
+
+	/* Caller should make sure we never exceed max_ios. */
+	Assert(pgsr->ios_in_progress < pgsr->max_ios);
+
+	/* Should only call if the head range has some blocks to read. */
+	head_range = &pgsr->ranges[pgsr->head];
+	Assert(head_range->nblocks > 0);
+
+	/*
+	 * If advice hasn't been suppressed, and this system supports it, this
+	 * isn't a strictly sequential pattern, then we'll issue advice.
+	 */
+	if (pgsr->advice_enabled && head_range->blocknum != pgsr->seq_blocknum)
+		flags = READ_BUFFERS_ISSUE_ADVICE;
+	else
+		flags = 0;
+
+
+	/* Start reading as many blocks as we can from the head range. */
+	nblocks_pinned = head_range->nblocks;
+	head_range->need_wait =
+		StartReadBuffers(pgsr->bmr,
+						 head_range->buffers,
+						 pgsr->forknum,
+						 head_range->blocknum,
+						 &nblocks_pinned,
+						 pgsr->strategy,
+						 flags,
+						 &head_range->operation);
+
+	/* Did that start an I/O? */
+	if (head_range->need_wait && (flags & READ_BUFFERS_ISSUE_ADVICE))
+	{
+		head_range->advice_issued = true;
+		pgsr->ios_in_progress++;
+		Assert(pgsr->ios_in_progress <= pgsr->max_ios);
+	}
+
+	/*
+	 * StartReadBuffers() might have pinned fewer blocks than we asked it to,
+	 * but always at least one.
+	 */
+	Assert(nblocks_pinned <= head_range->nblocks);
+	Assert(nblocks_pinned >= 1);
+	pgsr->pinned_buffers += nblocks_pinned;
+
+	/*
+	 * Remember where the next block would be after that, so we can detect
+	 * sequential access next time.
+	 */
+	pgsr->seq_blocknum = head_range->blocknum + nblocks_pinned;
+
+	/*
+	 * Create a new head range.  There must be space, because we have enough
+	 * elements for every range to hold just one block, up to the pin limit.
+	 */
+	Assert(pgsr->size > pgsr->max_pinned_buffers);
+	Assert((pgsr->head + 1) % pgsr->size != pgsr->tail);
+	if (++pgsr->head == pgsr->size)
+		pgsr->head = 0;
+	new_head_range = &pgsr->ranges[pgsr->head];
+	new_head_range->nblocks = 0;
+	new_head_range->advice_issued = false;
+
+	/*
+	 * If we didn't manage to start the whole read above, we split the range,
+	 * moving the remainder into the new head range.
+	 */
+	if (nblocks_pinned < head_range->nblocks)
+	{
+		int			nblocks_remaining = head_range->nblocks - nblocks_pinned;
+
+		head_range->nblocks = nblocks_pinned;
+
+		new_head_range->blocknum = head_range->blocknum + nblocks_pinned;
+		new_head_range->nblocks = nblocks_remaining;
+	}
+
+	/* The new range has per-buffer data starting after the previous range. */
+	new_head_range->per_buffer_data_index =
+		get_per_buffer_data_index(pgsr, head_range, nblocks_pinned);
+
+	return new_head_range;
+}
+
+/*
+ * Ask the callback which block it would like us to read next, with a small
+ * buffer in front to allow pg_streaming_unget_block() to work.
+ */
+static BlockNumber
+pg_streaming_get_block(PgStreamingRead *pgsr, void *per_buffer_data)
+{
+	BlockNumber result;
+
+	if (unlikely(pgsr->unget_blocknum != InvalidBlockNumber))
+	{
+		/*
+		 * If we had to unget a block, now it is time to return that one
+		 * again.
+		 */
+		result = pgsr->unget_blocknum;
+		pgsr->unget_blocknum = InvalidBlockNumber;
+
+		/*
+		 * The same per_buffer_data element must have been used, and still
+		 * contains whatever data the callback wrote into it.  So we just
+		 * sanity-check that we were called with the value that
+		 * pg_streaming_unget_block() pushed back.
+		 */
+		Assert(per_buffer_data == pgsr->unget_per_buffer_data);
+	}
+	else
+	{
+		/* Use the installed callback directly. */
+		result = pgsr->callback(pgsr, pgsr->pgsr_private, per_buffer_data);
+	}
+
+	return result;
+}
+
+/*
+ * In order to deal with short reads in StartReadBuffers(), we sometimes need
+ * to defer handling of a block until later.  This *must* be called with the
+ * last value returned by pg_streaming_get_block().
+ */
+static void
+pg_streaming_unget_block(PgStreamingRead *pgsr, BlockNumber blocknum, void *per_buffer_data)
+{
+	Assert(pgsr->unget_blocknum == InvalidBlockNumber);
+	pgsr->unget_blocknum = blocknum;
+	pgsr->unget_per_buffer_data = per_buffer_data;
+}
+
+static void
+pg_streaming_read_look_ahead(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *range;
+
+	/*
+	 * If we're still ramping up, we may have to stall to wait for buffers to
+	 * be consumed first before we do any more prefetching.
+	 */
+	if (pgsr->ramp_up_pin_stall > 0)
+	{
+		Assert(pgsr->pinned_buffers > 0);
+		return;
+	}
+
+	/*
+	 * If we're finished or can't start more I/O, then don't look ahead.
+	 */
+	if (pgsr->finished || pgsr->ios_in_progress == pgsr->max_ios)
+		return;
+
+	/*
+	 * We'll also wait until the number of pinned buffers falls below our
+	 * trigger level, so that we have the chance to create a full range.
+	 */
+	if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+		return;
+
+	do
+	{
+		BlockNumber blocknum;
+		void	   *per_buffer_data;
+
+		/* Do we have a full-sized range? */
+		range = &pgsr->ranges[pgsr->head];
+		if (range->nblocks == lengthof(range->buffers))
+		{
+			/* Start as much of it as we can. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/* If we're now at the I/O limit, stop here. */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+				return;
+
+			/*
+			 * If we couldn't form a full range, then stop here to avoid
+			 * creating small I/O.
+			 */
+			if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+				return;
+
+			/*
+			 * That might have only been partially started, but always
+			 * processes at least one so that'll do for now.
+			 */
+			Assert(range->nblocks < lengthof(range->buffers));
+		}
+
+		/* Find per-buffer data slot for the next block. */
+		per_buffer_data = get_per_buffer_data(pgsr, range, range->nblocks);
+
+		/* Find out which block the callback wants to read next. */
+		blocknum = pg_streaming_get_block(pgsr, per_buffer_data);
+		if (blocknum == InvalidBlockNumber)
+		{
+			/* End of stream. */
+			pgsr->finished = true;
+			break;
+		}
+
+		/*
+		 * Is there a head range that we cannot extend, because the requested
+		 * block is not consecutive?
+		 */
+		if (range->nblocks > 0 &&
+			range->blocknum + range->nblocks != blocknum)
+		{
+			/* Yes.  Start it, so we can begin building a new one. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * It's possible that it was only partially started, and we have a
+			 * new range with the remainder.  Keep starting I/Os until we get
+			 * it all out of the way, or we hit the I/O limit.
+			 */
+			while (range->nblocks > 0 && pgsr->ios_in_progress < pgsr->max_ios)
+				range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * We have to 'unget' the block returned by the callback if we
+			 * don't have enough I/O capacity left to start something.
+			 */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+			{
+				pg_streaming_unget_block(pgsr, blocknum, per_buffer_data);
+				return;
+			}
+		}
+
+		/* If we have a new, empty range, initialize the start block. */
+		if (range->nblocks == 0)
+		{
+			range->blocknum = blocknum;
+		}
+
+		/* This block extends the range by one. */
+		Assert(range->blocknum + range->nblocks == blocknum);
+		range->nblocks++;
+
+	} while (pgsr->pinned_buffers + range->nblocks < pgsr->max_pinned_buffers &&
+			 pgsr->pinned_buffers + range->nblocks < pgsr->ramp_up_pin_limit);
+
+	/* If we've hit the ramp-up limit, insert a stall. */
+	if (pgsr->pinned_buffers + range->nblocks >= pgsr->ramp_up_pin_limit)
+	{
+		/* Can't get here if an earlier stall hasn't finished. */
+		Assert(pgsr->ramp_up_pin_stall == 0);
+		/* Don't do any more prefetching until these buffers are consumed. */
+		pgsr->ramp_up_pin_stall = pgsr->ramp_up_pin_limit;
+		/* Double it.  It will soon be out of the way. */
+		pgsr->ramp_up_pin_limit *= 2;
+	}
+
+	/* Start as much as we can. */
+	while (range->nblocks > 0)
+	{
+		range = pg_streaming_read_start_head_range(pgsr);
+		if (pgsr->ios_in_progress == pgsr->max_ios)
+			break;
+	}
+}
+
+Buffer
+pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_data)
+{
+	pg_streaming_read_look_ahead(pgsr);
+
+	/* See if we have one buffer to return. */
+	while (pgsr->tail != pgsr->head)
+	{
+		PgStreamingReadRange *tail_range;
+
+		tail_range = &pgsr->ranges[pgsr->tail];
+
+		/*
+		 * Do we need to perform an I/O before returning the buffers from this
+		 * range?
+		 */
+		if (tail_range->need_wait)
+		{
+			WaitReadBuffers(&tail_range->operation);
+			tail_range->need_wait = false;
+
+			/*
+			 * We don't really know if the kernel generated a physical I/O
+			 * when we issued advice, let alone when it finished, but it has
+			 * certainly finished now because we've performed the read.
+			 */
+			if (tail_range->advice_issued)
+			{
+				Assert(pgsr->ios_in_progress > 0);
+				pgsr->ios_in_progress--;
+			}
+		}
+
+		/* Are there more buffers available in this range? */
+		if (pgsr->next_tail_buffer < tail_range->nblocks)
+		{
+			int			buffer_index;
+			Buffer		buffer;
+
+			buffer_index = pgsr->next_tail_buffer++;
+			buffer = tail_range->buffers[buffer_index];
+
+			Assert(BufferIsValid(buffer));
+
+			/* We are giving away ownership of this pinned buffer. */
+			Assert(pgsr->pinned_buffers > 0);
+			pgsr->pinned_buffers--;
+
+			if (pgsr->ramp_up_pin_stall > 0)
+				pgsr->ramp_up_pin_stall--;
+
+			if (per_buffer_data)
+				*per_buffer_data = get_per_buffer_data(pgsr, tail_range, buffer_index);
+
+			return buffer;
+		}
+
+		/* Advance tail to next range, if there is one. */
+		if (++pgsr->tail == pgsr->size)
+			pgsr->tail = 0;
+		pgsr->next_tail_buffer = 0;
+
+		/*
+		 * If tail crashed into head, and head is not empty, then it is time
+		 * to start that range.
+		 */
+		if (pgsr->tail == pgsr->head &&
+			pgsr->ranges[pgsr->head].nblocks > 0)
+			pg_streaming_read_start_head_range(pgsr);
+	}
+
+	Assert(pgsr->pinned_buffers == 0);
+
+	return InvalidBuffer;
+}
+
+void
+pg_streaming_read_free(PgStreamingRead *pgsr)
+{
+	Buffer		buffer;
+
+	/* Stop looking ahead. */
+	pgsr->finished = true;
+
+	/* Unpin anything that wasn't consumed. */
+	while ((buffer = pg_streaming_read_buffer_get_next(pgsr, NULL)) != InvalidBuffer)
+		ReleaseBuffer(buffer);
+
+	Assert(pgsr->pinned_buffers == 0);
+	Assert(pgsr->ios_in_progress == 0);
+
+	/* Release memory. */
+	if (pgsr->per_buffer_data)
+		pfree(pgsr->per_buffer_data);
+
+	pfree(pgsr);
+}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f0f8d4259c5..729d1f91721 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -19,6 +19,11 @@
  *		and pin it so that no one can destroy it while this process
  *		is using it.
  *
+ * StartReadBuffers() -- as above, but for multiple contiguous blocks in
+ *		two steps.
+ *
+ * WaitReadBuffers() -- second step of StartReadBuffers().
+ *
  * ReleaseBuffer() -- unpin a buffer
  *
  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
@@ -471,10 +476,9 @@ ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
 )
 
 
-static Buffer ReadBuffer_common(SMgrRelation smgr, char relpersistence,
+static Buffer ReadBuffer_common(BufferManagerRelation bmr,
 								ForkNumber forkNum, BlockNumber blockNum,
-								ReadBufferMode mode, BufferAccessStrategy strategy,
-								bool *hit);
+								ReadBufferMode mode, BufferAccessStrategy strategy);
 static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
 										   ForkNumber fork,
 										   BufferAccessStrategy strategy,
@@ -500,7 +504,7 @@ static uint32 WaitBufHdrUnlocked(BufferDesc *buf);
 static int	SyncOneBuffer(int buf_id, bool skip_recently_used,
 						  WritebackContext *wb_context);
 static void WaitIO(BufferDesc *buf);
-static bool StartBufferIO(BufferDesc *buf, bool forInput);
+static bool StartBufferIO(BufferDesc *buf, bool forInput, bool nowait);
 static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
 							  uint32 set_flag_bits, bool forget_owner);
 static void AbortBufferIO(Buffer buffer);
@@ -781,7 +785,6 @@ Buffer
 ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				   ReadBufferMode mode, BufferAccessStrategy strategy)
 {
-	bool		hit;
 	Buffer		buf;
 
 	/*
@@ -794,15 +797,9 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("cannot access temporary tables of other sessions")));
 
-	/*
-	 * Read the buffer, and update pgstat counters to reflect a cache hit or
-	 * miss.
-	 */
-	pgstat_count_buffer_read(reln);
-	buf = ReadBuffer_common(RelationGetSmgr(reln), reln->rd_rel->relpersistence,
-							forkNum, blockNum, mode, strategy, &hit);
-	if (hit)
-		pgstat_count_buffer_hit(reln);
+	buf = ReadBuffer_common(BMR_REL(reln),
+							forkNum, blockNum, mode, strategy);
+
 	return buf;
 }
 
@@ -822,13 +819,12 @@ ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
 						  BlockNumber blockNum, ReadBufferMode mode,
 						  BufferAccessStrategy strategy, bool permanent)
 {
-	bool		hit;
-
 	SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
 
-	return ReadBuffer_common(smgr, permanent ? RELPERSISTENCE_PERMANENT :
-							 RELPERSISTENCE_UNLOGGED, forkNum, blockNum,
-							 mode, strategy, &hit);
+	return ReadBuffer_common(BMR_SMGR(smgr, permanent ? RELPERSISTENCE_PERMANENT :
+									  RELPERSISTENCE_UNLOGGED),
+							 forkNum, blockNum,
+							 mode, strategy);
 }
 
 /*
@@ -994,35 +990,68 @@ ExtendBufferedRelTo(BufferManagerRelation bmr,
 	 */
 	if (buffer == InvalidBuffer)
 	{
-		bool		hit;
-
 		Assert(extended_by == 0);
-		buffer = ReadBuffer_common(bmr.smgr, bmr.relpersistence,
-								   fork, extend_to - 1, mode, strategy,
-								   &hit);
+		buffer = ReadBuffer_common(bmr, fork, extend_to - 1, mode, strategy);
 	}
 
 	return buffer;
 }
 
+/*
+ * Zero a buffer and lock it, as part of the implementation of
+ * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK.  The buffer must be already
+ * pinned.  It does not have to be valid, but it is valid and locked on
+ * return.
+ */
+static void
+ZeroBuffer(Buffer buffer, ReadBufferMode mode)
+{
+	BufferDesc *bufHdr;
+	uint32		buf_state;
+
+	Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
+
+	if (BufferIsLocal(buffer))
+		bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+	else
+	{
+		bufHdr = GetBufferDescriptor(buffer - 1);
+		if (mode == RBM_ZERO_AND_LOCK)
+			LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
+		else
+			LockBufferForCleanup(buffer);
+	}
+
+	memset(BufferGetPage(buffer), 0, BLCKSZ);
+
+	if (BufferIsLocal(buffer))
+	{
+		buf_state = pg_atomic_read_u32(&bufHdr->state);
+		buf_state |= BM_VALID;
+		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+	}
+	else
+	{
+		buf_state = LockBufHdr(bufHdr);
+		buf_state |= BM_VALID;
+		UnlockBufHdr(bufHdr, buf_state);
+	}
+}
+
 /*
  * ReadBuffer_common -- common logic for all ReadBuffer variants
  *
  * *hit is set to true if the request was satisfied from shared buffer cache.
  */
 static Buffer
-ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
+ReadBuffer_common(BufferManagerRelation bmr, ForkNumber forkNum,
 				  BlockNumber blockNum, ReadBufferMode mode,
-				  BufferAccessStrategy strategy, bool *hit)
+				  BufferAccessStrategy strategy)
 {
-	BufferDesc *bufHdr;
-	Block		bufBlock;
-	bool		found;
-	IOContext	io_context;
-	IOObject	io_object;
-	bool		isLocalBuf = SmgrIsTemp(smgr);
-
-	*hit = false;
+	ReadBuffersOperation operation;
+	Buffer		buffer;
+	int			nblocks;
+	int			flags;
 
 	/*
 	 * Backward compatibility path, most code should use ExtendBufferedRel()
@@ -1041,181 +1070,404 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
 			flags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_SMGR(smgr, relpersistence),
-								 forkNum, strategy, flags);
+		return ExtendBufferedRel(bmr, forkNum, strategy, flags);
 	}
 
-	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
-									   smgr->smgr_rlocator.locator.spcOid,
-									   smgr->smgr_rlocator.locator.dbOid,
-									   smgr->smgr_rlocator.locator.relNumber,
-									   smgr->smgr_rlocator.backend);
+	nblocks = 1;
+	if (mode == RBM_ZERO_ON_ERROR)
+		flags = READ_BUFFERS_ZERO_ON_ERROR;
+	else
+		flags = 0;
+	if (StartReadBuffers(bmr,
+						 &buffer,
+						 forkNum,
+						 blockNum,
+						 &nblocks,
+						 strategy,
+						 flags,
+						 &operation))
+		WaitReadBuffers(&operation);
+	Assert(nblocks == 1);		/* single block can't be short */
+
+	if (mode == RBM_ZERO_AND_CLEANUP_LOCK || mode == RBM_ZERO_AND_LOCK)
+		ZeroBuffer(buffer, mode);
+
+	return buffer;
+}
+
+static Buffer
+PrepareReadBuffer(BufferManagerRelation bmr,
+				  ForkNumber forkNum,
+				  BlockNumber blockNum,
+				  BufferAccessStrategy strategy,
+				  bool *foundPtr)
+{
+	BufferDesc *bufHdr;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	Assert(blockNum != P_NEW);
 
+	Assert(bmr.smgr);
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/*
-		 * We do not use a BufferAccessStrategy for I/O of temporary tables.
-		 * However, in some cases, the "strategy" may not be NULL, so we can't
-		 * rely on IOContextForStrategy() to set the right IOContext for us.
-		 * This may happen in cases like CREATE TEMPORARY TABLE AS...
-		 */
 		io_context = IOCONTEXT_NORMAL;
 		io_object = IOOBJECT_TEMP_RELATION;
-		bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, &found);
-		if (found)
-			pgBufferUsage.local_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.local_blks_read++;
 	}
 	else
 	{
-		/*
-		 * lookup the buffer.  IO_IN_PROGRESS is set if the requested block is
-		 * not currently in memory.
-		 */
 		io_context = IOContextForStrategy(strategy);
 		io_object = IOOBJECT_RELATION;
-		bufHdr = BufferAlloc(smgr, relpersistence, forkNum, blockNum,
-							 strategy, &found, io_context);
-		if (found)
-			pgBufferUsage.shared_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.shared_blks_read++;
 	}
 
-	/* At this point we do NOT hold any locks. */
+	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
+									   bmr.smgr->smgr_rlocator.locator.spcOid,
+									   bmr.smgr->smgr_rlocator.locator.dbOid,
+									   bmr.smgr->smgr_rlocator.locator.relNumber,
+									   bmr.smgr->smgr_rlocator.backend);
 
-	/* if it was already in the buffer pool, we're done */
-	if (found)
+	ResourceOwnerEnlarge(CurrentResourceOwner);
+	if (isLocalBuf)
+	{
+		bufHdr = LocalBufferAlloc(bmr.smgr, forkNum, blockNum, foundPtr);
+		if (*foundPtr)
+			pgBufferUsage.local_blks_hit++;
+	}
+	else
+	{
+		bufHdr = BufferAlloc(bmr.smgr, bmr.relpersistence, forkNum, blockNum,
+							 strategy, foundPtr, io_context);
+		if (*foundPtr)
+			pgBufferUsage.shared_blks_hit++;
+	}
+	if (bmr.rel)
+	{
+		/*
+		 * While pgBufferUsage's "read" counter isn't bumped unless we reach
+		 * WaitReadBuffers() (so, not for hits, and not for buffers that are
+		 * zeroed instead), the per-relation stats always count them.
+		 */
+		pgstat_count_buffer_read(bmr.rel);
+		if (*foundPtr)
+			pgstat_count_buffer_hit(bmr.rel);
+	}
+	if (*foundPtr)
 	{
-		/* Just need to update stats before we exit */
-		*hit = true;
 		VacuumPageHit++;
 		pgstat_count_io_op(io_object, io_context, IOOP_HIT);
-
 		if (VacuumCostActive)
 			VacuumCostBalance += VacuumCostPageHit;
 
 		TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-										  smgr->smgr_rlocator.locator.spcOid,
-										  smgr->smgr_rlocator.locator.dbOid,
-										  smgr->smgr_rlocator.locator.relNumber,
-										  smgr->smgr_rlocator.backend,
-										  found);
+										  bmr.smgr->smgr_rlocator.locator.spcOid,
+										  bmr.smgr->smgr_rlocator.locator.dbOid,
+										  bmr.smgr->smgr_rlocator.locator.relNumber,
+										  bmr.smgr->smgr_rlocator.backend,
+										  true);
+	}
 
-		/*
-		 * In RBM_ZERO_AND_LOCK mode the caller expects the page to be locked
-		 * on return.
-		 */
-		if (!isLocalBuf)
-		{
-			if (mode == RBM_ZERO_AND_LOCK)
-				LWLockAcquire(BufferDescriptorGetContentLock(bufHdr),
-							  LW_EXCLUSIVE);
-			else if (mode == RBM_ZERO_AND_CLEANUP_LOCK)
-				LockBufferForCleanup(BufferDescriptorGetBuffer(bufHdr));
-		}
+	return BufferDescriptorGetBuffer(bufHdr);
+}
 
-		return BufferDescriptorGetBuffer(bufHdr);
+/*
+ * Begin reading a range of blocks beginning at blockNum and extending for
+ * *nblocks.  On return, up to *nblocks pinned buffers holding those blocks
+ * are written into the buffers array, and *nblocks is updated to contain the
+ * actual number, which may be fewer than requested.
+ *
+ * If false is returned, no I/O is necessary and WaitReadBuffers() is not
+ * necessary.  If true is returned, one I/O has been started, and
+ * WaitReadBuffers() must be called with the same operation object before the
+ * buffers are accessed.  Along with the operation object, the caller-supplied
+ * array of buffers must remain valid until WaitReadBuffers() is called.
+ *
+ * Currently the I/O is only started with optional operating system advice,
+ * and the real I/O happens in WaitReadBuffers().  In future work, true I/O
+ * could be initiated here.
+ */
+bool
+StartReadBuffers(BufferManagerRelation bmr,
+				 Buffer *buffers,
+				 ForkNumber forkNum,
+				 BlockNumber blockNum,
+				 int *nblocks,
+				 BufferAccessStrategy strategy,
+				 int flags,
+				 ReadBuffersOperation *operation)
+{
+	int			actual_nblocks = *nblocks;
+
+	if (bmr.rel)
+	{
+		bmr.smgr = RelationGetSmgr(bmr.rel);
+		bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
 	}
 
-	/*
-	 * if we have gotten to this point, we have allocated a buffer for the
-	 * page but its contents are not yet valid.  IO_IN_PROGRESS is set for it,
-	 * if it's a shared buffer.
-	 */
-	Assert(!(pg_atomic_read_u32(&bufHdr->state) & BM_VALID));	/* spinlock not needed */
+	operation->bmr = bmr;
+	operation->forknum = forkNum;
+	operation->blocknum = blockNum;
+	operation->buffers = buffers;
+	operation->nblocks = actual_nblocks;
+	operation->strategy = strategy;
+	operation->flags = flags;
 
-	bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
+	operation->io_buffers_len = 0;
 
-	/*
-	 * Read in the page, unless the caller intends to overwrite it and just
-	 * wants us to allocate a buffer.
-	 */
-	if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-		MemSet((char *) bufBlock, 0, BLCKSZ);
-	else
+	for (int i = 0; i < actual_nblocks; ++i)
 	{
-		instr_time	io_start = pgstat_prepare_io_time(track_io_timing);
+		bool		found;
 
-		smgrread(smgr, forkNum, blockNum, bufBlock);
+		buffers[i] = PrepareReadBuffer(bmr,
+									   forkNum,
+									   blockNum + i,
+									   strategy,
+									   &found);
 
-		pgstat_count_io_op_time(io_object, io_context,
-								IOOP_READ, io_start, 1);
+		if (found)
+		{
+			/*
+			 * Terminate the read as soon as we get a hit.  It could be a
+			 * single buffer hit, or it could be a hit that follows a readable
+			 * range.  We don't want to create more than one readable range,
+			 * so we stop here.
+			 */
+			actual_nblocks = operation->nblocks = *nblocks = i + 1;
+		}
+		else
+		{
+			/* Extend the readable range to cover this block. */
+			operation->io_buffers_len++;
+		}
+	}
 
-		/* check for garbage data */
-		if (!PageIsVerifiedExtended((Page) bufBlock, blockNum,
-									PIV_LOG_WARNING | PIV_REPORT_STAT))
+	if (operation->io_buffers_len > 0)
+	{
+		if (flags & READ_BUFFERS_ISSUE_ADVICE)
 		{
-			if (mode == RBM_ZERO_ON_ERROR || zero_damaged_pages)
-			{
-				ereport(WARNING,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s; zeroing out page",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
-				MemSet((char *) bufBlock, 0, BLCKSZ);
-			}
-			else
-				ereport(ERROR,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
+			/*
+			 * In theory we should only do this if PrepareReadBuffers() had to
+			 * allocate new buffers above.  That way, if two calls to
+			 * StartReadBuffers() were made for the same blocks before
+			 * WaitReadBuffers(), only the first would issue the advice.
+			 * That'd be a better simulation of true asynchronous I/O, which
+			 * would only start the I/O once, but isn't done here for
+			 * simplicity.  Note also that the following call might actually
+			 * issue two advice calls if we cross a segment boundary; in a
+			 * true asynchronous version we might choose to process only one
+			 * real I/O at a time in that case.
+			 */
+			smgrprefetch(bmr.smgr, forkNum, blockNum, operation->io_buffers_len);
 		}
+
+		/* Indicate that WaitReadBuffers() should be called. */
+		return true;
 	}
+	else
+	{
+		return false;
+	}
+}
 
-	/*
-	 * In RBM_ZERO_AND_LOCK / RBM_ZERO_AND_CLEANUP_LOCK mode, grab the buffer
-	 * content lock before marking the page as valid, to make sure that no
-	 * other backend sees the zeroed page before the caller has had a chance
-	 * to initialize it.
-	 *
-	 * Since no-one else can be looking at the page contents yet, there is no
-	 * difference between an exclusive lock and a cleanup-strength lock. (Note
-	 * that we cannot use LockBuffer() or LockBufferForCleanup() here, because
-	 * they assert that the buffer is already valid.)
-	 */
-	if ((mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK) &&
-		!isLocalBuf)
+static inline bool
+WaitReadBuffersCanStartIO(Buffer buffer, bool nowait)
+{
+	if (BufferIsLocal(buffer))
 	{
-		LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_EXCLUSIVE);
+		BufferDesc *bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+
+		return (pg_atomic_read_u32(&bufHdr->state) & BM_VALID) == 0;
 	}
+	else
+		return StartBufferIO(GetBufferDescriptor(buffer - 1), true, nowait);
+}
+
+void
+WaitReadBuffers(ReadBuffersOperation *operation)
+{
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	int			nblocks;
+	BlockNumber blocknum;
+	ForkNumber	forknum;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	/*
+	 * Currently operations are only allowed to include a read of some range,
+	 * with an optional extra buffer that is already pinned at the end.  So
+	 * nblocks can be at most one more than io_buffers_len.
+	 */
+	Assert((operation->nblocks == operation->io_buffers_len) ||
+		   (operation->nblocks == operation->io_buffers_len + 1));
 
+	/* Find the range of the physical read we need to perform. */
+	nblocks = operation->io_buffers_len;
+	if (nblocks == 0)
+		return;					/* nothing to do */
+
+	buffers = &operation->buffers[0];
+	blocknum = operation->blocknum;
+	forknum = operation->forknum;
+	bmr = operation->bmr;
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/* Only need to adjust flags */
-		uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
-
-		buf_state |= BM_VALID;
-		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+		io_context = IOCONTEXT_NORMAL;
+		io_object = IOOBJECT_TEMP_RELATION;
 	}
 	else
 	{
-		/* Set BM_VALID, terminate IO, and wake up any waiters */
-		TerminateBufferIO(bufHdr, false, BM_VALID, true);
+		io_context = IOContextForStrategy(operation->strategy);
+		io_object = IOOBJECT_RELATION;
 	}
 
-	VacuumPageMiss++;
-	if (VacuumCostActive)
-		VacuumCostBalance += VacuumCostPageMiss;
+	/*
+	 * We count all these blocks as read by this backend.  This is traditional
+	 * behavior, but might turn out to be not true if we find that someone
+	 * else has beaten us and completed the read of some of these blocks.  In
+	 * that case the system globally double-counts, but we traditionally don't
+	 * count this as a "hit", and we don't have a separate counter for "miss,
+	 * but another backend completed the read".
+	 */
+	if (isLocalBuf)
+		pgBufferUsage.local_blks_read += nblocks;
+	else
+		pgBufferUsage.shared_blks_read += nblocks;
 
-	TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-									  smgr->smgr_rlocator.locator.spcOid,
-									  smgr->smgr_rlocator.locator.dbOid,
-									  smgr->smgr_rlocator.locator.relNumber,
-									  smgr->smgr_rlocator.backend,
-									  found);
+	for (int i = 0; i < nblocks; ++i)
+	{
+		int			io_buffers_len;
+		Buffer		io_buffers[MAX_BUFFERS_PER_TRANSFER];
+		void	   *io_pages[MAX_BUFFERS_PER_TRANSFER];
+		instr_time	io_start;
+		BlockNumber io_first_block;
 
-	return BufferDescriptorGetBuffer(bufHdr);
+		/*
+		 * Skip this block if someone else has already completed it.  If an
+		 * I/O is already in progress in another backend, this will wait for
+		 * the outcome: either done, or something went wrong and we will
+		 * retry.
+		 */
+		if (!WaitReadBuffersCanStartIO(buffers[i], false))
+		{
+			/*
+			 * Report this as a 'hit' for this backend, even though it must
+			 * have started out as a miss in PrepareReadBuffer().
+			 */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, blocknum + i,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  true);
+			continue;
+		}
+
+		/* We found a buffer that we need to read in. */
+		io_buffers[0] = buffers[i];
+		io_pages[0] = BufferGetBlock(buffers[i]);
+		io_first_block = blocknum + i;
+		io_buffers_len = 1;
+
+		/*
+		 * How many neighboring-on-disk blocks can we can scatter-read into
+		 * other buffers at the same time?  In this case we don't wait if we
+		 * see an I/O already in progress.  We already hold BM_IO_IN_PROGRESS
+		 * for the head block, so we should get on with that I/O as soon as
+		 * possible.  We'll come back to this block again, above.
+		 */
+		while ((i + 1) < nblocks &&
+			   WaitReadBuffersCanStartIO(buffers[i + 1], true))
+		{
+			/* Must be consecutive block numbers. */
+			Assert(BufferGetBlockNumber(buffers[i + 1]) ==
+				   BufferGetBlockNumber(buffers[i]) + 1);
+
+			io_buffers[io_buffers_len] = buffers[++i];
+			io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
+		}
+
+		io_start = pgstat_prepare_io_time(track_io_timing);
+		smgrreadv(bmr.smgr, forknum, io_first_block, io_pages, io_buffers_len);
+		pgstat_count_io_op_time(io_object, io_context, IOOP_READ, io_start,
+								io_buffers_len);
+
+		/* Verify each block we read, and terminate the I/O. */
+		for (int j = 0; j < io_buffers_len; ++j)
+		{
+			BufferDesc *bufHdr;
+			Block		bufBlock;
+
+			if (isLocalBuf)
+			{
+				bufHdr = GetLocalBufferDescriptor(-io_buffers[j] - 1);
+				bufBlock = LocalBufHdrGetBlock(bufHdr);
+			}
+			else
+			{
+				bufHdr = GetBufferDescriptor(io_buffers[j] - 1);
+				bufBlock = BufHdrGetBlock(bufHdr);
+			}
+
+			/* check for garbage data */
+			if (!PageIsVerifiedExtended((Page) bufBlock, io_first_block + j,
+										PIV_LOG_WARNING | PIV_REPORT_STAT))
+			{
+				if ((operation->flags & READ_BUFFERS_ZERO_ON_ERROR) || zero_damaged_pages)
+				{
+					ereport(WARNING,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s; zeroing out page",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+					memset(bufBlock, 0, BLCKSZ);
+				}
+				else
+					ereport(ERROR,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+			}
+
+			/* Terminate I/O and set BM_VALID. */
+			if (isLocalBuf)
+			{
+				uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
+
+				buf_state |= BM_VALID;
+				pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+			}
+			else
+			{
+				/* Set BM_VALID, terminate IO, and wake up any waiters */
+				TerminateBufferIO(bufHdr, false, BM_VALID, true);
+			}
+
+			/* Report I/Os as completing individually. */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, io_first_block + j,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  false);
+		}
+
+		VacuumPageMiss += io_buffers_len;
+		if (VacuumCostActive)
+			VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
+	}
 }
 
 /*
- * BufferAlloc -- subroutine for ReadBuffer.  Handles lookup of a shared
- *		buffer.  If no buffer exists already, selects a replacement
- *		victim and evicts the old page, but does NOT read in new page.
+ * BufferAlloc -- subroutine for StartReadBuffers.  Handles lookup of a shared
+ *		buffer.  If no buffer exists already, selects a replacement victim and
+ *		evicts the old page, but does NOT read in new page.
  *
  * "strategy" can be a buffer replacement strategy object, or NULL for
  * the default strategy.  The selected buffer's usage_count is advanced when
@@ -1223,11 +1475,7 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
  *
  * The returned buffer is pinned and is already marked as holding the
  * desired page.  If it already did have the desired page, *foundPtr is
- * set true.  Otherwise, *foundPtr is set false and the buffer is marked
- * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.
- *
- * *foundPtr is actually redundant with the buffer's BM_VALID flag, but
- * we keep it for simplicity in ReadBuffer.
+ * set true.  Otherwise, *foundPtr is set false.
  *
  * io_context is passed as an output parameter to avoid calling
  * IOContextForStrategy() when there is a shared buffers hit and no IO
@@ -1286,19 +1534,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(buf, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return buf;
@@ -1363,19 +1602,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(existing_buf_hdr, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return existing_buf_hdr;
@@ -1407,15 +1637,9 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 	LWLockRelease(newPartitionLock);
 
 	/*
-	 * Buffer contents are currently invalid.  Try to obtain the right to
-	 * start I/O.  If StartBufferIO returns false, then someone else managed
-	 * to read it before we did, so there's nothing left for BufferAlloc() to
-	 * do.
+	 * Buffer contents are currently invalid.
 	 */
-	if (StartBufferIO(victim_buf_hdr, true))
-		*foundPtr = false;
-	else
-		*foundPtr = true;
+	*foundPtr = false;
 
 	return victim_buf_hdr;
 }
@@ -1769,7 +1993,7 @@ again:
  * pessimistic, but outside of toy-sized shared_buffers it should allow
  * sufficient pins.
  */
-static void
+void
 LimitAdditionalPins(uint32 *additional_pins)
 {
 	uint32		max_backends;
@@ -2034,7 +2258,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 
 				buf_state &= ~BM_VALID;
 				UnlockBufHdr(existing_hdr, buf_state);
-			} while (!StartBufferIO(existing_hdr, true));
+			} while (!StartBufferIO(existing_hdr, true, false));
 		}
 		else
 		{
@@ -2057,7 +2281,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 			LWLockRelease(partition_lock);
 
 			/* XXX: could combine the locked operations in it with the above */
-			StartBufferIO(victim_buf_hdr, true);
+			StartBufferIO(victim_buf_hdr, true, false);
 		}
 	}
 
@@ -2372,7 +2596,12 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 	else
 	{
 		/*
-		 * If we previously pinned the buffer, it must surely be valid.
+		 * If we previously pinned the buffer, it is likely to be valid, but
+		 * it may not be if StartReadBuffers() was called and
+		 * WaitReadBuffers() hasn't been called yet.  We'll check by loading
+		 * the flags without locking.  This is racy, but it's OK to return
+		 * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
+		 * it'll see that it's now valid.
 		 *
 		 * Note: We deliberately avoid a Valgrind client request here.
 		 * Individual access methods can optionally superimpose buffer page
@@ -2381,7 +2610,7 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 		 * that the buffer page is legitimately non-accessible here.  We
 		 * cannot meddle with that.
 		 */
-		result = true;
+		result = (pg_atomic_read_u32(&buf->state) & BM_VALID) != 0;
 	}
 
 	ref->refcount++;
@@ -3449,7 +3678,7 @@ FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
 	 * someone else flushed the buffer before we could, so we need not do
 	 * anything.
 	 */
-	if (!StartBufferIO(buf, false))
+	if (!StartBufferIO(buf, false, false))
 		return;
 
 	/* Setup error traceback support for ereport() */
@@ -5184,9 +5413,15 @@ WaitIO(BufferDesc *buf)
  *
  * Returns true if we successfully marked the buffer as I/O busy,
  * false if someone else already did the work.
+ *
+ * If nowait is true, then we don't wait for an I/O to be finished by another
+ * backend.  In that case, false indicates either that the I/O was already
+ * finished, or is still in progress.  This is useful for callers that want to
+ * find out if they can perform the I/O as part of a larger operation, without
+ * waiting for the answer or distinguishing the reasons why not.
  */
 static bool
-StartBufferIO(BufferDesc *buf, bool forInput)
+StartBufferIO(BufferDesc *buf, bool forInput, bool nowait)
 {
 	uint32		buf_state;
 
@@ -5199,6 +5434,8 @@ StartBufferIO(BufferDesc *buf, bool forInput)
 		if (!(buf_state & BM_IO_IN_PROGRESS))
 			break;
 		UnlockBufHdr(buf, buf_state);
+		if (nowait)
+			return false;
 		WaitIO(buf);
 	}
 
diff --git a/src/backend/storage/buffer/localbuf.c b/src/backend/storage/buffer/localbuf.c
index fcfac335a57..985a2c7049c 100644
--- a/src/backend/storage/buffer/localbuf.c
+++ b/src/backend/storage/buffer/localbuf.c
@@ -108,10 +108,9 @@ PrefetchLocalBuffer(SMgrRelation smgr, ForkNumber forkNum,
  * LocalBufferAlloc -
  *	  Find or create a local buffer for the given page of the given relation.
  *
- * API is similar to bufmgr.c's BufferAlloc, except that we do not need
- * to do any locking since this is all local.   Also, IO_IN_PROGRESS
- * does not get set.  Lastly, we support only default access strategy
- * (hence, usage_count is always advanced).
+ * API is similar to bufmgr.c's BufferAlloc, except that we do not need to do
+ * any locking since this is all local.  We support only default access
+ * strategy (hence, usage_count is always advanced).
  */
 BufferDesc *
 LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum,
@@ -287,7 +286,7 @@ GetLocalVictimBuffer(void)
 }
 
 /* see LimitAdditionalPins() */
-static void
+void
 LimitAdditionalLocalPins(uint32 *additional_pins)
 {
 	uint32		max_pins;
@@ -297,9 +296,10 @@ LimitAdditionalLocalPins(uint32 *additional_pins)
 
 	/*
 	 * In contrast to LimitAdditionalPins() other backends don't play a role
-	 * here. We can allow up to NLocBuffer pins in total.
+	 * here. We can allow up to NLocBuffer pins in total, but it might not be
+	 * initialized yet so read num_temp_buffers.
 	 */
-	max_pins = (NLocBuffer - NLocalPinnedBuffers);
+	max_pins = (num_temp_buffers - NLocalPinnedBuffers);
 
 	if (*additional_pins >= max_pins)
 		*additional_pins = max_pins;
diff --git a/src/backend/storage/meson.build b/src/backend/storage/meson.build
index 40345bdca27..739d13293fb 100644
--- a/src/backend/storage/meson.build
+++ b/src/backend/storage/meson.build
@@ -1,5 +1,6 @@
 # Copyright (c) 2022-2024, PostgreSQL Global Development Group
 
+subdir('aio')
 subdir('buffer')
 subdir('file')
 subdir('freespace')
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index d51d46d3353..b57f71f97e3 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -14,6 +14,7 @@
 #ifndef BUFMGR_H
 #define BUFMGR_H
 
+#include "port/pg_iovec.h"
 #include "storage/block.h"
 #include "storage/buf.h"
 #include "storage/bufpage.h"
@@ -158,6 +159,11 @@ extern PGDLLIMPORT int32 *LocalRefCount;
 #define BUFFER_LOCK_SHARE		1
 #define BUFFER_LOCK_EXCLUSIVE	2
 
+/*
+ * Maximum number of buffers for multi-buffer I/O functions.  This is set to
+ * allow 128kB transfers, unless BLCKSZ and IOV_MAX imply a a smaller maximum.
+ */
+#define MAX_BUFFERS_PER_TRANSFER Min(PG_IOV_MAX, (128 * 1024) / BLCKSZ)
 
 /*
  * prototypes for functions in bufmgr.c
@@ -177,6 +183,42 @@ extern Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator,
 										ForkNumber forkNum, BlockNumber blockNum,
 										ReadBufferMode mode, BufferAccessStrategy strategy,
 										bool permanent);
+
+#define READ_BUFFERS_ZERO_ON_ERROR 0x01
+#define READ_BUFFERS_ISSUE_ADVICE 0x02
+
+/*
+ * Private state used by StartReadBuffers() and WaitReadBuffers().  Declared
+ * in public header only to allow inclusion in other structs, but contents
+ * should not be accessed.
+ */
+struct ReadBuffersOperation
+{
+	/* Parameters passed in to StartReadBuffers(). */
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	ForkNumber	forknum;
+	BlockNumber blocknum;
+	int			nblocks;
+	BufferAccessStrategy strategy;
+	int			flags;
+
+	/* Range of buffers, if we need to perform a read. */
+	int			io_buffers_len;
+};
+
+typedef struct ReadBuffersOperation ReadBuffersOperation;
+
+extern bool StartReadBuffers(BufferManagerRelation bmr,
+							 Buffer *buffers,
+							 ForkNumber forknum,
+							 BlockNumber blocknum,
+							 int *nblocks,
+							 BufferAccessStrategy strategy,
+							 int flags,
+							 ReadBuffersOperation *operation);
+extern void WaitReadBuffers(ReadBuffersOperation *operation);
+
 extern void ReleaseBuffer(Buffer buffer);
 extern void UnlockReleaseBuffer(Buffer buffer);
 extern bool BufferIsExclusiveLocked(Buffer buffer);
@@ -250,6 +292,9 @@ extern bool HoldingBufferPinThatDelaysRecovery(void);
 
 extern bool BgBufferSync(struct WritebackContext *wb_context);
 
+extern void LimitAdditionalPins(uint32 *additional_pins);
+extern void LimitAdditionalLocalPins(uint32 *additional_pins);
+
 /* in buf_init.c */
 extern void InitBufferPool(void);
 extern Size BufferShmemSize(void);
diff --git a/src/include/storage/streaming_read.h b/src/include/storage/streaming_read.h
new file mode 100644
index 00000000000..c4d3892bb26
--- /dev/null
+++ b/src/include/storage/streaming_read.h
@@ -0,0 +1,52 @@
+#ifndef STREAMING_READ_H
+#define STREAMING_READ_H
+
+#include "storage/bufmgr.h"
+#include "storage/fd.h"
+#include "storage/smgr.h"
+
+/* Default tuning, reasonable for many users. */
+#define PGSR_FLAG_DEFAULT 0x00
+
+/*
+ * I/O streams that are performing maintenance work on behalf of potentially
+ * many users.
+ */
+#define PGSR_FLAG_MAINTENANCE 0x01
+
+/*
+ * We usually avoid issuing prefetch advice automatically when sequential
+ * access is detected, but this flag explicitly disables it, for cases that
+ * might not be correctly detected.  Explicit advice is known to perform worse
+ * than letting the kernel (at least Linux) detect sequential access.
+ */
+#define PGSR_FLAG_SEQUENTIAL 0x02
+
+/*
+ * We usually ramp up from smaller reads to larger ones, to support users who
+ * don't know if it's worth reading lots of buffers yet.  This flag disables
+ * that, declaring ahead of time that we'll be reading all available buffers.
+ */
+#define PGSR_FLAG_FULL 0x04
+
+struct PgStreamingRead;
+typedef struct PgStreamingRead PgStreamingRead;
+
+/* Callback that returns the next block number to read. */
+typedef BlockNumber (*PgStreamingReadBufferCB) (PgStreamingRead *pgsr,
+												void *pgsr_private,
+												void *per_buffer_private);
+
+extern PgStreamingRead *pg_streaming_read_buffer_alloc(int flags,
+													   void *pgsr_private,
+													   size_t per_buffer_private_size,
+													   BufferAccessStrategy strategy,
+													   BufferManagerRelation bmr,
+													   ForkNumber forknum,
+													   PgStreamingReadBufferCB next_block_cb);
+
+extern void pg_streaming_read_prefetch(PgStreamingRead *pgsr);
+extern Buffer pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_private);
+extern void pg_streaming_read_free(PgStreamingRead *pgsr);
+
+#endif
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index cc3611e6068..5f637f07eeb 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2097,6 +2097,8 @@ PgStat_TableCounts
 PgStat_TableStatus
 PgStat_TableXactStatus
 PgStat_WalStats
+PgStreamingRead
+PgStreamingReadRange
 PgXmlErrorContext
 PgXmlStrictness
 Pg_finfo_record
@@ -2267,6 +2269,7 @@ ReInitializeDSMForeignScan_function
 ReScanForeignScan_function
 ReadBufPtrType
 ReadBufferMode
+ReadBuffersOperation
 ReadBytePtrType
 ReadExtraTocPtrType
 ReadFunc
-- 
2.40.1

  [text/x-diff] v7-0006-Vacuum-first-pass-uses-Streaming-Read-interface.patch (11.0K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/7-v7-0006-Vacuum-first-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From bc9d97de3729e65752ef6a6e9cbfc0808c4725ac Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 11:29:02 -0500
Subject: [PATCH v7 6/7] Vacuum first pass uses Streaming Read interface

Now vacuum's first pass, which HOT prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by implementing a
streaming read callback which invokes heap_vac_scan_next_block().
---
 src/backend/access/heap/vacuumlazy.c | 131 +++++++++++++++++++--------
 1 file changed, 92 insertions(+), 39 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index d2c8f27fc57..d07a2a58b15 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -54,6 +54,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/streaming_read.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/pg_rusage.h"
@@ -168,7 +169,12 @@ typedef struct LVRelState
 	char	   *relnamespace;
 	char	   *relname;
 	char	   *indname;		/* Current index name */
-	BlockNumber blkno;			/* used only for heap operations */
+
+	/*
+	 * The current block being processed by vacuum. Used only for heap
+	 * operations. Primarily for error reporting and logging.
+	 */
+	BlockNumber blkno;
 	OffsetNumber offnum;		/* used only for heap operations */
 	VacErrPhase phase;
 	bool		verbose;		/* VACUUM VERBOSE? */
@@ -220,6 +226,12 @@ typedef struct LVRelState
 		BlockNumber next_unskippable_block;
 		/* Next unskippable block's visibility status */
 		bool		next_unskippable_allvis;
+
+		/*
+		 * Buffer containing block of VM with visibility information for
+		 * next_unskippable_block.
+		 */
+		Buffer		next_unskippable_vmbuffer;
 	}			next_block_state;
 } LVRelState;
 
@@ -233,8 +245,7 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
-									 BlockNumber *blkno,
+static void heap_vac_scan_next_block(LVRelState *vacrel,
 									 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -777,6 +788,47 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 	}
 }
 
+static BlockNumber
+vacuum_scan_pgsr_next(PgStreamingRead *pgsr,
+					  void *pgsr_private, void *per_buffer_data)
+{
+	LVRelState *vacrel = pgsr_private;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
+
+	heap_vac_scan_next_block(vacrel,
+							 all_visible_according_to_vm);
+
+	/*
+	 * If there are no further blocks to vacuum in the relation, release the
+	 * vmbuffer.
+	 */
+	if (!BlockNumberIsValid(vacrel->next_block_state.current_block) &&
+		BufferIsValid(vacrel->next_block_state.next_unskippable_vmbuffer))
+	{
+		ReleaseBuffer(vacrel->next_block_state.next_unskippable_vmbuffer);
+		vacrel->next_block_state.next_unskippable_vmbuffer = InvalidBuffer;
+	}
+
+	return vacrel->next_block_state.current_block;
+}
+
+static inline PgStreamingRead *
+vac_scan_pgsr_alloc(LVRelState *vacrel, PgStreamingReadBufferCB next_block_cb)
+{
+	PgStreamingRead *result = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+															 sizeof(bool), vacrel->bstrategy, BMR_REL(vacrel->rel),
+															 MAIN_FORKNUM, next_block_cb);
+
+	/*
+	 * Initialize for first heap_vac_scan_next_block() call. These rely on
+	 * InvalidBlockNumber + 1 = 0
+	 */
+	vacrel->next_block_state.current_block = InvalidBlockNumber;
+	vacrel->next_block_state.next_unskippable_block = InvalidBlockNumber;
+
+	return result;
+}
+
 /*
  *	lazy_scan_heap() -- workhorse function for VACUUM
  *
@@ -816,10 +868,10 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm;
 
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
@@ -830,23 +882,27 @@ lazy_scan_heap(LVRelState *vacrel)
 	};
 	int64		initprog_val[3];
 
+	PgStreamingRead *pgsr = vac_scan_pgsr_alloc(vacrel, vacuum_scan_pgsr_next);
+
 	/* Report that we're scanning the heap, advertising total # of blocks */
 	initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
 	initprog_val[1] = rel_pages;
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	/* Initialize for first heap_vac_scan_next_block() call */
-	vacrel->next_block_state.current_block = InvalidBlockNumber;
-	vacrel->next_block_state.next_unskippable_block = InvalidBlockNumber;
-
-	while (heap_vac_scan_next_block(vacrel, &vmbuffer,
-									&blkno, &all_visible_according_to_vm))
+	while (BufferIsValid(buf = pg_streaming_read_buffer_get_next(pgsr,
+																 (void **) &all_visible_according_to_vm)))
 	{
-		Buffer		buf;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
+		BlockNumber blkno;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		CheckBufferIsPinnedOnce(buf);
+
+		page = BufferGetPage(buf);
 
 		vacrel->scanned_pages++;
 
@@ -914,9 +970,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
 
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
@@ -973,7 +1026,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1030,7 +1083,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, vacrel->rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1045,6 +1098,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	pg_streaming_read_free(pgsr);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1056,11 +1111,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (vacrel->rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, vacrel->rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, vacrel->rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1072,12 +1127,13 @@ lazy_scan_heap(LVRelState *vacrel)
  *
  * lazy_scan_heap() calls here every time it needs to get the next block to
  * prune and vacuum, using the visibility map, vacuum options, and various
- * thresholds to skip blocks which do not need to be processed and set blkno to
- * the next block that actually needs to be processed.
+ * thresholds to skip blocks which do not need to be processed and set
+ * current_block to the next block that actually needs to be processed.
  *
- * The block number and visibility status of the next block to process are set
- * in blkno and all_visible_according_to_vm. heap_vac_scan_next_block()
- * returns false if there are no further blocks to process.
+ * The number and visibility status of the next block to process are set in
+ * vacrel->next_block_state->current_block and all_visible_according_to_vm.
+ * vacrel->next_block_state->current_block is set to InvalidBlockNumber if
+ * there are no further blocks to process.
  *
  * vacrel is an in/out parameter here; vacuum options and information about the
  * relation are read, members of vacrel->next_block_state are read and set as
@@ -1085,12 +1141,10 @@ lazy_scan_heap(LVRelState *vacrel)
  * don't advance relfrozenxid when we have skipped vacuuming all-visible
  * blocks.
  *
- * vmbuffer is an output parameter which, upon return, will contain the block
- * from the VM containing visibility information for the next unskippable heap
- * block. If we decide not to skip this heap block, the caller is responsible
- * for fetching the correct VM block into vmbuffer before using it. This is
- * okay as providing it as an output parameter is an optimization, not a
- * requirement.
+ * vacrel->next_block_state->vmbuffer will contain visibility information for
+ * the next unskippable heap block. If we decide not to skip this heap block,
+ * the caller is responsible for fetching the correct VM block into the
+ * vmbuffer before using it.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1100,9 +1154,9 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
-						 BlockNumber *blkno, bool *all_visible_according_to_vm)
+static void
+heap_vac_scan_next_block(LVRelState *vacrel,
+						 bool *all_visible_according_to_vm)
 {
 	/* Relies on InvalidBlockNumber + 1 == 0 */
 	BlockNumber next_block = vacrel->next_block_state.current_block + 1;
@@ -1129,8 +1183,8 @@ heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
 	 */
 	if (next_block >= vacrel->rel_pages)
 	{
-		vacrel->next_block_state.current_block = *blkno = InvalidBlockNumber;
-		return false;
+		vacrel->next_block_state.current_block = InvalidBlockNumber;
+		return;
 	}
 
 	if (vacrel->next_block_state.next_unskippable_block == InvalidBlockNumber ||
@@ -1144,7 +1198,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
 		{
 			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 														   next_unskippable_block,
-														   vmbuffer);
+														   &vacrel->next_block_state.next_unskippable_vmbuffer);
 
 			vacrel->next_block_state.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
@@ -1224,8 +1278,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, Buffer *vmbuffer,
 	else
 		*all_visible_according_to_vm = true;
 
-	vacrel->next_block_state.current_block = *blkno = next_block;
-	return true;
+	vacrel->next_block_state.current_block = next_block;
 }
 
 /*
-- 
2.40.1

  [text/x-diff] v7-0007-Vacuum-second-pass-uses-Streaming-Read-interface.patch (8.6K, ../../20240308004614.xn7x3k6qz7jw7ljx@liskov/8-v7-0007-Vacuum-second-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From c3cf35fcb3110da791e9edc1b3325dc8d0080068 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 27 Feb 2024 14:35:36 -0500
Subject: [PATCH v7 7/7] Vacuum second pass uses Streaming Read interface

Now vacuum's second pass, which removes dead items referring to dead
tuples catalogued in the first pass, uses the streaming read API by
implementing a streaming read callback which returns the next block
containing previously catalogued dead items. A new struct,
VacReapBlkState, is introduced to provide the caller with the starting
and ending indexes of dead items to vacuum.
---
 src/backend/access/heap/vacuumlazy.c | 110 ++++++++++++++++++++-------
 src/tools/pgindent/typedefs.list     |   1 +
 2 files changed, 85 insertions(+), 26 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index d07a2a58b15..375b66a62c4 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -195,6 +195,12 @@ typedef struct LVRelState
 	BlockNumber missed_dead_pages;	/* # pages with missed dead tuples */
 	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
 
+	/*
+	 * The index of the next TID in dead_items to reap during the second
+	 * vacuum pass.
+	 */
+	int			idx_prefetch;
+
 	/* Statistics output by us, for table */
 	double		new_rel_tuples; /* new estimated total # of tuples */
 	double		new_live_tuples;	/* new estimated total # of live tuples */
@@ -243,6 +249,21 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+/*
+ * State set up in streaming read callback during vacuum's second pass which
+ * removes dead items referring to dead tuples catalogued in the first pass
+ */
+typedef struct VacReapBlkState
+{
+	/*
+	 * The indexes of the TIDs of the first and last dead tuples in a single
+	 * block in the currently vacuumed relation. The callback will set these
+	 * up prior to adding this block to the stream.
+	 */
+	int			start_idx;
+	int			end_idx;
+} VacReapBlkState;
+
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vac_scan_next_block(LVRelState *vacrel,
@@ -260,8 +281,9 @@ static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 static void lazy_vacuum(LVRelState *vacrel);
 static bool lazy_vacuum_all_indexes(LVRelState *vacrel);
 static void lazy_vacuum_heap_rel(LVRelState *vacrel);
-static int	lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
-								  Buffer buffer, int index, Buffer vmbuffer);
+static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+								  Buffer buffer, Buffer vmbuffer,
+								  VacReapBlkState *rbstate);
 static bool lazy_check_wraparound_failsafe(LVRelState *vacrel);
 static void lazy_cleanup_all_indexes(LVRelState *vacrel);
 static IndexBulkDeleteResult *lazy_vacuum_one_index(Relation indrel,
@@ -2426,6 +2448,37 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_pgsr_next(PgStreamingRead *pgsr,
+						 void *pgsr_private,
+						 void *per_buffer_data)
+{
+	BlockNumber blkno;
+	LVRelState *vacrel = pgsr_private;
+	VacReapBlkState *rbstate = per_buffer_data;
+
+	VacDeadItems *dead_items = vacrel->dead_items;
+
+	if (vacrel->idx_prefetch == dead_items->num_items)
+		return InvalidBlockNumber;
+
+	blkno = ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+	rbstate->start_idx = vacrel->idx_prefetch;
+
+	for (; vacrel->idx_prefetch < dead_items->num_items; vacrel->idx_prefetch++)
+	{
+		BlockNumber curblkno =
+			ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+
+		if (blkno != curblkno)
+			break;				/* past end of tuples for this block */
+	}
+
+	rbstate->end_idx = vacrel->idx_prefetch;
+
+	return blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2447,7 +2500,9 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
-	int			index = 0;
+	Buffer		buf;
+	PgStreamingRead *pgsr;
+	VacReapBlkState *rbstate;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2465,17 +2520,21 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 VACUUM_ERRCB_PHASE_VACUUM_HEAP,
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
-	while (index < vacrel->dead_items->num_items)
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(VacReapBlkState), vacrel->bstrategy, BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM, vacuum_reap_lp_pgsr_next);
+
+	while (BufferIsValid(buf =
+						 pg_streaming_read_buffer_get_next(pgsr,
+														   (void **) &rbstate)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 
 		vacuum_delay_point();
 
-		blkno = ItemPointerGetBlockNumber(&vacrel->dead_items->items[index]);
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		/*
 		 * Pin the visibility map page in case we need to mark the page
@@ -2485,10 +2544,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
-		index = lazy_vacuum_heap_page(vacrel, blkno, buf, index, vmbuffer);
+		lazy_vacuum_heap_page(vacrel, blkno, buf, vmbuffer, rbstate);
 
 		/* Now that we've vacuumed the page, record its available space */
 		page = BufferGetPage(buf);
@@ -2507,14 +2564,16 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 	 * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
 	 * the second heap pass.  No more, no less.
 	 */
-	Assert(index > 0);
+	Assert(rbstate->end_idx > 0);
 	Assert(vacrel->num_index_scans > 1 ||
-		   (index == vacrel->lpdead_items &&
+		   (rbstate->end_idx == vacrel->lpdead_items &&
 			vacuumed_pages == vacrel->lpdead_item_pages));
 
+	pg_streaming_read_free(pgsr);
+
 	ereport(DEBUG2,
 			(errmsg("table \"%s\": removed %lld dead item identifiers in %u pages",
-					vacrel->relname, (long long) index, vacuumed_pages)));
+					vacrel->relname, (long long) rbstate->end_idx, vacuumed_pages)));
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
@@ -2528,13 +2587,12 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
  * cleanup lock is also acceptable).  vmbuffer must be valid and already have
  * a pin on blkno's visibility map page.
  *
- * index is an offset into the vacrel->dead_items array for the first listed
- * LP_DEAD item on the page.  The return value is the first index immediately
- * after all LP_DEAD items for the same page in the array.
+ * Given a block and dead items recorded during the first pass, set those items
+ * dead and truncate the line pointer array. Update the VM as appropriate.
  */
-static int
-lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
-					  int index, Buffer vmbuffer)
+static void
+lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+					  Buffer buffer, Buffer vmbuffer, VacReapBlkState *rbstate)
 {
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Page		page = BufferGetPage(buffer);
@@ -2555,16 +2613,17 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	START_CRIT_SECTION();
 
-	for (; index < dead_items->num_items; index++)
+	for (int i = rbstate->start_idx; i < rbstate->end_idx; i++)
 	{
-		BlockNumber tblk;
 		OffsetNumber toff;
+		ItemPointer dead_item;
 		ItemId		itemid;
 
-		tblk = ItemPointerGetBlockNumber(&dead_items->items[index]);
-		if (tblk != blkno)
-			break;				/* past end of tuples for this block */
-		toff = ItemPointerGetOffsetNumber(&dead_items->items[index]);
+		dead_item = &dead_items->items[i];
+
+		Assert(ItemPointerGetBlockNumber(dead_item) == blkno);
+
+		toff = ItemPointerGetOffsetNumber(dead_item);
 		itemid = PageGetItemId(page, toff);
 
 		Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
@@ -2634,7 +2693,6 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
-	return index;
 }
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 5f637f07eeb..20b85a69f9d 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2972,6 +2972,7 @@ VacOptValue
 VacuumParams
 VacuumRelation
 VacuumStmt
+VacReapBlkState
 ValidIOData
 ValidateIndexState
 ValuesScan
-- 
2.40.1

^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-08 13:49                   ` Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 15:40                     ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 15:44                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 2 replies; 81+ messages in thread

From: Heikki Linnakangas @ 2024-03-08 13:49 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Peter Geoghegan <pg@bowt.ie>

On 08/03/2024 02:46, Melanie Plageman wrote:
> On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
>>> I feel heap_vac_scan_get_next_block() function could use some love. Maybe
>>> just some rewording of the comments, or maybe some other refactoring; not
>>> sure. But I'm pretty happy with the function signature and how it's called.
> 
> I've cleaned up the comments on heap_vac_scan_next_block() in the first
> couple patches (not so much in the streaming read user). Let me know if
> it addresses your feelings or if I should look for other things I could
> change.

Thanks, that is better. I think I now finally understand how the 
function works, and now I can see some more issues and refactoring 
opportunities :-).

Looking at current lazy_scan_skip() code in 'master', one thing now 
caught my eye (and it's the same with your patches):

> 	*next_unskippable_allvis = true;
> 	while (next_unskippable_block < rel_pages)
> 	{
> 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
> 													   next_unskippable_block,
> 													   vmbuffer);
> 
> 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
> 		{
> 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
> 			*next_unskippable_allvis = false;
> 			break;
> 		}
> 
> 		/*
> 		 * Caller must scan the last page to determine whether it has tuples
> 		 * (caller must have the opportunity to set vacrel->nonempty_pages).
> 		 * This rule avoids having lazy_truncate_heap() take access-exclusive
> 		 * lock on rel to attempt a truncation that fails anyway, just because
> 		 * there are tuples on the last page (it is likely that there will be
> 		 * tuples on other nearby pages as well, but those can be skipped).
> 		 *
> 		 * Implement this by always treating the last block as unsafe to skip.
> 		 */
> 		if (next_unskippable_block == rel_pages - 1)
> 			break;
> 
> 		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
> 		if (!vacrel->skipwithvm)
> 		{
> 			/* Caller shouldn't rely on all_visible_according_to_vm */
> 			*next_unskippable_allvis = false;
> 			break;
> 		}
> 
> 		/*
> 		 * Aggressive VACUUM caller can't skip pages just because they are
> 		 * all-visible.  They may still skip all-frozen pages, which can't
> 		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
> 		 */
> 		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
> 		{
> 			if (vacrel->aggressive)
> 				break;
> 
> 			/*
> 			 * All-visible block is safe to skip in non-aggressive case.  But
> 			 * remember that the final range contains such a block for later.
> 			 */
> 			skipsallvis = true;
> 		}
> 
> 		/* XXX: is it OK to remove this? */
> 		vacuum_delay_point();
> 		next_unskippable_block++;
> 		nskippable_blocks++;
> 	}

Firstly, it seems silly to check DISABLE_PAGE_SKIPPING within the loop. 
When DISABLE_PAGE_SKIPPING is set, we always return the next block and 
set *next_unskippable_allvis = false regardless of the visibility map, 
so why bother checking the visibility map at all?

Except at the very last block of the relation! If you look carefully, 
at the last block we do return *next_unskippable_allvis = true, if the 
VM says so, even if DISABLE_PAGE_SKIPPING is set. I think that's wrong. 
Surely the intention was to pretend that none of the VM bits were set if 
DISABLE_PAGE_SKIPPING is used, also for the last block.

This was changed in commit 980ae17310:

> @@ -1311,7 +1327,11 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
>  
>                 /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
>                 if (!vacrel->skipwithvm)
> +               {
> +                       /* Caller shouldn't rely on all_visible_according_to_vm */
> +                       *next_unskippable_allvis = false;
>                         break;
> +               }

Before that, *next_unskippable_allvis was set correctly according to the 
VM, even when DISABLE_PAGE_SKIPPING was used. It's not clear to me why 
that was changed. And I think setting it to 'true' would be a more 
failsafe value than 'false'. When *next_unskippable_allvis is set to 
true, the caller cannot rely on it because a concurrent modification 
could immediately clear the VM bit. But because VACUUM is the only 
process that sets VM bits, if it's set to false, the caller can assume 
that it's still not set later on.

One consequence of that is that with DISABLE_PAGE_SKIPPING, 
lazy_scan_heap() dirties all pages, even if there are no changes. The 
attached test script demonstrates that.

ISTM we should revert the above hunk, and backpatch it to v16. I'm a 
little wary because I don't understand why that change was made in the 
first place, though. I think it was just an ill-advised attempt at 
tidying up the code as part of the larger commit, but I'm not sure. 
Peter, do you remember?

I wonder if we should give up trying to set all_visible_according_to_vm 
correctly when we decide what to skip, and always do 
"all_visible_according_to_vm = visibilitymap_get_status(...)" in 
lazy_scan_prune(). It would be more expensive, but maybe it doesn't 
matter in practice. It would get rid of this tricky bookkeeping in 
heap_vac_scan_next_block().

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments:

  [application/sql] vactest.sql (844B, ../../3df2b582-dc1c-46b6-99b6-38eddd1b2784@iki.fi/2-vactest.sql)
  download

^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
@ 2024-03-08 15:40                     ` Peter Geoghegan <pg@bowt.ie>
  2024-03-08 15:48                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Peter Geoghegan @ 2024-03-08 15:40 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Fri, Mar 8, 2024 at 8:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> ISTM we should revert the above hunk, and backpatch it to v16. I'm a
> little wary because I don't understand why that change was made in the
> first place, though. I think it was just an ill-advised attempt at
> tidying up the code as part of the larger commit, but I'm not sure.
> Peter, do you remember?

I think that it makes sense to set the VM when indicated by
lazy_scan_prune, independent of what either the visibility map or the
page's PD_ALL_VISIBLE marking say. The whole point of
DISABLE_PAGE_SKIPPING is to deal with VM corruption, after all.

In retrospect I didn't handle this particular aspect very well in
commit 980ae17310. The approach I took is a bit crude (and in any case
slightly wrong in that it is inconsistent in how it handles the last
page). But it has the merit of fixing the case where we just have the
VM's all-frozen bit set for a given block (not the all-visible bit
set) -- which is always wrong. There was good reason to be concerned
about that possibility when 980ae17310 went in.

--
Peter Geoghegan





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 15:40                     ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
@ 2024-03-08 15:48                       ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:00                         ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 15:48 UTC (permalink / raw)
  To: Peter Geoghegan <pg@bowt.ie>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Fri, Mar 8, 2024 at 10:41 AM Peter Geoghegan <pg@bowt.ie> wrote:
>
> On Fri, Mar 8, 2024 at 8:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> > ISTM we should revert the above hunk, and backpatch it to v16. I'm a
> > little wary because I don't understand why that change was made in the
> > first place, though. I think it was just an ill-advised attempt at
> > tidying up the code as part of the larger commit, but I'm not sure.
> > Peter, do you remember?
>
> I think that it makes sense to set the VM when indicated by
> lazy_scan_prune, independent of what either the visibility map or the
> page's PD_ALL_VISIBLE marking say. The whole point of
> DISABLE_PAGE_SKIPPING is to deal with VM corruption, after all.

Not that it will be fun to maintain another special case in the VM
update code in lazy_scan_prune(), but we could have a special case
that checks if DISABLE_PAGE_SKIPPING was passed to vacuum and if
all_visible_according_to_vm is true and all_visible is true, we update
the VM but don't dirty the page. The docs on DISABLE_PAGE_SKIPPING say
it is meant to deal with VM corruption -- it doesn't say anything
about dealing with incorrectly set PD_ALL_VISIBLE markings.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 15:40                     ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 15:48                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-08 16:00                         ` Peter Geoghegan <pg@bowt.ie>
  2024-03-08 16:06                           ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 16:31                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Peter Geoghegan @ 2024-03-08 16:00 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Fri, Mar 8, 2024 at 10:48 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> Not that it will be fun to maintain another special case in the VM
> update code in lazy_scan_prune(), but we could have a special case
> that checks if DISABLE_PAGE_SKIPPING was passed to vacuum and if
> all_visible_according_to_vm is true and all_visible is true, we update
> the VM but don't dirty the page.

It wouldn't necessarily have to be a special case, I think.

We already conditionally set PD_ALL_VISIBLE/call PageIsAllVisible() in
the block where lazy_scan_prune marks a previously all-visible page
all-frozen -- we don't want to dirty the page unnecessarily there.
Making it conditional is defensive in that particular block (this was
also added by this same commit of mine), and avoids dirtying the page.

Seems like it might be possible to simplify/consolidate the VM-setting
code that's now located at the end of lazy_scan_prune. Perhaps the two
distinct blocks that call visibilitymap_set() could be combined into
one.

-- 
Peter Geoghegan





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 15:40                     ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 15:48                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:00                         ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
@ 2024-03-08 16:06                           ` Peter Geoghegan <pg@bowt.ie>
  1 sibling, 0 replies; 81+ messages in thread

From: Peter Geoghegan @ 2024-03-08 16:06 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Fri, Mar 8, 2024 at 11:00 AM Peter Geoghegan <pg@bowt.ie> wrote:
> Seems like it might be possible to simplify/consolidate the VM-setting
> code that's now located at the end of lazy_scan_prune. Perhaps the two
> distinct blocks that call visibilitymap_set() could be combined into
> one.

FWIW I think that my error here might have had something to do with
hallucinating that the code already did things that way.

At the time this went in, I was working on a patchset that did things
this way (more or less). It broke the dependency on
all_visible_according_to_vm entirely, which simplified the
set-and-check-VM code that's now at the end of lazy_scan_prune.

Not sure how practical it'd be to do something like that now (not
offhand), but something to consider.

-- 
Peter Geoghegan





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 15:40                     ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 15:48                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:00                         ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
@ 2024-03-08 16:31                           ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:41                             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 16:31 UTC (permalink / raw)
  To: Peter Geoghegan <pg@bowt.ie>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Fri, Mar 8, 2024 at 11:00 AM Peter Geoghegan <pg@bowt.ie> wrote:
>
> On Fri, Mar 8, 2024 at 10:48 AM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> > Not that it will be fun to maintain another special case in the VM
> > update code in lazy_scan_prune(), but we could have a special case
> > that checks if DISABLE_PAGE_SKIPPING was passed to vacuum and if
> > all_visible_according_to_vm is true and all_visible is true, we update
> > the VM but don't dirty the page.
>
> It wouldn't necessarily have to be a special case, I think.
>
> We already conditionally set PD_ALL_VISIBLE/call PageIsAllVisible() in
> the block where lazy_scan_prune marks a previously all-visible page
> all-frozen -- we don't want to dirty the page unnecessarily there.
> Making it conditional is defensive in that particular block (this was
> also added by this same commit of mine), and avoids dirtying the page.

Ah, I see. I got confused. Even if the VM is suspect, if the page is
all visible and the heap block is already set all-visible in the VM,
there is no need to update it.

This did make me realize that it seems like there is a case we don't
handle in master with the current code that would be fixed by changing
that code Heikki mentioned:

Right now, even if the heap block is incorrectly marked all-visible in
the VM, if DISABLE_PAGE_SKIPPING is passed to vacuum,
all_visible_according_to_vm will be passed to lazy_scan_prune() as
false. Then even if lazy_scan_prune() finds that the page is not
all-visible, we won't call visibilitymap_clear().

If we revert the code setting next_unskippable_allvis to false in
lazy_scan_skip() when vacrel->skipwithvm is false and allow
all_visible_according_to_vm to be true when the VM has it incorrectly
set to true, then once lazy_scan_prune() discovers the page is not
all-visible and assuming PD_ALL_VISIBLE is not marked so
PageIsAllVisible() returns false, we will call visibilitymap_clear()
to clear the incorrectly set VM bit (without dirtying the page).

Here is a table of the variable states at the end of lazy_scan_prune()
for clarity:

master:
all_visible_according_to_vm: false
all_visible:                 false
VM says all vis:             true
PageIsAllVisible:            false

if fixed:
all_visible_according_to_vm: true
all_visible:                 false
VM says all vis:             true
PageIsAllVisible:            false

> Seems like it might be possible to simplify/consolidate the VM-setting
> code that's now located at the end of lazy_scan_prune. Perhaps the two
> distinct blocks that call visibilitymap_set() could be combined into
> one.

I agree. I have some code to do that in an unproposed patch which
combines the VM updates into the prune record. We will definitely want
to reorganize the code when we do that record combining.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 15:40                     ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 15:48                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:00                         ` Re: Confine vacuum skip logic to lazy_scan_skip Peter Geoghegan <pg@bowt.ie>
  2024-03-08 16:31                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-08 16:41                             ` Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 16:41 UTC (permalink / raw)
  To: Peter Geoghegan <pg@bowt.ie>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Fri, Mar 8, 2024 at 11:31 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Fri, Mar 8, 2024 at 11:00 AM Peter Geoghegan <pg@bowt.ie> wrote:
> >
> > On Fri, Mar 8, 2024 at 10:48 AM Melanie Plageman
> > <melanieplageman@gmail.com> wrote:
> > > Not that it will be fun to maintain another special case in the VM
> > > update code in lazy_scan_prune(), but we could have a special case
> > > that checks if DISABLE_PAGE_SKIPPING was passed to vacuum and if
> > > all_visible_according_to_vm is true and all_visible is true, we update
> > > the VM but don't dirty the page.
> >
> > It wouldn't necessarily have to be a special case, I think.
> >
> > We already conditionally set PD_ALL_VISIBLE/call PageIsAllVisible() in
> > the block where lazy_scan_prune marks a previously all-visible page
> > all-frozen -- we don't want to dirty the page unnecessarily there.
> > Making it conditional is defensive in that particular block (this was
> > also added by this same commit of mine), and avoids dirtying the page.
>
> Ah, I see. I got confused. Even if the VM is suspect, if the page is
> all visible and the heap block is already set all-visible in the VM,
> there is no need to update it.
>
> This did make me realize that it seems like there is a case we don't
> handle in master with the current code that would be fixed by changing
> that code Heikki mentioned:
>
> Right now, even if the heap block is incorrectly marked all-visible in
> the VM, if DISABLE_PAGE_SKIPPING is passed to vacuum,
> all_visible_according_to_vm will be passed to lazy_scan_prune() as
> false. Then even if lazy_scan_prune() finds that the page is not
> all-visible, we won't call visibilitymap_clear().
>
> If we revert the code setting next_unskippable_allvis to false in
> lazy_scan_skip() when vacrel->skipwithvm is false and allow
> all_visible_according_to_vm to be true when the VM has it incorrectly
> set to true, then once lazy_scan_prune() discovers the page is not
> all-visible and assuming PD_ALL_VISIBLE is not marked so
> PageIsAllVisible() returns false, we will call visibilitymap_clear()
> to clear the incorrectly set VM bit (without dirtying the page).
>
> Here is a table of the variable states at the end of lazy_scan_prune()
> for clarity:
>
> master:
> all_visible_according_to_vm: false
> all_visible:                 false
> VM says all vis:             true
> PageIsAllVisible:            false
>
> if fixed:
> all_visible_according_to_vm: true
> all_visible:                 false
> VM says all vis:             true
> PageIsAllVisible:            false

Okay, I now see from Heikki's v8-0001 that he was already aware of this.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 13:49                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
@ 2024-03-08 15:44                     ` Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 15:44 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Peter Geoghegan <pg@bowt.ie>

On Fri, Mar 8, 2024 at 8:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>
> On 08/03/2024 02:46, Melanie Plageman wrote:
> > On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
> >>> I feel heap_vac_scan_get_next_block() function could use some love. Maybe
> >>> just some rewording of the comments, or maybe some other refactoring; not
> >>> sure. But I'm pretty happy with the function signature and how it's called.
> >
> > I've cleaned up the comments on heap_vac_scan_next_block() in the first
> > couple patches (not so much in the streaming read user). Let me know if
> > it addresses your feelings or if I should look for other things I could
> > change.
>
> Thanks, that is better. I think I now finally understand how the
> function works, and now I can see some more issues and refactoring
> opportunities :-).
>
> Looking at current lazy_scan_skip() code in 'master', one thing now
> caught my eye (and it's the same with your patches):
>
> >       *next_unskippable_allvis = true;
> >       while (next_unskippable_block < rel_pages)
> >       {
> >               uint8           mapbits = visibilitymap_get_status(vacrel->rel,
> >                                                                                                          next_unskippable_block,
> >                                                                                                          vmbuffer);
> >
> >               if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
> >               {
> >                       Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
> >                       *next_unskippable_allvis = false;
> >                       break;
> >               }
> >
> >               /*
> >                * Caller must scan the last page to determine whether it has tuples
> >                * (caller must have the opportunity to set vacrel->nonempty_pages).
> >                * This rule avoids having lazy_truncate_heap() take access-exclusive
> >                * lock on rel to attempt a truncation that fails anyway, just because
> >                * there are tuples on the last page (it is likely that there will be
> >                * tuples on other nearby pages as well, but those can be skipped).
> >                *
> >                * Implement this by always treating the last block as unsafe to skip.
> >                */
> >               if (next_unskippable_block == rel_pages - 1)
> >                       break;
> >
> >               /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
> >               if (!vacrel->skipwithvm)
> >               {
> >                       /* Caller shouldn't rely on all_visible_according_to_vm */
> >                       *next_unskippable_allvis = false;
> >                       break;
> >               }
> >
> >               /*
> >                * Aggressive VACUUM caller can't skip pages just because they are
> >                * all-visible.  They may still skip all-frozen pages, which can't
> >                * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
> >                */
> >               if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
> >               {
> >                       if (vacrel->aggressive)
> >                               break;
> >
> >                       /*
> >                        * All-visible block is safe to skip in non-aggressive case.  But
> >                        * remember that the final range contains such a block for later.
> >                        */
> >                       skipsallvis = true;
> >               }
> >
> >               /* XXX: is it OK to remove this? */
> >               vacuum_delay_point();
> >               next_unskippable_block++;
> >               nskippable_blocks++;
> >       }
>
> Firstly, it seems silly to check DISABLE_PAGE_SKIPPING within the loop.
> When DISABLE_PAGE_SKIPPING is set, we always return the next block and
> set *next_unskippable_allvis = false regardless of the visibility map,
> so why bother checking the visibility map at all?
>
> Except at the very last block of the relation! If you look carefully,
> at the last block we do return *next_unskippable_allvis = true, if the
> VM says so, even if DISABLE_PAGE_SKIPPING is set. I think that's wrong.
> Surely the intention was to pretend that none of the VM bits were set if
> DISABLE_PAGE_SKIPPING is used, also for the last block.

I agree that having next_unskippable_allvis and, as a consequence,
all_visible_according_to_vm set to true for the last block seems
wrong. And It makes sense from a loop efficiency standpoint also to
move it up to the top. However, making that change would have us end
up dirtying all pages in your example.

> This was changed in commit 980ae17310:
>
> > @@ -1311,7 +1327,11 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
> >
> >                 /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
> >                 if (!vacrel->skipwithvm)
> > +               {
> > +                       /* Caller shouldn't rely on all_visible_according_to_vm */
> > +                       *next_unskippable_allvis = false;
> >                         break;
> > +               }
>
> Before that, *next_unskippable_allvis was set correctly according to the
> VM, even when DISABLE_PAGE_SKIPPING was used. It's not clear to me why
> that was changed. And I think setting it to 'true' would be a more
> failsafe value than 'false'. When *next_unskippable_allvis is set to
> true, the caller cannot rely on it because a concurrent modification
> could immediately clear the VM bit. But because VACUUM is the only
> process that sets VM bits, if it's set to false, the caller can assume
> that it's still not set later on.
>
> One consequence of that is that with DISABLE_PAGE_SKIPPING,
> lazy_scan_heap() dirties all pages, even if there are no changes. The
> attached test script demonstrates that.

This does seem undesirable.

However, if we do as you suggest above and don't check
DISABLE_PAGE_SKIPPING in the loop and instead return without checking
the VM when DISABLE_PAGE_SKIPPING is passed, setting
next_unskippable_allvis = false, we will end up dirtying all pages as
in your example. It would fix the last block issue but it would result
in dirtying all pages in your example.

> ISTM we should revert the above hunk, and backpatch it to v16. I'm a
> little wary because I don't understand why that change was made in the
> first place, though. I think it was just an ill-advised attempt at
> tidying up the code as part of the larger commit, but I'm not sure.
> Peter, do you remember?

If we revert this, then the when all_visible_according_to_vm and
all_visible are true in lazy_scan_prune(), the VM will only get
updated when all_frozen is true and the VM doesn't have all frozen set
yet, so maybe that is inconsistent with the goal of
DISABLE_PAGE_SKIPPING to update the VM when its contents are "suspect"
(according to docs).

> I wonder if we should give up trying to set all_visible_according_to_vm
> correctly when we decide what to skip, and always do
> "all_visible_according_to_vm = visibilitymap_get_status(...)" in
> lazy_scan_prune(). It would be more expensive, but maybe it doesn't
> matter in practice. It would get rid of this tricky bookkeeping in
> heap_vac_scan_next_block().

I did some experiments on this in the past and thought that it did
have a perf impact to call visibilitymap_get_status() every time. But
let me try and dig those up. (doesn't speak to whether or not in
matters in practice)

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-08 16:07                   ` Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 17:34                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Heikki Linnakangas @ 2024-03-08 16:07 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On 08/03/2024 02:46, Melanie Plageman wrote:
> On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
>> On Wed, Mar 06, 2024 at 09:55:21PM +0200, Heikki Linnakangas wrote:
> I will say that now all of the variable names are *very* long. I didn't
> want to remove the "state" from LVRelState->next_block_state. (In fact, I
> kind of miss the "get". But I had to draw the line somewhere.) I think
> without "state" in the name, next_block sounds too much like a function.
> 
> Any ideas for shortening the names of next_block_state and its members
> or are you fine with them?

Hmm, we can remove the inner struct and add the fields directly into 
LVRelState. LVRelState already contains many groups of variables, like 
"Error reporting state", with no inner structs. I did it that way in the 
attached patch. I also used local variables more.

>> I was wondering if we should remove the "get" and just go with
>> heap_vac_scan_next_block(). I didn't do that originally because I didn't
>> want to imply that the next block was literally the sequentially next
>> block, but I think maybe I was overthinking it.
>>
>> Another idea is to call it heap_scan_vac_next_block() and then the order
>> of the words is more like the table AM functions that get the next block
>> (e.g. heapam_scan_bitmap_next_block()). Though maybe we don't want it to
>> be too similar to those since this isn't a table AM callback.
> 
> I've done a version of this.

+1

> However, by adding a vmbuffer to next_block_state, the callback may be
> able to avoid extra VM fetches from one invocation to the next.

That's a good idea, holding separate VM buffer pins for the 
next-unskippable block and the block we're processing. I adopted that 
approach.

My compiler caught one small bug when I was playing with various 
refactorings of this: heap_vac_scan_next_block() must set *blkno to 
rel_pages, not InvalidBlockNumber, after the last block. The caller uses 
the 'blkno' variable also after the loop, and assumes that it's set to 
rel_pages.

I'm pretty happy with the attached patches now. The first one fixes the 
existing bug I mentioned in the other email (based on the on-going 
discussion that might not how we want to fix it though). Second commit 
is a squash of most of the patches. Third patch is the removal of the 
delay point, that seems worthwhile to keep separate.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments:

  [text/x-patch] v8-0001-Set-all_visible_according_to_vm-correctly-with-DI.patch (1.7K, ../../906e656f-d9ae-4f1a-acb6-afa607e48ca3@iki.fi/2-v8-0001-Set-all_visible_according_to_vm-correctly-with-DI.patch)
  download | inline diff:
From b68cb29c547de3c4acd10f31aad47b453d154666 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Fri, 8 Mar 2024 16:00:22 +0200
Subject: [PATCH v8 1/3] Set all_visible_according_to_vm correctly with
 DISABLE_PAGE_SKIPPING

It's important for 'all_visible_according_to_vm' to correctly reflect
whether the VM bit is set or not, even when we are not trusting the VM
to skip pages, because contrary to what the comment said,
lazy_scan_prune() relies on it.

If it's incorrectly set to 'false', when the VM bit is in fact set,
lazy_scan_prune() will try to set the VM bit again and dirty the page
unnecessarily. As a result, if you used DISABLE_PAGE_SKIPPING, all
heap pages were dirtied, even if there were no changes. We would also
fail to clear any VM bits that were set incorrectly.

This was broken in commit 980ae17310, so backpatch to v16.

Backpatch-through: 16
Reviewed-by: Melanie Plageman
Discussion: https://www.postgresql.org/message-id/3df2b582-dc1c-46b6-99b6-38eddd1b2784@iki.fi
---
 src/backend/access/heap/vacuumlazy.c | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8b320c3f89a..ac55ebd2ae5 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1136,11 +1136,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
 		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
 			break;
-		}
 
 		/*
 		 * Aggressive VACUUM caller can't skip pages just because they are
-- 
2.39.2



  [text/x-patch] v8-0002-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (14.9K, ../../906e656f-d9ae-4f1a-acb6-afa607e48ca3@iki.fi/3-v8-0002-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From 47af1ca65cf55ca876869b43bff47f9d43f0750e Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Fri, 8 Mar 2024 17:32:19 +0200
Subject: [PATCH v8 2/3] Confine vacuum skip logic to lazy_scan_skip()

Rename lazy_scan_skip() to heap_vac_scan_next_block() and move more
code into the function, so that the caller doesn't need to know about
ranges or skipping anymore. heap_vac_scan_next_block() returns the
next block to process, and the logic for determining that block is all
within the function. This makes the skipping logic easier to
understand, as it's all in the same function, and makes the calling
code easier to understand as it's less cluttered. The state variables
needed to manage the skipping logic are moved to LVRelState.

heap_vac_scan_next_block() now manages its own VM buffer separately
from the caller's vmbuffer variable. The caller's vmbuffer holds the
VM page for the current block its processing, while
heap_vac_scan_next_block() keeps a pin on the VM page for the next
unskippable block. Most of the time they are the same, so we hold two
pins on the same buffer, but it's more convenient to manage them
separately.

This refactoring will also help future patches to switch to using a
streaming read interface, and eventually AIO
(https://postgr.es/m/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com)

Author: Melanie Plageman, with some changes by me
Discussion: https://postgr.es/m/CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 256 +++++++++++++++------------
 1 file changed, 141 insertions(+), 115 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index ac55ebd2ae5..0aa08762015 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -204,6 +204,12 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/* State maintained by heap_vac_scan_next_block() */
+	BlockNumber current_block;	/* last block returned */
+	BlockNumber next_unskippable_block; /* next unskippable block */
+	bool		next_unskippable_allvis;	/* its visibility status */
+	Buffer		next_unskippable_vmbuffer;	/* buffer containing its VM bit */
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -217,10 +223,8 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
+									 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -803,12 +807,11 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -822,44 +825,19 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+	/* Initialize for the first heap_vac_scan_next_block() call */
+	vacrel->current_block = InvalidBlockNumber;
+	vacrel->next_unskippable_block = InvalidBlockNumber;
+	vacrel->next_unskippable_allvis = false;
+	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
+
+	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
-
-			Assert(next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1077,18 +1055,22 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
+ *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum.  The function uses the visibility map, vacuum options,
+ * and various thresholds to skip blocks which do not need to be processed and
+ * sets blkno to the next block that actually needs to be processed.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * The block number and visibility status of the next block to process are set
+ * in *blkno and *all_visible_according_to_vm.  The return value is false if
+ * there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about
+ * the relation are read, and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all-visible blocks.  It
+ * also holds information about the next unskippable block, as bookkeeping for
+ * this function.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1098,88 +1080,132 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static bool
+heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
+						 bool *all_visible_according_to_vm)
 {
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+	BlockNumber next_block;
 	bool		skipsallvis = false;
+	BlockNumber rel_pages = vacrel->rel_pages;
+	BlockNumber next_unskippable_block;
+	bool		next_unskippable_allvis;
+	Buffer		next_unskippable_vmbuffer;
 
-	*next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
-	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   vmbuffer);
+	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
+	next_block = vacrel->current_block + 1;
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	/* Have we reached the end of the relation? */
+	if (next_block >= rel_pages)
+	{
+		if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
-			break;
+			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
+			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
+		*blkno = rel_pages;
+		return false;
+	}
 
+	next_unskippable_block = vacrel->next_unskippable_block;
+	next_unskippable_allvis = vacrel->next_unskippable_allvis;
+	if (next_unskippable_block == InvalidBlockNumber ||
+		next_block > next_unskippable_block)
+	{
 		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
+		 * Find the next unskippable block using the visibility map.
 		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+		next_unskippable_block = next_block;
+		next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
+		for (;;)
+		{
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   &next_unskippable_vmbuffer);
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-			break;
+			next_unskippable_allvis = (mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0;
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * A block is unskippable if it is not all visible according to
+			 * the visibility map.
+			 */
+			if (!next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
+
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages).  This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
+				break;
+
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
 				break;
 
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
+			next_unskippable_block++;
 		}
+		/* write the local variables back to vacrel */
+		vacrel->next_unskippable_block = next_unskippable_block;
+		vacrel->next_unskippable_allvis = next_unskippable_allvis;
+		vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-		nskippable_blocks++;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
 	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (next_block == next_unskippable_block)
+		*all_visible_according_to_vm = next_unskippable_allvis;
 	else
-	{
-		*skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
-
-	return next_unskippable_block;
+		*all_visible_according_to_vm = true;
+	*blkno = vacrel->current_block = next_block;
+	return true;
 }
 
 /*
@@ -1752,8 +1778,8 @@ lazy_scan_prune(LVRelState *vacrel,
 
 	/*
 	 * Handle setting visibility map bit based on information from the VM (as
-	 * of last lazy_scan_skip() call), and from all_visible and all_frozen
-	 * variables
+	 * of last heap_vac_scan_next_block() call), and from all_visible and
+	 * all_frozen variables
 	 */
 	if (!all_visible_according_to_vm && all_visible)
 	{
@@ -1788,8 +1814,8 @@ lazy_scan_prune(LVRelState *vacrel,
 	/*
 	 * As of PostgreSQL 9.2, the visibility map bit should never be set if the
 	 * page-level bit is clear.  However, it's possible that the bit got
-	 * cleared after lazy_scan_skip() was called, so we must recheck with
-	 * buffer lock before concluding that the VM is corrupt.
+	 * cleared after heap_vac_scan_next_block() was called, so we must recheck
+	 * with buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
 			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
-- 
2.39.2



  [text/x-patch] v8-0003-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.0K, ../../906e656f-d9ae-4f1a-acb6-afa607e48ca3@iki.fi/4-v8-0003-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From 941ae7522ab6ac24ca5981303e4e7f6e2cba7458 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v8 3/3] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 0aa08762015..e1657ef4f9b 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1172,7 +1172,6 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 				skipsallvis = true;
 			}
 
-			vacuum_delay_point();
 			next_unskippable_block++;
 		}
 		/* write the local variables back to vacrel */
-- 
2.39.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
@ 2024-03-08 17:34                     ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 18:21                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 09:29                       ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 2 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 17:34 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On Fri, Mar 08, 2024 at 06:07:33PM +0200, Heikki Linnakangas wrote:
> On 08/03/2024 02:46, Melanie Plageman wrote:
> > On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
> > > On Wed, Mar 06, 2024 at 09:55:21PM +0200, Heikki Linnakangas wrote:
> > I will say that now all of the variable names are *very* long. I didn't
> > want to remove the "state" from LVRelState->next_block_state. (In fact, I
> > kind of miss the "get". But I had to draw the line somewhere.) I think
> > without "state" in the name, next_block sounds too much like a function.
> > 
> > Any ideas for shortening the names of next_block_state and its members
> > or are you fine with them?
> 
> Hmm, we can remove the inner struct and add the fields directly into
> LVRelState. LVRelState already contains many groups of variables, like
> "Error reporting state", with no inner structs. I did it that way in the
> attached patch. I also used local variables more.

+1; I like the result of this.

> > However, by adding a vmbuffer to next_block_state, the callback may be
> > able to avoid extra VM fetches from one invocation to the next.
> 
> That's a good idea, holding separate VM buffer pins for the next-unskippable
> block and the block we're processing. I adopted that approach.

Cool. It can't be avoided with streaming read vacuum, but I wonder if
there would ever be adverse effects to doing it on master? Maybe if we
are doing a lot of skipping and the block of the VM for the heap blocks
we are processing ends up changing each time but we would have had the
right block of the VM if we used the one from
heap_vac_scan_next_block()?

Frankly, I'm in favor of just doing it now because it makes
lazy_scan_heap() less confusing.

> My compiler caught one small bug when I was playing with various
> refactorings of this: heap_vac_scan_next_block() must set *blkno to
> rel_pages, not InvalidBlockNumber, after the last block. The caller uses the
> 'blkno' variable also after the loop, and assumes that it's set to
> rel_pages.

Oops! Thanks for catching that.

> I'm pretty happy with the attached patches now. The first one fixes the
> existing bug I mentioned in the other email (based on the on-going
> discussion that might not how we want to fix it though).

ISTM we should still do the fix you mentioned -- seems like it has more
upsides than downsides?

> From b68cb29c547de3c4acd10f31aad47b453d154666 Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Fri, 8 Mar 2024 16:00:22 +0200
> Subject: [PATCH v8 1/3] Set all_visible_according_to_vm correctly with
>  DISABLE_PAGE_SKIPPING
> 
> It's important for 'all_visible_according_to_vm' to correctly reflect
> whether the VM bit is set or not, even when we are not trusting the VM
> to skip pages, because contrary to what the comment said,
> lazy_scan_prune() relies on it.
> 
> If it's incorrectly set to 'false', when the VM bit is in fact set,
> lazy_scan_prune() will try to set the VM bit again and dirty the page
> unnecessarily. As a result, if you used DISABLE_PAGE_SKIPPING, all
> heap pages were dirtied, even if there were no changes. We would also
> fail to clear any VM bits that were set incorrectly.
> 
> This was broken in commit 980ae17310, so backpatch to v16.

LGTM.

> From 47af1ca65cf55ca876869b43bff47f9d43f0750e Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Fri, 8 Mar 2024 17:32:19 +0200
> Subject: [PATCH v8 2/3] Confine vacuum skip logic to lazy_scan_skip()
> ---
>  src/backend/access/heap/vacuumlazy.c | 256 +++++++++++++++------------
>  1 file changed, 141 insertions(+), 115 deletions(-)
> 
> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
> index ac55ebd2ae5..0aa08762015 100644
> --- a/src/backend/access/heap/vacuumlazy.c
> +++ b/src/backend/access/heap/vacuumlazy.c
> @@ -204,6 +204,12 @@ typedef struct LVRelState
>  	int64		live_tuples;	/* # live tuples remaining */
>  	int64		recently_dead_tuples;	/* # dead, but not yet removable */
>  	int64		missed_dead_tuples; /* # removable, but not removed */

Perhaps we should add a comment to the blkno member of LVRelState
indicating that it is used for error reporting and logging?

> +	/* State maintained by heap_vac_scan_next_block() */
> +	BlockNumber current_block;	/* last block returned */
> +	BlockNumber next_unskippable_block; /* next unskippable block */
> +	bool		next_unskippable_allvis;	/* its visibility status */
> +	Buffer		next_unskippable_vmbuffer;	/* buffer containing its VM bit */
>  } LVRelState;

>  /*
> -static BlockNumber
> -lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
> -			   bool *next_unskippable_allvis, bool *skipping_current_range)
> +static bool
> +heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
> +						 bool *all_visible_according_to_vm)
>  {
> -	BlockNumber rel_pages = vacrel->rel_pages,
> -				next_unskippable_block = next_block,
> -				nskippable_blocks = 0;
> +	BlockNumber next_block;
>  	bool		skipsallvis = false;
> +	BlockNumber rel_pages = vacrel->rel_pages;
> +	BlockNumber next_unskippable_block;
> +	bool		next_unskippable_allvis;
> +	Buffer		next_unskippable_vmbuffer;
>  
> -	*next_unskippable_allvis = true;
> -	while (next_unskippable_block < rel_pages)
> -	{
> -		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
> -													   next_unskippable_block,
> -													   vmbuffer);
> +	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
> +	next_block = vacrel->current_block + 1;
>  
> -		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
> +	/* Have we reached the end of the relation? */
> +	if (next_block >= rel_pages)
> +	{
> +		if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
>  		{
> -			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
> -			*next_unskippable_allvis = false;
> -			break;
> +			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
> +			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
>  		}

Good catch here. Also, I noticed that I set current_block to
InvalidBlockNumber too which seems strictly worse than leaving it as
rel_pages + 1 -- just in case a future dev makes a change that
accidentally causes heap_vac_scan_next_block() to be called again and
adding InvalidBlockNumber + 1 would end up going back to 0. So this all
looks correct to me.

> +		*blkno = rel_pages;
> +		return false;
> +	}

> +	next_unskippable_block = vacrel->next_unskippable_block;
> +	next_unskippable_allvis = vacrel->next_unskippable_allvis;

Wishe there was a newline here.

I see why you removed my treatise-level comment that was here about
unskipped skippable blocks. However, when I was trying to understand
this code, I did wish there was some comment that explained to me why we
needed all of the variables next_unskippable_block,
next_unskippable_allvis, all_visible_according_to_vm, and current_block.

The idea that we would choose not to skip a skippable block because of
kernel readahead makes sense. The part that I had trouble wrapping my
head around was that we want to also keep the visibility status of both
the beginning and ending blocks of the skippable range and then use
those to infer the visibility status of the intervening blocks without
another VM lookup if we decide not to skip them.

> +	if (next_unskippable_block == InvalidBlockNumber ||
> +		next_block > next_unskippable_block)
> +	{
>  		/*
> -		 * Caller must scan the last page to determine whether it has tuples
> -		 * (caller must have the opportunity to set vacrel->nonempty_pages).
> -		 * This rule avoids having lazy_truncate_heap() take access-exclusive
> -		 * lock on rel to attempt a truncation that fails anyway, just because
> -		 * there are tuples on the last page (it is likely that there will be
> -		 * tuples on other nearby pages as well, but those can be skipped).
> -		 *
> -		 * Implement this by always treating the last block as unsafe to skip.
> +		 * Find the next unskippable block using the visibility map.
>  		 */
> -		if (next_unskippable_block == rel_pages - 1)
> -			break;
> +		next_unskippable_block = next_block;
> +		next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
> +		for (;;)

Ah yes, my old loop condition was redundant with the break if
next_unskippable_block == rel_pages - 1. This is better

> +		{
> +			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
> +														   next_unskippable_block,
> +														   &next_unskippable_vmbuffer);
>  
> -		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
> -		if (!vacrel->skipwithvm)

...
> +			}
> +
> +			vacuum_delay_point();
> +			next_unskippable_block++;
>  		}

Would love a newline here

> +		/* write the local variables back to vacrel */
> +		vacrel->next_unskippable_block = next_unskippable_block;
> +		vacrel->next_unskippable_allvis = next_unskippable_allvis;
> +		vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
>  
...

> -	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
> -		*skipping_current_range = false;
> +	if (next_block == next_unskippable_block)
> +		*all_visible_according_to_vm = next_unskippable_allvis;
>  	else
> -	{
> -		*skipping_current_range = true;
> -		if (skipsallvis)
> -			vacrel->skippedallvis = true;
> -	}
> -
> -	return next_unskippable_block;
> +		*all_visible_according_to_vm = true;

Also a newline here

> +	*blkno = vacrel->current_block = next_block;
> +	return true;
>  }
>  

> From 941ae7522ab6ac24ca5981303e4e7f6e2cba7458 Mon Sep 17 00:00:00 2001
> From: Melanie Plageman <melanieplageman@gmail.com>
> Date: Sun, 31 Dec 2023 12:49:56 -0500
> Subject: [PATCH v8 3/3] Remove unneeded vacuum_delay_point from
>  heap_vac_scan_get_next_block
> 
> heap_vac_scan_get_next_block() does relatively little work, so there is
> no need to call vacuum_delay_point(). A future commit will call
> heap_vac_scan_get_next_block() from a callback, and we would like to
> avoid calling vacuum_delay_point() in that callback.
> ---
>  src/backend/access/heap/vacuumlazy.c | 1 -
>  1 file changed, 1 deletion(-)
> 
> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
> index 0aa08762015..e1657ef4f9b 100644
> --- a/src/backend/access/heap/vacuumlazy.c
> +++ b/src/backend/access/heap/vacuumlazy.c
> @@ -1172,7 +1172,6 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
>  				skipsallvis = true;
>  			}
>  
> -			vacuum_delay_point();
>  			next_unskippable_block++;
>  		}
>  		/* write the local variables back to vacrel */
> -- 
> 2.39.2
> 

LGTM

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 17:34                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-08 18:21                       ` Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-03-08 18:21 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On Fri, Mar 8, 2024 at 12:34 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Fri, Mar 08, 2024 at 06:07:33PM +0200, Heikki Linnakangas wrote:
> > On 08/03/2024 02:46, Melanie Plageman wrote:
> > > On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
> > > > On Wed, Mar 06, 2024 at 09:55:21PM +0200, Heikki Linnakangas wrote:
> > > I will say that now all of the variable names are *very* long. I didn't
> > > want to remove the "state" from LVRelState->next_block_state. (In fact, I
> > > kind of miss the "get". But I had to draw the line somewhere.) I think
> > > without "state" in the name, next_block sounds too much like a function.
> > >
> > > Any ideas for shortening the names of next_block_state and its members
> > > or are you fine with them?
> >
> > Hmm, we can remove the inner struct and add the fields directly into
> > LVRelState. LVRelState already contains many groups of variables, like
> > "Error reporting state", with no inner structs. I did it that way in the
> > attached patch. I also used local variables more.
>
> +1; I like the result of this.

I did some perf testing of 0002 and 0003 using that fully-in-SB vacuum
test I mentioned in an earlier email. 0002 is a vacuum time reduction
from an average of 11.5 ms on master to 9.6 ms with 0002 applied. And
0003 reduces the time vacuum takes from 11.5 ms on master to 7.4 ms
with 0003 applied.

I profiled them and 0002 seems to simply spend less time in
heap_vac_scan_next_block() than master did in lazy_scan_skip().

And 0003 reduces the time vacuum takes because vacuum_delay_point()
shows up pretty high in the profile.

Here are the profiles for my test.

profile of master:

+   29.79%  postgres  postgres           [.] visibilitymap_get_status
+   27.35%  postgres  postgres           [.] vacuum_delay_point
+   17.00%  postgres  postgres           [.] lazy_scan_skip
+    6.59%  postgres  postgres           [.] heap_vacuum_rel
+    6.43%  postgres  postgres           [.] BufferGetBlockNumber

profile with 0001-0002:

+   40.30%  postgres  postgres           [.] visibilitymap_get_status
+   20.32%  postgres  postgres           [.] vacuum_delay_point
+   20.26%  postgres  postgres           [.] heap_vacuum_rel
+    5.17%  postgres  postgres           [.] BufferGetBlockNumber

profile with 0001-0003

+   59.77%  postgres  postgres           [.] visibilitymap_get_status
+   23.86%  postgres  postgres           [.] heap_vacuum_rel
+    6.59%  postgres  postgres           [.] StrategyGetBuffer

Test DDL and setup:

psql -c "ALTER SYSTEM SET shared_buffers = '16 GB';"
psql -c "CREATE TABLE foo(id INT, a INT, b INT, c INT, d INT, e INT, f
INT, g INT) with (autovacuum_enabled=false, fillfactor=25);"
psql -c "INSERT INTO foo SELECT i, i, i, i, i, i, i, i FROM
generate_series(1, 46000000)i;"
psql -c "VACUUM (FREEZE) foo;"
pg_ctl restart
psql -c "SELECT pg_prewarm('foo');"
# make sure there isn't an ill-timed checkpoint
psql -c "\timing on" -c "vacuum (verbose) foo;"

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 17:34                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-11 09:29                       ` Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-11 16:15                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Heikki Linnakangas @ 2024-03-11 09:29 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On 08/03/2024 19:34, Melanie Plageman wrote:
> On Fri, Mar 08, 2024 at 06:07:33PM +0200, Heikki Linnakangas wrote:
>> On 08/03/2024 02:46, Melanie Plageman wrote:
>>> On Wed, Mar 06, 2024 at 10:00:23PM -0500, Melanie Plageman wrote:
>>>> On Wed, Mar 06, 2024 at 09:55:21PM +0200, Heikki Linnakangas wrote:
>>> However, by adding a vmbuffer to next_block_state, the callback may be
>>> able to avoid extra VM fetches from one invocation to the next.
>>
>> That's a good idea, holding separate VM buffer pins for the next-unskippable
>> block and the block we're processing. I adopted that approach.
> 
> Cool. It can't be avoided with streaming read vacuum, but I wonder if
> there would ever be adverse effects to doing it on master? Maybe if we
> are doing a lot of skipping and the block of the VM for the heap blocks
> we are processing ends up changing each time but we would have had the
> right block of the VM if we used the one from
> heap_vac_scan_next_block()?
> 
> Frankly, I'm in favor of just doing it now because it makes
> lazy_scan_heap() less confusing.

+1

>> I'm pretty happy with the attached patches now. The first one fixes the
>> existing bug I mentioned in the other email (based on the on-going
>> discussion that might not how we want to fix it though).
> 
> ISTM we should still do the fix you mentioned -- seems like it has more
> upsides than downsides?
> 
>>  From b68cb29c547de3c4acd10f31aad47b453d154666 Mon Sep 17 00:00:00 2001
>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
>> Date: Fri, 8 Mar 2024 16:00:22 +0200
>> Subject: [PATCH v8 1/3] Set all_visible_according_to_vm correctly with
>>   DISABLE_PAGE_SKIPPING
>>
>> It's important for 'all_visible_according_to_vm' to correctly reflect
>> whether the VM bit is set or not, even when we are not trusting the VM
>> to skip pages, because contrary to what the comment said,
>> lazy_scan_prune() relies on it.
>>
>> If it's incorrectly set to 'false', when the VM bit is in fact set,
>> lazy_scan_prune() will try to set the VM bit again and dirty the page
>> unnecessarily. As a result, if you used DISABLE_PAGE_SKIPPING, all
>> heap pages were dirtied, even if there were no changes. We would also
>> fail to clear any VM bits that were set incorrectly.
>>
>> This was broken in commit 980ae17310, so backpatch to v16.
> 
> LGTM.

Committed and backpatched this.

>>  From 47af1ca65cf55ca876869b43bff47f9d43f0750e Mon Sep 17 00:00:00 2001
>> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
>> Date: Fri, 8 Mar 2024 17:32:19 +0200
>> Subject: [PATCH v8 2/3] Confine vacuum skip logic to lazy_scan_skip()
>> ---
>>   src/backend/access/heap/vacuumlazy.c | 256 +++++++++++++++------------
>>   1 file changed, 141 insertions(+), 115 deletions(-)
>>
>> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
>> index ac55ebd2ae5..0aa08762015 100644
>> --- a/src/backend/access/heap/vacuumlazy.c
>> +++ b/src/backend/access/heap/vacuumlazy.c
>> @@ -204,6 +204,12 @@ typedef struct LVRelState
>>   	int64		live_tuples;	/* # live tuples remaining */
>>   	int64		recently_dead_tuples;	/* # dead, but not yet removable */
>>   	int64		missed_dead_tuples; /* # removable, but not removed */
> 
> Perhaps we should add a comment to the blkno member of LVRelState
> indicating that it is used for error reporting and logging?

Well, it's already under the "/* Error reporting state */" section. I 
agree this is a little confusing, the name 'blkno' doesn't convey that 
it's supposed to be used just for error reporting. But it's a 
pre-existing issue so I left it alone. It can be changed with a separate 
patch if we come up with a good idea.

> I see why you removed my treatise-level comment that was here about
> unskipped skippable blocks. However, when I was trying to understand
> this code, I did wish there was some comment that explained to me why we
> needed all of the variables next_unskippable_block,
> next_unskippable_allvis, all_visible_according_to_vm, and current_block.
> 
> The idea that we would choose not to skip a skippable block because of
> kernel readahead makes sense. The part that I had trouble wrapping my
> head around was that we want to also keep the visibility status of both
> the beginning and ending blocks of the skippable range and then use
> those to infer the visibility status of the intervening blocks without
> another VM lookup if we decide not to skip them.

Right, I removed the comment because looked a little out of place and it 
duplicated the other comments sprinkled in the function. I agree this 
could still use some more comments though.

Here's yet another attempt at making this more readable. I moved the 
logic to find the next unskippable block to a separate function, and 
added comments to make the states more explicit. What do you think?

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments:

  [text/x-patch] v9-0001-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (13.9K, ../../27d51713-b1dc-49d1-9b3a-2650b7fb9613@iki.fi/2-v9-0001-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From c21480e9da61e145573de3b502551dde1b8fa3f6 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Fri, 8 Mar 2024 17:32:19 +0200
Subject: [PATCH v9 1/2] Confine vacuum skip logic to lazy_scan_skip()

Rename lazy_scan_skip() to heap_vac_scan_next_block() and move more
code into the function, so that the caller doesn't need to know about
ranges or skipping anymore. heap_vac_scan_next_block() returns the
next block to process, and the logic for determining that block is all
within the function. This makes the skipping logic easier to
understand, as it's all in the same function, and makes the calling
code easier to understand as it's less cluttered. The state variables
needed to manage the skipping logic are moved to LVRelState.

heap_vac_scan_next_block() now manages its own VM buffer separately
from the caller's vmbuffer variable. The caller's vmbuffer holds the
VM page for the current block its processing, while
heap_vac_scan_next_block() keeps a pin on the VM page for the next
unskippable block. Most of the time they are the same, so we hold two
pins on the same buffer, but it's more convenient to manage them
separately.

For readability inside heap_vac_scan_next_block(), move the logic of
finding the next unskippable block to separate function, and add some
comments.

This refactoring will also help future patches to switch to using a
streaming read interface, and eventually AIO
(https://postgr.es/m/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com)

Author: Melanie Plageman, with some changes by me
Discussion: https://postgr.es/m/CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 233 +++++++++++++++++----------
 1 file changed, 146 insertions(+), 87 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index ac55ebd2ae..1757eb49b7 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -204,6 +204,12 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/* State maintained by heap_vac_scan_next_block() */
+	BlockNumber current_block;	/* last block returned */
+	BlockNumber next_unskippable_block; /* next unskippable block */
+	bool		next_unskippable_allvis;	/* its visibility status */
+	Buffer		next_unskippable_vmbuffer;	/* buffer containing its VM bit */
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -217,10 +223,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
+									 bool *all_visible_according_to_vm);
+static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock, Buffer vmbuffer);
@@ -803,12 +808,11 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -822,44 +826,19 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
-	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+	/* Initialize for the first heap_vac_scan_next_block() call */
+	vacrel->current_block = InvalidBlockNumber;
+	vacrel->next_unskippable_block = InvalidBlockNumber;
+	vacrel->next_unskippable_allvis = false;
+	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
+
+	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
-
-			Assert(next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1077,18 +1056,22 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
+ *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum.  The function uses the visibility map, vacuum options,
+ * and various thresholds to skip blocks which do not need to be processed and
+ * sets blkno to the next block that actually needs to be processed.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * The block number and visibility status of the next block to process are set
+ * in *blkno and *all_visible_according_to_vm.  The return value is false if
+ * there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about
+ * the relation are read, and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all-visible blocks.  It
+ * also holds information about the next unskippable block, as bookkeeping for
+ * this function.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1098,26 +1081,119 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static bool
+heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
+						 bool *all_visible_according_to_vm)
 {
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
-	bool		skipsallvis = false;
+	BlockNumber next_block;
 
-	*next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
+	next_block = vacrel->current_block + 1;
+
+	/* Have we reached the end of the relation? */
+	if (next_block >= vacrel->rel_pages)
+	{
+		if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
+		{
+			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
+			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
+		}
+		*blkno = vacrel->rel_pages;
+		return false;
+	}
+
+	/*
+	 * We must be in one of the three following states:
+	 */
+	if (vacrel->next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->next_unskippable_block)
+	{
+		/*
+		 * 1. We have just processed an unskippable block (or we're at the
+		 * beginning of the scan).  Find the next unskippable block using the
+		 * visibility map.
+		 */
+		bool		skipsallvis;
+
+		find_next_unskippable_block(vacrel, &skipsallvis);
+
+		/*
+		 * We now know the next block that we must process.  It can be the
+		 * next block after the one we just processed, or something further
+		 * ahead.  If it's further ahead, we can jump to it, but we choose to
+		 * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then.  Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
+	}
+
+	/* Now we must be in one of the two remaining states: */
+	if (next_block < vacrel->next_unskippable_block)
+	{
+		/*
+		 * 2. We are processing a range of blocks that we could have skipped
+		 * but chose not to.  We know that they are all-visible in the VM,
+		 * otherwise they would've been unskippable.
+		 */
+		*blkno = vacrel->current_block = next_block;
+		*all_visible_according_to_vm = true;
+		return true;
+	}
+	else
+	{
+		/*
+		 * 3. We reached the next unskippable block.  Process it.  On next
+		 * iteration, we will be back in state 1.
+		 */
+		Assert(next_block == vacrel->next_unskippable_block);
+
+		*blkno = vacrel->current_block = next_block;
+		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
+		return true;
+	}
+}
+
+/*
+ * Find the next unskippable block in a vacuum scan using the visibility map.
+ */
+static void
+find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
+{
+	BlockNumber rel_pages = vacrel->rel_pages;
+	BlockNumber next_unskippable_block = vacrel->next_unskippable_block + 1;
+	Buffer		next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
+	bool		next_unskippable_allvis;
+
+	*skipsallvis = false;
+
+	for (;;)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
-													   vmbuffer);
+													   &next_unskippable_vmbuffer);
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+		next_unskippable_allvis = (mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0;
+
+		/*
+		 * A block is unskippable if it is not all visible according to the
+		 * visibility map.
+		 */
+		if (!next_unskippable_allvis)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1152,34 +1228,17 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			 * All-visible block is safe to skip in non-aggressive case.  But
 			 * remember that the final range contains such a block for later.
 			 */
-			skipsallvis = true;
+			*skipsallvis = true;
 		}
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
-	}
-
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
-	else
-	{
-		*skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
 	}
 
-	return next_unskippable_block;
+	/* write the local variables back to vacrel */
+	vacrel->next_unskippable_block = next_unskippable_block;
+	vacrel->next_unskippable_allvis = next_unskippable_allvis;
+	vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
 }
 
 /*
@@ -1752,8 +1811,8 @@ lazy_scan_prune(LVRelState *vacrel,
 
 	/*
 	 * Handle setting visibility map bit based on information from the VM (as
-	 * of last lazy_scan_skip() call), and from all_visible and all_frozen
-	 * variables
+	 * of last heap_vac_scan_next_block() call), and from all_visible and
+	 * all_frozen variables
 	 */
 	if (!all_visible_according_to_vm && all_visible)
 	{
@@ -1788,8 +1847,8 @@ lazy_scan_prune(LVRelState *vacrel,
 	/*
 	 * As of PostgreSQL 9.2, the visibility map bit should never be set if the
 	 * page-level bit is clear.  However, it's possible that the bit got
-	 * cleared after lazy_scan_skip() was called, so we must recheck with
-	 * buffer lock before concluding that the VM is corrupt.
+	 * cleared after heap_vac_scan_next_block() was called, so we must recheck
+	 * with buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
 			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
-- 
2.39.2



  [text/x-patch] v9-0002-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch (1.1K, ../../27d51713-b1dc-49d1-9b3a-2650b7fb9613@iki.fi/3-v9-0002-Remove-unneeded-vacuum_delay_point-from-heap_vac_.patch)
  download | inline diff:
From 07437212d629ab00b571dfcadb41497a6c5b43d5 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Mon, 11 Mar 2024 10:01:37 +0200
Subject: [PATCH v9 2/2] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there
is no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.

Author: Melanie Plageman
Discussion: https://postgr.es/m/CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1757eb49b7..58ee12fdfb 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1231,7 +1231,6 @@ find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
 			*skipsallvis = true;
 		}
 
-		vacuum_delay_point();
 		next_unskippable_block++;
 	}
 
-- 
2.39.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 17:34                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 09:29                       ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
@ 2024-03-11 16:15                         ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 18:47                           ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-11 16:15 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On Mon, Mar 11, 2024 at 11:29:44AM +0200, Heikki Linnakangas wrote:
>
> > I see why you removed my treatise-level comment that was here about
> > unskipped skippable blocks. However, when I was trying to understand
> > this code, I did wish there was some comment that explained to me why we
> > needed all of the variables next_unskippable_block,
> > next_unskippable_allvis, all_visible_according_to_vm, and current_block.
> > 
> > The idea that we would choose not to skip a skippable block because of
> > kernel readahead makes sense. The part that I had trouble wrapping my
> > head around was that we want to also keep the visibility status of both
> > the beginning and ending blocks of the skippable range and then use
> > those to infer the visibility status of the intervening blocks without
> > another VM lookup if we decide not to skip them.
> 
> Right, I removed the comment because looked a little out of place and it
> duplicated the other comments sprinkled in the function. I agree this could
> still use some more comments though.
> 
> Here's yet another attempt at making this more readable. I moved the logic
> to find the next unskippable block to a separate function, and added
> comments to make the states more explicit. What do you think?

Oh, I like the new structure. Very cool! Just a few remarks:

> From c21480e9da61e145573de3b502551dde1b8fa3f6 Mon Sep 17 00:00:00 2001
> From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
> Date: Fri, 8 Mar 2024 17:32:19 +0200
> Subject: [PATCH v9 1/2] Confine vacuum skip logic to lazy_scan_skip()
> 
> Rename lazy_scan_skip() to heap_vac_scan_next_block() and move more
> code into the function, so that the caller doesn't need to know about
> ranges or skipping anymore. heap_vac_scan_next_block() returns the
> next block to process, and the logic for determining that block is all
> within the function. This makes the skipping logic easier to
> understand, as it's all in the same function, and makes the calling
> code easier to understand as it's less cluttered. The state variables
> needed to manage the skipping logic are moved to LVRelState.
> 
> heap_vac_scan_next_block() now manages its own VM buffer separately
> from the caller's vmbuffer variable. The caller's vmbuffer holds the
> VM page for the current block its processing, while
> heap_vac_scan_next_block() keeps a pin on the VM page for the next
> unskippable block. Most of the time they are the same, so we hold two
> pins on the same buffer, but it's more convenient to manage them
> separately.
> 
> For readability inside heap_vac_scan_next_block(), move the logic of
> finding the next unskippable block to separate function, and add some
> comments.
> 
> This refactoring will also help future patches to switch to using a
> streaming read interface, and eventually AIO
> (https://postgr.es/m/CA%2BhUKGJkOiOCa%2Bmag4BF%2BzHo7qo%3Do9CFheB8%3Dg6uT5TUm2gkvA%40mail.gmail.com)
> 
> Author: Melanie Plageman, with some changes by me

I'd argue you earned co-authorship by now :)

> Discussion: https://postgr.es/m/CAAKRu_Yf3gvXGcCnqqfoq0Q8LX8UM-e-qbm_B1LeZh60f8WhWA%40mail.gmail.com
> ---
>  src/backend/access/heap/vacuumlazy.c | 233 +++++++++++++++++----------
>  1 file changed, 146 insertions(+), 87 deletions(-)
> 
> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
> index ac55ebd2ae..1757eb49b7 100644
> --- a/src/backend/access/heap/vacuumlazy.c
> +++ b/src/backend/access/heap/vacuumlazy.c
> +

>  /*
> - *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
> + *	heap_vac_scan_next_block() -- get next block for vacuum to process
>   *
> - * lazy_scan_heap() calls here every time it needs to set up a new range of
> - * blocks to skip via the visibility map.  Caller passes the next block in
> - * line.  We return a next_unskippable_block for this range.  When there are
> - * no skippable blocks we just return caller's next_block.  The all-visible
> - * status of the returned block is set in *next_unskippable_allvis for caller,
> - * too.  Block usually won't be all-visible (since it's unskippable), but it
> - * can be during aggressive VACUUMs (as well as in certain edge cases).
> + * lazy_scan_heap() calls here every time it needs to get the next block to
> + * prune and vacuum.  The function uses the visibility map, vacuum options,
> + * and various thresholds to skip blocks which do not need to be processed and

I wonder if "need" is too strong a word since this function
(heap_vac_scan_next_block()) specifically can set blkno to a block which
doesn't *need* to be processed but which it chooses to process because
of SKIP_PAGES_THRESHOLD.

> + * sets blkno to the next block that actually needs to be processed.
>   *
> - * Sets *skipping_current_range to indicate if caller should skip this range.
> - * Costs and benefits drive our decision.  Very small ranges won't be skipped.
> + * The block number and visibility status of the next block to process are set
> + * in *blkno and *all_visible_according_to_vm.  The return value is false if
> + * there are no further blocks to process.
> + *
> + * vacrel is an in/out parameter here; vacuum options and information about
> + * the relation are read, and vacrel->skippedallvis is set to ensure we don't
> + * advance relfrozenxid when we have skipped vacuuming all-visible blocks.  It

Maybe this should say when we have skipped vacuuming all-visible blocks
which are not all-frozen or just blocks which are not all-frozen.

> + * also holds information about the next unskippable block, as bookkeeping for
> + * this function.
>   *
>   * Note: our opinion of which blocks can be skipped can go stale immediately.
>   * It's okay if caller "misses" a page whose all-visible or all-frozen marking

Wonder if it makes sense to move this note to
find_next_nunskippable_block().

> @@ -1098,26 +1081,119 @@ lazy_scan_heap(LVRelState *vacrel)
>   * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
>   * choice to skip such a range is actually made, making everything safe.)
>   */
> -static BlockNumber
> -lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
> -			   bool *next_unskippable_allvis, bool *skipping_current_range)
> +static bool
> +heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
> +						 bool *all_visible_according_to_vm)
>  {
> -	BlockNumber rel_pages = vacrel->rel_pages,
> -				next_unskippable_block = next_block,
> -				nskippable_blocks = 0;
> -	bool		skipsallvis = false;
> +	BlockNumber next_block;
>  
> -	*next_unskippable_allvis = true;
> -	while (next_unskippable_block < rel_pages)
> +	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
> +	next_block = vacrel->current_block + 1;
> +
> +	/* Have we reached the end of the relation? */

No strong opinion on this, but I wonder if being at the end of the
relation counts as a fourth state?

> +	if (next_block >= vacrel->rel_pages)
> +	{
> +		if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
> +		{
> +			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
> +			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
> +		}
> +		*blkno = vacrel->rel_pages;
> +		return false;
> +	}
> +
> +	/*
> +	 * We must be in one of the three following states:
> +	 */
> +	if (vacrel->next_unskippable_block == InvalidBlockNumber ||
> +		next_block > vacrel->next_unskippable_block)
> +	{
> +		/*
> +		 * 1. We have just processed an unskippable block (or we're at the
> +		 * beginning of the scan).  Find the next unskippable block using the
> +		 * visibility map.
> +		 */

I would reorder the options in the comment or in the if statement since
they seem to be in the reverse order.

> +		bool		skipsallvis;
> +
> +		find_next_unskippable_block(vacrel, &skipsallvis);
> +
> +		/*
> +		 * We now know the next block that we must process.  It can be the
> +		 * next block after the one we just processed, or something further
> +		 * ahead.  If it's further ahead, we can jump to it, but we choose to
> +		 * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
> +		 * pages.  Since we're reading sequentially, the OS should be doing
> +		 * readahead for us, so there's no gain in skipping a page now and
> +		 * then.  Skipping such a range might even discourage sequential
> +		 * detection.
> +		 *
> +		 * This test also enables more frequent relfrozenxid advancement
> +		 * during non-aggressive VACUUMs.  If the range has any all-visible
> +		 * pages then skipping makes updating relfrozenxid unsafe, which is a
> +		 * real downside.
> +		 */
> +		if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
> +		{
> +			next_block = vacrel->next_unskippable_block;
> +			if (skipsallvis)
> +				vacrel->skippedallvis = true;
> +		}

> +
> +/*
> + * Find the next unskippable block in a vacuum scan using the visibility map.

To expand this comment, I might mention it is a helper function for
heap_vac_scan_next_block(). I would also say that the next unskippable
block and its visibility information are recorded in vacrel. And that
skipsallvis is set to true if any of the intervening skipped blocks are
not all-frozen.

> + */
> +static void
> +find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
> +{
> +	BlockNumber rel_pages = vacrel->rel_pages;
> +	BlockNumber next_unskippable_block = vacrel->next_unskippable_block + 1;
> +	Buffer		next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
> +	bool		next_unskippable_allvis;
> +
> +	*skipsallvis = false;
> +
> +	for (;;)
>  	{
>  		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
>  													   next_unskippable_block,
> -													   vmbuffer);
> +													   &next_unskippable_vmbuffer);
>  
> -		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
> +		next_unskippable_allvis = (mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0;

Otherwise LGTM

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 17:34                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 09:29                       ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-11 16:15                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-11 18:47                           ` Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-11 20:41                             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Heikki Linnakangas @ 2024-03-11 18:47 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On 11/03/2024 18:15, Melanie Plageman wrote:
> On Mon, Mar 11, 2024 at 11:29:44AM +0200, Heikki Linnakangas wrote:
>> diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
>> index ac55ebd2ae..1757eb49b7 100644
>> --- a/src/backend/access/heap/vacuumlazy.c
>> +++ b/src/backend/access/heap/vacuumlazy.c
>> +
> 
>>   /*
>> - *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
>> + *	heap_vac_scan_next_block() -- get next block for vacuum to process
>>    *
>> - * lazy_scan_heap() calls here every time it needs to set up a new range of
>> - * blocks to skip via the visibility map.  Caller passes the next block in
>> - * line.  We return a next_unskippable_block for this range.  When there are
>> - * no skippable blocks we just return caller's next_block.  The all-visible
>> - * status of the returned block is set in *next_unskippable_allvis for caller,
>> - * too.  Block usually won't be all-visible (since it's unskippable), but it
>> - * can be during aggressive VACUUMs (as well as in certain edge cases).
>> + * lazy_scan_heap() calls here every time it needs to get the next block to
>> + * prune and vacuum.  The function uses the visibility map, vacuum options,
>> + * and various thresholds to skip blocks which do not need to be processed and
>> + * sets blkno to the next block that actually needs to be processed.
> 
> I wonder if "need" is too strong a word since this function
> (heap_vac_scan_next_block()) specifically can set blkno to a block which
> doesn't *need* to be processed but which it chooses to process because
> of SKIP_PAGES_THRESHOLD.

Ok yeah, there's a lot of "needs" here :-). Fixed.

>>    *
>> - * Sets *skipping_current_range to indicate if caller should skip this range.
>> - * Costs and benefits drive our decision.  Very small ranges won't be skipped.
>> + * The block number and visibility status of the next block to process are set
>> + * in *blkno and *all_visible_according_to_vm.  The return value is false if
>> + * there are no further blocks to process.
>> + *
>> + * vacrel is an in/out parameter here; vacuum options and information about
>> + * the relation are read, and vacrel->skippedallvis is set to ensure we don't
>> + * advance relfrozenxid when we have skipped vacuuming all-visible blocks.  It
> 
> Maybe this should say when we have skipped vacuuming all-visible blocks
> which are not all-frozen or just blocks which are not all-frozen.

Ok, rephrased.

>> + * also holds information about the next unskippable block, as bookkeeping for
>> + * this function.
>>    *
>>    * Note: our opinion of which blocks can be skipped can go stale immediately.
>>    * It's okay if caller "misses" a page whose all-visible or all-frozen marking
> 
> Wonder if it makes sense to move this note to
> find_next_nunskippable_block().

Moved.

>> @@ -1098,26 +1081,119 @@ lazy_scan_heap(LVRelState *vacrel)
>>    * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
>>    * choice to skip such a range is actually made, making everything safe.)
>>    */
>> -static BlockNumber
>> -lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
>> -			   bool *next_unskippable_allvis, bool *skipping_current_range)
>> +static bool
>> +heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
>> +						 bool *all_visible_according_to_vm)
>>   {
>> -	BlockNumber rel_pages = vacrel->rel_pages,
>> -				next_unskippable_block = next_block,
>> -				nskippable_blocks = 0;
>> -	bool		skipsallvis = false;
>> +	BlockNumber next_block;
>>   
>> -	*next_unskippable_allvis = true;
>> -	while (next_unskippable_block < rel_pages)
>> +	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
>> +	next_block = vacrel->current_block + 1;
>> +
>> +	/* Have we reached the end of the relation? */
> 
> No strong opinion on this, but I wonder if being at the end of the
> relation counts as a fourth state?

Yeah, perhaps. But I think it makes sense to treat it as a special case.

>> +	if (next_block >= vacrel->rel_pages)
>> +	{
>> +		if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
>> +		{
>> +			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
>> +			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
>> +		}
>> +		*blkno = vacrel->rel_pages;
>> +		return false;
>> +	}
>> +
>> +	/*
>> +	 * We must be in one of the three following states:
>> +	 */
>> +	if (vacrel->next_unskippable_block == InvalidBlockNumber ||
>> +		next_block > vacrel->next_unskippable_block)
>> +	{
>> +		/*
>> +		 * 1. We have just processed an unskippable block (or we're at the
>> +		 * beginning of the scan).  Find the next unskippable block using the
>> +		 * visibility map.
>> +		 */
> 
> I would reorder the options in the comment or in the if statement since
> they seem to be in the reverse order.

Reordered them in the statement.

It feels a bit wrong to test next_block > vacrel->next_unskippable_block 
before vacrel->next_unskippable_block == InvalidBlockNumber. But it 
works, and that order makes more sense in the comment IMHO.

>> +		bool		skipsallvis;
>> +
>> +		find_next_unskippable_block(vacrel, &skipsallvis);
>> +
>> +		/*
>> +		 * We now know the next block that we must process.  It can be the
>> +		 * next block after the one we just processed, or something further
>> +		 * ahead.  If it's further ahead, we can jump to it, but we choose to
>> +		 * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
>> +		 * pages.  Since we're reading sequentially, the OS should be doing
>> +		 * readahead for us, so there's no gain in skipping a page now and
>> +		 * then.  Skipping such a range might even discourage sequential
>> +		 * detection.
>> +		 *
>> +		 * This test also enables more frequent relfrozenxid advancement
>> +		 * during non-aggressive VACUUMs.  If the range has any all-visible
>> +		 * pages then skipping makes updating relfrozenxid unsafe, which is a
>> +		 * real downside.
>> +		 */
>> +		if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
>> +		{
>> +			next_block = vacrel->next_unskippable_block;
>> +			if (skipsallvis)
>> +				vacrel->skippedallvis = true;
>> +		}
> 
>> +
>> +/*
>> + * Find the next unskippable block in a vacuum scan using the visibility map.
> 
> To expand this comment, I might mention it is a helper function for
> heap_vac_scan_next_block(). I would also say that the next unskippable
> block and its visibility information are recorded in vacrel. And that
> skipsallvis is set to true if any of the intervening skipped blocks are
> not all-frozen.

Added comments.

> Otherwise LGTM

Ok, pushed! Thank you, this is much more understandable now!

-- 
Heikki Linnakangas
Neon (https://neon.tech)





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 19:55             ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-07 03:00               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 00:46                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-08 16:07                   ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-08 17:34                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 09:29                       ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
  2024-03-11 16:15                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 18:47                           ` Re: Confine vacuum skip logic to lazy_scan_skip Heikki Linnakangas <hlinnaka@iki.fi>
@ 2024-03-11 20:41                             ` Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-03-11 20:41 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Robert Haas <robertmhaas@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Andres Freund <andres@anarazel.de>; vignesh C <vignesh21@gmail.com>; pgsql-hackers

On Mon, Mar 11, 2024 at 2:47 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>
>
> > Otherwise LGTM
>
> Ok, pushed! Thank you, this is much more understandable now!

Cool, thanks!





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-06 23:47             ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-06 23:47 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Tue, Feb 27, 2024 at 02:47:03PM -0500, Melanie Plageman wrote:
> On Mon, Jan 29, 2024 at 8:18 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> >
> > On Fri, Jan 26, 2024 at 8:28 AM vignesh C <vignesh21@gmail.com> wrote:
> > >
> > > CFBot shows that the patch does not apply anymore as in [1]:
> > > === applying patch
> > > ./v3-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelStat.patch
> > > patching file src/backend/access/heap/vacuumlazy.c
> > > ...
> > > Hunk #10 FAILED at 1042.
> > > Hunk #11 FAILED at 1121.
> > > Hunk #12 FAILED at 1132.
> > > Hunk #13 FAILED at 1161.
> > > Hunk #14 FAILED at 1172.
> > > Hunk #15 FAILED at 1194.
> > > ...
> > > 6 out of 21 hunks FAILED -- saving rejects to file
> > > src/backend/access/heap/vacuumlazy.c.rej
> > >
> > > Please post an updated version for the same.
> > >
> > > [1] - http://cfbot.cputube.org/patch_46_4755.log
> >
> > Fixed in attached rebased v4
> 
> In light of Thomas' update to the streaming read API [1], I have
> rebased and updated this patch set.
> 
> The attached v5 has some simplifications when compared to v4 but takes
> largely the same approach.

Attached is a patch set (v5a) which updates the streaming read user for
vacuum to fix an issue Andrey Borodin pointed out to me off-list.

Note that I started writing this email before seeing Heikki's upthread
review [1], so I will respond to that in a bit. There are no changes in
v5a to any of the prelim refactoring patches which Heikki reviewed in
that email. I only changed the vacuum streaming read users (last two
patches in the set).

Back to this patch set:
Andrey pointed out that it was failing to compile on windows and the
reason is that I had accidentally left an undefined variable "index" in
these places

	Assert(index > 0);
...
	ereport(DEBUG2,
			(errmsg("table \"%s\": removed %lld dead item identifiers in %u pages",
					vacrel->relname, (long long) index, vacuumed_pages)));

See https://cirrus-ci.com/task/6312305361682432

I don't understand how this didn't warn me (or fail to compile) for an
assert build on my own workstation. It seems to think "index" is a
function?

Anyway, thinking about what the correct assertion would be here:

	Assert(index > 0);
	Assert(vacrel->num_index_scans > 1 ||
		   (rbstate->end_idx == vacrel->lpdead_items &&
			vacuumed_pages == vacrel->lpdead_item_pages));

I think I can just replace "index" with "rbstate->end_index". At the end
of reaping, this should have the same value that index would have had.
The issue with this is if pg_streaming_read_buffer_get_next() somehow
never returned a valid buffer (there were no dead items), then rbstate
would potentially be uninitialized. The old assertion (index > 0) would
only have been true if there were some dead items, but there isn't an
explicit assertion in this function that there were some dead items.
Perhaps it is worth adding this? Even if we add this, perhaps it is
unacceptable from a programming standpoint to use rbstate in that scope?

In addition to fixing this slip-up, I have done some performance testing
for streaming read vacuum. Note that these tests are for both vacuum
passes (1 and 2) using streaming read.

Performance results:

The TL;DR of my performance results is that streaming read vacuum is
faster. However there is an issue with the interaction of the streaming
read code and the vacuum buffer access strategy which must be addressed.

Note that "master" in the results below is actually just a commit on my
branch [2] before the one adding the vacuum streaming read users. So it
includes all of my refactoring of the vacuum code from the preliminary
patches.

I tested two vacuum "data states". Both are relatively small tables
because the impact of streaming read can easily be seen even at small
table sizes. DDL for both data states is at the end of the email.

The first data state is a 28 MB table which has never been vacuumed and
has one or two dead tuples on every block. All of the blocks have dead
tuples, so all of the blocks must be vacuumed. We'll call this the
"sequential" data state.

The second data state is a 67 MB table which has been vacuumed and then
a small percentage of the blocks (non-consecutive blocks at irregular
intervals) are updated afterward. Because the visibility map has been
updated and only a few blocks have dead tuples, large ranges of blocks
do not need to be vacuumed. There is at least one run of blocks with
dead tuples larger than 1 block but most of the blocks with dead tuples
are a single block followed by many blocks with no dead tuples. We'll
call this the "few" data state.

I tested these data states with "master" and with streaming read vacuum
with three caching options:

- table data fully in shared buffers (via pg_prewarm)
- table data in the kernel buffer cache but not in shared buffers
- table data completely uncached

I tested the OS cached and uncached caching options with both the
default vacuum buffer access strategy and with BUFFER_USAGE_LIMIT 0
(which uses as many shared buffers as needed).

For the streaming read vacuum, I tested with maintenance_io_concurrency
10, 100, and 1000. 10 is the current default on master.
maintenance_io_concurrency is not used by vacuum on master AFAICT.

maintenance_io_concurrency is used by streaming read to determine how
many buffers it can pin at the same time (with the hope of combining
consecutive blocks into larger IOs) and, in the case of vacuum, it is
used to determine prefetch distance.

In the following results, I ran vacuum at least five times and averaged
the timing results.

Table data cached in shared buffers
===================================

Sequential data state
---------------------

The only noticeable difference in performance was that streaming read
vacuum took 2% longer than master (19 ms vs 18.6 ms). It was a bit more
noticeable at maintenance_io_concurrency 1000 than 10.

This may be resolved by a patch Thomas is working on to avoid pinning
too many buffers if larger IOs cannot be created (like in a fully SB
resident workload). We should revisit this when that patch is available.

Few data state
--------------

There was no difference in timing for any of the scenarios.

Table data cached in OS buffer cache
====================================

Sequential data state
---------------------

With the buffer access strategy disabled, streaming read vacuum took 11%
less time regardless of maintenance_io_concurrency (26 ms vs 23 ms).

With the default vacuum buffer access strategy,
maintenance_io_concurrency had a large impact:

  Note that "mic" is maintenace_io_concurrency

| data state | code      | mic  | time (ms) |
+------------+-----------+------+-----------+
| sequential | master    | NA   | 99        |
| sequential | streaming | 10   | 122       |
| sequential | streaming | 100  | 28        |

The streaming read API calculates the maximum number of pinned buffers
as 4 * maintenance_io_concurrency. The default vacuum buffer access
strategy ring buffer is 256 kB -- which is 32 buffers.

With maintenance_io_concurrency 10, streaming read code wants to pin 40
buffers. There is likely an interaction between this and the buffer
access strategy which leads to the slowdown at
maintenance_io_concurrency 10.

We could change the default maintenance_io_concurrency, but a better
option is to take the buffer access strategy into account in the
streaming read code.

Few data state
--------------

There was no difference in timing for any of the scenarios.

Table data uncached
===================

Sequential data state
---------------------

When the buffer access strategy is disabled, streaming read vacuum takes
12% less time regardless of maintenance_io_concurrency (36 ms vs 41 ms).

With the default buffer access strategy (ring buffer 256 kB) and
maintenance_io_concurrency 10 (the default), the streaming read vacuum
takes 19% more time. But if we bump maintenance_io_concurrency up to
100+, streaming read vacuum takes 64% less time:

| data state | code      | mic  | time (ms) |
+------------+-----------+------+-----------+
| sequential | master    | NA   | 113       |
| sequential | streaming | 10   | 140       |
| sequential | streaming | 100  | 41        |

This is likely due to the same adverse interaction between streaming
reads' max pinned buffers and the buffer access strategy ring buffer
size.

Few data state
--------------

The buffer access strategy had no impact here, so all of these results
are with the default buffer access strategy. The streaming read vacuum
takes 20-25% less time than master vacuum.

| data state | code      | mic  | time (ms) |
+------------+-----------+------+-----------+
| few        | master    | NA   | 4.5       |
| few        | streaming | 10   | 3.4       |
| few        | streaming | 100  | 3.5       |

The improvement is likely due to prefetching and the one range of
consecutive blocks containing dead tuples which could be merged into a
larger IO.

Higher maintenance_io_concurrency only helps a little probably because:

1) most the blocks to vacuum are not consecutive so we can't make bigger
IOs in most cases
2) we are not vacuuming enough blocks such that we want to prefetch more
than 10 blocks.

This experiment should probably be redone with larger tables containing
more blocks needing vacuum. At 3-4 ms, a 20% performance difference
isn't really that interesting.

The next step (other than the preliminary refactoring patches) is to
decide how the streaming read API should use the buffer access strategy.

Sequential Data State DDL:
  drop table if exists foo;
  create table foo (a int) with (autovacuum_enabled=false, fillfactor=25);
  insert into foo select i % 3 from generate_series(1,200000)i;
  update foo set a = 5 where a = 1;

Few Data State DDL:
  drop table if exists foo;
  create table foo (a int) with (autovacuum_enabled=false, fillfactor=25);
  insert into foo select i from generate_series(2,20000)i;
  insert into foo select 1 from generate_series(1,200)i;
  insert into foo select i from generate_series(2,20000)i;
  insert into foo select 1 from generate_series(1,200)i;
  insert into foo select i from generate_series(2,200000)i;
  insert into foo select 1 from generate_series(1,200)i;
  insert into foo select i from generate_series(2,20000)i;
  insert into foo select 1 from generate_series(1,2000)i;
  insert into foo select i from generate_series(2,20000)i;
  insert into foo select 1 from generate_series(1,200)i;
  insert into foo select i from generate_series(2,200000)i;
  insert into foo select 1 from generate_series(1,200)i;
  vacuum (freeze) foo;
  update foo set a = 5 where a = 1;

- Melanie

[1] https://www.postgresql.org/message-id/1eeccf12-d5d1-4b7e-b88b-7342410129d7%40iki.fi
[2] https://github.com/melanieplageman/postgres/tree/vac_pgsr

Attachments:

  [text/x-diff] v5a-0001-lazy_scan_skip-remove-unneeded-local-var-nskippa.patch (1.7K, ../../20240306234733.nd4a636colxkgq2e@liskov/2-v5a-0001-lazy_scan_skip-remove-unneeded-local-var-nskippa.patch)
  download | inline diff:
From c7a16bbf477c08ebf553da855e0554077c21de69 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:30:59 -0500
Subject: [PATCH v5a 1/7] lazy_scan_skip remove unneeded local var
 nskippable_blocks

nskippable_blocks can be easily derived from next_unskippable_block's
progress when compared to the passed in next_block.
---
 src/backend/access/heap/vacuumlazy.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8b320c3f89a..1dc6cc8e4db 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1103,8 +1103,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 			   bool *next_unskippable_allvis, bool *skipping_current_range)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block,
-				nskippable_blocks = 0;
+				next_unskippable_block = next_block;
 	bool		skipsallvis = false;
 
 	*next_unskippable_allvis = true;
@@ -1161,7 +1160,6 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 
 		vacuum_delay_point();
 		next_unskippable_block++;
-		nskippable_blocks++;
 	}
 
 	/*
@@ -1174,7 +1172,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (nskippable_blocks < SKIP_PAGES_THRESHOLD)
+	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
 		*skipping_current_range = false;
 	else
 	{
-- 
2.40.1

  [text/x-diff] v5a-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelSta.patch (15.8K, ../../20240306234733.nd4a636colxkgq2e@liskov/3-v5a-0002-Add-lazy_scan_skip-unskippable-state-to-LVRelSta.patch)
  download | inline diff:
From c27436eaeedbc1551072922d92460ca1c30ed116 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:22:12 -0500
Subject: [PATCH v5a 2/7] Add lazy_scan_skip unskippable state to LVRelState

Future commits will remove all skipping logic from lazy_scan_heap() and
confine it to lazy_scan_skip(). To make those commits more clear, first
introduce add a struct to LVRelState containing variables needed to skip
ranges less than SKIP_PAGES_THRESHOLD.

lazy_scan_prune() and lazy_scan_new_or_empty() can now access the
buffer containing the relevant block of the visibility map through the
LVRelState.skip, so it no longer needs to be a separate function
parameter.

While we are at it, add additional information to the lazy_scan_skip()
comment, including descriptions of the role and expectations for its
function parameters.
---
 src/backend/access/heap/vacuumlazy.c | 154 ++++++++++++++++-----------
 1 file changed, 90 insertions(+), 64 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1dc6cc8e4db..0ddb986bc03 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -204,6 +204,22 @@ typedef struct LVRelState
 	int64		live_tuples;	/* # live tuples remaining */
 	int64		recently_dead_tuples;	/* # dead, but not yet removable */
 	int64		missed_dead_tuples; /* # removable, but not removed */
+
+	/*
+	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
+	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 */
+	struct
+	{
+		/* Next unskippable block */
+		BlockNumber next_unskippable_block;
+		/* Buffer containing next unskippable block's visibility info */
+		Buffer		vmbuffer;
+		/* Next unskippable block's visibility status */
+		bool		next_unskippable_allvis;
+		/* Whether or not skippable blocks should be skipped */
+		bool		skipping_current_range;
+	}			skip;
 } LVRelState;
 
 /* Struct for saving and restoring vacuum error information. */
@@ -214,19 +230,15 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
-
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static BlockNumber lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer,
-								  BlockNumber next_block,
-								  bool *next_unskippable_allvis,
-								  bool *skipping_current_range);
+static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
-								   bool sharelock, Buffer vmbuffer);
+								   bool sharelock);
 static void lazy_scan_prune(LVRelState *vacrel, Buffer buf,
 							BlockNumber blkno, Page page,
-							Buffer vmbuffer, bool all_visible_according_to_vm,
+							bool all_visible_according_to_vm,
 							bool *has_lpdead_items);
 static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 							  BlockNumber blkno, Page page,
@@ -803,12 +815,8 @@ lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
-				next_unskippable_block,
 				next_fsm_block_to_vacuum = 0;
 	VacDeadItems *dead_items = vacrel->dead_items;
-	Buffer		vmbuffer = InvalidBuffer;
-	bool		next_unskippable_allvis,
-				skipping_current_range;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
 		PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
@@ -822,10 +830,9 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.vmbuffer = InvalidBuffer;
 	/* Set up an initial range of skippable blocks using the visibility map */
-	next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer, 0,
-											&next_unskippable_allvis,
-											&skipping_current_range);
+	lazy_scan_skip(vacrel, 0);
 	for (blkno = 0; blkno < rel_pages; blkno++)
 	{
 		Buffer		buf;
@@ -834,26 +841,23 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == next_unskippable_block)
+		if (blkno == vacrel->skip.next_unskippable_block)
 		{
 			/*
 			 * Can't skip this page safely.  Must scan the page.  But
 			 * determine the next skippable range after the page first.
 			 */
-			all_visible_according_to_vm = next_unskippable_allvis;
-			next_unskippable_block = lazy_scan_skip(vacrel, &vmbuffer,
-													blkno + 1,
-													&next_unskippable_allvis,
-													&skipping_current_range);
+			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
+			lazy_scan_skip(vacrel, blkno + 1);
 
-			Assert(next_unskippable_block >= blkno + 1);
+			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
 		}
 		else
 		{
 			/* Last page always scanned (may need to set nonempty_pages) */
 			Assert(blkno < rel_pages - 1);
 
-			if (skipping_current_range)
+			if (vacrel->skip.skipping_current_range)
 				continue;
 
 			/* Current range is too small to skip -- just scan the page */
@@ -896,10 +900,10 @@ lazy_scan_heap(LVRelState *vacrel)
 			 * correctness, but we do it anyway to avoid holding the pin
 			 * across a lengthy, unrelated operation.
 			 */
-			if (BufferIsValid(vmbuffer))
+			if (BufferIsValid(vacrel->skip.vmbuffer))
 			{
-				ReleaseBuffer(vmbuffer);
-				vmbuffer = InvalidBuffer;
+				ReleaseBuffer(vacrel->skip.vmbuffer);
+				vacrel->skip.vmbuffer = InvalidBuffer;
 			}
 
 			/* Perform a round of index and heap vacuuming */
@@ -924,7 +928,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * all-visible.  In most cases this will be very cheap, because we'll
 		 * already have the correct page pinned anyway.
 		 */
-		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
+		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
 		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
 								 vacrel->bstrategy);
@@ -942,8 +946,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			LockBuffer(buf, BUFFER_LOCK_SHARE);
 
 		/* Check for new or empty pages before lazy_scan_[no]prune call */
-		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
-								   vmbuffer))
+		if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock))
 		{
 			/* Processed as new/empty page (lock and pin released) */
 			continue;
@@ -985,7 +988,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1035,8 +1038,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
-	if (BufferIsValid(vmbuffer))
-		ReleaseBuffer(vmbuffer);
+	if (BufferIsValid(vacrel->skip.vmbuffer))
+	{
+		ReleaseBuffer(vacrel->skip.vmbuffer);
+		vacrel->skip.vmbuffer = InvalidBuffer;
+	}
 
 	/* report that everything is now scanned */
 	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
@@ -1080,15 +1086,34 @@ lazy_scan_heap(LVRelState *vacrel)
  *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
  *
  * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes the next block in
- * line.  We return a next_unskippable_block for this range.  When there are
- * no skippable blocks we just return caller's next_block.  The all-visible
- * status of the returned block is set in *next_unskippable_allvis for caller,
- * too.  Block usually won't be all-visible (since it's unskippable), but it
- * can be during aggressive VACUUMs (as well as in certain edge cases).
+ * blocks to skip via the visibility map.  Caller passes next_block, the next
+ * block in line. The parameters of the skipped range are recorded in skip.
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
+ *
+ * A block is unskippable if it is not all visible according to the visibility
+ * map. It is also unskippable if it is the last block in the relation, if the
+ * vacuum is an aggressive vacuum, or if DISABLE_PAGE_SKIPPING was passed to
+ * vacuum.
  *
- * Sets *skipping_current_range to indicate if caller should skip this range.
- * Costs and benefits drive our decision.  Very small ranges won't be skipped.
+ * Even if a block is skippable, we may choose not to skip it if the range of
+ * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
+ * consequence, we must keep track of the next truly unskippable block and its
+ * visibility status along with whether or not we are skipping the current
+ * range of skippable blocks. This can be used to derive the next block
+ * lazy_scan_heap() must process and its visibility status.
+ *
+ * The block number and visibility status of the next unskippable block are set
+ * in skip->next_unskippable_block and next_unskippable_allvis.
+ * skip->skipping_current_range indicates to the caller whether or not it is
+ * processing a skippable (and thus all-visible) block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1098,25 +1123,26 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static BlockNumber
-lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
-			   bool *next_unskippable_allvis, bool *skipping_current_range)
+static void
+lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
 {
+	/* Use local variables for better optimized loop code */
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_unskippable_block = next_block;
+
 	bool		skipsallvis = false;
 
-	*next_unskippable_allvis = true;
+	vacrel->skip.next_unskippable_allvis = true;
 	while (next_unskippable_block < rel_pages)
 	{
 		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
 													   next_unskippable_block,
-													   vmbuffer);
+													   &vacrel->skip.vmbuffer);
 
 		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
 		{
 			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1137,7 +1163,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		if (!vacrel->skipwithvm)
 		{
 			/* Caller shouldn't rely on all_visible_according_to_vm */
-			*next_unskippable_allvis = false;
+			vacrel->skip.next_unskippable_allvis = false;
 			break;
 		}
 
@@ -1162,6 +1188,8 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 		next_unskippable_block++;
 	}
 
+	vacrel->skip.next_unskippable_block = next_unskippable_block;
+
 	/*
 	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
 	 * pages.  Since we're reading sequentially, the OS should be doing
@@ -1172,16 +1200,14 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
 	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
 	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
 	 */
-	if (next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		*skipping_current_range = false;
+	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
+		vacrel->skip.skipping_current_range = false;
 	else
 	{
-		*skipping_current_range = true;
+		vacrel->skip.skipping_current_range = true;
 		if (skipsallvis)
 			vacrel->skippedallvis = true;
 	}
-
-	return next_unskippable_block;
 }
 
 /*
@@ -1214,7 +1240,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block,
  */
 static bool
 lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
-					   Page page, bool sharelock, Buffer vmbuffer)
+					   Page page, bool sharelock)
 {
 	Size		freespace;
 
@@ -1300,7 +1326,7 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
 
 			PageSetAllVisible(page);
 			visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-							  vmbuffer, InvalidTransactionId,
+							  vacrel->skip.vmbuffer, InvalidTransactionId,
 							  VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
 			END_CRIT_SECTION();
 		}
@@ -1336,10 +1362,11 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
  * any tuple that becomes dead after the call to heap_page_prune() can't need to
  * be frozen, because it was visible to another session when vacuum started.
  *
- * vmbuffer is the buffer containing the VM block with visibility information
- * for the heap block, blkno. all_visible_according_to_vm is the saved
- * visibility status of the heap block looked up earlier by the caller. We
- * won't rely entirely on this status, as it may be out of date.
+ * vacrel->skipstate.vmbuffer is the buffer containing the VM block with
+ * visibility information for the heap block, blkno.
+ * all_visible_according_to_vm is the saved visibility status of the heap block
+ * looked up earlier by the caller. We won't rely entirely on this status, as
+ * it may be out of date.
  *
  * *has_lpdead_items is set to true or false depending on whether, upon return
  * from this function, any LP_DEAD items are still present on the page.
@@ -1349,7 +1376,6 @@ lazy_scan_prune(LVRelState *vacrel,
 				Buffer buf,
 				BlockNumber blkno,
 				Page page,
-				Buffer vmbuffer,
 				bool all_visible_according_to_vm,
 				bool *has_lpdead_items)
 {
@@ -1783,7 +1809,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		PageSetAllVisible(page);
 		MarkBufferDirty(buf);
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, visibility_cutoff_xid,
+						  vacrel->skip.vmbuffer, visibility_cutoff_xid,
 						  flags);
 	}
 
@@ -1794,11 +1820,11 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * buffer lock before concluding that the VM is corrupt.
 	 */
 	else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
-			 visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
+			 visibilitymap_get_status(vacrel->rel, blkno, &vacrel->skip.vmbuffer) != 0)
 	{
 		elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
 			 vacrel->relname, blkno);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1822,7 +1848,7 @@ lazy_scan_prune(LVRelState *vacrel,
 			 vacrel->relname, blkno);
 		PageClearAllVisible(page);
 		MarkBufferDirty(buf);
-		visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
+		visibilitymap_clear(vacrel->rel, blkno, vacrel->skip.vmbuffer,
 							VISIBILITYMAP_VALID_BITS);
 	}
 
@@ -1832,7 +1858,7 @@ lazy_scan_prune(LVRelState *vacrel,
 	 * true, so we must check both all_visible and all_frozen.
 	 */
 	else if (all_visible_according_to_vm && all_visible &&
-			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
+			 all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vacrel->skip.vmbuffer))
 	{
 		/*
 		 * Avoid relying on all_visible_according_to_vm as a proxy for the
@@ -1854,7 +1880,7 @@ lazy_scan_prune(LVRelState *vacrel,
 		 */
 		Assert(!TransactionIdIsValid(visibility_cutoff_xid));
 		visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
-						  vmbuffer, InvalidTransactionId,
+						  vacrel->skip.vmbuffer, InvalidTransactionId,
 						  VISIBILITYMAP_ALL_VISIBLE |
 						  VISIBILITYMAP_ALL_FROZEN);
 	}
-- 
2.40.1

  [text/x-diff] v5a-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch (14.0K, ../../20240306234733.nd4a636colxkgq2e@liskov/4-v5a-0003-Confine-vacuum-skip-logic-to-lazy_scan_skip.patch)
  download | inline diff:
From a33c255419eb539901b8d07852e1c4b189b615df Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sat, 30 Dec 2023 16:59:27 -0500
Subject: [PATCH v5a 3/7] Confine vacuum skip logic to lazy_scan_skip

In preparation for vacuum to use the streaming read interface (and
eventually AIO), refactor vacuum's logic for skipping blocks such that
it is entirely confined to lazy_scan_skip(). This turns lazy_scan_skip()
and the skip state in LVRelState it uses into an iterator which yields
blocks to lazy_scan_heap(). Such a structure is conducive to an async
interface. While we are at it, rename lazy_scan_skip() to
heap_vac_scan_get_next_block(), which now more accurately describes it.

By always calling heap_vac_scan_get_next_block() -- instead of only when
we have reached the next unskippable block, we no longer need the
skipping_current_range variable. lazy_scan_heap() no longer needs to
manage the skipped range -- checking if we reached the end in order to
then call heap_vac_scan_get_next_block(). And
heap_vac_scan_get_next_block() can derive the visibility status of a
block from whether or not we are in a skippable range -- that is,
whether or not the next_block is equal to the next unskippable block.
---
 src/backend/access/heap/vacuumlazy.c | 243 ++++++++++++++-------------
 1 file changed, 126 insertions(+), 117 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 0ddb986bc03..99d160335e1 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -206,8 +206,8 @@ typedef struct LVRelState
 	int64		missed_dead_tuples; /* # removable, but not removed */
 
 	/*
-	 * Parameters maintained by lazy_scan_skip() to manage skipping ranges of
-	 * pages greater than SKIP_PAGES_THRESHOLD.
+	 * Parameters maintained by heap_vac_scan_get_next_block() to manage
+	 * skipping ranges of pages greater than SKIP_PAGES_THRESHOLD.
 	 */
 	struct
 	{
@@ -232,7 +232,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static void lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block);
+static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+										 BlockNumber *blkno,
+										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
 								   bool sharelock);
@@ -814,8 +816,11 @@ static void
 lazy_scan_heap(LVRelState *vacrel)
 {
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
+	bool		all_visible_according_to_vm;
+
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -830,40 +835,17 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
-	/* Set up an initial range of skippable blocks using the visibility map */
-	lazy_scan_skip(vacrel, 0);
-	for (blkno = 0; blkno < rel_pages; blkno++)
+
+	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
+										&blkno, &all_visible_according_to_vm))
 	{
 		Buffer		buf;
 		Page		page;
-		bool		all_visible_according_to_vm;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		if (blkno == vacrel->skip.next_unskippable_block)
-		{
-			/*
-			 * Can't skip this page safely.  Must scan the page.  But
-			 * determine the next skippable range after the page first.
-			 */
-			all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
-			lazy_scan_skip(vacrel, blkno + 1);
-
-			Assert(vacrel->skip.next_unskippable_block >= blkno + 1);
-		}
-		else
-		{
-			/* Last page always scanned (may need to set nonempty_pages) */
-			Assert(blkno < rel_pages - 1);
-
-			if (vacrel->skip.skipping_current_range)
-				continue;
-
-			/* Current range is too small to skip -- just scan the page */
-			all_visible_according_to_vm = true;
-		}
-
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1083,20 +1065,14 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	lazy_scan_skip() -- set up range of skippable blocks using visibility map.
- *
- * lazy_scan_heap() calls here every time it needs to set up a new range of
- * blocks to skip via the visibility map.  Caller passes next_block, the next
- * block in line. The parameters of the skipped range are recorded in skip.
- * vacrel is an in/out parameter here; vacuum options and information about the
- * relation are read and vacrel->skippedallvis is set to ensure we don't
- * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *	heap_vac_scan_get_next_block() -- get next block for vacuum to process
  *
- * skip->vmbuffer will contain the block from the VM containing visibility
- * information for the next unskippable heap block. We may end up needed a
- * different block from the VM (if we decide not to skip a skippable block).
- * This is okay; visibilitymap_pin() will take care of this while processing
- * the block.
+ * lazy_scan_heap() calls here every time it needs to get the next block to
+ * prune and vacuum, using the visibility map, vacuum options, and various
+ * thresholds to skip blocks which do not need to be processed. Caller passes
+ * next_block, the next block in line. This block may end up being skipped.
+ * heap_vac_scan_get_next_block() sets blkno to next block that actually needs
+ * to be processed.
  *
  * A block is unskippable if it is not all visible according to the visibility
  * map. It is also unskippable if it is the last block in the relation, if the
@@ -1106,14 +1082,25 @@ lazy_scan_heap(LVRelState *vacrel)
  * Even if a block is skippable, we may choose not to skip it if the range of
  * skippable blocks is too small (below SKIP_PAGES_THRESHOLD). As a
  * consequence, we must keep track of the next truly unskippable block and its
- * visibility status along with whether or not we are skipping the current
- * range of skippable blocks. This can be used to derive the next block
- * lazy_scan_heap() must process and its visibility status.
+ * visibility status separate from the next block lazy_scan_heap() should
+ * process (and its visibility status).
  *
  * The block number and visibility status of the next unskippable block are set
- * in skip->next_unskippable_block and next_unskippable_allvis.
- * skip->skipping_current_range indicates to the caller whether or not it is
- * processing a skippable (and thus all-visible) block.
+ * in vacrel->skip->next_unskippable_block and next_unskippable_allvis.
+ *
+ * The block number and visibility status of the next block to process are set
+ * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
+ * returns false if there are no further blocks to process.
+ *
+ * vacrel is an in/out parameter here; vacuum options and information about the
+ * relation are read and vacrel->skippedallvis is set to ensure we don't
+ * advance relfrozenxid when we have skipped vacuuming all visible blocks.
+ *
+ * skip->vmbuffer will contain the block from the VM containing visibility
+ * information for the next unskippable heap block. We may end up needed a
+ * different block from the VM (if we decide not to skip a skippable block).
+ * This is okay; visibilitymap_pin() will take care of this while processing
+ * the block.
  *
  * Note: our opinion of which blocks can be skipped can go stale immediately.
  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
@@ -1123,91 +1110,113 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static void
-lazy_scan_skip(LVRelState *vacrel, BlockNumber next_block)
+static bool
+heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
-	/* Use local variables for better optimized loop code */
-	BlockNumber rel_pages = vacrel->rel_pages,
-				next_unskippable_block = next_block;
-
 	bool		skipsallvis = false;
 
-	vacrel->skip.next_unskippable_allvis = true;
-	while (next_unskippable_block < rel_pages)
+	if (next_block >= vacrel->rel_pages)
 	{
-		uint8		mapbits = visibilitymap_get_status(vacrel->rel,
-													   next_unskippable_block,
-													   &vacrel->skip.vmbuffer);
+		*blkno = InvalidBlockNumber;
+		return false;
+	}
 
-		if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
+	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
+		next_block > vacrel->skip.next_unskippable_block)
+	{
+		/* Use local variables for better optimized loop code */
+		BlockNumber rel_pages = vacrel->rel_pages;
+		BlockNumber next_unskippable_block = vacrel->skip.next_unskippable_block;
+
+		while (++next_unskippable_block < rel_pages)
 		{
-			Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			uint8		mapbits = visibilitymap_get_status(vacrel->rel,
+														   next_unskippable_block,
+														   &vacrel->skip.vmbuffer);
 
-		/*
-		 * Caller must scan the last page to determine whether it has tuples
-		 * (caller must have the opportunity to set vacrel->nonempty_pages).
-		 * This rule avoids having lazy_truncate_heap() take access-exclusive
-		 * lock on rel to attempt a truncation that fails anyway, just because
-		 * there are tuples on the last page (it is likely that there will be
-		 * tuples on other nearby pages as well, but those can be skipped).
-		 *
-		 * Implement this by always treating the last block as unsafe to skip.
-		 */
-		if (next_unskippable_block == rel_pages - 1)
-			break;
+			vacrel->skip.next_unskippable_allvis = mapbits & VISIBILITYMAP_ALL_VISIBLE;
 
-		/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
-		if (!vacrel->skipwithvm)
-		{
-			/* Caller shouldn't rely on all_visible_according_to_vm */
-			vacrel->skip.next_unskippable_allvis = false;
-			break;
-		}
+			if (!vacrel->skip.next_unskippable_allvis)
+			{
+				Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
+				break;
+			}
 
-		/*
-		 * Aggressive VACUUM caller can't skip pages just because they are
-		 * all-visible.  They may still skip all-frozen pages, which can't
-		 * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
-		 */
-		if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
-		{
-			if (vacrel->aggressive)
+			/*
+			 * Caller must scan the last page to determine whether it has
+			 * tuples (caller must have the opportunity to set
+			 * vacrel->nonempty_pages). This rule avoids having
+			 * lazy_truncate_heap() take access-exclusive lock on rel to
+			 * attempt a truncation that fails anyway, just because there are
+			 * tuples on the last page (it is likely that there will be tuples
+			 * on other nearby pages as well, but those can be skipped).
+			 *
+			 * Implement this by always treating the last block as unsafe to
+			 * skip.
+			 */
+			if (next_unskippable_block == rel_pages - 1)
 				break;
 
+			/* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
+			if (!vacrel->skipwithvm)
+			{
+				/* Caller shouldn't rely on all_visible_according_to_vm */
+				vacrel->skip.next_unskippable_allvis = false;
+				break;
+			}
+
 			/*
-			 * All-visible block is safe to skip in non-aggressive case.  But
-			 * remember that the final range contains such a block for later.
+			 * Aggressive VACUUM caller can't skip pages just because they are
+			 * all-visible.  They may still skip all-frozen pages, which can't
+			 * contain XIDs < OldestXmin (XIDs that aren't already frozen by
+			 * now).
 			 */
-			skipsallvis = true;
+			if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
+			{
+				if (vacrel->aggressive)
+					break;
+
+				/*
+				 * All-visible block is safe to skip in non-aggressive case.
+				 * But remember that the final range contains such a block for
+				 * later.
+				 */
+				skipsallvis = true;
+			}
+
+			vacuum_delay_point();
 		}
 
-		vacuum_delay_point();
-		next_unskippable_block++;
-	}
+		vacrel->skip.next_unskippable_block = next_unskippable_block;
 
-	vacrel->skip.next_unskippable_block = next_unskippable_block;
+		/*
+		 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
+		 * pages.  Since we're reading sequentially, the OS should be doing
+		 * readahead for us, so there's no gain in skipping a page now and
+		 * then. Skipping such a range might even discourage sequential
+		 * detection.
+		 *
+		 * This test also enables more frequent relfrozenxid advancement
+		 * during non-aggressive VACUUMs.  If the range has any all-visible
+		 * pages then skipping makes updating relfrozenxid unsafe, which is a
+		 * real downside.
+		 */
+		if (vacrel->skip.next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
+		{
+			next_block = vacrel->skip.next_unskippable_block;
+			if (skipsallvis)
+				vacrel->skippedallvis = true;
+		}
+	}
 
-	/*
-	 * We only skip a range with at least SKIP_PAGES_THRESHOLD consecutive
-	 * pages.  Since we're reading sequentially, the OS should be doing
-	 * readahead for us, so there's no gain in skipping a page now and then.
-	 * Skipping such a range might even discourage sequential detection.
-	 *
-	 * This test also enables more frequent relfrozenxid advancement during
-	 * non-aggressive VACUUMs.  If the range has any all-visible pages then
-	 * skipping makes updating relfrozenxid unsafe, which is a real downside.
-	 */
-	if (vacrel->skip.next_unskippable_block - next_block < SKIP_PAGES_THRESHOLD)
-		vacrel->skip.skipping_current_range = false;
+	if (next_block == vacrel->skip.next_unskippable_block)
+		*all_visible_according_to_vm = vacrel->skip.next_unskippable_allvis;
 	else
-	{
-		vacrel->skip.skipping_current_range = true;
-		if (skipsallvis)
-			vacrel->skippedallvis = true;
-	}
+		*all_visible_according_to_vm = true;
+
+	*blkno = next_block;
+	return true;
 }
 
 /*
-- 
2.40.1

  [text/x-diff] v5a-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac.patch (1.0K, ../../20240306234733.nd4a636colxkgq2e@liskov/5-v5a-0004-Remove-unneeded-vacuum_delay_point-from-heap_vac.patch)
  download | inline diff:
From 4ab5ed0863ca4fcdc197811d60011971a29b8857 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 12:49:56 -0500
Subject: [PATCH v5a 4/7] Remove unneeded vacuum_delay_point from
 heap_vac_scan_get_next_block

heap_vac_scan_get_next_block() does relatively little work, so there is
no need to call vacuum_delay_point(). A future commit will call
heap_vac_scan_get_next_block() from a callback, and we would like to
avoid calling vacuum_delay_point() in that callback.
---
 src/backend/access/heap/vacuumlazy.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 99d160335e1..65d257aab83 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1184,8 +1184,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 				 */
 				skipsallvis = true;
 			}
-
-			vacuum_delay_point();
 		}
 
 		vacrel->skip.next_unskippable_block = next_unskippable_block;
-- 
2.40.1

  [text/x-diff] v5a-0005-Streaming-Read-API.patch (54.8K, ../../20240306234733.nd4a636colxkgq2e@liskov/6-v5a-0005-Streaming-Read-API.patch)
  download | inline diff:
From 0c82c513818f1aa3e8aa982344aaac13f54629e4 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 6 Mar 2024 14:46:08 -0500
Subject: [PATCH v5a 5/7] Streaming Read API

---
 src/backend/storage/Makefile             |   2 +-
 src/backend/storage/aio/Makefile         |  14 +
 src/backend/storage/aio/meson.build      |   5 +
 src/backend/storage/aio/streaming_read.c | 612 ++++++++++++++++++++++
 src/backend/storage/buffer/bufmgr.c      | 641 ++++++++++++++++-------
 src/backend/storage/buffer/localbuf.c    |  14 +-
 src/backend/storage/meson.build          |   1 +
 src/include/storage/bufmgr.h             |  45 ++
 src/include/storage/streaming_read.h     |  52 ++
 src/tools/pgindent/typedefs.list         |   3 +
 10 files changed, 1179 insertions(+), 210 deletions(-)
 create mode 100644 src/backend/storage/aio/Makefile
 create mode 100644 src/backend/storage/aio/meson.build
 create mode 100644 src/backend/storage/aio/streaming_read.c
 create mode 100644 src/include/storage/streaming_read.h

diff --git a/src/backend/storage/Makefile b/src/backend/storage/Makefile
index 8376cdfca20..eec03f6f2b4 100644
--- a/src/backend/storage/Makefile
+++ b/src/backend/storage/Makefile
@@ -8,6 +8,6 @@ subdir = src/backend/storage
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
-SUBDIRS     = buffer file freespace ipc large_object lmgr page smgr sync
+SUBDIRS     = aio buffer file freespace ipc large_object lmgr page smgr sync
 
 include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/Makefile b/src/backend/storage/aio/Makefile
new file mode 100644
index 00000000000..bcab44c802f
--- /dev/null
+++ b/src/backend/storage/aio/Makefile
@@ -0,0 +1,14 @@
+#
+# Makefile for storage/aio
+#
+# src/backend/storage/aio/Makefile
+#
+
+subdir = src/backend/storage/aio
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+
+OBJS = \
+	streaming_read.o
+
+include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/meson.build b/src/backend/storage/aio/meson.build
new file mode 100644
index 00000000000..39aef2a84a2
--- /dev/null
+++ b/src/backend/storage/aio/meson.build
@@ -0,0 +1,5 @@
+# Copyright (c) 2024, PostgreSQL Global Development Group
+
+backend_sources += files(
+  'streaming_read.c',
+)
diff --git a/src/backend/storage/aio/streaming_read.c b/src/backend/storage/aio/streaming_read.c
new file mode 100644
index 00000000000..71f2c4a70b6
--- /dev/null
+++ b/src/backend/storage/aio/streaming_read.c
@@ -0,0 +1,612 @@
+#include "postgres.h"
+
+#include "storage/streaming_read.h"
+#include "utils/rel.h"
+
+/*
+ * Element type for PgStreamingRead's circular array of block ranges.
+ */
+typedef struct PgStreamingReadRange
+{
+	bool		need_wait;
+	bool		advice_issued;
+	BlockNumber blocknum;
+	int			nblocks;
+	int			per_buffer_data_index;
+	Buffer		buffers[MAX_BUFFERS_PER_TRANSFER];
+	ReadBuffersOperation operation;
+} PgStreamingReadRange;
+
+/*
+ * Streaming read object.
+ */
+struct PgStreamingRead
+{
+	int			max_ios;
+	int			ios_in_progress;
+	int			max_pinned_buffers;
+	int			pinned_buffers;
+	int			pinned_buffers_trigger;
+	int			next_tail_buffer;
+	int			ramp_up_pin_limit;
+	int			ramp_up_pin_stall;
+	bool		finished;
+	bool		advice_enabled;
+	void	   *pgsr_private;
+	PgStreamingReadBufferCB callback;
+
+	BufferAccessStrategy strategy;
+	BufferManagerRelation bmr;
+	ForkNumber	forknum;
+
+	/* Sometimes we need to buffer one block for flow control. */
+	BlockNumber unget_blocknum;
+	void	   *unget_per_buffer_data;
+
+	/* Next expected block, for detecting sequential access. */
+	BlockNumber seq_blocknum;
+
+	/* Space for optional per-buffer private data. */
+	size_t		per_buffer_data_size;
+	void	   *per_buffer_data;
+
+	/* Circular buffer of ranges. */
+	int			size;
+	int			head;
+	int			tail;
+	PgStreamingReadRange ranges[FLEXIBLE_ARRAY_MEMBER];
+};
+
+static PgStreamingRead *
+pg_streaming_read_buffer_alloc_internal(int flags,
+										void *pgsr_private,
+										size_t per_buffer_data_size,
+										BufferAccessStrategy strategy)
+{
+	PgStreamingRead *pgsr;
+	int			size;
+	int			max_ios;
+	uint32		max_pinned_buffers;
+
+
+	/*
+	 * Decide how many assumed I/Os we will allow to run concurrently.  That
+	 * is, advice to the kernel to tell it that we will soon read.  This
+	 * number also affects how far we look ahead for opportunities to start
+	 * more I/Os.
+	 */
+	if (flags & PGSR_FLAG_MAINTENANCE)
+		max_ios = maintenance_io_concurrency;
+	else
+		max_ios = effective_io_concurrency;
+
+	/*
+	 * The desired level of I/O concurrency controls how far ahead we are
+	 * willing to look ahead.  We also clamp it to at least
+	 * MAX_BUFFER_PER_TRANFER so that we can have a chance to build up a full
+	 * sized read, even when max_ios is zero.
+	 */
+	max_pinned_buffers = Max(max_ios * 4, MAX_BUFFERS_PER_TRANSFER);
+
+	/*
+	 * The *_io_concurrency GUCs might be set to 0, but we want to allow at
+	 * least one, to keep our gating logic simple.
+	 */
+	max_ios = Max(max_ios, 1);
+
+	/*
+	 * Don't allow this backend to pin too many buffers.  For now we'll apply
+	 * the limit for the shared buffer pool and the local buffer pool, without
+	 * worrying which it is.
+	 */
+	LimitAdditionalPins(&max_pinned_buffers);
+	LimitAdditionalLocalPins(&max_pinned_buffers);
+	Assert(max_pinned_buffers > 0);
+
+	/*
+	 * pgsr->ranges is a circular buffer.  When it is empty, head == tail.
+	 * When it is full, there is an empty element between head and tail.  Head
+	 * can also be empty (nblocks == 0), therefore we need two extra elements
+	 * for non-occupied ranges, on top of max_pinned_buffers to allow for the
+	 * maxmimum possible number of occupied ranges of the smallest possible
+	 * size of one.
+	 */
+	size = max_pinned_buffers + 2;
+
+	pgsr = (PgStreamingRead *)
+		palloc0(offsetof(PgStreamingRead, ranges) +
+				sizeof(pgsr->ranges[0]) * size);
+
+	pgsr->max_ios = max_ios;
+	pgsr->per_buffer_data_size = per_buffer_data_size;
+	pgsr->max_pinned_buffers = max_pinned_buffers;
+	pgsr->pgsr_private = pgsr_private;
+	pgsr->strategy = strategy;
+	pgsr->size = size;
+
+	pgsr->unget_blocknum = InvalidBlockNumber;
+
+#ifdef USE_PREFETCH
+
+	/*
+	 * This system supports prefetching advice.  As long as direct I/O isn't
+	 * enabled, and the caller hasn't promised sequential access, we can use
+	 * it.
+	 */
+	if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
+		(flags & PGSR_FLAG_SEQUENTIAL) == 0)
+		pgsr->advice_enabled = true;
+#endif
+
+	/*
+	 * We start off building small ranges, but double that quickly, for the
+	 * benefit of users that don't know how far ahead they'll read.  This can
+	 * be disabled by users that already know they'll read all the way.
+	 */
+	if (flags & PGSR_FLAG_FULL)
+		pgsr->ramp_up_pin_limit = INT_MAX;
+	else
+		pgsr->ramp_up_pin_limit = 1;
+
+	/*
+	 * We want to avoid creating ranges that are smaller than they could be
+	 * just because we hit max_pinned_buffers.  We only look ahead when the
+	 * number of pinned buffers falls below this trigger number, or put
+	 * another way, we stop looking ahead when we wouldn't be able to build a
+	 * "full sized" range.
+	 */
+	pgsr->pinned_buffers_trigger =
+		Max(1, (int) max_pinned_buffers - MAX_BUFFERS_PER_TRANSFER);
+
+	/* Space for the callback to store extra data along with each block. */
+	if (per_buffer_data_size)
+		pgsr->per_buffer_data = palloc(per_buffer_data_size * max_pinned_buffers);
+
+	return pgsr;
+}
+
+/*
+ * Create a new streaming read object that can be used to perform the
+ * equivalent of a series of ReadBuffer() calls for one fork of one relation.
+ * Internally, it generates larger vectored reads where possible by looking
+ * ahead.
+ */
+PgStreamingRead *
+pg_streaming_read_buffer_alloc(int flags,
+							   void *pgsr_private,
+							   size_t per_buffer_data_size,
+							   BufferAccessStrategy strategy,
+							   BufferManagerRelation bmr,
+							   ForkNumber forknum,
+							   PgStreamingReadBufferCB next_block_cb)
+{
+	PgStreamingRead *result;
+
+	result = pg_streaming_read_buffer_alloc_internal(flags,
+													 pgsr_private,
+													 per_buffer_data_size,
+													 strategy);
+	result->callback = next_block_cb;
+	result->bmr = bmr;
+	result->forknum = forknum;
+
+	return result;
+}
+
+/*
+ * Find the per-buffer data index for the Nth block of a range.
+ */
+static int
+get_per_buffer_data_index(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	int			result;
+
+	/*
+	 * Find slot in the circular buffer of per-buffer data, without using the
+	 * expensive % operator.
+	 */
+	result = range->per_buffer_data_index + n;
+	if (result >= pgsr->max_pinned_buffers)
+		result -= pgsr->max_pinned_buffers;
+	Assert(result == (range->per_buffer_data_index + n) % pgsr->max_pinned_buffers);
+
+	return result;
+}
+
+/*
+ * Return a pointer to the per-buffer data by index.
+ */
+static void *
+get_per_buffer_data_by_index(PgStreamingRead *pgsr, int per_buffer_data_index)
+{
+	return (char *) pgsr->per_buffer_data +
+		pgsr->per_buffer_data_size * per_buffer_data_index;
+}
+
+/*
+ * Return a pointer to the per-buffer data for the Nth block of a range.
+ */
+static void *
+get_per_buffer_data(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	return get_per_buffer_data_by_index(pgsr,
+										get_per_buffer_data_index(pgsr,
+																  range,
+																  n));
+}
+
+/*
+ * Start reading the head range, and create a new head range.  The new head
+ * range is returned.  It may not be empty, if StartReadBuffers() couldn't
+ * start the entire range; in that case the returned range contains the
+ * remaining portion of the range.
+ */
+static PgStreamingReadRange *
+pg_streaming_read_start_head_range(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *head_range;
+	PgStreamingReadRange *new_head_range;
+	int			nblocks_pinned;
+	int			flags;
+
+	/* Caller should make sure we never exceed max_ios. */
+	Assert(pgsr->ios_in_progress < pgsr->max_ios);
+
+	/* Should only call if the head range has some blocks to read. */
+	head_range = &pgsr->ranges[pgsr->head];
+	Assert(head_range->nblocks > 0);
+
+	/*
+	 * If advice hasn't been suppressed, and this system supports it, this
+	 * isn't a strictly sequential pattern, then we'll issue advice.
+	 */
+	if (pgsr->advice_enabled && head_range->blocknum != pgsr->seq_blocknum)
+		flags = READ_BUFFERS_ISSUE_ADVICE;
+	else
+		flags = 0;
+
+
+	/* Start reading as many blocks as we can from the head range. */
+	nblocks_pinned = head_range->nblocks;
+	head_range->need_wait =
+		StartReadBuffers(pgsr->bmr,
+						 head_range->buffers,
+						 pgsr->forknum,
+						 head_range->blocknum,
+						 &nblocks_pinned,
+						 pgsr->strategy,
+						 flags,
+						 &head_range->operation);
+
+	/* Did that start an I/O? */
+	if (head_range->need_wait && (flags & READ_BUFFERS_ISSUE_ADVICE))
+	{
+		head_range->advice_issued = true;
+		pgsr->ios_in_progress++;
+		Assert(pgsr->ios_in_progress <= pgsr->max_ios);
+	}
+
+	/*
+	 * StartReadBuffers() might have pinned fewer blocks than we asked it to,
+	 * but always at least one.
+	 */
+	Assert(nblocks_pinned <= head_range->nblocks);
+	Assert(nblocks_pinned >= 1);
+	pgsr->pinned_buffers += nblocks_pinned;
+
+	/*
+	 * Remember where the next block would be after that, so we can detect
+	 * sequential access next time.
+	 */
+	pgsr->seq_blocknum = head_range->blocknum + nblocks_pinned;
+
+	/*
+	 * Create a new head range.  There must be space, because we have enough
+	 * elements for every range to hold just one block, up to the pin limit.
+	 */
+	Assert(pgsr->size > pgsr->max_pinned_buffers);
+	Assert((pgsr->head + 1) % pgsr->size != pgsr->tail);
+	if (++pgsr->head == pgsr->size)
+		pgsr->head = 0;
+	new_head_range = &pgsr->ranges[pgsr->head];
+	new_head_range->nblocks = 0;
+	new_head_range->advice_issued = false;
+
+	/*
+	 * If we didn't manage to start the whole read above, we split the range,
+	 * moving the remainder into the new head range.
+	 */
+	if (nblocks_pinned < head_range->nblocks)
+	{
+		int			nblocks_remaining = head_range->nblocks - nblocks_pinned;
+
+		head_range->nblocks = nblocks_pinned;
+
+		new_head_range->blocknum = head_range->blocknum + nblocks_pinned;
+		new_head_range->nblocks = nblocks_remaining;
+	}
+
+	/* The new range has per-buffer data starting after the previous range. */
+	new_head_range->per_buffer_data_index =
+		get_per_buffer_data_index(pgsr, head_range, nblocks_pinned);
+
+	return new_head_range;
+}
+
+/*
+ * Ask the callback which block it would like us to read next, with a small
+ * buffer in front to allow pg_streaming_unget_block() to work.
+ */
+static BlockNumber
+pg_streaming_get_block(PgStreamingRead *pgsr, void *per_buffer_data)
+{
+	BlockNumber result;
+
+	if (unlikely(pgsr->unget_blocknum != InvalidBlockNumber))
+	{
+		/*
+		 * If we had to unget a block, now it is time to return that one
+		 * again.
+		 */
+		result = pgsr->unget_blocknum;
+		pgsr->unget_blocknum = InvalidBlockNumber;
+
+		/*
+		 * The same per_buffer_data element must have been used, and still
+		 * contains whatever data the callback wrote into it.  So we just
+		 * sanity-check that we were called with the value that
+		 * pg_streaming_unget_block() pushed back.
+		 */
+		Assert(per_buffer_data == pgsr->unget_per_buffer_data);
+	}
+	else
+	{
+		/* Use the installed callback directly. */
+		result = pgsr->callback(pgsr, pgsr->pgsr_private, per_buffer_data);
+	}
+
+	return result;
+}
+
+/*
+ * In order to deal with short reads in StartReadBuffers(), we sometimes need
+ * to defer handling of a block until later.  This *must* be called with the
+ * last value returned by pg_streaming_get_block().
+ */
+static void
+pg_streaming_unget_block(PgStreamingRead *pgsr, BlockNumber blocknum, void *per_buffer_data)
+{
+	Assert(pgsr->unget_blocknum == InvalidBlockNumber);
+	pgsr->unget_blocknum = blocknum;
+	pgsr->unget_per_buffer_data = per_buffer_data;
+}
+
+static void
+pg_streaming_read_look_ahead(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *range;
+
+	/*
+	 * If we're still ramping up, we may have to stall to wait for buffers to
+	 * be consumed first before we do any more prefetching.
+	 */
+	if (pgsr->ramp_up_pin_stall > 0)
+	{
+		Assert(pgsr->pinned_buffers > 0);
+		return;
+	}
+
+	/*
+	 * If we're finished or can't start more I/O, then don't look ahead.
+	 */
+	if (pgsr->finished || pgsr->ios_in_progress == pgsr->max_ios)
+		return;
+
+	/*
+	 * We'll also wait until the number of pinned buffers falls below our
+	 * trigger level, so that we have the chance to create a full range.
+	 */
+	if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+		return;
+
+	do
+	{
+		BlockNumber blocknum;
+		void	   *per_buffer_data;
+
+		/* Do we have a full-sized range? */
+		range = &pgsr->ranges[pgsr->head];
+		if (range->nblocks == lengthof(range->buffers))
+		{
+			/* Start as much of it as we can. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/* If we're now at the I/O limit, stop here. */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+				return;
+
+			/*
+			 * If we couldn't form a full range, then stop here to avoid
+			 * creating small I/O.
+			 */
+			if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+				return;
+
+			/*
+			 * That might have only been partially started, but always
+			 * processes at least one so that'll do for now.
+			 */
+			Assert(range->nblocks < lengthof(range->buffers));
+		}
+
+		/* Find per-buffer data slot for the next block. */
+		per_buffer_data = get_per_buffer_data(pgsr, range, range->nblocks);
+
+		/* Find out which block the callback wants to read next. */
+		blocknum = pg_streaming_get_block(pgsr, per_buffer_data);
+		if (blocknum == InvalidBlockNumber)
+		{
+			/* End of stream. */
+			pgsr->finished = true;
+			break;
+		}
+
+		/*
+		 * Is there a head range that we cannot extend, because the requested
+		 * block is not consecutive?
+		 */
+		if (range->nblocks > 0 &&
+			range->blocknum + range->nblocks != blocknum)
+		{
+			/* Yes.  Start it, so we can begin building a new one. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * It's possible that it was only partially started, and we have a
+			 * new range with the remainder.  Keep starting I/Os until we get
+			 * it all out of the way, or we hit the I/O limit.
+			 */
+			while (range->nblocks > 0 && pgsr->ios_in_progress < pgsr->max_ios)
+				range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * We have to 'unget' the block returned by the callback if we
+			 * don't have enough I/O capacity left to start something.
+			 */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+			{
+				pg_streaming_unget_block(pgsr, blocknum, per_buffer_data);
+				return;
+			}
+		}
+
+		/* If we have a new, empty range, initialize the start block. */
+		if (range->nblocks == 0)
+		{
+			range->blocknum = blocknum;
+		}
+
+		/* This block extends the range by one. */
+		Assert(range->blocknum + range->nblocks == blocknum);
+		range->nblocks++;
+
+	} while (pgsr->pinned_buffers + range->nblocks < pgsr->max_pinned_buffers &&
+			 pgsr->pinned_buffers + range->nblocks < pgsr->ramp_up_pin_limit);
+
+	/* If we've hit the ramp-up limit, insert a stall. */
+	if (pgsr->pinned_buffers + range->nblocks >= pgsr->ramp_up_pin_limit)
+	{
+		/* Can't get here if an earlier stall hasn't finished. */
+		Assert(pgsr->ramp_up_pin_stall == 0);
+		/* Don't do any more prefetching until these buffers are consumed. */
+		pgsr->ramp_up_pin_stall = pgsr->ramp_up_pin_limit;
+		/* Double it.  It will soon be out of the way. */
+		pgsr->ramp_up_pin_limit *= 2;
+	}
+
+	/* Start as much as we can. */
+	while (range->nblocks > 0)
+	{
+		range = pg_streaming_read_start_head_range(pgsr);
+		if (pgsr->ios_in_progress == pgsr->max_ios)
+			break;
+	}
+}
+
+Buffer
+pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_data)
+{
+	pg_streaming_read_look_ahead(pgsr);
+
+	/* See if we have one buffer to return. */
+	while (pgsr->tail != pgsr->head)
+	{
+		PgStreamingReadRange *tail_range;
+
+		tail_range = &pgsr->ranges[pgsr->tail];
+
+		/*
+		 * Do we need to perform an I/O before returning the buffers from this
+		 * range?
+		 */
+		if (tail_range->need_wait)
+		{
+			WaitReadBuffers(&tail_range->operation);
+			tail_range->need_wait = false;
+
+			/*
+			 * We don't really know if the kernel generated a physical I/O
+			 * when we issued advice, let alone when it finished, but it has
+			 * certainly finished now because we've performed the read.
+			 */
+			if (tail_range->advice_issued)
+			{
+				Assert(pgsr->ios_in_progress > 0);
+				pgsr->ios_in_progress--;
+			}
+		}
+
+		/* Are there more buffers available in this range? */
+		if (pgsr->next_tail_buffer < tail_range->nblocks)
+		{
+			int			buffer_index;
+			Buffer		buffer;
+
+			buffer_index = pgsr->next_tail_buffer++;
+			buffer = tail_range->buffers[buffer_index];
+
+			Assert(BufferIsValid(buffer));
+
+			/* We are giving away ownership of this pinned buffer. */
+			Assert(pgsr->pinned_buffers > 0);
+			pgsr->pinned_buffers--;
+
+			if (pgsr->ramp_up_pin_stall > 0)
+				pgsr->ramp_up_pin_stall--;
+
+			if (per_buffer_data)
+				*per_buffer_data = get_per_buffer_data(pgsr, tail_range, buffer_index);
+
+			return buffer;
+		}
+
+		/* Advance tail to next range, if there is one. */
+		if (++pgsr->tail == pgsr->size)
+			pgsr->tail = 0;
+		pgsr->next_tail_buffer = 0;
+
+		/*
+		 * If tail crashed into head, and head is not empty, then it is time
+		 * to start that range.
+		 */
+		if (pgsr->tail == pgsr->head &&
+			pgsr->ranges[pgsr->head].nblocks > 0)
+			pg_streaming_read_start_head_range(pgsr);
+	}
+
+	Assert(pgsr->pinned_buffers == 0);
+
+	return InvalidBuffer;
+}
+
+void
+pg_streaming_read_free(PgStreamingRead *pgsr)
+{
+	Buffer		buffer;
+
+	/* Stop looking ahead. */
+	pgsr->finished = true;
+
+	/* Unpin anything that wasn't consumed. */
+	while ((buffer = pg_streaming_read_buffer_get_next(pgsr, NULL)) != InvalidBuffer)
+		ReleaseBuffer(buffer);
+
+	Assert(pgsr->pinned_buffers == 0);
+	Assert(pgsr->ios_in_progress == 0);
+
+	/* Release memory. */
+	if (pgsr->per_buffer_data)
+		pfree(pgsr->per_buffer_data);
+
+	pfree(pgsr);
+}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f0f8d4259c5..729d1f91721 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -19,6 +19,11 @@
  *		and pin it so that no one can destroy it while this process
  *		is using it.
  *
+ * StartReadBuffers() -- as above, but for multiple contiguous blocks in
+ *		two steps.
+ *
+ * WaitReadBuffers() -- second step of StartReadBuffers().
+ *
  * ReleaseBuffer() -- unpin a buffer
  *
  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
@@ -471,10 +476,9 @@ ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
 )
 
 
-static Buffer ReadBuffer_common(SMgrRelation smgr, char relpersistence,
+static Buffer ReadBuffer_common(BufferManagerRelation bmr,
 								ForkNumber forkNum, BlockNumber blockNum,
-								ReadBufferMode mode, BufferAccessStrategy strategy,
-								bool *hit);
+								ReadBufferMode mode, BufferAccessStrategy strategy);
 static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
 										   ForkNumber fork,
 										   BufferAccessStrategy strategy,
@@ -500,7 +504,7 @@ static uint32 WaitBufHdrUnlocked(BufferDesc *buf);
 static int	SyncOneBuffer(int buf_id, bool skip_recently_used,
 						  WritebackContext *wb_context);
 static void WaitIO(BufferDesc *buf);
-static bool StartBufferIO(BufferDesc *buf, bool forInput);
+static bool StartBufferIO(BufferDesc *buf, bool forInput, bool nowait);
 static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
 							  uint32 set_flag_bits, bool forget_owner);
 static void AbortBufferIO(Buffer buffer);
@@ -781,7 +785,6 @@ Buffer
 ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				   ReadBufferMode mode, BufferAccessStrategy strategy)
 {
-	bool		hit;
 	Buffer		buf;
 
 	/*
@@ -794,15 +797,9 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("cannot access temporary tables of other sessions")));
 
-	/*
-	 * Read the buffer, and update pgstat counters to reflect a cache hit or
-	 * miss.
-	 */
-	pgstat_count_buffer_read(reln);
-	buf = ReadBuffer_common(RelationGetSmgr(reln), reln->rd_rel->relpersistence,
-							forkNum, blockNum, mode, strategy, &hit);
-	if (hit)
-		pgstat_count_buffer_hit(reln);
+	buf = ReadBuffer_common(BMR_REL(reln),
+							forkNum, blockNum, mode, strategy);
+
 	return buf;
 }
 
@@ -822,13 +819,12 @@ ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
 						  BlockNumber blockNum, ReadBufferMode mode,
 						  BufferAccessStrategy strategy, bool permanent)
 {
-	bool		hit;
-
 	SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
 
-	return ReadBuffer_common(smgr, permanent ? RELPERSISTENCE_PERMANENT :
-							 RELPERSISTENCE_UNLOGGED, forkNum, blockNum,
-							 mode, strategy, &hit);
+	return ReadBuffer_common(BMR_SMGR(smgr, permanent ? RELPERSISTENCE_PERMANENT :
+									  RELPERSISTENCE_UNLOGGED),
+							 forkNum, blockNum,
+							 mode, strategy);
 }
 
 /*
@@ -994,35 +990,68 @@ ExtendBufferedRelTo(BufferManagerRelation bmr,
 	 */
 	if (buffer == InvalidBuffer)
 	{
-		bool		hit;
-
 		Assert(extended_by == 0);
-		buffer = ReadBuffer_common(bmr.smgr, bmr.relpersistence,
-								   fork, extend_to - 1, mode, strategy,
-								   &hit);
+		buffer = ReadBuffer_common(bmr, fork, extend_to - 1, mode, strategy);
 	}
 
 	return buffer;
 }
 
+/*
+ * Zero a buffer and lock it, as part of the implementation of
+ * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK.  The buffer must be already
+ * pinned.  It does not have to be valid, but it is valid and locked on
+ * return.
+ */
+static void
+ZeroBuffer(Buffer buffer, ReadBufferMode mode)
+{
+	BufferDesc *bufHdr;
+	uint32		buf_state;
+
+	Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
+
+	if (BufferIsLocal(buffer))
+		bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+	else
+	{
+		bufHdr = GetBufferDescriptor(buffer - 1);
+		if (mode == RBM_ZERO_AND_LOCK)
+			LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
+		else
+			LockBufferForCleanup(buffer);
+	}
+
+	memset(BufferGetPage(buffer), 0, BLCKSZ);
+
+	if (BufferIsLocal(buffer))
+	{
+		buf_state = pg_atomic_read_u32(&bufHdr->state);
+		buf_state |= BM_VALID;
+		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+	}
+	else
+	{
+		buf_state = LockBufHdr(bufHdr);
+		buf_state |= BM_VALID;
+		UnlockBufHdr(bufHdr, buf_state);
+	}
+}
+
 /*
  * ReadBuffer_common -- common logic for all ReadBuffer variants
  *
  * *hit is set to true if the request was satisfied from shared buffer cache.
  */
 static Buffer
-ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
+ReadBuffer_common(BufferManagerRelation bmr, ForkNumber forkNum,
 				  BlockNumber blockNum, ReadBufferMode mode,
-				  BufferAccessStrategy strategy, bool *hit)
+				  BufferAccessStrategy strategy)
 {
-	BufferDesc *bufHdr;
-	Block		bufBlock;
-	bool		found;
-	IOContext	io_context;
-	IOObject	io_object;
-	bool		isLocalBuf = SmgrIsTemp(smgr);
-
-	*hit = false;
+	ReadBuffersOperation operation;
+	Buffer		buffer;
+	int			nblocks;
+	int			flags;
 
 	/*
 	 * Backward compatibility path, most code should use ExtendBufferedRel()
@@ -1041,181 +1070,404 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
 			flags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_SMGR(smgr, relpersistence),
-								 forkNum, strategy, flags);
+		return ExtendBufferedRel(bmr, forkNum, strategy, flags);
 	}
 
-	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
-									   smgr->smgr_rlocator.locator.spcOid,
-									   smgr->smgr_rlocator.locator.dbOid,
-									   smgr->smgr_rlocator.locator.relNumber,
-									   smgr->smgr_rlocator.backend);
+	nblocks = 1;
+	if (mode == RBM_ZERO_ON_ERROR)
+		flags = READ_BUFFERS_ZERO_ON_ERROR;
+	else
+		flags = 0;
+	if (StartReadBuffers(bmr,
+						 &buffer,
+						 forkNum,
+						 blockNum,
+						 &nblocks,
+						 strategy,
+						 flags,
+						 &operation))
+		WaitReadBuffers(&operation);
+	Assert(nblocks == 1);		/* single block can't be short */
+
+	if (mode == RBM_ZERO_AND_CLEANUP_LOCK || mode == RBM_ZERO_AND_LOCK)
+		ZeroBuffer(buffer, mode);
+
+	return buffer;
+}
+
+static Buffer
+PrepareReadBuffer(BufferManagerRelation bmr,
+				  ForkNumber forkNum,
+				  BlockNumber blockNum,
+				  BufferAccessStrategy strategy,
+				  bool *foundPtr)
+{
+	BufferDesc *bufHdr;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	Assert(blockNum != P_NEW);
 
+	Assert(bmr.smgr);
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/*
-		 * We do not use a BufferAccessStrategy for I/O of temporary tables.
-		 * However, in some cases, the "strategy" may not be NULL, so we can't
-		 * rely on IOContextForStrategy() to set the right IOContext for us.
-		 * This may happen in cases like CREATE TEMPORARY TABLE AS...
-		 */
 		io_context = IOCONTEXT_NORMAL;
 		io_object = IOOBJECT_TEMP_RELATION;
-		bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, &found);
-		if (found)
-			pgBufferUsage.local_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.local_blks_read++;
 	}
 	else
 	{
-		/*
-		 * lookup the buffer.  IO_IN_PROGRESS is set if the requested block is
-		 * not currently in memory.
-		 */
 		io_context = IOContextForStrategy(strategy);
 		io_object = IOOBJECT_RELATION;
-		bufHdr = BufferAlloc(smgr, relpersistence, forkNum, blockNum,
-							 strategy, &found, io_context);
-		if (found)
-			pgBufferUsage.shared_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.shared_blks_read++;
 	}
 
-	/* At this point we do NOT hold any locks. */
+	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
+									   bmr.smgr->smgr_rlocator.locator.spcOid,
+									   bmr.smgr->smgr_rlocator.locator.dbOid,
+									   bmr.smgr->smgr_rlocator.locator.relNumber,
+									   bmr.smgr->smgr_rlocator.backend);
 
-	/* if it was already in the buffer pool, we're done */
-	if (found)
+	ResourceOwnerEnlarge(CurrentResourceOwner);
+	if (isLocalBuf)
+	{
+		bufHdr = LocalBufferAlloc(bmr.smgr, forkNum, blockNum, foundPtr);
+		if (*foundPtr)
+			pgBufferUsage.local_blks_hit++;
+	}
+	else
+	{
+		bufHdr = BufferAlloc(bmr.smgr, bmr.relpersistence, forkNum, blockNum,
+							 strategy, foundPtr, io_context);
+		if (*foundPtr)
+			pgBufferUsage.shared_blks_hit++;
+	}
+	if (bmr.rel)
+	{
+		/*
+		 * While pgBufferUsage's "read" counter isn't bumped unless we reach
+		 * WaitReadBuffers() (so, not for hits, and not for buffers that are
+		 * zeroed instead), the per-relation stats always count them.
+		 */
+		pgstat_count_buffer_read(bmr.rel);
+		if (*foundPtr)
+			pgstat_count_buffer_hit(bmr.rel);
+	}
+	if (*foundPtr)
 	{
-		/* Just need to update stats before we exit */
-		*hit = true;
 		VacuumPageHit++;
 		pgstat_count_io_op(io_object, io_context, IOOP_HIT);
-
 		if (VacuumCostActive)
 			VacuumCostBalance += VacuumCostPageHit;
 
 		TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-										  smgr->smgr_rlocator.locator.spcOid,
-										  smgr->smgr_rlocator.locator.dbOid,
-										  smgr->smgr_rlocator.locator.relNumber,
-										  smgr->smgr_rlocator.backend,
-										  found);
+										  bmr.smgr->smgr_rlocator.locator.spcOid,
+										  bmr.smgr->smgr_rlocator.locator.dbOid,
+										  bmr.smgr->smgr_rlocator.locator.relNumber,
+										  bmr.smgr->smgr_rlocator.backend,
+										  true);
+	}
 
-		/*
-		 * In RBM_ZERO_AND_LOCK mode the caller expects the page to be locked
-		 * on return.
-		 */
-		if (!isLocalBuf)
-		{
-			if (mode == RBM_ZERO_AND_LOCK)
-				LWLockAcquire(BufferDescriptorGetContentLock(bufHdr),
-							  LW_EXCLUSIVE);
-			else if (mode == RBM_ZERO_AND_CLEANUP_LOCK)
-				LockBufferForCleanup(BufferDescriptorGetBuffer(bufHdr));
-		}
+	return BufferDescriptorGetBuffer(bufHdr);
+}
 
-		return BufferDescriptorGetBuffer(bufHdr);
+/*
+ * Begin reading a range of blocks beginning at blockNum and extending for
+ * *nblocks.  On return, up to *nblocks pinned buffers holding those blocks
+ * are written into the buffers array, and *nblocks is updated to contain the
+ * actual number, which may be fewer than requested.
+ *
+ * If false is returned, no I/O is necessary and WaitReadBuffers() is not
+ * necessary.  If true is returned, one I/O has been started, and
+ * WaitReadBuffers() must be called with the same operation object before the
+ * buffers are accessed.  Along with the operation object, the caller-supplied
+ * array of buffers must remain valid until WaitReadBuffers() is called.
+ *
+ * Currently the I/O is only started with optional operating system advice,
+ * and the real I/O happens in WaitReadBuffers().  In future work, true I/O
+ * could be initiated here.
+ */
+bool
+StartReadBuffers(BufferManagerRelation bmr,
+				 Buffer *buffers,
+				 ForkNumber forkNum,
+				 BlockNumber blockNum,
+				 int *nblocks,
+				 BufferAccessStrategy strategy,
+				 int flags,
+				 ReadBuffersOperation *operation)
+{
+	int			actual_nblocks = *nblocks;
+
+	if (bmr.rel)
+	{
+		bmr.smgr = RelationGetSmgr(bmr.rel);
+		bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
 	}
 
-	/*
-	 * if we have gotten to this point, we have allocated a buffer for the
-	 * page but its contents are not yet valid.  IO_IN_PROGRESS is set for it,
-	 * if it's a shared buffer.
-	 */
-	Assert(!(pg_atomic_read_u32(&bufHdr->state) & BM_VALID));	/* spinlock not needed */
+	operation->bmr = bmr;
+	operation->forknum = forkNum;
+	operation->blocknum = blockNum;
+	operation->buffers = buffers;
+	operation->nblocks = actual_nblocks;
+	operation->strategy = strategy;
+	operation->flags = flags;
 
-	bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
+	operation->io_buffers_len = 0;
 
-	/*
-	 * Read in the page, unless the caller intends to overwrite it and just
-	 * wants us to allocate a buffer.
-	 */
-	if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-		MemSet((char *) bufBlock, 0, BLCKSZ);
-	else
+	for (int i = 0; i < actual_nblocks; ++i)
 	{
-		instr_time	io_start = pgstat_prepare_io_time(track_io_timing);
+		bool		found;
 
-		smgrread(smgr, forkNum, blockNum, bufBlock);
+		buffers[i] = PrepareReadBuffer(bmr,
+									   forkNum,
+									   blockNum + i,
+									   strategy,
+									   &found);
 
-		pgstat_count_io_op_time(io_object, io_context,
-								IOOP_READ, io_start, 1);
+		if (found)
+		{
+			/*
+			 * Terminate the read as soon as we get a hit.  It could be a
+			 * single buffer hit, or it could be a hit that follows a readable
+			 * range.  We don't want to create more than one readable range,
+			 * so we stop here.
+			 */
+			actual_nblocks = operation->nblocks = *nblocks = i + 1;
+		}
+		else
+		{
+			/* Extend the readable range to cover this block. */
+			operation->io_buffers_len++;
+		}
+	}
 
-		/* check for garbage data */
-		if (!PageIsVerifiedExtended((Page) bufBlock, blockNum,
-									PIV_LOG_WARNING | PIV_REPORT_STAT))
+	if (operation->io_buffers_len > 0)
+	{
+		if (flags & READ_BUFFERS_ISSUE_ADVICE)
 		{
-			if (mode == RBM_ZERO_ON_ERROR || zero_damaged_pages)
-			{
-				ereport(WARNING,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s; zeroing out page",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
-				MemSet((char *) bufBlock, 0, BLCKSZ);
-			}
-			else
-				ereport(ERROR,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
+			/*
+			 * In theory we should only do this if PrepareReadBuffers() had to
+			 * allocate new buffers above.  That way, if two calls to
+			 * StartReadBuffers() were made for the same blocks before
+			 * WaitReadBuffers(), only the first would issue the advice.
+			 * That'd be a better simulation of true asynchronous I/O, which
+			 * would only start the I/O once, but isn't done here for
+			 * simplicity.  Note also that the following call might actually
+			 * issue two advice calls if we cross a segment boundary; in a
+			 * true asynchronous version we might choose to process only one
+			 * real I/O at a time in that case.
+			 */
+			smgrprefetch(bmr.smgr, forkNum, blockNum, operation->io_buffers_len);
 		}
+
+		/* Indicate that WaitReadBuffers() should be called. */
+		return true;
 	}
+	else
+	{
+		return false;
+	}
+}
 
-	/*
-	 * In RBM_ZERO_AND_LOCK / RBM_ZERO_AND_CLEANUP_LOCK mode, grab the buffer
-	 * content lock before marking the page as valid, to make sure that no
-	 * other backend sees the zeroed page before the caller has had a chance
-	 * to initialize it.
-	 *
-	 * Since no-one else can be looking at the page contents yet, there is no
-	 * difference between an exclusive lock and a cleanup-strength lock. (Note
-	 * that we cannot use LockBuffer() or LockBufferForCleanup() here, because
-	 * they assert that the buffer is already valid.)
-	 */
-	if ((mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK) &&
-		!isLocalBuf)
+static inline bool
+WaitReadBuffersCanStartIO(Buffer buffer, bool nowait)
+{
+	if (BufferIsLocal(buffer))
 	{
-		LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_EXCLUSIVE);
+		BufferDesc *bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+
+		return (pg_atomic_read_u32(&bufHdr->state) & BM_VALID) == 0;
 	}
+	else
+		return StartBufferIO(GetBufferDescriptor(buffer - 1), true, nowait);
+}
+
+void
+WaitReadBuffers(ReadBuffersOperation *operation)
+{
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	int			nblocks;
+	BlockNumber blocknum;
+	ForkNumber	forknum;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	/*
+	 * Currently operations are only allowed to include a read of some range,
+	 * with an optional extra buffer that is already pinned at the end.  So
+	 * nblocks can be at most one more than io_buffers_len.
+	 */
+	Assert((operation->nblocks == operation->io_buffers_len) ||
+		   (operation->nblocks == operation->io_buffers_len + 1));
 
+	/* Find the range of the physical read we need to perform. */
+	nblocks = operation->io_buffers_len;
+	if (nblocks == 0)
+		return;					/* nothing to do */
+
+	buffers = &operation->buffers[0];
+	blocknum = operation->blocknum;
+	forknum = operation->forknum;
+	bmr = operation->bmr;
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/* Only need to adjust flags */
-		uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
-
-		buf_state |= BM_VALID;
-		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+		io_context = IOCONTEXT_NORMAL;
+		io_object = IOOBJECT_TEMP_RELATION;
 	}
 	else
 	{
-		/* Set BM_VALID, terminate IO, and wake up any waiters */
-		TerminateBufferIO(bufHdr, false, BM_VALID, true);
+		io_context = IOContextForStrategy(operation->strategy);
+		io_object = IOOBJECT_RELATION;
 	}
 
-	VacuumPageMiss++;
-	if (VacuumCostActive)
-		VacuumCostBalance += VacuumCostPageMiss;
+	/*
+	 * We count all these blocks as read by this backend.  This is traditional
+	 * behavior, but might turn out to be not true if we find that someone
+	 * else has beaten us and completed the read of some of these blocks.  In
+	 * that case the system globally double-counts, but we traditionally don't
+	 * count this as a "hit", and we don't have a separate counter for "miss,
+	 * but another backend completed the read".
+	 */
+	if (isLocalBuf)
+		pgBufferUsage.local_blks_read += nblocks;
+	else
+		pgBufferUsage.shared_blks_read += nblocks;
 
-	TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-									  smgr->smgr_rlocator.locator.spcOid,
-									  smgr->smgr_rlocator.locator.dbOid,
-									  smgr->smgr_rlocator.locator.relNumber,
-									  smgr->smgr_rlocator.backend,
-									  found);
+	for (int i = 0; i < nblocks; ++i)
+	{
+		int			io_buffers_len;
+		Buffer		io_buffers[MAX_BUFFERS_PER_TRANSFER];
+		void	   *io_pages[MAX_BUFFERS_PER_TRANSFER];
+		instr_time	io_start;
+		BlockNumber io_first_block;
 
-	return BufferDescriptorGetBuffer(bufHdr);
+		/*
+		 * Skip this block if someone else has already completed it.  If an
+		 * I/O is already in progress in another backend, this will wait for
+		 * the outcome: either done, or something went wrong and we will
+		 * retry.
+		 */
+		if (!WaitReadBuffersCanStartIO(buffers[i], false))
+		{
+			/*
+			 * Report this as a 'hit' for this backend, even though it must
+			 * have started out as a miss in PrepareReadBuffer().
+			 */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, blocknum + i,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  true);
+			continue;
+		}
+
+		/* We found a buffer that we need to read in. */
+		io_buffers[0] = buffers[i];
+		io_pages[0] = BufferGetBlock(buffers[i]);
+		io_first_block = blocknum + i;
+		io_buffers_len = 1;
+
+		/*
+		 * How many neighboring-on-disk blocks can we can scatter-read into
+		 * other buffers at the same time?  In this case we don't wait if we
+		 * see an I/O already in progress.  We already hold BM_IO_IN_PROGRESS
+		 * for the head block, so we should get on with that I/O as soon as
+		 * possible.  We'll come back to this block again, above.
+		 */
+		while ((i + 1) < nblocks &&
+			   WaitReadBuffersCanStartIO(buffers[i + 1], true))
+		{
+			/* Must be consecutive block numbers. */
+			Assert(BufferGetBlockNumber(buffers[i + 1]) ==
+				   BufferGetBlockNumber(buffers[i]) + 1);
+
+			io_buffers[io_buffers_len] = buffers[++i];
+			io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
+		}
+
+		io_start = pgstat_prepare_io_time(track_io_timing);
+		smgrreadv(bmr.smgr, forknum, io_first_block, io_pages, io_buffers_len);
+		pgstat_count_io_op_time(io_object, io_context, IOOP_READ, io_start,
+								io_buffers_len);
+
+		/* Verify each block we read, and terminate the I/O. */
+		for (int j = 0; j < io_buffers_len; ++j)
+		{
+			BufferDesc *bufHdr;
+			Block		bufBlock;
+
+			if (isLocalBuf)
+			{
+				bufHdr = GetLocalBufferDescriptor(-io_buffers[j] - 1);
+				bufBlock = LocalBufHdrGetBlock(bufHdr);
+			}
+			else
+			{
+				bufHdr = GetBufferDescriptor(io_buffers[j] - 1);
+				bufBlock = BufHdrGetBlock(bufHdr);
+			}
+
+			/* check for garbage data */
+			if (!PageIsVerifiedExtended((Page) bufBlock, io_first_block + j,
+										PIV_LOG_WARNING | PIV_REPORT_STAT))
+			{
+				if ((operation->flags & READ_BUFFERS_ZERO_ON_ERROR) || zero_damaged_pages)
+				{
+					ereport(WARNING,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s; zeroing out page",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+					memset(bufBlock, 0, BLCKSZ);
+				}
+				else
+					ereport(ERROR,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+			}
+
+			/* Terminate I/O and set BM_VALID. */
+			if (isLocalBuf)
+			{
+				uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
+
+				buf_state |= BM_VALID;
+				pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+			}
+			else
+			{
+				/* Set BM_VALID, terminate IO, and wake up any waiters */
+				TerminateBufferIO(bufHdr, false, BM_VALID, true);
+			}
+
+			/* Report I/Os as completing individually. */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, io_first_block + j,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  false);
+		}
+
+		VacuumPageMiss += io_buffers_len;
+		if (VacuumCostActive)
+			VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
+	}
 }
 
 /*
- * BufferAlloc -- subroutine for ReadBuffer.  Handles lookup of a shared
- *		buffer.  If no buffer exists already, selects a replacement
- *		victim and evicts the old page, but does NOT read in new page.
+ * BufferAlloc -- subroutine for StartReadBuffers.  Handles lookup of a shared
+ *		buffer.  If no buffer exists already, selects a replacement victim and
+ *		evicts the old page, but does NOT read in new page.
  *
  * "strategy" can be a buffer replacement strategy object, or NULL for
  * the default strategy.  The selected buffer's usage_count is advanced when
@@ -1223,11 +1475,7 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
  *
  * The returned buffer is pinned and is already marked as holding the
  * desired page.  If it already did have the desired page, *foundPtr is
- * set true.  Otherwise, *foundPtr is set false and the buffer is marked
- * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.
- *
- * *foundPtr is actually redundant with the buffer's BM_VALID flag, but
- * we keep it for simplicity in ReadBuffer.
+ * set true.  Otherwise, *foundPtr is set false.
  *
  * io_context is passed as an output parameter to avoid calling
  * IOContextForStrategy() when there is a shared buffers hit and no IO
@@ -1286,19 +1534,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(buf, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return buf;
@@ -1363,19 +1602,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(existing_buf_hdr, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return existing_buf_hdr;
@@ -1407,15 +1637,9 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 	LWLockRelease(newPartitionLock);
 
 	/*
-	 * Buffer contents are currently invalid.  Try to obtain the right to
-	 * start I/O.  If StartBufferIO returns false, then someone else managed
-	 * to read it before we did, so there's nothing left for BufferAlloc() to
-	 * do.
+	 * Buffer contents are currently invalid.
 	 */
-	if (StartBufferIO(victim_buf_hdr, true))
-		*foundPtr = false;
-	else
-		*foundPtr = true;
+	*foundPtr = false;
 
 	return victim_buf_hdr;
 }
@@ -1769,7 +1993,7 @@ again:
  * pessimistic, but outside of toy-sized shared_buffers it should allow
  * sufficient pins.
  */
-static void
+void
 LimitAdditionalPins(uint32 *additional_pins)
 {
 	uint32		max_backends;
@@ -2034,7 +2258,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 
 				buf_state &= ~BM_VALID;
 				UnlockBufHdr(existing_hdr, buf_state);
-			} while (!StartBufferIO(existing_hdr, true));
+			} while (!StartBufferIO(existing_hdr, true, false));
 		}
 		else
 		{
@@ -2057,7 +2281,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 			LWLockRelease(partition_lock);
 
 			/* XXX: could combine the locked operations in it with the above */
-			StartBufferIO(victim_buf_hdr, true);
+			StartBufferIO(victim_buf_hdr, true, false);
 		}
 	}
 
@@ -2372,7 +2596,12 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 	else
 	{
 		/*
-		 * If we previously pinned the buffer, it must surely be valid.
+		 * If we previously pinned the buffer, it is likely to be valid, but
+		 * it may not be if StartReadBuffers() was called and
+		 * WaitReadBuffers() hasn't been called yet.  We'll check by loading
+		 * the flags without locking.  This is racy, but it's OK to return
+		 * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
+		 * it'll see that it's now valid.
 		 *
 		 * Note: We deliberately avoid a Valgrind client request here.
 		 * Individual access methods can optionally superimpose buffer page
@@ -2381,7 +2610,7 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 		 * that the buffer page is legitimately non-accessible here.  We
 		 * cannot meddle with that.
 		 */
-		result = true;
+		result = (pg_atomic_read_u32(&buf->state) & BM_VALID) != 0;
 	}
 
 	ref->refcount++;
@@ -3449,7 +3678,7 @@ FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
 	 * someone else flushed the buffer before we could, so we need not do
 	 * anything.
 	 */
-	if (!StartBufferIO(buf, false))
+	if (!StartBufferIO(buf, false, false))
 		return;
 
 	/* Setup error traceback support for ereport() */
@@ -5184,9 +5413,15 @@ WaitIO(BufferDesc *buf)
  *
  * Returns true if we successfully marked the buffer as I/O busy,
  * false if someone else already did the work.
+ *
+ * If nowait is true, then we don't wait for an I/O to be finished by another
+ * backend.  In that case, false indicates either that the I/O was already
+ * finished, or is still in progress.  This is useful for callers that want to
+ * find out if they can perform the I/O as part of a larger operation, without
+ * waiting for the answer or distinguishing the reasons why not.
  */
 static bool
-StartBufferIO(BufferDesc *buf, bool forInput)
+StartBufferIO(BufferDesc *buf, bool forInput, bool nowait)
 {
 	uint32		buf_state;
 
@@ -5199,6 +5434,8 @@ StartBufferIO(BufferDesc *buf, bool forInput)
 		if (!(buf_state & BM_IO_IN_PROGRESS))
 			break;
 		UnlockBufHdr(buf, buf_state);
+		if (nowait)
+			return false;
 		WaitIO(buf);
 	}
 
diff --git a/src/backend/storage/buffer/localbuf.c b/src/backend/storage/buffer/localbuf.c
index fcfac335a57..985a2c7049c 100644
--- a/src/backend/storage/buffer/localbuf.c
+++ b/src/backend/storage/buffer/localbuf.c
@@ -108,10 +108,9 @@ PrefetchLocalBuffer(SMgrRelation smgr, ForkNumber forkNum,
  * LocalBufferAlloc -
  *	  Find or create a local buffer for the given page of the given relation.
  *
- * API is similar to bufmgr.c's BufferAlloc, except that we do not need
- * to do any locking since this is all local.   Also, IO_IN_PROGRESS
- * does not get set.  Lastly, we support only default access strategy
- * (hence, usage_count is always advanced).
+ * API is similar to bufmgr.c's BufferAlloc, except that we do not need to do
+ * any locking since this is all local.  We support only default access
+ * strategy (hence, usage_count is always advanced).
  */
 BufferDesc *
 LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum,
@@ -287,7 +286,7 @@ GetLocalVictimBuffer(void)
 }
 
 /* see LimitAdditionalPins() */
-static void
+void
 LimitAdditionalLocalPins(uint32 *additional_pins)
 {
 	uint32		max_pins;
@@ -297,9 +296,10 @@ LimitAdditionalLocalPins(uint32 *additional_pins)
 
 	/*
 	 * In contrast to LimitAdditionalPins() other backends don't play a role
-	 * here. We can allow up to NLocBuffer pins in total.
+	 * here. We can allow up to NLocBuffer pins in total, but it might not be
+	 * initialized yet so read num_temp_buffers.
 	 */
-	max_pins = (NLocBuffer - NLocalPinnedBuffers);
+	max_pins = (num_temp_buffers - NLocalPinnedBuffers);
 
 	if (*additional_pins >= max_pins)
 		*additional_pins = max_pins;
diff --git a/src/backend/storage/meson.build b/src/backend/storage/meson.build
index 40345bdca27..739d13293fb 100644
--- a/src/backend/storage/meson.build
+++ b/src/backend/storage/meson.build
@@ -1,5 +1,6 @@
 # Copyright (c) 2022-2024, PostgreSQL Global Development Group
 
+subdir('aio')
 subdir('buffer')
 subdir('file')
 subdir('freespace')
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index d51d46d3353..b57f71f97e3 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -14,6 +14,7 @@
 #ifndef BUFMGR_H
 #define BUFMGR_H
 
+#include "port/pg_iovec.h"
 #include "storage/block.h"
 #include "storage/buf.h"
 #include "storage/bufpage.h"
@@ -158,6 +159,11 @@ extern PGDLLIMPORT int32 *LocalRefCount;
 #define BUFFER_LOCK_SHARE		1
 #define BUFFER_LOCK_EXCLUSIVE	2
 
+/*
+ * Maximum number of buffers for multi-buffer I/O functions.  This is set to
+ * allow 128kB transfers, unless BLCKSZ and IOV_MAX imply a a smaller maximum.
+ */
+#define MAX_BUFFERS_PER_TRANSFER Min(PG_IOV_MAX, (128 * 1024) / BLCKSZ)
 
 /*
  * prototypes for functions in bufmgr.c
@@ -177,6 +183,42 @@ extern Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator,
 										ForkNumber forkNum, BlockNumber blockNum,
 										ReadBufferMode mode, BufferAccessStrategy strategy,
 										bool permanent);
+
+#define READ_BUFFERS_ZERO_ON_ERROR 0x01
+#define READ_BUFFERS_ISSUE_ADVICE 0x02
+
+/*
+ * Private state used by StartReadBuffers() and WaitReadBuffers().  Declared
+ * in public header only to allow inclusion in other structs, but contents
+ * should not be accessed.
+ */
+struct ReadBuffersOperation
+{
+	/* Parameters passed in to StartReadBuffers(). */
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	ForkNumber	forknum;
+	BlockNumber blocknum;
+	int			nblocks;
+	BufferAccessStrategy strategy;
+	int			flags;
+
+	/* Range of buffers, if we need to perform a read. */
+	int			io_buffers_len;
+};
+
+typedef struct ReadBuffersOperation ReadBuffersOperation;
+
+extern bool StartReadBuffers(BufferManagerRelation bmr,
+							 Buffer *buffers,
+							 ForkNumber forknum,
+							 BlockNumber blocknum,
+							 int *nblocks,
+							 BufferAccessStrategy strategy,
+							 int flags,
+							 ReadBuffersOperation *operation);
+extern void WaitReadBuffers(ReadBuffersOperation *operation);
+
 extern void ReleaseBuffer(Buffer buffer);
 extern void UnlockReleaseBuffer(Buffer buffer);
 extern bool BufferIsExclusiveLocked(Buffer buffer);
@@ -250,6 +292,9 @@ extern bool HoldingBufferPinThatDelaysRecovery(void);
 
 extern bool BgBufferSync(struct WritebackContext *wb_context);
 
+extern void LimitAdditionalPins(uint32 *additional_pins);
+extern void LimitAdditionalLocalPins(uint32 *additional_pins);
+
 /* in buf_init.c */
 extern void InitBufferPool(void);
 extern Size BufferShmemSize(void);
diff --git a/src/include/storage/streaming_read.h b/src/include/storage/streaming_read.h
new file mode 100644
index 00000000000..c4d3892bb26
--- /dev/null
+++ b/src/include/storage/streaming_read.h
@@ -0,0 +1,52 @@
+#ifndef STREAMING_READ_H
+#define STREAMING_READ_H
+
+#include "storage/bufmgr.h"
+#include "storage/fd.h"
+#include "storage/smgr.h"
+
+/* Default tuning, reasonable for many users. */
+#define PGSR_FLAG_DEFAULT 0x00
+
+/*
+ * I/O streams that are performing maintenance work on behalf of potentially
+ * many users.
+ */
+#define PGSR_FLAG_MAINTENANCE 0x01
+
+/*
+ * We usually avoid issuing prefetch advice automatically when sequential
+ * access is detected, but this flag explicitly disables it, for cases that
+ * might not be correctly detected.  Explicit advice is known to perform worse
+ * than letting the kernel (at least Linux) detect sequential access.
+ */
+#define PGSR_FLAG_SEQUENTIAL 0x02
+
+/*
+ * We usually ramp up from smaller reads to larger ones, to support users who
+ * don't know if it's worth reading lots of buffers yet.  This flag disables
+ * that, declaring ahead of time that we'll be reading all available buffers.
+ */
+#define PGSR_FLAG_FULL 0x04
+
+struct PgStreamingRead;
+typedef struct PgStreamingRead PgStreamingRead;
+
+/* Callback that returns the next block number to read. */
+typedef BlockNumber (*PgStreamingReadBufferCB) (PgStreamingRead *pgsr,
+												void *pgsr_private,
+												void *per_buffer_private);
+
+extern PgStreamingRead *pg_streaming_read_buffer_alloc(int flags,
+													   void *pgsr_private,
+													   size_t per_buffer_private_size,
+													   BufferAccessStrategy strategy,
+													   BufferManagerRelation bmr,
+													   ForkNumber forknum,
+													   PgStreamingReadBufferCB next_block_cb);
+
+extern void pg_streaming_read_prefetch(PgStreamingRead *pgsr);
+extern Buffer pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_private);
+extern void pg_streaming_read_free(PgStreamingRead *pgsr);
+
+#endif
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 95ae7845d86..aea8babd71a 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2097,6 +2097,8 @@ PgStat_TableCounts
 PgStat_TableStatus
 PgStat_TableXactStatus
 PgStat_WalStats
+PgStreamingRead
+PgStreamingReadRange
 PgXmlErrorContext
 PgXmlStrictness
 Pg_finfo_record
@@ -2267,6 +2269,7 @@ ReInitializeDSMForeignScan_function
 ReScanForeignScan_function
 ReadBufPtrType
 ReadBufferMode
+ReadBuffersOperation
 ReadBytePtrType
 ReadExtraTocPtrType
 ReadFunc
-- 
2.40.1

  [text/x-diff] v5a-0006-Vacuum-first-pass-uses-Streaming-Read-interface.patch (8.3K, ../../20240306234733.nd4a636colxkgq2e@liskov/7-v5a-0006-Vacuum-first-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From 2e5ed537b9053ff3212177c1732d6afa2100fa0f Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Sun, 31 Dec 2023 11:29:02 -0500
Subject: [PATCH v5a 6/7] Vacuum first pass uses Streaming Read interface

Now vacuum's first pass, which HOT prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by implementing a
streaming read callback which invokes heap_vac_scan_get_next_block().
---
 src/backend/access/heap/vacuumlazy.c | 79 +++++++++++++++++++++-------
 1 file changed, 59 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 65d257aab83..fbbc87938e4 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -54,6 +54,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/streaming_read.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/pg_rusage.h"
@@ -168,7 +169,12 @@ typedef struct LVRelState
 	char	   *relnamespace;
 	char	   *relname;
 	char	   *indname;		/* Current index name */
-	BlockNumber blkno;			/* used only for heap operations */
+
+	/*
+	 * The current block being processed by vacuum. Used only for heap
+	 * operations. Primarily for error reporting and logging.
+	 */
+	BlockNumber blkno;
 	OffsetNumber offnum;		/* used only for heap operations */
 	VacErrPhase phase;
 	bool		verbose;		/* VACUUM VERBOSE? */
@@ -189,6 +195,12 @@ typedef struct LVRelState
 	BlockNumber missed_dead_pages;	/* # pages with missed dead tuples */
 	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
 
+	/*
+	 * The most recent block submitted in the streaming read callback by the
+	 * first vacuum pass.
+	 */
+	BlockNumber blkno_prefetch;
+
 	/* Statistics output by us, for table */
 	double		new_rel_tuples; /* new estimated total # of tuples */
 	double		new_live_tuples;	/* new estimated total # of live tuples */
@@ -232,7 +244,7 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
+static void heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 										 BlockNumber *blkno,
 										 bool *all_visible_according_to_vm);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
@@ -416,6 +428,9 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 	vacrel->nonempty_pages = 0;
 	/* dead_items_alloc allocates vacrel->dead_items later on */
 
+	/* relies on InvalidBlockNumber overflowing to 0 */
+	vacrel->blkno_prefetch = InvalidBlockNumber;
+
 	/* Allocate/initialize output statistics state */
 	vacrel->new_rel_tuples = 0;
 	vacrel->new_live_tuples = 0;
@@ -776,6 +791,22 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 	}
 }
 
+static BlockNumber
+vacuum_scan_pgsr_next(PgStreamingRead *pgsr,
+					  void *pgsr_private, void *per_buffer_data)
+{
+	LVRelState *vacrel = pgsr_private;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
+
+	vacrel->blkno_prefetch++;
+
+	heap_vac_scan_get_next_block(vacrel,
+								 vacrel->blkno_prefetch, &vacrel->blkno_prefetch,
+								 all_visible_according_to_vm);
+
+	return vacrel->blkno_prefetch;
+}
+
 /*
  *	lazy_scan_heap() -- workhorse function for VACUUM
  *
@@ -815,12 +846,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
 	BlockNumber rel_pages = vacrel->rel_pages,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm;
 
-	/* relies on InvalidBlockNumber overflowing to 0 */
-	BlockNumber blkno = InvalidBlockNumber;
 	VacDeadItems *dead_items = vacrel->dead_items;
 	const int	initprog_index[] = {
 		PROGRESS_VACUUM_PHASE,
@@ -828,6 +858,11 @@ lazy_scan_heap(LVRelState *vacrel)
 		PROGRESS_VACUUM_MAX_DEAD_TUPLES
 	};
 	int64		initprog_val[3];
+	PgStreamingRead *pgsr;
+
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(bool), vacrel->bstrategy, BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM, vacuum_scan_pgsr_next);
 
 	/* Report that we're scanning the heap, advertising total # of blocks */
 	initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
@@ -838,13 +873,19 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->skip.next_unskippable_block = InvalidBlockNumber;
 	vacrel->skip.vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_get_next_block(vacrel, blkno + 1,
-										&blkno, &all_visible_according_to_vm))
+	while (BufferIsValid(buf =
+						 pg_streaming_read_buffer_get_next(pgsr, (void **) &all_visible_according_to_vm)))
 	{
-		Buffer		buf;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
+		BlockNumber blkno;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		CheckBufferIsPinnedOnce(buf);
+
+		page = BufferGetPage(buf);
 
 		vacrel->scanned_pages++;
 
@@ -912,9 +953,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vacrel->skip.vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
 
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
@@ -970,7 +1008,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							all_visible_according_to_vm,
+							*all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1027,7 +1065,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	}
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, vacrel->rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1042,6 +1080,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	pg_streaming_read_free(pgsr);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1053,11 +1093,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (vacrel->rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, vacrel->rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, vacrel->rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1090,7 +1130,7 @@ lazy_scan_heap(LVRelState *vacrel)
  *
  * The block number and visibility status of the next block to process are set
  * in blkno and all_visible_according_to_vm. heap_vac_scan_get_next_block()
- * returns false if there are no further blocks to process.
+ * sets blkno to InvalidBlockNumber if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here; vacuum options and information about the
  * relation are read and vacrel->skippedallvis is set to ensure we don't
@@ -1110,7 +1150,7 @@ lazy_scan_heap(LVRelState *vacrel)
  * older XIDs/MXIDs.  The vacrel->skippedallvis flag will be set here when the
  * choice to skip such a range is actually made, making everything safe.)
  */
-static bool
+static void
 heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 							 BlockNumber *blkno, bool *all_visible_according_to_vm)
 {
@@ -1119,7 +1159,7 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 	if (next_block >= vacrel->rel_pages)
 	{
 		*blkno = InvalidBlockNumber;
-		return false;
+		return;
 	}
 
 	if (vacrel->skip.next_unskippable_block == InvalidBlockNumber ||
@@ -1214,7 +1254,6 @@ heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
 		*all_visible_according_to_vm = true;
 
 	*blkno = next_block;
-	return true;
 }
 
 /*
-- 
2.40.1

  [text/x-diff] v5a-0007-Vacuum-second-pass-uses-Streaming-Read-interface.patch (8.5K, ../../20240306234733.nd4a636colxkgq2e@liskov/8-v5a-0007-Vacuum-second-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From 84a5907b486d1f6c2ffe029a2e28fc557065739f Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 27 Feb 2024 14:35:36 -0500
Subject: [PATCH v5a 7/7] Vacuum second pass uses Streaming Read interface

Now vacuum's second pass, which removes dead items referring to dead
tuples catalogued in the first pass, uses the streaming read API by
implementing a streaming read callback which returns the next block
containing previously catalogued dead items. A new struct,
VacReapBlkState, is introduced to provide the caller with the starting
and ending indexes of dead items to vacuum.

ci-os-only:
---
 src/backend/access/heap/vacuumlazy.c | 110 ++++++++++++++++++++-------
 src/tools/pgindent/typedefs.list     |   1 +
 2 files changed, 85 insertions(+), 26 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index fbbc87938e4..68c146984b1 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -201,6 +201,12 @@ typedef struct LVRelState
 	 */
 	BlockNumber blkno_prefetch;
 
+	/*
+	 * The index of the next TID in dead_items to reap during the second
+	 * vacuum pass.
+	 */
+	int			idx_prefetch;
+
 	/* Statistics output by us, for table */
 	double		new_rel_tuples; /* new estimated total # of tuples */
 	double		new_live_tuples;	/* new estimated total # of live tuples */
@@ -242,6 +248,21 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+/*
+ * State set up in streaming read callback during vacuum's second pass which
+ * removes dead items referring to dead tuples cataloged in the first pass
+ */
+typedef struct VacReapBlkState
+{
+	/*
+	 * The indexes of the TIDs of the first and last dead tuples in a single
+	 * block in the currently vacuumed relation. The callback will set these
+	 * up prior to adding this block to the stream.
+	 */
+	int			start_idx;
+	int			end_idx;
+} VacReapBlkState;
+
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vac_scan_get_next_block(LVRelState *vacrel, BlockNumber next_block,
@@ -260,8 +281,9 @@ static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 static void lazy_vacuum(LVRelState *vacrel);
 static bool lazy_vacuum_all_indexes(LVRelState *vacrel);
 static void lazy_vacuum_heap_rel(LVRelState *vacrel);
-static int	lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
-								  Buffer buffer, int index, Buffer vmbuffer);
+static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+								  Buffer buffer, Buffer vmbuffer,
+								  VacReapBlkState *rbstate);
 static bool lazy_check_wraparound_failsafe(LVRelState *vacrel);
 static void lazy_cleanup_all_indexes(LVRelState *vacrel);
 static IndexBulkDeleteResult *lazy_vacuum_one_index(Relation indrel,
@@ -2401,6 +2423,37 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_pgsr_next(PgStreamingRead *pgsr,
+						 void *pgsr_private,
+						 void *per_buffer_data)
+{
+	BlockNumber blkno;
+	LVRelState *vacrel = pgsr_private;
+	VacReapBlkState *rbstate = per_buffer_data;
+
+	VacDeadItems *dead_items = vacrel->dead_items;
+
+	if (vacrel->idx_prefetch == dead_items->num_items)
+		return InvalidBlockNumber;
+
+	blkno = ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+	rbstate->start_idx = vacrel->idx_prefetch;
+
+	for (; vacrel->idx_prefetch < dead_items->num_items; vacrel->idx_prefetch++)
+	{
+		BlockNumber curblkno =
+			ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+
+		if (blkno != curblkno)
+			break;				/* past end of tuples for this block */
+	}
+
+	rbstate->end_idx = vacrel->idx_prefetch;
+
+	return blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2422,7 +2475,9 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
-	int			index = 0;
+	Buffer		buf;
+	PgStreamingRead *pgsr;
+	VacReapBlkState *rbstate;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2440,17 +2495,21 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 VACUUM_ERRCB_PHASE_VACUUM_HEAP,
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
-	while (index < vacrel->dead_items->num_items)
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(VacReapBlkState), vacrel->bstrategy, BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM, vacuum_reap_lp_pgsr_next);
+
+	while (BufferIsValid(buf =
+						 pg_streaming_read_buffer_get_next(pgsr,
+														   (void **) &rbstate)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 
 		vacuum_delay_point();
 
-		blkno = ItemPointerGetBlockNumber(&vacrel->dead_items->items[index]);
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		/*
 		 * Pin the visibility map page in case we need to mark the page
@@ -2460,10 +2519,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
-		index = lazy_vacuum_heap_page(vacrel, blkno, buf, index, vmbuffer);
+		lazy_vacuum_heap_page(vacrel, blkno, buf, vmbuffer, rbstate);
 
 		/* Now that we've vacuumed the page, record its available space */
 		page = BufferGetPage(buf);
@@ -2482,14 +2539,16 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 	 * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
 	 * the second heap pass.  No more, no less.
 	 */
-	Assert(index > 0);
+	Assert(rbstate->end_idx > 0);
 	Assert(vacrel->num_index_scans > 1 ||
-		   (index == vacrel->lpdead_items &&
+		   (rbstate->end_idx == vacrel->lpdead_items &&
 			vacuumed_pages == vacrel->lpdead_item_pages));
 
+	pg_streaming_read_free(pgsr);
+
 	ereport(DEBUG2,
 			(errmsg("table \"%s\": removed %lld dead item identifiers in %u pages",
-					vacrel->relname, (long long) index, vacuumed_pages)));
+					vacrel->relname, (long long) rbstate->end_idx, vacuumed_pages)));
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
@@ -2503,13 +2562,12 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
  * cleanup lock is also acceptable).  vmbuffer must be valid and already have
  * a pin on blkno's visibility map page.
  *
- * index is an offset into the vacrel->dead_items array for the first listed
- * LP_DEAD item on the page.  The return value is the first index immediately
- * after all LP_DEAD items for the same page in the array.
+ * Given a block and dead items recorded during the first pass, set those items
+ * dead and truncate the line pointer array. Update the VM as appropriate.
  */
-static int
-lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
-					  int index, Buffer vmbuffer)
+static void
+lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+					  Buffer buffer, Buffer vmbuffer, VacReapBlkState *rbstate)
 {
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Page		page = BufferGetPage(buffer);
@@ -2530,16 +2588,17 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	START_CRIT_SECTION();
 
-	for (; index < dead_items->num_items; index++)
+	for (int i = rbstate->start_idx; i < rbstate->end_idx; i++)
 	{
-		BlockNumber tblk;
 		OffsetNumber toff;
+		ItemPointer dead_item;
 		ItemId		itemid;
 
-		tblk = ItemPointerGetBlockNumber(&dead_items->items[index]);
-		if (tblk != blkno)
-			break;				/* past end of tuples for this block */
-		toff = ItemPointerGetOffsetNumber(&dead_items->items[index]);
+		dead_item = &dead_items->items[i];
+
+		Assert(ItemPointerGetBlockNumber(dead_item) == blkno);
+
+		toff = ItemPointerGetOffsetNumber(dead_item);
 		itemid = PageGetItemId(page, toff);
 
 		Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
@@ -2609,7 +2668,6 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
-	return index;
 }
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index aea8babd71a..a8f0b5f091d 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2972,6 +2972,7 @@ VacOptValue
 VacuumParams
 VacuumRelation
 VacuumStmt
+VacReapBlkState
 ValidIOData
 ValidateIndexState
 ValuesScan
-- 
2.40.1

^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-10 16:31               ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-10 16:31 UTC (permalink / raw)
  To: vignesh C <vignesh21@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Thomas Munro <thomas.munro@gmail.com>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Wed, Mar 6, 2024 at 6:47 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> Performance results:
>
> The TL;DR of my performance results is that streaming read vacuum is
> faster. However there is an issue with the interaction of the streaming
> read code and the vacuum buffer access strategy which must be addressed.

I have investigated the interaction between
maintenance_io_concurrency, streaming reads, and the vacuum buffer
access strategy (BAS_VACUUM).

The streaming read API limits max_pinned_buffers to a pinned buffer
multiplier (currently 4) * maintenance_io_concurrency buffers with the
goal of constructing reads of at least MAX_BUFFERS_PER_TRANSFER size.

Since the BAS_VACUUM ring buffer is size 256 kB or 32 buffers with
default block size, that means that for a fully uncached vacuum in
which all blocks must be vacuumed and will be dirtied, you'd have to
set maintenance_io_concurrency at 8 or lower to see the same number of
reuses (and shared buffer consumption) as master.

Given that we allow users to specify BUFFER_USAGE_LIMIT to vacuum, it
seems like we should force max_pinned_buffers to a value that
guarantees the expected shared buffer usage by vacuum. But that means
that maintenance_io_concurrency does not have a predictable impact on
streaming read vacuum.

What is the right thing to do here?

At the least, the default size of the BAS_VACUUM ring buffer should be
BLCKSZ * pinned_buffer_multiplier * default maintenance_io_concurrency
(probably rounded up to the next power of two) bytes.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-11 03:01                 ` Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2024-03-11 03:01 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Mon, Mar 11, 2024 at 5:31 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> On Wed, Mar 6, 2024 at 6:47 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> > Performance results:
> >
> > The TL;DR of my performance results is that streaming read vacuum is
> > faster. However there is an issue with the interaction of the streaming
> > read code and the vacuum buffer access strategy which must be addressed.

Woo.

> I have investigated the interaction between
> maintenance_io_concurrency, streaming reads, and the vacuum buffer
> access strategy (BAS_VACUUM).
>
> The streaming read API limits max_pinned_buffers to a pinned buffer
> multiplier (currently 4) * maintenance_io_concurrency buffers with the
> goal of constructing reads of at least MAX_BUFFERS_PER_TRANSFER size.
>
> Since the BAS_VACUUM ring buffer is size 256 kB or 32 buffers with
> default block size, that means that for a fully uncached vacuum in
> which all blocks must be vacuumed and will be dirtied, you'd have to
> set maintenance_io_concurrency at 8 or lower to see the same number of
> reuses (and shared buffer consumption) as master.
>
> Given that we allow users to specify BUFFER_USAGE_LIMIT to vacuum, it
> seems like we should force max_pinned_buffers to a value that
> guarantees the expected shared buffer usage by vacuum. But that means
> that maintenance_io_concurrency does not have a predictable impact on
> streaming read vacuum.
>
> What is the right thing to do here?
>
> At the least, the default size of the BAS_VACUUM ring buffer should be
> BLCKSZ * pinned_buffer_multiplier * default maintenance_io_concurrency
> (probably rounded up to the next power of two) bytes.

Hmm, does the v6 look-ahead distance control algorithm mitigate that
problem?  Using the ABC classifications from the streaming read
thread, I think for A it should now pin only 1, for B 16 and for C, it
depends on the size of the random 'chunks': if you have a lot of size
1 random reads then it shouldn't go above 10 because of (default)
maintenance_io_concurrency.  The only way to get up to very high
numbers would be to have a lot of random chunks triggering behaviour
C, but each made up of long runs of misses.  For example one can
contrive a BHS query that happens to read pages 0-15 then 20-35 then
40-55 etc etc so that we want to get lots of wide I/Os running
concurrently.  Unless vacuum manages to do something like that, it
shouldn't be able to exceed 32 buffers very easily.

I suspect that if we taught streaming_read.c to ask the
BufferAccessStrategy (if one is passed in) what its recommended pin
limit is (strategy->nbuffers?), we could just clamp
max_pinned_buffers, and it would be hard to find a workload where that
makes a difference, and we could think about more complicated logic
later.

In other words, I think/hope your complaints about excessive pinning
from v5 WRT all-cached heap scans might have also already improved
this case by happy coincidence?  I haven't tried it out though, I just
read your description of the problem...





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2024-03-11 21:02                   ` Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-03-11 21:02 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Mar 10, 2024 at 11:01 PM Thomas Munro <thomas.munro@gmail.com> wrote:
>
> On Mon, Mar 11, 2024 at 5:31 AM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> > I have investigated the interaction between
> > maintenance_io_concurrency, streaming reads, and the vacuum buffer
> > access strategy (BAS_VACUUM).
> >
> > The streaming read API limits max_pinned_buffers to a pinned buffer
> > multiplier (currently 4) * maintenance_io_concurrency buffers with the
> > goal of constructing reads of at least MAX_BUFFERS_PER_TRANSFER size.
> >
> > Since the BAS_VACUUM ring buffer is size 256 kB or 32 buffers with
> > default block size, that means that for a fully uncached vacuum in
> > which all blocks must be vacuumed and will be dirtied, you'd have to
> > set maintenance_io_concurrency at 8 or lower to see the same number of
> > reuses (and shared buffer consumption) as master.
> >
> > Given that we allow users to specify BUFFER_USAGE_LIMIT to vacuum, it
> > seems like we should force max_pinned_buffers to a value that
> > guarantees the expected shared buffer usage by vacuum. But that means
> > that maintenance_io_concurrency does not have a predictable impact on
> > streaming read vacuum.
> >
> > What is the right thing to do here?
> >
> > At the least, the default size of the BAS_VACUUM ring buffer should be
> > BLCKSZ * pinned_buffer_multiplier * default maintenance_io_concurrency
> > (probably rounded up to the next power of two) bytes.
>
> Hmm, does the v6 look-ahead distance control algorithm mitigate that
> problem?  Using the ABC classifications from the streaming read
> thread, I think for A it should now pin only 1, for B 16 and for C, it
> depends on the size of the random 'chunks': if you have a lot of size
> 1 random reads then it shouldn't go above 10 because of (default)
> maintenance_io_concurrency.  The only way to get up to very high
> numbers would be to have a lot of random chunks triggering behaviour
> C, but each made up of long runs of misses.  For example one can
> contrive a BHS query that happens to read pages 0-15 then 20-35 then
> 40-55 etc etc so that we want to get lots of wide I/Os running
> concurrently.  Unless vacuum manages to do something like that, it
> shouldn't be able to exceed 32 buffers very easily.
>
> I suspect that if we taught streaming_read.c to ask the
> BufferAccessStrategy (if one is passed in) what its recommended pin
> limit is (strategy->nbuffers?), we could just clamp
> max_pinned_buffers, and it would be hard to find a workload where that
> makes a difference, and we could think about more complicated logic
> later.
>
> In other words, I think/hope your complaints about excessive pinning
> from v5 WRT all-cached heap scans might have also already improved
> this case by happy coincidence?  I haven't tried it out though, I just
> read your description of the problem...

I've rebased the attached v10 over top of the changes to
lazy_scan_heap() Heikki just committed and over the v6 streaming read
patch set. I started testing them and see that you are right, we no
longer pin too many buffers. However, the uncached example below is
now slower with streaming read than on master -- it looks to be
because it is doing twice as many WAL writes and syncs. I'm still
investigating why that is.

psql \
-c "create table small (a int) with (autovacuum_enabled=false,
fillfactor=25);" \
-c "insert into small select generate_series(1,200000) % 3;" \
-c "update small set a = 6 where a = 1;"

pg_ctl stop
# drop caches
pg_ctl start

psql -c "\timing on" -c "vacuum (verbose) small"

- Melanie

Attachments:

  [text/x-patch] v10-0001-Streaming-Read-API.patch (55.8K, ../../CAAKRu_byDppRvNJ+p5kq-SmXZDQuL6L8N6D06pHbO6WnBnanWQ@mail.gmail.com/2-v10-0001-Streaming-Read-API.patch)
  download | inline diff:
From 2b181d178f0cd55de45659540ec35536918a4c9d Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Mon, 11 Mar 2024 15:36:39 -0400
Subject: [PATCH v10 1/3] Streaming Read API

---
 src/backend/storage/Makefile             |   2 +-
 src/backend/storage/aio/Makefile         |  14 +
 src/backend/storage/aio/meson.build      |   5 +
 src/backend/storage/aio/streaming_read.c | 648 +++++++++++++++++++++++
 src/backend/storage/buffer/bufmgr.c      | 641 +++++++++++++++-------
 src/backend/storage/buffer/localbuf.c    |  14 +-
 src/backend/storage/meson.build          |   1 +
 src/include/storage/bufmgr.h             |  45 ++
 src/include/storage/streaming_read.h     |  52 ++
 src/tools/pgindent/typedefs.list         |   3 +
 10 files changed, 1215 insertions(+), 210 deletions(-)
 create mode 100644 src/backend/storage/aio/Makefile
 create mode 100644 src/backend/storage/aio/meson.build
 create mode 100644 src/backend/storage/aio/streaming_read.c
 create mode 100644 src/include/storage/streaming_read.h

diff --git a/src/backend/storage/Makefile b/src/backend/storage/Makefile
index 8376cdfca20..eec03f6f2b4 100644
--- a/src/backend/storage/Makefile
+++ b/src/backend/storage/Makefile
@@ -8,6 +8,6 @@ subdir = src/backend/storage
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
-SUBDIRS     = buffer file freespace ipc large_object lmgr page smgr sync
+SUBDIRS     = aio buffer file freespace ipc large_object lmgr page smgr sync
 
 include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/Makefile b/src/backend/storage/aio/Makefile
new file mode 100644
index 00000000000..bcab44c802f
--- /dev/null
+++ b/src/backend/storage/aio/Makefile
@@ -0,0 +1,14 @@
+#
+# Makefile for storage/aio
+#
+# src/backend/storage/aio/Makefile
+#
+
+subdir = src/backend/storage/aio
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+
+OBJS = \
+	streaming_read.o
+
+include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/aio/meson.build b/src/backend/storage/aio/meson.build
new file mode 100644
index 00000000000..39aef2a84a2
--- /dev/null
+++ b/src/backend/storage/aio/meson.build
@@ -0,0 +1,5 @@
+# Copyright (c) 2024, PostgreSQL Global Development Group
+
+backend_sources += files(
+  'streaming_read.c',
+)
diff --git a/src/backend/storage/aio/streaming_read.c b/src/backend/storage/aio/streaming_read.c
new file mode 100644
index 00000000000..404c95b7d3c
--- /dev/null
+++ b/src/backend/storage/aio/streaming_read.c
@@ -0,0 +1,648 @@
+#include "postgres.h"
+
+#include "catalog/pg_tablespace.h"
+#include "miscadmin.h"
+#include "storage/streaming_read.h"
+#include "utils/rel.h"
+#include "utils/spccache.h"
+
+/*
+ * Element type for PgStreamingRead's circular array of block ranges.
+ */
+typedef struct PgStreamingReadRange
+{
+	bool		need_wait;
+	bool		advice_issued;
+	BlockNumber blocknum;
+	int			nblocks;
+	int			per_buffer_data_index;
+	Buffer		buffers[MAX_BUFFERS_PER_TRANSFER];
+	ReadBuffersOperation operation;
+} PgStreamingReadRange;
+
+/*
+ * Streaming read object.
+ */
+struct PgStreamingRead
+{
+	int			max_ios;
+	int			ios_in_progress;
+	int			max_pinned_buffers;
+	int			pinned_buffers;
+	int			pinned_buffers_trigger;
+	int			next_tail_buffer;
+	int			distance;
+	bool		finished;
+	bool		advice_enabled;
+	void	   *pgsr_private;
+	PgStreamingReadBufferCB callback;
+
+	BufferAccessStrategy strategy;
+	BufferManagerRelation bmr;
+	ForkNumber	forknum;
+
+	/* Sometimes we need to buffer one block for flow control. */
+	BlockNumber unget_blocknum;
+	void	   *unget_per_buffer_data;
+
+	/* Next expected block, for detecting sequential access. */
+	BlockNumber seq_blocknum;
+
+	/* Space for optional per-buffer private data. */
+	size_t		per_buffer_data_size;
+	void	   *per_buffer_data;
+
+	/* Circular buffer of ranges. */
+	int			size;
+	int			head;
+	int			tail;
+	PgStreamingReadRange ranges[FLEXIBLE_ARRAY_MEMBER];
+};
+
+/*
+ * Create a new streaming read object that can be used to perform the
+ * equivalent of a series of ReadBuffer() calls for one fork of one relation.
+ * Internally, it generates larger vectored reads where possible by looking
+ * ahead.
+ */
+PgStreamingRead *
+pg_streaming_read_buffer_alloc(int flags,
+							   void *pgsr_private,
+							   size_t per_buffer_data_size,
+							   BufferAccessStrategy strategy,
+							   BufferManagerRelation bmr,
+							   ForkNumber forknum,
+							   PgStreamingReadBufferCB next_block_cb)
+{
+	PgStreamingRead *pgsr;
+	int			size;
+	int			max_ios;
+	uint32		max_pinned_buffers;
+	Oid			tablespace_id;
+
+	/*
+	 * Make sure our bmr's smgr and persistent are populated.  The caller
+	 * asserts that the storage manager will remain valid.
+	 */
+	if (!bmr.smgr)
+	{
+		bmr.smgr = RelationGetSmgr(bmr.rel);
+		bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
+	}
+
+	/*
+	 * Decide how many assumed I/Os we will allow to run concurrently.  That
+	 * is, advice to the kernel to tell it that we will soon read.  This
+	 * number also affects how far we look ahead for opportunities to start
+	 * more I/Os.
+	 */
+	tablespace_id = bmr.smgr->smgr_rlocator.locator.spcOid;
+	if (!OidIsValid(MyDatabaseId) ||
+		(bmr.rel && IsCatalogRelation(bmr.rel)) ||
+		IsCatalogRelationOid(bmr.smgr->smgr_rlocator.locator.relNumber))
+	{
+		/*
+		 * Avoid circularity while trying to look up tablespace settings or
+		 * before spccache.c is ready.
+		 */
+		max_ios = effective_io_concurrency;
+	}
+	else if (flags & PGSR_FLAG_MAINTENANCE)
+		max_ios = get_tablespace_maintenance_io_concurrency(tablespace_id);
+	else
+		max_ios = get_tablespace_io_concurrency(tablespace_id);
+
+	/*
+	 * The desired level of I/O concurrency controls how far ahead we are
+	 * willing to look ahead.  We also clamp it to at least
+	 * MAX_BUFFER_PER_TRANSFER so that we can have a chance to build up a full
+	 * sized read, even when max_ios is zero.
+	 */
+	max_pinned_buffers = Max(max_ios * 4, MAX_BUFFERS_PER_TRANSFER);
+
+	/* Don't allow this backend to pin more than its share of buffers. */
+	if (SmgrIsTemp(bmr.smgr))
+		LimitAdditionalLocalPins(&max_pinned_buffers);
+	else
+		LimitAdditionalPins(&max_pinned_buffers);
+	Assert(max_pinned_buffers > 0);
+
+	/*
+	 * pgsr->ranges is a circular buffer.  When it is empty, head == tail.
+	 * When it is full, there is an empty element between head and tail.  Head
+	 * can also be empty (nblocks == 0), therefore we need two extra elements
+	 * for non-occupied ranges, on top of max_pinned_buffers to allow for the
+	 * maxmimum possible number of occupied ranges of the smallest possible
+	 * size of one.
+	 */
+	size = max_pinned_buffers + 2;
+
+	pgsr = (PgStreamingRead *)
+		palloc0(offsetof(PgStreamingRead, ranges) +
+				sizeof(pgsr->ranges[0]) * size);
+
+	pgsr->max_ios = max_ios;
+	pgsr->per_buffer_data_size = per_buffer_data_size;
+	pgsr->max_pinned_buffers = max_pinned_buffers;
+	pgsr->pgsr_private = pgsr_private;
+	pgsr->strategy = strategy;
+	pgsr->size = size;
+
+	pgsr->callback = next_block_cb;
+	pgsr->bmr = bmr;
+	pgsr->forknum = forknum;
+
+	pgsr->unget_blocknum = InvalidBlockNumber;
+
+#ifdef USE_PREFETCH
+
+	/*
+	 * This system supports prefetching advice.  As long as direct I/O isn't
+	 * enabled, and the caller hasn't promised sequential access, we can use
+	 * it.
+	 */
+	if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
+		(flags & PGSR_FLAG_SEQUENTIAL) == 0)
+		pgsr->advice_enabled = true;
+#endif
+
+	/*
+	 * Skip the initial ramp-up phase if the caller says we're going to be
+	 * reading the whole relation.  This way we start out doing full-sized
+	 * reads.
+	 */
+	if (flags & PGSR_FLAG_FULL)
+		pgsr->distance = Min(MAX_BUFFERS_PER_TRANSFER, pgsr->max_pinned_buffers);
+	else
+		pgsr->distance = 1;
+
+	/*
+	 * We want to avoid creating ranges that are smaller than they could be
+	 * just because we hit max_pinned_buffers.  We only look ahead when the
+	 * number of pinned buffers falls below this trigger number, or put
+	 * another way, we stop looking ahead when we wouldn't be able to build a
+	 * "full sized" range.
+	 */
+	pgsr->pinned_buffers_trigger =
+		Max(1, (int) max_pinned_buffers - MAX_BUFFERS_PER_TRANSFER);
+
+	/* Space for the callback to store extra data along with each block. */
+	if (per_buffer_data_size)
+		pgsr->per_buffer_data = palloc(per_buffer_data_size * max_pinned_buffers);
+
+	return pgsr;
+}
+
+/*
+ * Find the per-buffer data index for the Nth block of a range.
+ */
+static int
+get_per_buffer_data_index(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	int			result;
+
+	/*
+	 * Find slot in the circular buffer of per-buffer data, without using the
+	 * expensive % operator.
+	 */
+	result = range->per_buffer_data_index + n;
+	while (result >= pgsr->max_pinned_buffers)
+		result -= pgsr->max_pinned_buffers;
+	Assert(result == (range->per_buffer_data_index + n) % pgsr->max_pinned_buffers);
+
+	return result;
+}
+
+/*
+ * Return a pointer to the per-buffer data by index.
+ */
+static void *
+get_per_buffer_data_by_index(PgStreamingRead *pgsr, int per_buffer_data_index)
+{
+	return (char *) pgsr->per_buffer_data +
+		pgsr->per_buffer_data_size * per_buffer_data_index;
+}
+
+/*
+ * Return a pointer to the per-buffer data for the Nth block of a range.
+ */
+static void *
+get_per_buffer_data(PgStreamingRead *pgsr, PgStreamingReadRange *range, int n)
+{
+	return get_per_buffer_data_by_index(pgsr,
+										get_per_buffer_data_index(pgsr,
+																  range,
+																  n));
+}
+
+/*
+ * Start reading the head range, and create a new head range.  The new head
+ * range is returned.  It may not be empty, if StartReadBuffers() couldn't
+ * start the entire range; in that case the returned range contains the
+ * remaining portion of the range.
+ */
+static PgStreamingReadRange *
+pg_streaming_read_start_head_range(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *head_range;
+	PgStreamingReadRange *new_head_range;
+	int			nblocks_pinned;
+	int			flags;
+
+	/* Caller should make sure we never exceed max_ios. */
+	Assert((pgsr->ios_in_progress < pgsr->max_ios) ||
+		   (pgsr->ios_in_progress == 0 && pgsr->max_ios == 0));
+
+	/* Should only call if the head range has some blocks to read. */
+	head_range = &pgsr->ranges[pgsr->head];
+	Assert(head_range->nblocks > 0);
+
+	/*
+	 * If advice hasn't been suppressed, and this system supports it, this
+	 * isn't a strictly sequential pattern, then we'll issue advice.
+	 */
+	if (pgsr->advice_enabled &&
+		pgsr->max_ios > 0 &&
+		head_range->blocknum != pgsr->seq_blocknum)
+		flags = READ_BUFFERS_ISSUE_ADVICE;
+	else
+		flags = 0;
+
+	/* We shouldn't be trying to pin more buffers that we're allowed to. */
+	Assert(pgsr->pinned_buffers + head_range->nblocks <= pgsr->max_pinned_buffers);
+
+	/* Start reading as many blocks as we can from the head range. */
+	nblocks_pinned = head_range->nblocks;
+	head_range->need_wait =
+		StartReadBuffers(pgsr->bmr,
+						 head_range->buffers,
+						 pgsr->forknum,
+						 head_range->blocknum,
+						 &nblocks_pinned,
+						 pgsr->strategy,
+						 flags,
+						 &head_range->operation);
+
+	if (head_range->need_wait)
+	{
+		int		distance;
+
+		if (flags & READ_BUFFERS_ISSUE_ADVICE)
+		{
+			/*
+			 * Since we've issued advice, we count an I/O in progress until we
+			 * call WaitReadBuffers().
+			 */
+			head_range->advice_issued = true;
+			pgsr->ios_in_progress++;
+			Assert(pgsr->ios_in_progress <= pgsr->max_ios);
+
+			/*
+			 * Look-ahead distance ramps up rapidly, so we can search for more
+			 * I/Os to start.
+			 */
+			distance = pgsr->distance * 2;
+			distance = Min(distance, pgsr->max_pinned_buffers);
+			pgsr->distance = distance;
+		}
+		else
+		{
+			/*
+			 * There is no point in increasing look-ahead distance if we've
+			 * already reached the full I/O size, since we're not issuing
+			 * advice.  Extra distance would only pin more buffers for no
+			 * benefit.
+			 */
+			if (pgsr->distance > MAX_BUFFERS_PER_TRANSFER)
+			{
+				/* Look-ahead distance gradually decays. */
+				pgsr->distance--;
+			}
+			else
+			{
+				/*
+				 * Look-ahead distance ramps up rapidly, but not more that the
+				 * full I/O size.
+				 */
+				distance = pgsr->distance * 2;
+				distance = Min(distance, MAX_BUFFERS_PER_TRANSFER);
+				distance = Min(distance, pgsr->max_pinned_buffers);
+				pgsr->distance = distance;
+			}
+		}
+	}
+	else
+	{
+		/* No I/O necessary. Look-ahead distance gradually decays. */
+		if (pgsr->distance > 1)
+			pgsr->distance--;
+	}
+
+	/*
+	 * StartReadBuffers() might have pinned fewer blocks than we asked it to,
+	 * but always at least one.
+	 */
+	Assert(nblocks_pinned <= head_range->nblocks);
+	Assert(nblocks_pinned >= 1);
+	pgsr->pinned_buffers += nblocks_pinned;
+
+	/*
+	 * Remember where the next block would be after that, so we can detect
+	 * sequential access next time.
+	 */
+	pgsr->seq_blocknum = head_range->blocknum + nblocks_pinned;
+
+	/*
+	 * Create a new head range.  There must be space, because we have enough
+	 * elements for every range to hold just one block, up to the pin limit.
+	 */
+	Assert(pgsr->size > pgsr->max_pinned_buffers);
+	Assert((pgsr->head + 1) % pgsr->size != pgsr->tail);
+	if (++pgsr->head == pgsr->size)
+		pgsr->head = 0;
+	new_head_range = &pgsr->ranges[pgsr->head];
+	new_head_range->nblocks = 0;
+	new_head_range->advice_issued = false;
+
+	/*
+	 * If we didn't manage to start the whole read above, we split the range,
+	 * moving the remainder into the new head range.
+	 */
+	if (nblocks_pinned < head_range->nblocks)
+	{
+		int			nblocks_remaining = head_range->nblocks - nblocks_pinned;
+
+		head_range->nblocks = nblocks_pinned;
+
+		new_head_range->blocknum = head_range->blocknum + nblocks_pinned;
+		new_head_range->nblocks = nblocks_remaining;
+	}
+
+	/* The new range has per-buffer data starting after the previous range. */
+	new_head_range->per_buffer_data_index =
+		get_per_buffer_data_index(pgsr, head_range, nblocks_pinned);
+
+	return new_head_range;
+}
+
+/*
+ * Ask the callback which block it would like us to read next, with a small
+ * buffer in front to allow pg_streaming_unget_block() to work.
+ */
+static BlockNumber
+pg_streaming_get_block(PgStreamingRead *pgsr, void *per_buffer_data)
+{
+	BlockNumber result;
+
+	if (unlikely(pgsr->unget_blocknum != InvalidBlockNumber))
+	{
+		/*
+		 * If we had to unget a block, now it is time to return that one
+		 * again.
+		 */
+		result = pgsr->unget_blocknum;
+		pgsr->unget_blocknum = InvalidBlockNumber;
+
+		/*
+		 * The same per_buffer_data element must have been used, and still
+		 * contains whatever data the callback wrote into it.  So we just
+		 * sanity-check that we were called with the value that
+		 * pg_streaming_unget_block() pushed back.
+		 */
+		Assert(per_buffer_data == pgsr->unget_per_buffer_data);
+	}
+	else
+	{
+		/* Use the installed callback directly. */
+		result = pgsr->callback(pgsr, pgsr->pgsr_private, per_buffer_data);
+	}
+
+	return result;
+}
+
+/*
+ * In order to deal with short reads in StartReadBuffers(), we sometimes need
+ * to defer handling of a block until later.  This *must* be called with the
+ * last value returned by pg_streaming_get_block().
+ */
+static void
+pg_streaming_unget_block(PgStreamingRead *pgsr, BlockNumber blocknum, void *per_buffer_data)
+{
+	Assert(pgsr->unget_blocknum == InvalidBlockNumber);
+	pgsr->unget_blocknum = blocknum;
+	pgsr->unget_per_buffer_data = per_buffer_data;
+}
+
+static void
+pg_streaming_read_look_ahead(PgStreamingRead *pgsr)
+{
+	PgStreamingReadRange *range;
+
+	/* If we're finished, don't look ahead. */
+	if (pgsr->finished)
+		return;
+
+	/*
+	 * We we've already started the maximum allowed number of I/Os, don't look
+	 * ahead.  (The special case for max_ios == 0 is handle higher up.)
+	 */
+	if (pgsr->max_ios > 0 && pgsr->ios_in_progress == pgsr->max_ios)
+		return;
+
+	/*
+	 * We'll also wait until the number of pinned buffers falls below our
+	 * trigger level, so that we have the chance to create a full range.
+	 */
+	if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+		return;
+
+	do
+	{
+		BlockNumber blocknum;
+		void	   *per_buffer_data;
+
+		/* Do we have a full-sized range? */
+		range = &pgsr->ranges[pgsr->head];
+		if (range->nblocks == lengthof(range->buffers))
+		{
+			/* Start as much of it as we can. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/* If we're now at the I/O limit, stop here. */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+				return;
+
+			/*
+			 * If we couldn't form a full range, then stop here to avoid
+			 * creating small I/O.
+			 */
+			if (pgsr->pinned_buffers >= pgsr->pinned_buffers_trigger)
+				return;
+
+			/*
+			 * That might have only been partially started, but always
+			 * processes at least one so that'll do for now.
+			 */
+			Assert(range->nblocks < lengthof(range->buffers));
+		}
+
+		/* Find per-buffer data slot for the next block. */
+		per_buffer_data = get_per_buffer_data(pgsr, range, range->nblocks);
+
+		/* Find out which block the callback wants to read next. */
+		blocknum = pg_streaming_get_block(pgsr, per_buffer_data);
+		if (blocknum == InvalidBlockNumber)
+		{
+			/* End of stream. */
+			pgsr->finished = true;
+			break;
+		}
+
+		/*
+		 * Is there a head range that we cannot extend, because the requested
+		 * block is not consecutive?
+		 */
+		if (range->nblocks > 0 &&
+			range->blocknum + range->nblocks != blocknum)
+		{
+			/* Yes.  Start it, so we can begin building a new one. */
+			range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * It's possible that it was only partially started, and we have a
+			 * new range with the remainder.  Keep starting I/Os until we get
+			 * it all out of the way, or we hit the I/O limit.
+			 */
+			while (range->nblocks > 0 && pgsr->ios_in_progress < pgsr->max_ios)
+				range = pg_streaming_read_start_head_range(pgsr);
+
+			/*
+			 * We have to 'unget' the block returned by the callback if we
+			 * don't have enough I/O capacity left to start something.
+			 */
+			if (pgsr->ios_in_progress == pgsr->max_ios)
+			{
+				pg_streaming_unget_block(pgsr, blocknum, per_buffer_data);
+				return;
+			}
+		}
+
+		/* If we have a new, empty range, initialize the start block. */
+		if (range->nblocks == 0)
+		{
+			range->blocknum = blocknum;
+		}
+
+		/* This block extends the range by one. */
+		Assert(range->blocknum + range->nblocks == blocknum);
+		range->nblocks++;
+
+	} while (pgsr->pinned_buffers + range->nblocks < pgsr->distance);
+
+	/* Start as much as we can. */
+	while (range->nblocks > 0)
+	{
+		range = pg_streaming_read_start_head_range(pgsr);
+		if (pgsr->ios_in_progress == pgsr->max_ios)
+			break;
+	}
+}
+
+Buffer
+pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_data)
+{
+	/*
+	 * The setting max_ios == 0 requires special t...
+	 */
+	if (pgsr->max_ios > 0 || pgsr->pinned_buffers == 0)
+		pg_streaming_read_look_ahead(pgsr);
+
+	/* See if we have one buffer to return. */
+	while (pgsr->tail != pgsr->head)
+	{
+		PgStreamingReadRange *tail_range;
+
+		tail_range = &pgsr->ranges[pgsr->tail];
+
+		/*
+		 * Do we need to perform an I/O before returning the buffers from this
+		 * range?
+		 */
+		if (tail_range->need_wait)
+		{
+			WaitReadBuffers(&tail_range->operation);
+			tail_range->need_wait = false;
+
+			/*
+			 * We don't really know if the kernel generated a physical I/O
+			 * when we issued advice, let alone when it finished, but it has
+			 * certainly finished now because we've performed the read.
+			 */
+			if (tail_range->advice_issued)
+			{
+				Assert(pgsr->ios_in_progress > 0);
+				pgsr->ios_in_progress--;
+			}
+		}
+
+		/* Are there more buffers available in this range? */
+		if (pgsr->next_tail_buffer < tail_range->nblocks)
+		{
+			int			buffer_index;
+			Buffer		buffer;
+
+			buffer_index = pgsr->next_tail_buffer++;
+			buffer = tail_range->buffers[buffer_index];
+
+			Assert(BufferIsValid(buffer));
+
+			/* We are giving away ownership of this pinned buffer. */
+			Assert(pgsr->pinned_buffers > 0);
+			pgsr->pinned_buffers--;
+
+			if (per_buffer_data)
+				*per_buffer_data = get_per_buffer_data(pgsr, tail_range, buffer_index);
+
+			return buffer;
+		}
+
+		/* Advance tail to next range, if there is one. */
+		if (++pgsr->tail == pgsr->size)
+			pgsr->tail = 0;
+		pgsr->next_tail_buffer = 0;
+
+		/*
+		 * If tail crashed into head, and head is not empty, then it is time
+		 * to start that range.
+		 */
+		if (pgsr->tail == pgsr->head &&
+			pgsr->ranges[pgsr->head].nblocks > 0)
+			pg_streaming_read_start_head_range(pgsr);
+	}
+
+	Assert(pgsr->pinned_buffers == 0);
+
+	return InvalidBuffer;
+}
+
+void
+pg_streaming_read_free(PgStreamingRead *pgsr)
+{
+	Buffer		buffer;
+
+	/* Stop looking ahead. */
+	pgsr->finished = true;
+
+	/* Unpin anything that wasn't consumed. */
+	while ((buffer = pg_streaming_read_buffer_get_next(pgsr, NULL)) != InvalidBuffer)
+		ReleaseBuffer(buffer);
+
+	Assert(pgsr->pinned_buffers == 0);
+	Assert(pgsr->ios_in_progress == 0);
+
+	/* Release memory. */
+	if (pgsr->per_buffer_data)
+		pfree(pgsr->per_buffer_data);
+
+	pfree(pgsr);
+}
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index f0f8d4259c5..729d1f91721 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -19,6 +19,11 @@
  *		and pin it so that no one can destroy it while this process
  *		is using it.
  *
+ * StartReadBuffers() -- as above, but for multiple contiguous blocks in
+ *		two steps.
+ *
+ * WaitReadBuffers() -- second step of StartReadBuffers().
+ *
  * ReleaseBuffer() -- unpin a buffer
  *
  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
@@ -471,10 +476,9 @@ ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
 )
 
 
-static Buffer ReadBuffer_common(SMgrRelation smgr, char relpersistence,
+static Buffer ReadBuffer_common(BufferManagerRelation bmr,
 								ForkNumber forkNum, BlockNumber blockNum,
-								ReadBufferMode mode, BufferAccessStrategy strategy,
-								bool *hit);
+								ReadBufferMode mode, BufferAccessStrategy strategy);
 static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
 										   ForkNumber fork,
 										   BufferAccessStrategy strategy,
@@ -500,7 +504,7 @@ static uint32 WaitBufHdrUnlocked(BufferDesc *buf);
 static int	SyncOneBuffer(int buf_id, bool skip_recently_used,
 						  WritebackContext *wb_context);
 static void WaitIO(BufferDesc *buf);
-static bool StartBufferIO(BufferDesc *buf, bool forInput);
+static bool StartBufferIO(BufferDesc *buf, bool forInput, bool nowait);
 static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
 							  uint32 set_flag_bits, bool forget_owner);
 static void AbortBufferIO(Buffer buffer);
@@ -781,7 +785,6 @@ Buffer
 ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				   ReadBufferMode mode, BufferAccessStrategy strategy)
 {
-	bool		hit;
 	Buffer		buf;
 
 	/*
@@ -794,15 +797,9 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("cannot access temporary tables of other sessions")));
 
-	/*
-	 * Read the buffer, and update pgstat counters to reflect a cache hit or
-	 * miss.
-	 */
-	pgstat_count_buffer_read(reln);
-	buf = ReadBuffer_common(RelationGetSmgr(reln), reln->rd_rel->relpersistence,
-							forkNum, blockNum, mode, strategy, &hit);
-	if (hit)
-		pgstat_count_buffer_hit(reln);
+	buf = ReadBuffer_common(BMR_REL(reln),
+							forkNum, blockNum, mode, strategy);
+
 	return buf;
 }
 
@@ -822,13 +819,12 @@ ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
 						  BlockNumber blockNum, ReadBufferMode mode,
 						  BufferAccessStrategy strategy, bool permanent)
 {
-	bool		hit;
-
 	SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
 
-	return ReadBuffer_common(smgr, permanent ? RELPERSISTENCE_PERMANENT :
-							 RELPERSISTENCE_UNLOGGED, forkNum, blockNum,
-							 mode, strategy, &hit);
+	return ReadBuffer_common(BMR_SMGR(smgr, permanent ? RELPERSISTENCE_PERMANENT :
+									  RELPERSISTENCE_UNLOGGED),
+							 forkNum, blockNum,
+							 mode, strategy);
 }
 
 /*
@@ -994,35 +990,68 @@ ExtendBufferedRelTo(BufferManagerRelation bmr,
 	 */
 	if (buffer == InvalidBuffer)
 	{
-		bool		hit;
-
 		Assert(extended_by == 0);
-		buffer = ReadBuffer_common(bmr.smgr, bmr.relpersistence,
-								   fork, extend_to - 1, mode, strategy,
-								   &hit);
+		buffer = ReadBuffer_common(bmr, fork, extend_to - 1, mode, strategy);
 	}
 
 	return buffer;
 }
 
+/*
+ * Zero a buffer and lock it, as part of the implementation of
+ * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK.  The buffer must be already
+ * pinned.  It does not have to be valid, but it is valid and locked on
+ * return.
+ */
+static void
+ZeroBuffer(Buffer buffer, ReadBufferMode mode)
+{
+	BufferDesc *bufHdr;
+	uint32		buf_state;
+
+	Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
+
+	if (BufferIsLocal(buffer))
+		bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+	else
+	{
+		bufHdr = GetBufferDescriptor(buffer - 1);
+		if (mode == RBM_ZERO_AND_LOCK)
+			LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
+		else
+			LockBufferForCleanup(buffer);
+	}
+
+	memset(BufferGetPage(buffer), 0, BLCKSZ);
+
+	if (BufferIsLocal(buffer))
+	{
+		buf_state = pg_atomic_read_u32(&bufHdr->state);
+		buf_state |= BM_VALID;
+		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+	}
+	else
+	{
+		buf_state = LockBufHdr(bufHdr);
+		buf_state |= BM_VALID;
+		UnlockBufHdr(bufHdr, buf_state);
+	}
+}
+
 /*
  * ReadBuffer_common -- common logic for all ReadBuffer variants
  *
  * *hit is set to true if the request was satisfied from shared buffer cache.
  */
 static Buffer
-ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
+ReadBuffer_common(BufferManagerRelation bmr, ForkNumber forkNum,
 				  BlockNumber blockNum, ReadBufferMode mode,
-				  BufferAccessStrategy strategy, bool *hit)
+				  BufferAccessStrategy strategy)
 {
-	BufferDesc *bufHdr;
-	Block		bufBlock;
-	bool		found;
-	IOContext	io_context;
-	IOObject	io_object;
-	bool		isLocalBuf = SmgrIsTemp(smgr);
-
-	*hit = false;
+	ReadBuffersOperation operation;
+	Buffer		buffer;
+	int			nblocks;
+	int			flags;
 
 	/*
 	 * Backward compatibility path, most code should use ExtendBufferedRel()
@@ -1041,181 +1070,404 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
 			flags |= EB_LOCK_FIRST;
 
-		return ExtendBufferedRel(BMR_SMGR(smgr, relpersistence),
-								 forkNum, strategy, flags);
+		return ExtendBufferedRel(bmr, forkNum, strategy, flags);
 	}
 
-	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
-									   smgr->smgr_rlocator.locator.spcOid,
-									   smgr->smgr_rlocator.locator.dbOid,
-									   smgr->smgr_rlocator.locator.relNumber,
-									   smgr->smgr_rlocator.backend);
+	nblocks = 1;
+	if (mode == RBM_ZERO_ON_ERROR)
+		flags = READ_BUFFERS_ZERO_ON_ERROR;
+	else
+		flags = 0;
+	if (StartReadBuffers(bmr,
+						 &buffer,
+						 forkNum,
+						 blockNum,
+						 &nblocks,
+						 strategy,
+						 flags,
+						 &operation))
+		WaitReadBuffers(&operation);
+	Assert(nblocks == 1);		/* single block can't be short */
+
+	if (mode == RBM_ZERO_AND_CLEANUP_LOCK || mode == RBM_ZERO_AND_LOCK)
+		ZeroBuffer(buffer, mode);
+
+	return buffer;
+}
+
+static Buffer
+PrepareReadBuffer(BufferManagerRelation bmr,
+				  ForkNumber forkNum,
+				  BlockNumber blockNum,
+				  BufferAccessStrategy strategy,
+				  bool *foundPtr)
+{
+	BufferDesc *bufHdr;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	Assert(blockNum != P_NEW);
 
+	Assert(bmr.smgr);
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/*
-		 * We do not use a BufferAccessStrategy for I/O of temporary tables.
-		 * However, in some cases, the "strategy" may not be NULL, so we can't
-		 * rely on IOContextForStrategy() to set the right IOContext for us.
-		 * This may happen in cases like CREATE TEMPORARY TABLE AS...
-		 */
 		io_context = IOCONTEXT_NORMAL;
 		io_object = IOOBJECT_TEMP_RELATION;
-		bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, &found);
-		if (found)
-			pgBufferUsage.local_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.local_blks_read++;
 	}
 	else
 	{
-		/*
-		 * lookup the buffer.  IO_IN_PROGRESS is set if the requested block is
-		 * not currently in memory.
-		 */
 		io_context = IOContextForStrategy(strategy);
 		io_object = IOOBJECT_RELATION;
-		bufHdr = BufferAlloc(smgr, relpersistence, forkNum, blockNum,
-							 strategy, &found, io_context);
-		if (found)
-			pgBufferUsage.shared_blks_hit++;
-		else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
-				 mode == RBM_ZERO_ON_ERROR)
-			pgBufferUsage.shared_blks_read++;
 	}
 
-	/* At this point we do NOT hold any locks. */
+	TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
+									   bmr.smgr->smgr_rlocator.locator.spcOid,
+									   bmr.smgr->smgr_rlocator.locator.dbOid,
+									   bmr.smgr->smgr_rlocator.locator.relNumber,
+									   bmr.smgr->smgr_rlocator.backend);
 
-	/* if it was already in the buffer pool, we're done */
-	if (found)
+	ResourceOwnerEnlarge(CurrentResourceOwner);
+	if (isLocalBuf)
+	{
+		bufHdr = LocalBufferAlloc(bmr.smgr, forkNum, blockNum, foundPtr);
+		if (*foundPtr)
+			pgBufferUsage.local_blks_hit++;
+	}
+	else
+	{
+		bufHdr = BufferAlloc(bmr.smgr, bmr.relpersistence, forkNum, blockNum,
+							 strategy, foundPtr, io_context);
+		if (*foundPtr)
+			pgBufferUsage.shared_blks_hit++;
+	}
+	if (bmr.rel)
+	{
+		/*
+		 * While pgBufferUsage's "read" counter isn't bumped unless we reach
+		 * WaitReadBuffers() (so, not for hits, and not for buffers that are
+		 * zeroed instead), the per-relation stats always count them.
+		 */
+		pgstat_count_buffer_read(bmr.rel);
+		if (*foundPtr)
+			pgstat_count_buffer_hit(bmr.rel);
+	}
+	if (*foundPtr)
 	{
-		/* Just need to update stats before we exit */
-		*hit = true;
 		VacuumPageHit++;
 		pgstat_count_io_op(io_object, io_context, IOOP_HIT);
-
 		if (VacuumCostActive)
 			VacuumCostBalance += VacuumCostPageHit;
 
 		TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-										  smgr->smgr_rlocator.locator.spcOid,
-										  smgr->smgr_rlocator.locator.dbOid,
-										  smgr->smgr_rlocator.locator.relNumber,
-										  smgr->smgr_rlocator.backend,
-										  found);
+										  bmr.smgr->smgr_rlocator.locator.spcOid,
+										  bmr.smgr->smgr_rlocator.locator.dbOid,
+										  bmr.smgr->smgr_rlocator.locator.relNumber,
+										  bmr.smgr->smgr_rlocator.backend,
+										  true);
+	}
 
-		/*
-		 * In RBM_ZERO_AND_LOCK mode the caller expects the page to be locked
-		 * on return.
-		 */
-		if (!isLocalBuf)
-		{
-			if (mode == RBM_ZERO_AND_LOCK)
-				LWLockAcquire(BufferDescriptorGetContentLock(bufHdr),
-							  LW_EXCLUSIVE);
-			else if (mode == RBM_ZERO_AND_CLEANUP_LOCK)
-				LockBufferForCleanup(BufferDescriptorGetBuffer(bufHdr));
-		}
+	return BufferDescriptorGetBuffer(bufHdr);
+}
 
-		return BufferDescriptorGetBuffer(bufHdr);
+/*
+ * Begin reading a range of blocks beginning at blockNum and extending for
+ * *nblocks.  On return, up to *nblocks pinned buffers holding those blocks
+ * are written into the buffers array, and *nblocks is updated to contain the
+ * actual number, which may be fewer than requested.
+ *
+ * If false is returned, no I/O is necessary and WaitReadBuffers() is not
+ * necessary.  If true is returned, one I/O has been started, and
+ * WaitReadBuffers() must be called with the same operation object before the
+ * buffers are accessed.  Along with the operation object, the caller-supplied
+ * array of buffers must remain valid until WaitReadBuffers() is called.
+ *
+ * Currently the I/O is only started with optional operating system advice,
+ * and the real I/O happens in WaitReadBuffers().  In future work, true I/O
+ * could be initiated here.
+ */
+bool
+StartReadBuffers(BufferManagerRelation bmr,
+				 Buffer *buffers,
+				 ForkNumber forkNum,
+				 BlockNumber blockNum,
+				 int *nblocks,
+				 BufferAccessStrategy strategy,
+				 int flags,
+				 ReadBuffersOperation *operation)
+{
+	int			actual_nblocks = *nblocks;
+
+	if (bmr.rel)
+	{
+		bmr.smgr = RelationGetSmgr(bmr.rel);
+		bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
 	}
 
-	/*
-	 * if we have gotten to this point, we have allocated a buffer for the
-	 * page but its contents are not yet valid.  IO_IN_PROGRESS is set for it,
-	 * if it's a shared buffer.
-	 */
-	Assert(!(pg_atomic_read_u32(&bufHdr->state) & BM_VALID));	/* spinlock not needed */
+	operation->bmr = bmr;
+	operation->forknum = forkNum;
+	operation->blocknum = blockNum;
+	operation->buffers = buffers;
+	operation->nblocks = actual_nblocks;
+	operation->strategy = strategy;
+	operation->flags = flags;
 
-	bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
+	operation->io_buffers_len = 0;
 
-	/*
-	 * Read in the page, unless the caller intends to overwrite it and just
-	 * wants us to allocate a buffer.
-	 */
-	if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
-		MemSet((char *) bufBlock, 0, BLCKSZ);
-	else
+	for (int i = 0; i < actual_nblocks; ++i)
 	{
-		instr_time	io_start = pgstat_prepare_io_time(track_io_timing);
+		bool		found;
 
-		smgrread(smgr, forkNum, blockNum, bufBlock);
+		buffers[i] = PrepareReadBuffer(bmr,
+									   forkNum,
+									   blockNum + i,
+									   strategy,
+									   &found);
 
-		pgstat_count_io_op_time(io_object, io_context,
-								IOOP_READ, io_start, 1);
+		if (found)
+		{
+			/*
+			 * Terminate the read as soon as we get a hit.  It could be a
+			 * single buffer hit, or it could be a hit that follows a readable
+			 * range.  We don't want to create more than one readable range,
+			 * so we stop here.
+			 */
+			actual_nblocks = operation->nblocks = *nblocks = i + 1;
+		}
+		else
+		{
+			/* Extend the readable range to cover this block. */
+			operation->io_buffers_len++;
+		}
+	}
 
-		/* check for garbage data */
-		if (!PageIsVerifiedExtended((Page) bufBlock, blockNum,
-									PIV_LOG_WARNING | PIV_REPORT_STAT))
+	if (operation->io_buffers_len > 0)
+	{
+		if (flags & READ_BUFFERS_ISSUE_ADVICE)
 		{
-			if (mode == RBM_ZERO_ON_ERROR || zero_damaged_pages)
-			{
-				ereport(WARNING,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s; zeroing out page",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
-				MemSet((char *) bufBlock, 0, BLCKSZ);
-			}
-			else
-				ereport(ERROR,
-						(errcode(ERRCODE_DATA_CORRUPTED),
-						 errmsg("invalid page in block %u of relation %s",
-								blockNum,
-								relpath(smgr->smgr_rlocator, forkNum))));
+			/*
+			 * In theory we should only do this if PrepareReadBuffers() had to
+			 * allocate new buffers above.  That way, if two calls to
+			 * StartReadBuffers() were made for the same blocks before
+			 * WaitReadBuffers(), only the first would issue the advice.
+			 * That'd be a better simulation of true asynchronous I/O, which
+			 * would only start the I/O once, but isn't done here for
+			 * simplicity.  Note also that the following call might actually
+			 * issue two advice calls if we cross a segment boundary; in a
+			 * true asynchronous version we might choose to process only one
+			 * real I/O at a time in that case.
+			 */
+			smgrprefetch(bmr.smgr, forkNum, blockNum, operation->io_buffers_len);
 		}
+
+		/* Indicate that WaitReadBuffers() should be called. */
+		return true;
 	}
+	else
+	{
+		return false;
+	}
+}
 
-	/*
-	 * In RBM_ZERO_AND_LOCK / RBM_ZERO_AND_CLEANUP_LOCK mode, grab the buffer
-	 * content lock before marking the page as valid, to make sure that no
-	 * other backend sees the zeroed page before the caller has had a chance
-	 * to initialize it.
-	 *
-	 * Since no-one else can be looking at the page contents yet, there is no
-	 * difference between an exclusive lock and a cleanup-strength lock. (Note
-	 * that we cannot use LockBuffer() or LockBufferForCleanup() here, because
-	 * they assert that the buffer is already valid.)
-	 */
-	if ((mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK) &&
-		!isLocalBuf)
+static inline bool
+WaitReadBuffersCanStartIO(Buffer buffer, bool nowait)
+{
+	if (BufferIsLocal(buffer))
 	{
-		LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_EXCLUSIVE);
+		BufferDesc *bufHdr = GetLocalBufferDescriptor(-buffer - 1);
+
+		return (pg_atomic_read_u32(&bufHdr->state) & BM_VALID) == 0;
 	}
+	else
+		return StartBufferIO(GetBufferDescriptor(buffer - 1), true, nowait);
+}
+
+void
+WaitReadBuffers(ReadBuffersOperation *operation)
+{
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	int			nblocks;
+	BlockNumber blocknum;
+	ForkNumber	forknum;
+	bool		isLocalBuf;
+	IOContext	io_context;
+	IOObject	io_object;
+
+	/*
+	 * Currently operations are only allowed to include a read of some range,
+	 * with an optional extra buffer that is already pinned at the end.  So
+	 * nblocks can be at most one more than io_buffers_len.
+	 */
+	Assert((operation->nblocks == operation->io_buffers_len) ||
+		   (operation->nblocks == operation->io_buffers_len + 1));
 
+	/* Find the range of the physical read we need to perform. */
+	nblocks = operation->io_buffers_len;
+	if (nblocks == 0)
+		return;					/* nothing to do */
+
+	buffers = &operation->buffers[0];
+	blocknum = operation->blocknum;
+	forknum = operation->forknum;
+	bmr = operation->bmr;
+
+	isLocalBuf = SmgrIsTemp(bmr.smgr);
 	if (isLocalBuf)
 	{
-		/* Only need to adjust flags */
-		uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
-
-		buf_state |= BM_VALID;
-		pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+		io_context = IOCONTEXT_NORMAL;
+		io_object = IOOBJECT_TEMP_RELATION;
 	}
 	else
 	{
-		/* Set BM_VALID, terminate IO, and wake up any waiters */
-		TerminateBufferIO(bufHdr, false, BM_VALID, true);
+		io_context = IOContextForStrategy(operation->strategy);
+		io_object = IOOBJECT_RELATION;
 	}
 
-	VacuumPageMiss++;
-	if (VacuumCostActive)
-		VacuumCostBalance += VacuumCostPageMiss;
+	/*
+	 * We count all these blocks as read by this backend.  This is traditional
+	 * behavior, but might turn out to be not true if we find that someone
+	 * else has beaten us and completed the read of some of these blocks.  In
+	 * that case the system globally double-counts, but we traditionally don't
+	 * count this as a "hit", and we don't have a separate counter for "miss,
+	 * but another backend completed the read".
+	 */
+	if (isLocalBuf)
+		pgBufferUsage.local_blks_read += nblocks;
+	else
+		pgBufferUsage.shared_blks_read += nblocks;
 
-	TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
-									  smgr->smgr_rlocator.locator.spcOid,
-									  smgr->smgr_rlocator.locator.dbOid,
-									  smgr->smgr_rlocator.locator.relNumber,
-									  smgr->smgr_rlocator.backend,
-									  found);
+	for (int i = 0; i < nblocks; ++i)
+	{
+		int			io_buffers_len;
+		Buffer		io_buffers[MAX_BUFFERS_PER_TRANSFER];
+		void	   *io_pages[MAX_BUFFERS_PER_TRANSFER];
+		instr_time	io_start;
+		BlockNumber io_first_block;
 
-	return BufferDescriptorGetBuffer(bufHdr);
+		/*
+		 * Skip this block if someone else has already completed it.  If an
+		 * I/O is already in progress in another backend, this will wait for
+		 * the outcome: either done, or something went wrong and we will
+		 * retry.
+		 */
+		if (!WaitReadBuffersCanStartIO(buffers[i], false))
+		{
+			/*
+			 * Report this as a 'hit' for this backend, even though it must
+			 * have started out as a miss in PrepareReadBuffer().
+			 */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, blocknum + i,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  true);
+			continue;
+		}
+
+		/* We found a buffer that we need to read in. */
+		io_buffers[0] = buffers[i];
+		io_pages[0] = BufferGetBlock(buffers[i]);
+		io_first_block = blocknum + i;
+		io_buffers_len = 1;
+
+		/*
+		 * How many neighboring-on-disk blocks can we can scatter-read into
+		 * other buffers at the same time?  In this case we don't wait if we
+		 * see an I/O already in progress.  We already hold BM_IO_IN_PROGRESS
+		 * for the head block, so we should get on with that I/O as soon as
+		 * possible.  We'll come back to this block again, above.
+		 */
+		while ((i + 1) < nblocks &&
+			   WaitReadBuffersCanStartIO(buffers[i + 1], true))
+		{
+			/* Must be consecutive block numbers. */
+			Assert(BufferGetBlockNumber(buffers[i + 1]) ==
+				   BufferGetBlockNumber(buffers[i]) + 1);
+
+			io_buffers[io_buffers_len] = buffers[++i];
+			io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
+		}
+
+		io_start = pgstat_prepare_io_time(track_io_timing);
+		smgrreadv(bmr.smgr, forknum, io_first_block, io_pages, io_buffers_len);
+		pgstat_count_io_op_time(io_object, io_context, IOOP_READ, io_start,
+								io_buffers_len);
+
+		/* Verify each block we read, and terminate the I/O. */
+		for (int j = 0; j < io_buffers_len; ++j)
+		{
+			BufferDesc *bufHdr;
+			Block		bufBlock;
+
+			if (isLocalBuf)
+			{
+				bufHdr = GetLocalBufferDescriptor(-io_buffers[j] - 1);
+				bufBlock = LocalBufHdrGetBlock(bufHdr);
+			}
+			else
+			{
+				bufHdr = GetBufferDescriptor(io_buffers[j] - 1);
+				bufBlock = BufHdrGetBlock(bufHdr);
+			}
+
+			/* check for garbage data */
+			if (!PageIsVerifiedExtended((Page) bufBlock, io_first_block + j,
+										PIV_LOG_WARNING | PIV_REPORT_STAT))
+			{
+				if ((operation->flags & READ_BUFFERS_ZERO_ON_ERROR) || zero_damaged_pages)
+				{
+					ereport(WARNING,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s; zeroing out page",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+					memset(bufBlock, 0, BLCKSZ);
+				}
+				else
+					ereport(ERROR,
+							(errcode(ERRCODE_DATA_CORRUPTED),
+							 errmsg("invalid page in block %u of relation %s",
+									io_first_block + j,
+									relpath(bmr.smgr->smgr_rlocator, forknum))));
+			}
+
+			/* Terminate I/O and set BM_VALID. */
+			if (isLocalBuf)
+			{
+				uint32		buf_state = pg_atomic_read_u32(&bufHdr->state);
+
+				buf_state |= BM_VALID;
+				pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
+			}
+			else
+			{
+				/* Set BM_VALID, terminate IO, and wake up any waiters */
+				TerminateBufferIO(bufHdr, false, BM_VALID, true);
+			}
+
+			/* Report I/Os as completing individually. */
+			TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, io_first_block + j,
+											  bmr.smgr->smgr_rlocator.locator.spcOid,
+											  bmr.smgr->smgr_rlocator.locator.dbOid,
+											  bmr.smgr->smgr_rlocator.locator.relNumber,
+											  bmr.smgr->smgr_rlocator.backend,
+											  false);
+		}
+
+		VacuumPageMiss += io_buffers_len;
+		if (VacuumCostActive)
+			VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
+	}
 }
 
 /*
- * BufferAlloc -- subroutine for ReadBuffer.  Handles lookup of a shared
- *		buffer.  If no buffer exists already, selects a replacement
- *		victim and evicts the old page, but does NOT read in new page.
+ * BufferAlloc -- subroutine for StartReadBuffers.  Handles lookup of a shared
+ *		buffer.  If no buffer exists already, selects a replacement victim and
+ *		evicts the old page, but does NOT read in new page.
  *
  * "strategy" can be a buffer replacement strategy object, or NULL for
  * the default strategy.  The selected buffer's usage_count is advanced when
@@ -1223,11 +1475,7 @@ ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
  *
  * The returned buffer is pinned and is already marked as holding the
  * desired page.  If it already did have the desired page, *foundPtr is
- * set true.  Otherwise, *foundPtr is set false and the buffer is marked
- * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.
- *
- * *foundPtr is actually redundant with the buffer's BM_VALID flag, but
- * we keep it for simplicity in ReadBuffer.
+ * set true.  Otherwise, *foundPtr is set false.
  *
  * io_context is passed as an output parameter to avoid calling
  * IOContextForStrategy() when there is a shared buffers hit and no IO
@@ -1286,19 +1534,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(buf, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return buf;
@@ -1363,19 +1602,10 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 		{
 			/*
 			 * We can only get here if (a) someone else is still reading in
-			 * the page, or (b) a previous read attempt failed.  We have to
-			 * wait for any active read attempt to finish, and then set up our
-			 * own read attempt if the page is still not BM_VALID.
-			 * StartBufferIO does it all.
+			 * the page, (b) a previous read attempt failed, or (c) someone
+			 * called StartReadBuffers() but not yet WaitReadBuffers().
 			 */
-			if (StartBufferIO(existing_buf_hdr, true))
-			{
-				/*
-				 * If we get here, previous attempts to read the buffer must
-				 * have failed ... but we shall bravely try again.
-				 */
-				*foundPtr = false;
-			}
+			*foundPtr = false;
 		}
 
 		return existing_buf_hdr;
@@ -1407,15 +1637,9 @@ BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
 	LWLockRelease(newPartitionLock);
 
 	/*
-	 * Buffer contents are currently invalid.  Try to obtain the right to
-	 * start I/O.  If StartBufferIO returns false, then someone else managed
-	 * to read it before we did, so there's nothing left for BufferAlloc() to
-	 * do.
+	 * Buffer contents are currently invalid.
 	 */
-	if (StartBufferIO(victim_buf_hdr, true))
-		*foundPtr = false;
-	else
-		*foundPtr = true;
+	*foundPtr = false;
 
 	return victim_buf_hdr;
 }
@@ -1769,7 +1993,7 @@ again:
  * pessimistic, but outside of toy-sized shared_buffers it should allow
  * sufficient pins.
  */
-static void
+void
 LimitAdditionalPins(uint32 *additional_pins)
 {
 	uint32		max_backends;
@@ -2034,7 +2258,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 
 				buf_state &= ~BM_VALID;
 				UnlockBufHdr(existing_hdr, buf_state);
-			} while (!StartBufferIO(existing_hdr, true));
+			} while (!StartBufferIO(existing_hdr, true, false));
 		}
 		else
 		{
@@ -2057,7 +2281,7 @@ ExtendBufferedRelShared(BufferManagerRelation bmr,
 			LWLockRelease(partition_lock);
 
 			/* XXX: could combine the locked operations in it with the above */
-			StartBufferIO(victim_buf_hdr, true);
+			StartBufferIO(victim_buf_hdr, true, false);
 		}
 	}
 
@@ -2372,7 +2596,12 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 	else
 	{
 		/*
-		 * If we previously pinned the buffer, it must surely be valid.
+		 * If we previously pinned the buffer, it is likely to be valid, but
+		 * it may not be if StartReadBuffers() was called and
+		 * WaitReadBuffers() hasn't been called yet.  We'll check by loading
+		 * the flags without locking.  This is racy, but it's OK to return
+		 * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
+		 * it'll see that it's now valid.
 		 *
 		 * Note: We deliberately avoid a Valgrind client request here.
 		 * Individual access methods can optionally superimpose buffer page
@@ -2381,7 +2610,7 @@ PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
 		 * that the buffer page is legitimately non-accessible here.  We
 		 * cannot meddle with that.
 		 */
-		result = true;
+		result = (pg_atomic_read_u32(&buf->state) & BM_VALID) != 0;
 	}
 
 	ref->refcount++;
@@ -3449,7 +3678,7 @@ FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
 	 * someone else flushed the buffer before we could, so we need not do
 	 * anything.
 	 */
-	if (!StartBufferIO(buf, false))
+	if (!StartBufferIO(buf, false, false))
 		return;
 
 	/* Setup error traceback support for ereport() */
@@ -5184,9 +5413,15 @@ WaitIO(BufferDesc *buf)
  *
  * Returns true if we successfully marked the buffer as I/O busy,
  * false if someone else already did the work.
+ *
+ * If nowait is true, then we don't wait for an I/O to be finished by another
+ * backend.  In that case, false indicates either that the I/O was already
+ * finished, or is still in progress.  This is useful for callers that want to
+ * find out if they can perform the I/O as part of a larger operation, without
+ * waiting for the answer or distinguishing the reasons why not.
  */
 static bool
-StartBufferIO(BufferDesc *buf, bool forInput)
+StartBufferIO(BufferDesc *buf, bool forInput, bool nowait)
 {
 	uint32		buf_state;
 
@@ -5199,6 +5434,8 @@ StartBufferIO(BufferDesc *buf, bool forInput)
 		if (!(buf_state & BM_IO_IN_PROGRESS))
 			break;
 		UnlockBufHdr(buf, buf_state);
+		if (nowait)
+			return false;
 		WaitIO(buf);
 	}
 
diff --git a/src/backend/storage/buffer/localbuf.c b/src/backend/storage/buffer/localbuf.c
index fcfac335a57..985a2c7049c 100644
--- a/src/backend/storage/buffer/localbuf.c
+++ b/src/backend/storage/buffer/localbuf.c
@@ -108,10 +108,9 @@ PrefetchLocalBuffer(SMgrRelation smgr, ForkNumber forkNum,
  * LocalBufferAlloc -
  *	  Find or create a local buffer for the given page of the given relation.
  *
- * API is similar to bufmgr.c's BufferAlloc, except that we do not need
- * to do any locking since this is all local.   Also, IO_IN_PROGRESS
- * does not get set.  Lastly, we support only default access strategy
- * (hence, usage_count is always advanced).
+ * API is similar to bufmgr.c's BufferAlloc, except that we do not need to do
+ * any locking since this is all local.  We support only default access
+ * strategy (hence, usage_count is always advanced).
  */
 BufferDesc *
 LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum,
@@ -287,7 +286,7 @@ GetLocalVictimBuffer(void)
 }
 
 /* see LimitAdditionalPins() */
-static void
+void
 LimitAdditionalLocalPins(uint32 *additional_pins)
 {
 	uint32		max_pins;
@@ -297,9 +296,10 @@ LimitAdditionalLocalPins(uint32 *additional_pins)
 
 	/*
 	 * In contrast to LimitAdditionalPins() other backends don't play a role
-	 * here. We can allow up to NLocBuffer pins in total.
+	 * here. We can allow up to NLocBuffer pins in total, but it might not be
+	 * initialized yet so read num_temp_buffers.
 	 */
-	max_pins = (NLocBuffer - NLocalPinnedBuffers);
+	max_pins = (num_temp_buffers - NLocalPinnedBuffers);
 
 	if (*additional_pins >= max_pins)
 		*additional_pins = max_pins;
diff --git a/src/backend/storage/meson.build b/src/backend/storage/meson.build
index 40345bdca27..739d13293fb 100644
--- a/src/backend/storage/meson.build
+++ b/src/backend/storage/meson.build
@@ -1,5 +1,6 @@
 # Copyright (c) 2022-2024, PostgreSQL Global Development Group
 
+subdir('aio')
 subdir('buffer')
 subdir('file')
 subdir('freespace')
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index d51d46d3353..b57f71f97e3 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -14,6 +14,7 @@
 #ifndef BUFMGR_H
 #define BUFMGR_H
 
+#include "port/pg_iovec.h"
 #include "storage/block.h"
 #include "storage/buf.h"
 #include "storage/bufpage.h"
@@ -158,6 +159,11 @@ extern PGDLLIMPORT int32 *LocalRefCount;
 #define BUFFER_LOCK_SHARE		1
 #define BUFFER_LOCK_EXCLUSIVE	2
 
+/*
+ * Maximum number of buffers for multi-buffer I/O functions.  This is set to
+ * allow 128kB transfers, unless BLCKSZ and IOV_MAX imply a a smaller maximum.
+ */
+#define MAX_BUFFERS_PER_TRANSFER Min(PG_IOV_MAX, (128 * 1024) / BLCKSZ)
 
 /*
  * prototypes for functions in bufmgr.c
@@ -177,6 +183,42 @@ extern Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator,
 										ForkNumber forkNum, BlockNumber blockNum,
 										ReadBufferMode mode, BufferAccessStrategy strategy,
 										bool permanent);
+
+#define READ_BUFFERS_ZERO_ON_ERROR 0x01
+#define READ_BUFFERS_ISSUE_ADVICE 0x02
+
+/*
+ * Private state used by StartReadBuffers() and WaitReadBuffers().  Declared
+ * in public header only to allow inclusion in other structs, but contents
+ * should not be accessed.
+ */
+struct ReadBuffersOperation
+{
+	/* Parameters passed in to StartReadBuffers(). */
+	BufferManagerRelation bmr;
+	Buffer	   *buffers;
+	ForkNumber	forknum;
+	BlockNumber blocknum;
+	int			nblocks;
+	BufferAccessStrategy strategy;
+	int			flags;
+
+	/* Range of buffers, if we need to perform a read. */
+	int			io_buffers_len;
+};
+
+typedef struct ReadBuffersOperation ReadBuffersOperation;
+
+extern bool StartReadBuffers(BufferManagerRelation bmr,
+							 Buffer *buffers,
+							 ForkNumber forknum,
+							 BlockNumber blocknum,
+							 int *nblocks,
+							 BufferAccessStrategy strategy,
+							 int flags,
+							 ReadBuffersOperation *operation);
+extern void WaitReadBuffers(ReadBuffersOperation *operation);
+
 extern void ReleaseBuffer(Buffer buffer);
 extern void UnlockReleaseBuffer(Buffer buffer);
 extern bool BufferIsExclusiveLocked(Buffer buffer);
@@ -250,6 +292,9 @@ extern bool HoldingBufferPinThatDelaysRecovery(void);
 
 extern bool BgBufferSync(struct WritebackContext *wb_context);
 
+extern void LimitAdditionalPins(uint32 *additional_pins);
+extern void LimitAdditionalLocalPins(uint32 *additional_pins);
+
 /* in buf_init.c */
 extern void InitBufferPool(void);
 extern Size BufferShmemSize(void);
diff --git a/src/include/storage/streaming_read.h b/src/include/storage/streaming_read.h
new file mode 100644
index 00000000000..c4d3892bb26
--- /dev/null
+++ b/src/include/storage/streaming_read.h
@@ -0,0 +1,52 @@
+#ifndef STREAMING_READ_H
+#define STREAMING_READ_H
+
+#include "storage/bufmgr.h"
+#include "storage/fd.h"
+#include "storage/smgr.h"
+
+/* Default tuning, reasonable for many users. */
+#define PGSR_FLAG_DEFAULT 0x00
+
+/*
+ * I/O streams that are performing maintenance work on behalf of potentially
+ * many users.
+ */
+#define PGSR_FLAG_MAINTENANCE 0x01
+
+/*
+ * We usually avoid issuing prefetch advice automatically when sequential
+ * access is detected, but this flag explicitly disables it, for cases that
+ * might not be correctly detected.  Explicit advice is known to perform worse
+ * than letting the kernel (at least Linux) detect sequential access.
+ */
+#define PGSR_FLAG_SEQUENTIAL 0x02
+
+/*
+ * We usually ramp up from smaller reads to larger ones, to support users who
+ * don't know if it's worth reading lots of buffers yet.  This flag disables
+ * that, declaring ahead of time that we'll be reading all available buffers.
+ */
+#define PGSR_FLAG_FULL 0x04
+
+struct PgStreamingRead;
+typedef struct PgStreamingRead PgStreamingRead;
+
+/* Callback that returns the next block number to read. */
+typedef BlockNumber (*PgStreamingReadBufferCB) (PgStreamingRead *pgsr,
+												void *pgsr_private,
+												void *per_buffer_private);
+
+extern PgStreamingRead *pg_streaming_read_buffer_alloc(int flags,
+													   void *pgsr_private,
+													   size_t per_buffer_private_size,
+													   BufferAccessStrategy strategy,
+													   BufferManagerRelation bmr,
+													   ForkNumber forknum,
+													   PgStreamingReadBufferCB next_block_cb);
+
+extern void pg_streaming_read_prefetch(PgStreamingRead *pgsr);
+extern Buffer pg_streaming_read_buffer_get_next(PgStreamingRead *pgsr, void **per_buffer_private);
+extern void pg_streaming_read_free(PgStreamingRead *pgsr);
+
+#endif
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index d3a7f75b080..299c77ea69f 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2097,6 +2097,8 @@ PgStat_TableCounts
 PgStat_TableStatus
 PgStat_TableXactStatus
 PgStat_WalStats
+PgStreamingRead
+PgStreamingReadRange
 PgXmlErrorContext
 PgXmlStrictness
 Pg_finfo_record
@@ -2267,6 +2269,7 @@ ReInitializeDSMForeignScan_function
 ReScanForeignScan_function
 ReadBufPtrType
 ReadBufferMode
+ReadBuffersOperation
 ReadBytePtrType
 ReadExtraTocPtrType
 ReadFunc
-- 
2.40.1



  [text/x-patch] v10-0003-Vacuum-second-pass-uses-Streaming-Read-interface.patch (8.5K, ../../CAAKRu_byDppRvNJ+p5kq-SmXZDQuL6L8N6D06pHbO6WnBnanWQ@mail.gmail.com/3-v10-0003-Vacuum-second-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From 376edc13c9b03c80dd398c48b68d50a207aed099 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 27 Feb 2024 14:35:36 -0500
Subject: [PATCH v10 3/3] Vacuum second pass uses Streaming Read interface

Now vacuum's second pass, which removes dead items referring to dead
tuples catalogued in the first pass, uses the streaming read API by
implementing a streaming read callback which returns the next block
containing previously catalogued dead items. A new struct,
VacReapBlkState, is introduced to provide the caller with the starting
and ending indexes of dead items to vacuum.
---
 src/backend/access/heap/vacuumlazy.c | 109 ++++++++++++++++++++-------
 src/tools/pgindent/typedefs.list     |   1 +
 2 files changed, 84 insertions(+), 26 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index a83727f0c7d..4744b1c6e21 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -190,6 +190,12 @@ typedef struct LVRelState
 	BlockNumber missed_dead_pages;	/* # pages with missed dead tuples */
 	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
 
+	/*
+	 * The index of the next TID in dead_items to reap during the second
+	 * vacuum pass.
+	 */
+	int			idx_prefetch;
+
 	/* Statistics output by us, for table */
 	double		new_rel_tuples; /* new estimated total # of tuples */
 	double		new_live_tuples;	/* new estimated total # of live tuples */
@@ -221,6 +227,20 @@ typedef struct LVSavedErrInfo
 	VacErrPhase phase;
 } LVSavedErrInfo;
 
+/*
+ * State set up in streaming read callback during vacuum's second pass which
+ * removes dead items referring to dead tuples catalogued in the first pass
+ */
+typedef struct VacReapBlkState
+{
+	/*
+	 * The indexes of the TIDs of the first and last dead tuples in a single
+	 * block in the currently vacuumed relation. The callback will set these
+	 * up prior to adding this block to the stream.
+	 */
+	int			start_idx;
+	int			end_idx;
+} VacReapBlkState;
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
@@ -240,8 +260,9 @@ static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
 static void lazy_vacuum(LVRelState *vacrel);
 static bool lazy_vacuum_all_indexes(LVRelState *vacrel);
 static void lazy_vacuum_heap_rel(LVRelState *vacrel);
-static int	lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
-								  Buffer buffer, int index, Buffer vmbuffer);
+static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+								  Buffer buffer, Buffer vmbuffer,
+								  VacReapBlkState *rbstate);
 static bool lazy_check_wraparound_failsafe(LVRelState *vacrel);
 static void lazy_cleanup_all_indexes(LVRelState *vacrel);
 static IndexBulkDeleteResult *lazy_vacuum_one_index(Relation indrel,
@@ -2400,6 +2421,37 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_pgsr_next(PgStreamingRead *pgsr,
+						 void *pgsr_private,
+						 void *per_buffer_data)
+{
+	BlockNumber blkno;
+	LVRelState *vacrel = pgsr_private;
+	VacReapBlkState *rbstate = per_buffer_data;
+
+	VacDeadItems *dead_items = vacrel->dead_items;
+
+	if (vacrel->idx_prefetch == dead_items->num_items)
+		return InvalidBlockNumber;
+
+	blkno = ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+	rbstate->start_idx = vacrel->idx_prefetch;
+
+	for (; vacrel->idx_prefetch < dead_items->num_items; vacrel->idx_prefetch++)
+	{
+		BlockNumber curblkno =
+			ItemPointerGetBlockNumber(&dead_items->items[vacrel->idx_prefetch]);
+
+		if (blkno != curblkno)
+			break;				/* past end of tuples for this block */
+	}
+
+	rbstate->end_idx = vacrel->idx_prefetch;
+
+	return blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2421,7 +2473,9 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
-	int			index = 0;
+	Buffer		buf;
+	PgStreamingRead *pgsr;
+	VacReapBlkState *rbstate;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2439,17 +2493,21 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 VACUUM_ERRCB_PHASE_VACUUM_HEAP,
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
-	while (index < vacrel->dead_items->num_items)
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(VacReapBlkState), vacrel->bstrategy, BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM, vacuum_reap_lp_pgsr_next);
+
+	while (BufferIsValid(buf =
+						 pg_streaming_read_buffer_get_next(pgsr,
+														   (void **) &rbstate)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 
 		vacuum_delay_point();
 
-		blkno = ItemPointerGetBlockNumber(&vacrel->dead_items->items[index]);
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		/*
 		 * Pin the visibility map page in case we need to mark the page
@@ -2459,10 +2517,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
-		index = lazy_vacuum_heap_page(vacrel, blkno, buf, index, vmbuffer);
+		lazy_vacuum_heap_page(vacrel, blkno, buf, vmbuffer, rbstate);
 
 		/* Now that we've vacuumed the page, record its available space */
 		page = BufferGetPage(buf);
@@ -2481,14 +2537,16 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 	 * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
 	 * the second heap pass.  No more, no less.
 	 */
-	Assert(index > 0);
+	Assert(rbstate->end_idx > 0);
 	Assert(vacrel->num_index_scans > 1 ||
-		   (index == vacrel->lpdead_items &&
+		   (rbstate->end_idx == vacrel->lpdead_items &&
 			vacuumed_pages == vacrel->lpdead_item_pages));
 
+	pg_streaming_read_free(pgsr);
+
 	ereport(DEBUG2,
 			(errmsg("table \"%s\": removed %lld dead item identifiers in %u pages",
-					vacrel->relname, (long long) index, vacuumed_pages)));
+					vacrel->relname, (long long) rbstate->end_idx, vacuumed_pages)));
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
@@ -2502,13 +2560,12 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
  * cleanup lock is also acceptable).  vmbuffer must be valid and already have
  * a pin on blkno's visibility map page.
  *
- * index is an offset into the vacrel->dead_items array for the first listed
- * LP_DEAD item on the page.  The return value is the first index immediately
- * after all LP_DEAD items for the same page in the array.
+ * Given a block and dead items recorded during the first pass, set those items
+ * dead and truncate the line pointer array. Update the VM as appropriate.
  */
-static int
-lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
-					  int index, Buffer vmbuffer)
+static void
+lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
+					  Buffer buffer, Buffer vmbuffer, VacReapBlkState *rbstate)
 {
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Page		page = BufferGetPage(buffer);
@@ -2529,16 +2586,17 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	START_CRIT_SECTION();
 
-	for (; index < dead_items->num_items; index++)
+	for (int i = rbstate->start_idx; i < rbstate->end_idx; i++)
 	{
-		BlockNumber tblk;
 		OffsetNumber toff;
+		ItemPointer dead_item;
 		ItemId		itemid;
 
-		tblk = ItemPointerGetBlockNumber(&dead_items->items[index]);
-		if (tblk != blkno)
-			break;				/* past end of tuples for this block */
-		toff = ItemPointerGetOffsetNumber(&dead_items->items[index]);
+		dead_item = &dead_items->items[i];
+
+		Assert(ItemPointerGetBlockNumber(dead_item) == blkno);
+
+		toff = ItemPointerGetOffsetNumber(dead_item);
 		itemid = PageGetItemId(page, toff);
 
 		Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
@@ -2608,7 +2666,6 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
 
 	/* Revert to the previous phase information for error traceback */
 	restore_vacuum_error_info(vacrel, &saved_err_info);
-	return index;
 }
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 299c77ea69f..f4cfbce70b9 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2973,6 +2973,7 @@ VacOptValue
 VacuumParams
 VacuumRelation
 VacuumStmt
+VacReapBlkState
 ValidIOData
 ValidateIndexState
 ValuesScan
-- 
2.40.1



  [text/x-patch] v10-0002-Vacuum-first-pass-uses-Streaming-Read-interface.patch (8.2K, ../../CAAKRu_byDppRvNJ+p5kq-SmXZDQuL6L8N6D06pHbO6WnBnanWQ@mail.gmail.com/4-v10-0002-Vacuum-first-pass-uses-Streaming-Read-interface.patch)
  download | inline diff:
From 04ce6a6e22d28cdf6e44a6fb7a8abe85abaca4e8 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Mon, 11 Mar 2024 16:19:56 -0400
Subject: [PATCH v10 2/3] Vacuum first pass uses Streaming Read interface

Now vacuum's first pass, which HOT prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by converting
heap_vac_scan_next_block() to a streaming read callback.
---
 src/backend/access/heap/vacuumlazy.c | 75 ++++++++++++++++------------
 1 file changed, 44 insertions(+), 31 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 18004907750..a83727f0c7d 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -54,6 +54,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/streaming_read.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/pg_rusage.h"
@@ -223,8 +224,8 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm);
+static BlockNumber heap_vac_scan_next_block(PgStreamingRead *pgsr,
+											void *pgsr_private, void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -806,10 +807,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
+	PgStreamingRead *pgsr;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm;
 
 	VacDeadItems *dead_items = vacrel->dead_items;
 	Buffer		vmbuffer = InvalidBuffer;
@@ -826,19 +828,31 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items->max_items;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	pgsr = pg_streaming_read_buffer_alloc(PGSR_FLAG_MAINTENANCE, vacrel,
+										  sizeof(bool), vacrel->bstrategy,
+										  BMR_REL(vacrel->rel),
+										  MAIN_FORKNUM,
+										  heap_vac_scan_next_block);
+
 	/* Initialize for the first heap_vac_scan_next_block() call */
 	vacrel->current_block = InvalidBlockNumber;
 	vacrel->next_unskippable_block = InvalidBlockNumber;
 	vacrel->next_unskippable_allvis = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
+	while (BufferIsValid(buf = pg_streaming_read_buffer_get_next(pgsr,
+																 (void **) &all_visible_according_to_vm)))
 	{
-		Buffer		buf;
+		BlockNumber blkno;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -905,10 +919,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -964,7 +974,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1018,7 +1028,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		ReleaseBuffer(vmbuffer);
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1033,6 +1043,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	pg_streaming_read_free(pgsr);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1044,11 +1056,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1058,14 +1070,14 @@ lazy_scan_heap(LVRelState *vacrel)
 /*
  *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
+ * The streaming read callback invokes heap_vac_scan_next_block() every time
+ * lazy_scan_heap() needs the next block to prune and vacuum.  The function
+ * uses the visibility map, vacuum options, and various thresholds to skip
+ * blocks which do not need to be processed and returns the next block to
+ * process or InvalidBlockNumber if there are no remaining blocks.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process.
+ * The visibility status of the next block to process is set in the
+ * per_buffer_data.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1073,11 +1085,13 @@ lazy_scan_heap(LVRelState *vacrel)
  * relfrozenxid in that case.  vacrel also holds information about the next
  * unskippable block, as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm)
+static BlockNumber
+heap_vac_scan_next_block(PgStreamingRead *pgsr,
+						 void *pgsr_private, void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = pgsr_private;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1090,8 +1104,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1140,9 +1153,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = true;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1152,9 +1165,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.40.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-03-17 06:53                     ` Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2024-03-17 06:53 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Tue, Mar 12, 2024 at 10:03 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> I've rebased the attached v10 over top of the changes to
> lazy_scan_heap() Heikki just committed and over the v6 streaming read
> patch set. I started testing them and see that you are right, we no
> longer pin too many buffers. However, the uncached example below is
> now slower with streaming read than on master -- it looks to be
> because it is doing twice as many WAL writes and syncs. I'm still
> investigating why that is.

That makes sense to me.  We have 256kB of buffers in our ring, but now
we're trying to read ahead 128kB at a time, so it works out that we
can only flush the WAL accumulated while dirtying half the blocks at a
time, so we flush twice as often.

If I change the ring size to 384kB, allowing for that read-ahead
window, I see approximately the same WAL flushes.  Surely we'd never
be able to get the behaviour to match *and* keep the same ring size?
We simply need those 16 extra buffers to have a chance of accumulating
32 dirty buffers, and the associated WAL.  Do you see the same result,
or do you think something more than that is wrong here?

Here are some system call traces using your test that helped me see
the behaviour:

1. Unpatched, ie no streaming read, we flush 90kB of WAL generated by
32 pages before we write them out one at a time just before we read in
their replacements.  One flush covers the LSNs of all the pages that
will be written, even though it's only called for the first page to be
written.  That's because XLogFlush(lsn), if it decides to do anything,
flushes as far as it can... IOW when we hit the *oldest* dirty block,
that's when we write out the WAL up to where we dirtied the *newest*
block, which covers the 32 pwrite() calls here:

pwrite(30,...,90112,0xf90000) = 90112 (0x16000)
fdatasync(30) = 0 (0x0)
pwrite(27,...,8192,0x0) = 8192 (0x2000)
pread(27,...,8192,0x40000) = 8192 (0x2000)
pwrite(27,...,8192,0x2000) = 8192 (0x2000)
pread(27,...,8192,0x42000) = 8192 (0x2000)
pwrite(27,...,8192,0x4000) = 8192 (0x2000)
pread(27,...,8192,0x44000) = 8192 (0x2000)
pwrite(27,...,8192,0x6000) = 8192 (0x2000)
pread(27,...,8192,0x46000) = 8192 (0x2000)
pwrite(27,...,8192,0x8000) = 8192 (0x2000)
pread(27,...,8192,0x48000) = 8192 (0x2000)
pwrite(27,...,8192,0xa000) = 8192 (0x2000)
pread(27,...,8192,0x4a000) = 8192 (0x2000)
pwrite(27,...,8192,0xc000) = 8192 (0x2000)
pread(27,...,8192,0x4c000) = 8192 (0x2000)
pwrite(27,...,8192,0xe000) = 8192 (0x2000)
pread(27,...,8192,0x4e000) = 8192 (0x2000)
pwrite(27,...,8192,0x10000) = 8192 (0x2000)
pread(27,...,8192,0x50000) = 8192 (0x2000)
pwrite(27,...,8192,0x12000) = 8192 (0x2000)
pread(27,...,8192,0x52000) = 8192 (0x2000)
pwrite(27,...,8192,0x14000) = 8192 (0x2000)
pread(27,...,8192,0x54000) = 8192 (0x2000)
pwrite(27,...,8192,0x16000) = 8192 (0x2000)
pread(27,...,8192,0x56000) = 8192 (0x2000)
pwrite(27,...,8192,0x18000) = 8192 (0x2000)
pread(27,...,8192,0x58000) = 8192 (0x2000)
pwrite(27,...,8192,0x1a000) = 8192 (0x2000)
pread(27,...,8192,0x5a000) = 8192 (0x2000)
pwrite(27,...,8192,0x1c000) = 8192 (0x2000)
pread(27,...,8192,0x5c000) = 8192 (0x2000)
pwrite(27,...,8192,0x1e000) = 8192 (0x2000)
pread(27,...,8192,0x5e000) = 8192 (0x2000)
pwrite(27,...,8192,0x20000) = 8192 (0x2000)
pread(27,...,8192,0x60000) = 8192 (0x2000)
pwrite(27,...,8192,0x22000) = 8192 (0x2000)
pread(27,...,8192,0x62000) = 8192 (0x2000)
pwrite(27,...,8192,0x24000) = 8192 (0x2000)
pread(27,...,8192,0x64000) = 8192 (0x2000)
pwrite(27,...,8192,0x26000) = 8192 (0x2000)
pread(27,...,8192,0x66000) = 8192 (0x2000)
pwrite(27,...,8192,0x28000) = 8192 (0x2000)
pread(27,...,8192,0x68000) = 8192 (0x2000)
pwrite(27,...,8192,0x2a000) = 8192 (0x2000)
pread(27,...,8192,0x6a000) = 8192 (0x2000)
pwrite(27,...,8192,0x2c000) = 8192 (0x2000)
pread(27,...,8192,0x6c000) = 8192 (0x2000)
pwrite(27,...,8192,0x2e000) = 8192 (0x2000)
pread(27,...,8192,0x6e000) = 8192 (0x2000)
pwrite(27,...,8192,0x30000) = 8192 (0x2000)
pread(27,...,8192,0x70000) = 8192 (0x2000)
pwrite(27,...,8192,0x32000) = 8192 (0x2000)
pread(27,...,8192,0x72000) = 8192 (0x2000)
pwrite(27,...,8192,0x34000) = 8192 (0x2000)
pread(27,...,8192,0x74000) = 8192 (0x2000)
pwrite(27,...,8192,0x36000) = 8192 (0x2000)
pread(27,...,8192,0x76000) = 8192 (0x2000)
pwrite(27,...,8192,0x38000) = 8192 (0x2000)
pread(27,...,8192,0x78000) = 8192 (0x2000)
pwrite(27,...,8192,0x3a000) = 8192 (0x2000)
pread(27,...,8192,0x7a000) = 8192 (0x2000)
pwrite(27,...,8192,0x3c000) = 8192 (0x2000)
pread(27,...,8192,0x7c000) = 8192 (0x2000)
pwrite(27,...,8192,0x3e000) = 8192 (0x2000)
pread(27,...,8192,0x7e000) = 8192 (0x2000)

(Digression: this alternative tail-write-head-read pattern defeats the
read-ahead and write-behind on a bunch of OSes, but not Linux because
it only seems to worry about the reads, while other Unixes have
write-behind detection too, and I believe at least some are confused
by this pattern of tiny writes following along some distance behind
tiny reads; Andrew Gierth figured that out after noticing poor ring
buffer performance, and we eventually got that fixed for one such
system[1], separating the sequence detection for reads and writes.)

2. With your patches, we replace all those little pread calls with
nice wide calls, yay!, but now we only manage to write out about half
the amount of WAL at a time as you discovered.  The repeating blocks
of system calls now look like this, but there are twice as many of
them:

pwrite(32,...,40960,0x224000) = 40960 (0xa000)
fdatasync(32) = 0 (0x0)
pwrite(27,...,8192,0x5c000) = 8192 (0x2000)
preadv(27,[...],3,0x7e000) = 131072 (0x20000)
pwrite(27,...,8192,0x5e000) = 8192 (0x2000)
pwrite(27,...,8192,0x60000) = 8192 (0x2000)
pwrite(27,...,8192,0x62000) = 8192 (0x2000)
pwrite(27,...,8192,0x64000) = 8192 (0x2000)
pwrite(27,...,8192,0x66000) = 8192 (0x2000)
pwrite(27,...,8192,0x68000) = 8192 (0x2000)
pwrite(27,...,8192,0x6a000) = 8192 (0x2000)
pwrite(27,...,8192,0x6c000) = 8192 (0x2000)
pwrite(27,...,8192,0x6e000) = 8192 (0x2000)
pwrite(27,...,8192,0x70000) = 8192 (0x2000)
pwrite(27,...,8192,0x72000) = 8192 (0x2000)
pwrite(27,...,8192,0x74000) = 8192 (0x2000)
pwrite(27,...,8192,0x76000) = 8192 (0x2000)
pwrite(27,...,8192,0x78000) = 8192 (0x2000)
pwrite(27,...,8192,0x7a000) = 8192 (0x2000)

3. With your patches and test but this time using VACUUM
(BUFFER_USAGE_LIMIT = '384kB'), the repeating block grows bigger and
we get the larger WAL flushes back again, because now we're able to
collect 32 blocks' worth of WAL up front again:

pwrite(32,...,90112,0x50c000) = 90112 (0x16000)
fdatasync(32) = 0 (0x0)
pwrite(27,...,8192,0x1dc000) = 8192 (0x2000)
pread(27,...,131072,0x21e000) = 131072 (0x20000)
pwrite(27,...,8192,0x1de000) = 8192 (0x2000)
pwrite(27,...,8192,0x1e0000) = 8192 (0x2000)
pwrite(27,...,8192,0x1e2000) = 8192 (0x2000)
pwrite(27,...,8192,0x1e4000) = 8192 (0x2000)
pwrite(27,...,8192,0x1e6000) = 8192 (0x2000)
pwrite(27,...,8192,0x1e8000) = 8192 (0x2000)
pwrite(27,...,8192,0x1ea000) = 8192 (0x2000)
pwrite(27,...,8192,0x1ec000) = 8192 (0x2000)
pwrite(27,...,8192,0x1ee000) = 8192 (0x2000)
pwrite(27,...,8192,0x1f0000) = 8192 (0x2000)
pwrite(27,...,8192,0x1f2000) = 8192 (0x2000)
pwrite(27,...,8192,0x1f4000) = 8192 (0x2000)
pwrite(27,...,8192,0x1f6000) = 8192 (0x2000)
pwrite(27,...,8192,0x1f8000) = 8192 (0x2000)
pwrite(27,...,8192,0x1fa000) = 8192 (0x2000)
pwrite(27,...,8192,0x1fc000) = 8192 (0x2000)
preadv(27,[...],3,0x23e000) = 131072 (0x20000)
pwrite(27,...,8192,0x1fe000) = 8192 (0x2000)
pwrite(27,...,8192,0x200000) = 8192 (0x2000)
pwrite(27,...,8192,0x202000) = 8192 (0x2000)
pwrite(27,...,8192,0x204000) = 8192 (0x2000)
pwrite(27,...,8192,0x206000) = 8192 (0x2000)
pwrite(27,...,8192,0x208000) = 8192 (0x2000)
pwrite(27,...,8192,0x20a000) = 8192 (0x2000)
pwrite(27,...,8192,0x20c000) = 8192 (0x2000)
pwrite(27,...,8192,0x20e000) = 8192 (0x2000)
pwrite(27,...,8192,0x210000) = 8192 (0x2000)
pwrite(27,...,8192,0x212000) = 8192 (0x2000)
pwrite(27,...,8192,0x214000) = 8192 (0x2000)
pwrite(27,...,8192,0x216000) = 8192 (0x2000)
pwrite(27,...,8192,0x218000) = 8192 (0x2000)
pwrite(27,...,8192,0x21a000) = 8192 (0x2000)

4. For learning/exploration only, I rebased my experimental vectored
FlushBuffers() patch, which teaches the checkpointer to write relation
data out using smgrwritev().  The checkpointer explicitly sorts
blocks, but I think ring buffers should naturally often contain
consecutive blocks in ring order.  Highly experimental POC code pushed
to a public branch[2], but I am not proposing anything here, just
trying to understand things.  The nicest looking system call trace was
with BUFFER_USAGE_LIMIT set to 512kB, so it could do its writes, reads
and WAL writes 128kB at a time:

pwrite(32,...,131072,0xfc6000) = 131072 (0x20000)
fdatasync(32) = 0 (0x0)
pwrite(27,...,131072,0x6c0000) = 131072 (0x20000)
pread(27,...,131072,0x73e000) = 131072 (0x20000)
pwrite(27,...,131072,0x6e0000) = 131072 (0x20000)
pread(27,...,131072,0x75e000) = 131072 (0x20000)
pwritev(27,[...],3,0x77e000) = 131072 (0x20000)
preadv(27,[...],3,0x77e000) = 131072 (0x20000)

That was a fun experiment, but... I recognise that efficient cleaning
of ring buffers is a Hard Problem requiring more concurrency: it's
just too late to be flushing that WAL.  But we also don't want to
start writing back data immediately after dirtying pages (cf. OS
write-behind for big sequential writes in traditional Unixes), because
we're not allowed to write data out without writing the WAL first and
we currently need to build up bigger WAL writes to do so efficiently
(cf. some other systems that can write out fragments of WAL
concurrently so the latency-vs-throughput trade-off doesn't have to be
so extreme).  So we want to defer writing it, but not too long.  We
need something cleaning our buffers (or at least flushing the
associated WAL, but preferably also writing the data) not too late and
not too early, and more in sync with our scan than the WAL writer is.
What that machinery should look like I don't know (but I believe
Andres has ideas).

[1] https://github.com/freebsd/freebsd-src/commit/f2706588730a5d3b9a687ba8d4269e386650cc4f
[2] https://github.com/macdice/postgres/tree/vectored-ring-buffer





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2024-06-28 21:36                       ` Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2024-06-28 21:36 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Mar 17, 2024 at 2:53 AM Thomas Munro <thomas.munro@gmail.com> wrote:
>
> On Tue, Mar 12, 2024 at 10:03 AM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> > I've rebased the attached v10 over top of the changes to
> > lazy_scan_heap() Heikki just committed and over the v6 streaming read
> > patch set. I started testing them and see that you are right, we no
> > longer pin too many buffers. However, the uncached example below is
> > now slower with streaming read than on master -- it looks to be
> > because it is doing twice as many WAL writes and syncs. I'm still
> > investigating why that is.

--snip--

> 4. For learning/exploration only, I rebased my experimental vectored
> FlushBuffers() patch, which teaches the checkpointer to write relation
> data out using smgrwritev().  The checkpointer explicitly sorts
> blocks, but I think ring buffers should naturally often contain
> consecutive blocks in ring order.  Highly experimental POC code pushed
> to a public branch[2], but I am not proposing anything here, just
> trying to understand things.  The nicest looking system call trace was
> with BUFFER_USAGE_LIMIT set to 512kB, so it could do its writes, reads
> and WAL writes 128kB at a time:
>
> pwrite(32,...,131072,0xfc6000) = 131072 (0x20000)
> fdatasync(32) = 0 (0x0)
> pwrite(27,...,131072,0x6c0000) = 131072 (0x20000)
> pread(27,...,131072,0x73e000) = 131072 (0x20000)
> pwrite(27,...,131072,0x6e0000) = 131072 (0x20000)
> pread(27,...,131072,0x75e000) = 131072 (0x20000)
> pwritev(27,[...],3,0x77e000) = 131072 (0x20000)
> preadv(27,[...],3,0x77e000) = 131072 (0x20000)
>
> That was a fun experiment, but... I recognise that efficient cleaning
> of ring buffers is a Hard Problem requiring more concurrency: it's
> just too late to be flushing that WAL.  But we also don't want to
> start writing back data immediately after dirtying pages (cf. OS
> write-behind for big sequential writes in traditional Unixes), because
> we're not allowed to write data out without writing the WAL first and
> we currently need to build up bigger WAL writes to do so efficiently
> (cf. some other systems that can write out fragments of WAL
> concurrently so the latency-vs-throughput trade-off doesn't have to be
> so extreme).  So we want to defer writing it, but not too long.  We
> need something cleaning our buffers (or at least flushing the
> associated WAL, but preferably also writing the data) not too late and
> not too early, and more in sync with our scan than the WAL writer is.
> What that machinery should look like I don't know (but I believe
> Andres has ideas).

I've attached a WIP v11 streaming vacuum patch set here that is
rebased over master (by Thomas), so that I could add a CF entry for
it. It still has the problem with the extra WAL write and fsync calls
investigated by Thomas above. Thomas has some work in progress doing
streaming write-behind to alleviate the issues with the buffer access
strategy and streaming reads. When he gets a version of that ready to
share, he will start a new "Streaming Vacuum" thread.

- Melanie

Attachments:

  [text/x-patch] v11-0002-Refactor-tidstore.c-memory-management.patch (8.5K, ../../CAAKRu_bbkmwAzSBgnezancgJeXrQZXy4G4kBTd+5=cr86H5yew@mail.gmail.com/2-v11-0002-Refactor-tidstore.c-memory-management.patch)
  download | inline diff:
From 050b6c3fa73c9153aeef58fcd306533c1008802e Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Fri, 26 Apr 2024 08:32:44 +1200
Subject: [PATCH v11 2/3] Refactor tidstore.c memory management.

Previously, TidStoreIterateNext() would expand the set of offsets for
each block into a buffer that it overwrote each time.  In order to be
able to collect the offsets for multiple blocks before working with
them, change the contract.  Now, the offsets are obtained by a separate
call to TidStoreGetBlockOffsets(), which can be called at a later time,
and TidStoreIteratorResult objects are safe to copy and store in a
queue.

This will be used by a later patch, to avoid the need for expensive
extra copies of offset array and associated memory management.
---
 src/backend/access/common/tidstore.c          | 68 +++++++++----------
 src/backend/access/heap/vacuumlazy.c          |  9 ++-
 src/include/access/tidstore.h                 | 12 ++--
 .../modules/test_tidstore/test_tidstore.c     |  9 ++-
 4 files changed, 53 insertions(+), 45 deletions(-)

diff --git a/src/backend/access/common/tidstore.c b/src/backend/access/common/tidstore.c
index fb3949d69f6..c3c1987204b 100644
--- a/src/backend/access/common/tidstore.c
+++ b/src/backend/access/common/tidstore.c
@@ -147,9 +147,6 @@ struct TidStoreIter
 	TidStoreIterResult output;
 };
 
-static void tidstore_iter_extract_tids(TidStoreIter *iter, BlockNumber blkno,
-									   BlocktableEntry *page);
-
 /*
  * Create a TidStore. The TidStore will live in the memory context that is
  * CurrentMemoryContext at the time of this call. The TID storage, backed
@@ -486,13 +483,6 @@ TidStoreBeginIterate(TidStore *ts)
 	iter = palloc0(sizeof(TidStoreIter));
 	iter->ts = ts;
 
-	/*
-	 * We start with an array large enough to contain at least the offsets
-	 * from one completely full bitmap element.
-	 */
-	iter->output.max_offset = 2 * BITS_PER_BITMAPWORD;
-	iter->output.offsets = palloc(sizeof(OffsetNumber) * iter->output.max_offset);
-
 	if (TidStoreIsShared(ts))
 		iter->tree_iter.shared = shared_ts_begin_iterate(ts->tree.shared);
 	else
@@ -503,9 +493,9 @@ TidStoreBeginIterate(TidStore *ts)
 
 
 /*
- * Scan the TidStore and return the TIDs of the next block. The offsets in
- * each iteration result are ordered, as are the block numbers over all
- * iterations.
+ * Return a result that contains the next block number and that can be used to
+ * obtain the set of offsets by calling TidStoreGetBlockOffsets().  The result
+ * is copyable.
  */
 TidStoreIterResult *
 TidStoreIterateNext(TidStoreIter *iter)
@@ -521,10 +511,10 @@ TidStoreIterateNext(TidStoreIter *iter)
 	if (page == NULL)
 		return NULL;
 
-	/* Collect TIDs from the key-value pair */
-	tidstore_iter_extract_tids(iter, (BlockNumber) key, page);
+	iter->output.blkno = key;
+	iter->output.internal_page = page;
 
-	return &(iter->output);
+	return &iter->output;
 }
 
 /*
@@ -540,7 +530,6 @@ TidStoreEndIterate(TidStoreIter *iter)
 	else
 		local_ts_end_iterate(iter->tree_iter.local);
 
-	pfree(iter->output.offsets);
 	pfree(iter);
 }
 
@@ -575,16 +564,19 @@ TidStoreGetHandle(TidStore *ts)
 	return (dsa_pointer) shared_ts_get_handle(ts->tree.shared);
 }
 
-/* Extract TIDs from the given key-value pair */
-static void
-tidstore_iter_extract_tids(TidStoreIter *iter, BlockNumber blkno,
-						   BlocktableEntry *page)
+/*
+ * Given a TidStoreIterResult returned by TidStoreIterateNext(), extract the
+ * offset numbers.  Returns the number of offsets filled in, if <=
+ * max_offsets.  Otherwise, fills in as much as it can in the given space, and
+ * returns the size of the buffer that would be needed.
+ */
+int
+TidStoreGetBlockOffsets(TidStoreIterResult *result,
+						OffsetNumber *offsets,
+						int max_offsets)
 {
-	TidStoreIterResult *result = (&iter->output);
-	int			wordnum;
-
-	result->num_offsets = 0;
-	result->blkno = blkno;
+	BlocktableEntry *page = result->internal_page;
+	int			num_offsets = 0;
 
 	if (page->header.nwords == 0)
 	{
@@ -592,31 +584,33 @@ tidstore_iter_extract_tids(TidStoreIter *iter, BlockNumber blkno,
 		for (int i = 0; i < NUM_FULL_OFFSETS; i++)
 		{
 			if (page->header.full_offsets[i] != InvalidOffsetNumber)
-				result->offsets[result->num_offsets++] = page->header.full_offsets[i];
+			{
+				if (num_offsets < max_offsets)
+					offsets[num_offsets] = page->header.full_offsets[i];
+				num_offsets++;
+			}
 		}
 	}
 	else
 	{
-		for (wordnum = 0; wordnum < page->header.nwords; wordnum++)
+		for (int wordnum = 0; wordnum < page->header.nwords; wordnum++)
 		{
 			bitmapword	w = page->words[wordnum];
 			int			off = wordnum * BITS_PER_BITMAPWORD;
 
-			/* Make sure there is enough space to add offsets */
-			if ((result->num_offsets + BITS_PER_BITMAPWORD) > result->max_offset)
-			{
-				result->max_offset *= 2;
-				result->offsets = repalloc(result->offsets,
-										   sizeof(OffsetNumber) * result->max_offset);
-			}
-
 			while (w != 0)
 			{
 				if (w & 1)
-					result->offsets[result->num_offsets++] = (OffsetNumber) off;
+				{
+					if (num_offsets < max_offsets)
+						offsets[num_offsets] = (OffsetNumber) off;
+					num_offsets++;
+				}
 				off++;
 				w >>= 1;
 			}
 		}
 	}
+
+	return num_offsets;
 }
diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index f76ef2e7c63..19c13671666 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2144,12 +2144,17 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		Buffer		buf;
 		Page		page;
 		Size		freespace;
+		OffsetNumber offsets[MaxOffsetNumber];
+		int			num_offsets;
 
 		vacuum_delay_point();
 
 		blkno = iter_result->blkno;
 		vacrel->blkno = blkno;
 
+		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
+		Assert(num_offsets <= lengthof(offsets));
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -2161,8 +2166,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
 								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
-		lazy_vacuum_heap_page(vacrel, blkno, buf, iter_result->offsets,
-							  iter_result->num_offsets, vmbuffer);
+		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
+							  num_offsets, vmbuffer);
 
 		/* Now that we've vacuumed the page, record its available space */
 		page = BufferGetPage(buf);
diff --git a/src/include/access/tidstore.h b/src/include/access/tidstore.h
index 32aa9995193..d95cabd7b5e 100644
--- a/src/include/access/tidstore.h
+++ b/src/include/access/tidstore.h
@@ -20,13 +20,14 @@
 typedef struct TidStore TidStore;
 typedef struct TidStoreIter TidStoreIter;
 
-/* Result struct for TidStoreIterateNext */
+/*
+ * Result struct for TidStoreIterateNext.  This is copyable, but should be
+ * treated as opaque.  Call TidStoreGetOffsets() to obtain the offsets.
+ */
 typedef struct TidStoreIterResult
 {
 	BlockNumber blkno;
-	int			max_offset;
-	int			num_offsets;
-	OffsetNumber *offsets;
+	void	   *internal_page;
 } TidStoreIterResult;
 
 extern TidStore *TidStoreCreateLocal(size_t max_bytes, bool insert_only);
@@ -42,6 +43,9 @@ extern void TidStoreSetBlockOffsets(TidStore *ts, BlockNumber blkno, OffsetNumbe
 extern bool TidStoreIsMember(TidStore *ts, ItemPointer tid);
 extern TidStoreIter *TidStoreBeginIterate(TidStore *ts);
 extern TidStoreIterResult *TidStoreIterateNext(TidStoreIter *iter);
+extern int	TidStoreGetBlockOffsets(TidStoreIterResult *result,
+									OffsetNumber *offsets,
+									int max_offsets);
 extern void TidStoreEndIterate(TidStoreIter *iter);
 extern size_t TidStoreMemoryUsage(TidStore *ts);
 extern dsa_pointer TidStoreGetHandle(TidStore *ts);
diff --git a/src/test/modules/test_tidstore/test_tidstore.c b/src/test/modules/test_tidstore/test_tidstore.c
index 3f6a11bf21c..94ddcf1de82 100644
--- a/src/test/modules/test_tidstore/test_tidstore.c
+++ b/src/test/modules/test_tidstore/test_tidstore.c
@@ -267,9 +267,14 @@ check_set_block_offsets(PG_FUNCTION_ARGS)
 	iter = TidStoreBeginIterate(tidstore);
 	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
 	{
-		for (int i = 0; i < iter_result->num_offsets; i++)
+		OffsetNumber offsets[MaxOffsetNumber];
+		int			num_offsets;
+
+		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
+		Assert(num_offsets <= lengthof(offsets));
+		for (int i = 0; i < num_offsets; i++)
 			ItemPointerSet(&(items.iter_tids[num_iter_tids++]), iter_result->blkno,
-						   iter_result->offsets[i]);
+						   offsets[i]);
 	}
 	TidStoreEndIterate(iter);
 	TidStoreUnlock(tidstore);
-- 
2.34.1



  [text/x-patch] v11-0001-Use-streaming-I-O-in-VACUUM-first-pass.patch (8.3K, ../../CAAKRu_bbkmwAzSBgnezancgJeXrQZXy4G4kBTd+5=cr86H5yew@mail.gmail.com/3-v11-0001-Use-streaming-I-O-in-VACUUM-first-pass.patch)
  download | inline diff:
From fe4ab2059580d52c2855a6ea2c6bac80d06970c4 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Mon, 11 Mar 2024 16:19:56 -0400
Subject: [PATCH v11 1/3] Use streaming I/O in VACUUM first pass.

Now vacuum's first pass, which HOT-prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by converting
heap_vac_scan_next_block() to a read stream callback.

Author: Melanie Plageman <melanieplageman@gmail.com>
---
 src/backend/access/heap/vacuumlazy.c | 80 +++++++++++++++++-----------
 1 file changed, 49 insertions(+), 31 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3f88cf1e8ef..f76ef2e7c63 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -55,6 +55,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/pg_rusage.h"
@@ -229,8 +230,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -815,10 +817,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm;
 
 	TidStore   *dead_items = vacrel->dead_items;
 	VacDeadItemsInfo *dead_items_info = vacrel->dead_items_info;
@@ -836,19 +839,33 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items_info->max_bytes;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(bool));
+
 	/* Initialize for the first heap_vac_scan_next_block() call */
 	vacrel->current_block = InvalidBlockNumber;
 	vacrel->next_unskippable_block = InvalidBlockNumber;
 	vacrel->next_unskippable_allvis = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
+	while (BufferIsValid(buf = read_stream_next_buffer(stream,
+													   (void **) &all_visible_according_to_vm)))
 	{
-		Buffer		buf;
+		BlockNumber blkno;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -914,10 +931,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -973,7 +986,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1027,7 +1040,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		ReleaseBuffer(vmbuffer);
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1042,6 +1055,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1053,11 +1068,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1067,14 +1082,14 @@ lazy_scan_heap(LVRelState *vacrel)
 /*
  *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
+ * The streaming read callback invokes heap_vac_scan_next_block() every time
+ * lazy_scan_heap() needs the next block to prune and vacuum.  The function
+ * uses the visibility map, vacuum options, and various thresholds to skip
+ * blocks which do not need to be processed and returns the next block to
+ * process or InvalidBlockNumber if there are no remaining blocks.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process.
+ * The visibility status of the next block to process is set in the
+ * per_buffer_data.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1082,11 +1097,14 @@ lazy_scan_heap(LVRelState *vacrel)
  * relfrozenxid in that case.  vacrel also holds information about the next
  * unskippable block, as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1099,8 +1117,8 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		vacrel->current_block = vacrel->rel_pages;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1149,9 +1167,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = true;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1161,9 +1179,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



  [text/x-patch] v11-0003-Use-streaming-I-O-in-VACUUM-second-pass.patch (3.5K, ../../CAAKRu_bbkmwAzSBgnezancgJeXrQZXy4G4kBTd+5=cr86H5yew@mail.gmail.com/4-v11-0003-Use-streaming-I-O-in-VACUUM-second-pass.patch)
  download | inline diff:
From 5c74eccade69374a449f0b0fd4003545863c9538 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 27 Feb 2024 14:35:36 -0500
Subject: [PATCH v11 3/3] Use streaming I/O in VACUUM second pass.

Now vacuum's second pass, which removes dead items referring to dead
tuples collected in the first pass, uses a read stream that looks ahead
in the TidStore.

Originally developed by Melanie, refactored to work with the new
TidStore by Thomas.

Author: Melanie Plageman <melanieplageman@gmail.com>
Author: Thomas Munro <thomas.munro@gmail.com>
---
 src/backend/access/heap/vacuumlazy.c | 38 +++++++++++++++++++++++-----
 1 file changed, 32 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 19c13671666..14eee89af83 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2098,6 +2098,24 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/* Save the TidStoreIterResult for later, so we can extract the offsets. */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2118,6 +2136,8 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	Buffer		buf;
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2138,10 +2158,18 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (BufferIsValid(buf = read_stream_next_buffer(stream,
+													   (void **) &iter_result)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 		OffsetNumber offsets[MaxOffsetNumber];
@@ -2149,8 +2177,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point();
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
@@ -2163,8 +2190,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2177,6 +2202,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2024-07-07 14:49                         ` Noah Misch <noah@leadboat.com>
  2024-07-08 18:16                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Noah Misch @ 2024-07-07 14:49 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Thomas Munro <thomas.munro@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Fri, Jun 28, 2024 at 05:36:25PM -0400, Melanie Plageman wrote:
> I've attached a WIP v11 streaming vacuum patch set here that is
> rebased over master (by Thomas), so that I could add a CF entry for
> it. It still has the problem with the extra WAL write and fsync calls
> investigated by Thomas above. Thomas has some work in progress doing
> streaming write-behind to alleviate the issues with the buffer access
> strategy and streaming reads. When he gets a version of that ready to
> share, he will start a new "Streaming Vacuum" thread.

To avoid reviewing the wrong patch, I'm writing to verify the status here.
This is Needs Review in the commitfest.  I think one of these two holds:

1. Needs Review is valid.
2. It's actually Waiting on Author.  You're commissioning a review of the
   future-thread patch, not this one.

If it's (1), given the WIP marking, what is the scope of the review you seek?
I'm guessing performance is out of scope; what else is in or out of scope?





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
@ 2024-07-08 18:16                           ` Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2024-07-08 18:16 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Thomas Munro <thomas.munro@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Jul 7, 2024 at 10:49 AM Noah Misch <noah@leadboat.com> wrote:
>
> On Fri, Jun 28, 2024 at 05:36:25PM -0400, Melanie Plageman wrote:
> > I've attached a WIP v11 streaming vacuum patch set here that is
> > rebased over master (by Thomas), so that I could add a CF entry for
> > it. It still has the problem with the extra WAL write and fsync calls
> > investigated by Thomas above. Thomas has some work in progress doing
> > streaming write-behind to alleviate the issues with the buffer access
> > strategy and streaming reads. When he gets a version of that ready to
> > share, he will start a new "Streaming Vacuum" thread.
>
> To avoid reviewing the wrong patch, I'm writing to verify the status here.
> This is Needs Review in the commitfest.  I think one of these two holds:
>
> 1. Needs Review is valid.
> 2. It's actually Waiting on Author.  You're commissioning a review of the
>    future-thread patch, not this one.
>
> If it's (1), given the WIP marking, what is the scope of the review you seek?
> I'm guessing performance is out of scope; what else is in or out of scope?

Ah, you're right. I moved it to "Waiting on Author" as we are waiting
on Thomas' version which has a fix for the extra WAL write/sync
behavior.

Sorry for the "Needs Review" noise!

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
@ 2024-07-15 03:26                           ` Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2024-07-15 03:26 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Mon, Jul 8, 2024 at 2:49 AM Noah Misch <noah@leadboat.com> wrote:
> what is the scope of the review you seek?

The patch "Refactor tidstore.c memory management." could definitely
use some review.  I wasn't sure if that should be proposed in a new
thread of its own, but then the need for it comes from this
streamifying project, so...  The basic problem was that we want to
build up a stream of block to be vacuumed (so that we can perform the
I/O combining etc) + some extra data attached to each buffer, in this
case the TID list, but the implementation of tidstore.c in master
would require us to make an extra intermediate copy of the TIDs,
because it keeps overwriting its internal buffer.  The proposal here
is to make it so that you can get get a tiny copyable object that can
later be used to retrieve the data into a caller-supplied buffer, so
that tidstore.c's iterator machinery doesn't have to have its own
internal buffer at all, and then calling code can safely queue up a
few of these at once.





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2024-07-16 01:52                             ` Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Noah Misch @ 2024-07-16 01:52 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Mon, Jul 15, 2024 at 03:26:32PM +1200, Thomas Munro wrote:
> On Mon, Jul 8, 2024 at 2:49 AM Noah Misch <noah@leadboat.com> wrote:
> > what is the scope of the review you seek?
> 
> The patch "Refactor tidstore.c memory management." could definitely
> use some review.

That's reasonable.  radixtree already forbids mutations concurrent with
iteration, so there's no new concurrency hazard.  One alternative is
per_buffer_data big enough for MaxOffsetNumber, but that might thrash caches
measurably.  That patch is good to go apart from these trivialities:

> -	return &(iter->output);
> +	return &iter->output;

This cosmetic change is orthogonal to the patch's mission.

> -		for (wordnum = 0; wordnum < page->header.nwords; wordnum++)
> +		for (int wordnum = 0; wordnum < page->header.nwords; wordnum++)

Likewise.





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
@ 2024-07-24 05:40                               ` Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-10-22 16:12                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 81+ messages in thread

From: Thomas Munro @ 2024-07-24 05:40 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Tue, Jul 16, 2024 at 1:52 PM Noah Misch <noah@leadboat.com> wrote:
> On Mon, Jul 15, 2024 at 03:26:32PM +1200, Thomas Munro wrote:
> That's reasonable.  radixtree already forbids mutations concurrent with
> iteration, so there's no new concurrency hazard.  One alternative is
> per_buffer_data big enough for MaxOffsetNumber, but that might thrash caches
> measurably.  That patch is good to go apart from these trivialities:

Thanks!  I have pushed that patch, without those changes you didn't like.

Here's are Melanie's patches again.  They work, and the WAL flush
frequency problem is mostly gone since we increased the BAS_VACUUM
default ring size (commit 98f320eb), but I'm still looking into how
this read-ahead and the write-behind generated by vacuum (using
patches not yet posted) should interact with each other and the ring
system, and bouncing ideas around about that with my colleagues.  More
on that soon, hopefully.  I suspect that there won't be changes to
these patches as a result, but I still want to hold off for a bit.

Attachments:

  [text/x-patch] v12-0001-Use-streaming-I-O-in-VACUUM-first-pass.patch (8.3K, ../../CA+hUKGKN3oy0bN_3yv8hd78a4+M1tJC9z7mD8+f+yA+GeoFUwQ@mail.gmail.com/2-v12-0001-Use-streaming-I-O-in-VACUUM-first-pass.patch)
  download | inline diff:
From ac826d0187252bf446fb5f12489def5208d20289 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Mon, 11 Mar 2024 16:19:56 -0400
Subject: [PATCH v12 1/2] Use streaming I/O in VACUUM first pass.

Now vacuum's first pass, which HOT-prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by converting
heap_vac_scan_next_block() to a read stream callback.

Author: Melanie Plageman <melanieplageman@gmail.com>
---
 src/backend/access/heap/vacuumlazy.c | 80 +++++++++++++++++-----------
 1 file changed, 49 insertions(+), 31 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 835b53415d0..d92fac7e7e3 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -55,6 +55,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/pg_rusage.h"
@@ -229,8 +230,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -815,10 +817,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	Buffer		buf;
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm;
 
 	TidStore   *dead_items = vacrel->dead_items;
 	VacDeadItemsInfo *dead_items_info = vacrel->dead_items_info;
@@ -836,19 +839,33 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = dead_items_info->max_bytes;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(bool));
+
 	/* Initialize for the first heap_vac_scan_next_block() call */
 	vacrel->current_block = InvalidBlockNumber;
 	vacrel->next_unskippable_block = InvalidBlockNumber;
 	vacrel->next_unskippable_allvis = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
+	while (BufferIsValid(buf = read_stream_next_buffer(stream,
+													   (void **) &all_visible_according_to_vm)))
 	{
-		Buffer		buf;
+		BlockNumber blkno;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+
 		vacrel->scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -914,10 +931,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -973,7 +986,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1027,7 +1040,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		ReleaseBuffer(vmbuffer);
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1042,6 +1055,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1053,11 +1068,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1067,14 +1082,14 @@ lazy_scan_heap(LVRelState *vacrel)
 /*
  *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
+ * The streaming read callback invokes heap_vac_scan_next_block() every time
+ * lazy_scan_heap() needs the next block to prune and vacuum.  The function
+ * uses the visibility map, vacuum options, and various thresholds to skip
+ * blocks which do not need to be processed and returns the next block to
+ * process or InvalidBlockNumber if there are no remaining blocks.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process.
+ * The visibility status of the next block to process is set in the
+ * per_buffer_data.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1082,11 +1097,14 @@ lazy_scan_heap(LVRelState *vacrel)
  * relfrozenxid in that case.  vacrel also holds information about the next
  * unskippable block, as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1099,8 +1117,8 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		vacrel->current_block = vacrel->rel_pages;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1149,9 +1167,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = true;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1161,9 +1179,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.45.2



  [text/x-patch] v12-0002-Use-streaming-I-O-in-VACUUM-second-pass.patch (3.4K, ../../CA+hUKGKN3oy0bN_3yv8hd78a4+M1tJC9z7mD8+f+yA+GeoFUwQ@mail.gmail.com/3-v12-0002-Use-streaming-I-O-in-VACUUM-second-pass.patch)
  download | inline diff:
From 096f16b1e76ac28438752e7828b7c325f84edf4e Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 27 Feb 2024 14:35:36 -0500
Subject: [PATCH v12 2/2] Use streaming I/O in VACUUM second pass.

Now vacuum's second pass, which removes dead items referring to dead
tuples collected in the first pass, uses a read stream that looks ahead
in the TidStore.

Author: Melanie Plageman <melanieplageman@gmail.com>
---
 src/backend/access/heap/vacuumlazy.c | 38 +++++++++++++++++++++++-----
 1 file changed, 32 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index d92fac7e7e3..2b7d191d175 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2098,6 +2098,24 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/* Save the TidStoreIterResult for later, so we can extract the offsets. */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2118,6 +2136,8 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	Buffer		buf;
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2138,10 +2158,18 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (BufferIsValid(buf = read_stream_next_buffer(stream,
+													   (void **) &iter_result)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 		OffsetNumber offsets[MaxOffsetNumber];
@@ -2149,8 +2177,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point();
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
@@ -2163,8 +2190,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2177,6 +2202,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.45.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2024-12-15 15:10                                 ` Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Tomas Vondra @ 2024-12-15 15:10 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On 7/24/24 07:40, Thomas Munro wrote:
> On Tue, Jul 16, 2024 at 1:52 PM Noah Misch <noah@leadboat.com> wrote:
>> On Mon, Jul 15, 2024 at 03:26:32PM +1200, Thomas Munro wrote:
>> That's reasonable.  radixtree already forbids mutations concurrent with
>> iteration, so there's no new concurrency hazard.  One alternative is
>> per_buffer_data big enough for MaxOffsetNumber, but that might thrash caches
>> measurably.  That patch is good to go apart from these trivialities:
> 
> Thanks!  I have pushed that patch, without those changes you didn't like.
> 
> Here's are Melanie's patches again.  They work, and the WAL flush
> frequency problem is mostly gone since we increased the BAS_VACUUM
> default ring size (commit 98f320eb), but I'm still looking into how
> this read-ahead and the write-behind generated by vacuum (using
> patches not yet posted) should interact with each other and the ring
> system, and bouncing ideas around about that with my colleagues.  More
> on that soon, hopefully.  I suspect that there won't be changes to
> these patches as a result, but I still want to hold off for a bit.

I've been looking at some other vacuum-related patches, so I took a look
at these remaining bits too. I don't have much to say about the code
(seems perfectly fine to me), so I decided to do a bit of testing.

I did a simple test (see the attached .sh script) that runs vacuum on a
table with different fractions of rows updated. The table has ~100 rows
per page, with 50% fill factor, and the updates touch ~1%, 0.1%, 0.05%
rows, and then even smaller fractions up to 0.0001%. This determines how
many pages get touched. With 1% fraction almost every page gets
modified, then the fraction quickly drops. With 0.0001% only about 0.01%
of pages gets modified.

Attached is a CSV with raw results from two machines, and also a PDF
with a comparison of the two build (master vs. patched). In vast
majority of cases, the patched build is much faster, usually 2-3x.

There are a couple cases where it regresses by ~30%, but only on one of
the machines with older storage (RAID on SATA SSDs), with 1% rows
updated (which means almost all pages get modified). So this is about
sequential access. It's a bit weird, but probably not a fatal issue.

There is also a couple smaller regressions on the "xeon" machine with
M.2 SSD, for lower update fractions - 0.05% rows updated means 5% pages
need vacuum. But I think this is more a sign of us being too aggressive
in detecting (and forcing) sequential patterns - on master, we end up
scanning 50% pages, thanks to SKIP_PAGES_THRESHOLD. I'll start a new
thread about that ...

Anyway, these results look very nice - a couple limited regressions,
substantial speedups in plausible/common cases.


regards

-- 
Tomas Vondra

Attachments:

  [application/x-shellscript] run-vacuum-stream.sh (1.9K, ../../eb657bfe-ba96-4aef-82f9-b952724de863@vondra.me/2-run-vacuum-stream.sh)
  download

  [text/csv] vacuum-stream-results.csv (117.5K, ../../eb657bfe-ba96-4aef-82f9-b952724de863@vondra.me/3-vacuum-stream-results.csv)
  download

  [application/pdf] vacuum-streaming.pdf (46.9K, ../../eb657bfe-ba96-4aef-82f9-b952724de863@vondra.me/4-vacuum-streaming.pdf)
  download

^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
@ 2025-01-16 01:45                                   ` Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-01-16 01:45 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Dec 15, 2024 at 10:10 AM Tomas Vondra <tomas@vondra.me> wrote:
>
> I've been looking at some other vacuum-related patches, so I took a look
> at these remaining bits too. I don't have much to say about the code
> (seems perfectly fine to me), so I decided to do a bit of testing.

Thanks for doing this!

> I did a simple test (see the attached .sh script) that runs vacuum on a
> table with different fractions of rows updated. The table has ~100 rows
> per page, with 50% fill factor, and the updates touch ~1%, 0.1%, 0.05%
> rows, and then even smaller fractions up to 0.0001%. This determines how
> many pages get touched. With 1% fraction almost every page gets
> modified, then the fraction quickly drops. With 0.0001% only about 0.01%
> of pages gets modified.
>
> Attached is a CSV with raw results from two machines, and also a PDF
> with a comparison of the two build (master vs. patched). In vast
> majority of cases, the patched build is much faster, usually 2-3x.
>
> There are a couple cases where it regresses by ~30%, but only on one of
> the machines with older storage (RAID on SATA SSDs), with 1% rows
> updated (which means almost all pages get modified). So this is about
> sequential access. It's a bit weird, but probably not a fatal issue.

Actually, while rebasing these with the intent to start investigating
the regressions you report, I noticed something quite wrong with my
code. In lazy_scan_heap(), I had put read_stream_next_buffer() before
a few expensive operations (like a round of index vacuuming and dead
item reaping if the TID store is full). It returns the pinned buffer,
so this could mean a buffer remaining pinned for a whole round of
vacuuming of items from the TID store. Not good. Anyway, this version
has fixed that. I do wonder if there is any chance that this affected
your benchmarks.

I've attached a new v13. Perhaps you could give it another go and see
if the regressions are still there?

> There is also a couple smaller regressions on the "xeon" machine with
> M.2 SSD, for lower update fractions - 0.05% rows updated means 5% pages
> need vacuum. But I think this is more a sign of us being too aggressive
> in detecting (and forcing) sequential patterns - on master, we end up
> scanning 50% pages, thanks to SKIP_PAGES_THRESHOLD. I'll start a new
> thread about that ...

Hmm. If only 5% of pages need vacuum, then you are right, readahead
seems like it would often be wasted (depending on _which_ 5% needs
vacuuming). But, the read stream API will only prefetch and build up
larger I/Os of blocks we actually need. So, it seems like this would
behave the same on master and with the patch. That is, both would do
extra unneeded I/O because of SKIP_PAGES_THRESHOLD. Is the 5% of the
table that needs vacuuming dispersed randomly throughout or
concentrated?

If it is concentrated and readahead would be useful, then maybe we
need to increase read_ahead_kb. You mentioned off-list that the
read_ahead_kb on this machine for this SSD was 128kB -- the same as
io_combine_limit. If we want to read ahead, issuing 128 kB I/Os might
be thwarting us and increasing latency.

- Melanie

Attachments:

  [application/octet-stream] v13-0001-Use-streaming-I-O-in-VACUUM-s-first-phase.patch (9.4K, ../../CAAKRu_aLwANZpxHc0tC-6OT0OQT4TftDGkKAO5yigMUOv_Tcsw@mail.gmail.com/2-v13-0001-Use-streaming-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From 17cae28be7d432b53a7cd1b8fdc04c8abd92be02 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 15 Jan 2025 19:56:37 -0500
Subject: [PATCH v13 1/2] Use streaming I/O in VACUUM's first phase

Now vacuum's first phase, which HOT-prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by converting
heap_vac_scan_next_block() to a read stream callback.
---
 src/backend/access/heap/vacuumlazy.c | 100 +++++++++++++++++----------
 1 file changed, 62 insertions(+), 38 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 5b0e790e121..dce5dae9d02 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -108,6 +108,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -296,8 +297,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -904,10 +906,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm = NULL;
 
 	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
@@ -923,26 +926,27 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = vacrel->dead_items_info->max_bytes;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(bool));
+
 	/* Initialize for the first heap_vac_scan_next_block() call */
 	vacrel->current_block = InvalidBlockNumber;
 	vacrel->next_unskippable_block = InvalidBlockNumber;
 	vacrel->next_unskippable_allvis = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point();
 
 		/*
@@ -983,7 +987,8 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages.  Note that blkno is the previously
+			 * processed block.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
 									blkno);
@@ -994,6 +999,24 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, (void **) &all_visible_according_to_vm);
+
+		if (!BufferIsValid(buf))
+			break;
+
+		Assert(all_visible_according_to_vm);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+
+		vacrel->scanned_pages++;
+
+		blkno = BufferGetBlockNumber(buf);
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1001,10 +1024,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1060,7 +1079,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1114,7 +1133,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		ReleaseBuffer(vmbuffer);
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1129,6 +1148,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1140,11 +1161,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1154,14 +1175,14 @@ lazy_scan_heap(LVRelState *vacrel)
 /*
  *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
+ * The streaming read callback invokes heap_vac_scan_next_block() every time
+ * lazy_scan_heap() needs the next block to prune and vacuum.  The function
+ * uses the visibility map, vacuum options, and various thresholds to skip
+ * blocks which do not need to be processed and returns the next block to
+ * process or InvalidBlockNumber if there are no remaining blocks.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process.
+ * The visibility status of the next block to process is set in the
+ * per_buffer_data.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1169,11 +1190,14 @@ lazy_scan_heap(LVRelState *vacrel)
  * relfrozenxid in that case.  vacrel also holds information about the next
  * unskippable block, as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1186,8 +1210,8 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		vacrel->current_block = vacrel->rel_pages;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1236,9 +1260,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = true;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1248,9 +1272,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.45.2



  [application/octet-stream] v13-0002-Use-streaming-I-O-in-VACUUM-s-third-phase.patch (3.3K, ../../CAAKRu_aLwANZpxHc0tC-6OT0OQT4TftDGkKAO5yigMUOv_Tcsw@mail.gmail.com/3-v13-0002-Use-streaming-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From 24c8f1da03f5bb887a23581fced19f74a47fb2d1 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 15 Jan 2025 20:16:16 -0500
Subject: [PATCH v13 2/2] Use streaming I/O in VACUUM's third phase

Now vacuum's third phase (its second pass over the heap), which removes
dead items referring to dead tuples collected in the first phase, uses a
read stream that looks ahead in the TidStore.
---
 src/backend/access/heap/vacuumlazy.c | 39 +++++++++++++++++++++++-----
 1 file changed, 33 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index dce5dae9d02..c07ce578931 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2247,6 +2247,24 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/* Save the TidStoreIterResult for later, so we can extract the offsets. */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2267,6 +2285,8 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	Buffer		buf;
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2287,10 +2307,18 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (BufferIsValid(buf = read_stream_next_buffer(stream,
+													   (void **) &iter_result)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 		OffsetNumber offsets[MaxOffsetNumber];
@@ -2298,8 +2326,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point();
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
@@ -2312,8 +2339,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2326,6 +2351,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.45.2



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-01-18 16:51                                     ` Tomas Vondra <tomas@vondra.me>
  2025-01-18 21:31                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Tomas Vondra @ 2025-01-18 16:51 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>



On 1/16/25 02:45, Melanie Plageman wrote:
> On Sun, Dec 15, 2024 at 10:10 AM Tomas Vondra <tomas@vondra.me> wrote:
>>
>> I've been looking at some other vacuum-related patches, so I took a look
>> at these remaining bits too. I don't have much to say about the code
>> (seems perfectly fine to me), so I decided to do a bit of testing.
> 
> Thanks for doing this!
> 
>> I did a simple test (see the attached .sh script) that runs vacuum on a
>> table with different fractions of rows updated. The table has ~100 rows
>> per page, with 50% fill factor, and the updates touch ~1%, 0.1%, 0.05%
>> rows, and then even smaller fractions up to 0.0001%. This determines how
>> many pages get touched. With 1% fraction almost every page gets
>> modified, then the fraction quickly drops. With 0.0001% only about 0.01%
>> of pages gets modified.
>>
>> Attached is a CSV with raw results from two machines, and also a PDF
>> with a comparison of the two build (master vs. patched). In vast
>> majority of cases, the patched build is much faster, usually 2-3x.
>>
>> There are a couple cases where it regresses by ~30%, but only on one of
>> the machines with older storage (RAID on SATA SSDs), with 1% rows
>> updated (which means almost all pages get modified). So this is about
>> sequential access. It's a bit weird, but probably not a fatal issue.
> 
> Actually, while rebasing these with the intent to start investigating
> the regressions you report, I noticed something quite wrong with my
> code. In lazy_scan_heap(), I had put read_stream_next_buffer() before
> a few expensive operations (like a round of index vacuuming and dead
> item reaping if the TID store is full). It returns the pinned buffer,
> so this could mean a buffer remaining pinned for a whole round of
> vacuuming of items from the TID store. Not good. Anyway, this version
> has fixed that. I do wonder if there is any chance that this affected
> your benchmarks.
> 
> I've attached a new v13. Perhaps you could give it another go and see
> if the regressions are still there?
> 

Sure. I repeated the benchmark with v13, and it seems the behavior did
change. I no longer see the "big" regression when most of the pages get
updated (and need vacuuming).

I can't be 100% sure this is due to changes in the patch, because I did
some significant upgrades to the machine since that time - it has Ryzen
9900x instead of the ancient i5-2500k, new mobo/RAM/...  It's pretty
much a new machine, I only kept the "old" SATA SSD RAID storage so that
I can do some tests with non-NVMe.

So there's a (small) chance the previous runs were hitting a bottleneck
that does not exist on the new hardware.

Anyway, just to make this information more complete, the machine now has
this configuration:

* Ryzen 9 9900x (12/24C), 64GB RAM
* storage:
  - data: Samsung SSD 990 PRO 4TB (NVMe)
  - raid-nvme: RAID0 4x Samsung SSD 990 PRO 1TB (NVMe)
  - raid-sata: RAID0 6x Intel DC3700 100GB (SATA)

Attached is the script, raw results (CSV) and two PDFs summarizing the
results as a pivot table for different test parameters. Compared to the
earlier run I tweaked the script to also vary io_combine_limit (ioc), as
I wanted to see how it interacts with effective_io_concurrency (eic).

Looking at the new results, I don't see any regressions, except for two
cases - data (single NVMe) and raid-nvme (4x NVMe). There's a small area
of regression for eic=32 and perc=0.0005, but only with WAL-logging.

I'm not sure this is worth worrying about too much. It's a heuristics
and for every heuristics there's some combination parameters where it
doesn't quite do the optimal thing. The area where the patch brings
massive improvements (or does not regress) are much more significant.

I personally am happy with this behavior, seems to be performing fine.

>> There is also a couple smaller regressions on the "xeon" machine with
>> M.2 SSD, for lower update fractions - 0.05% rows updated means 5% pages
>> need vacuum. But I think this is more a sign of us being too aggressive
>> in detecting (and forcing) sequential patterns - on master, we end up
>> scanning 50% pages, thanks to SKIP_PAGES_THRESHOLD. I'll start a new
>> thread about that ...
> 
> Hmm. If only 5% of pages need vacuum, then you are right, readahead
> seems like it would often be wasted (depending on _which_ 5% needs
> vacuuming). But, the read stream API will only prefetch and build up
> larger I/Os of blocks we actually need. So, it seems like this would
> behave the same on master and with the patch. That is, both would do
> extra unneeded I/O because of SKIP_PAGES_THRESHOLD. Is the 5% of the
> table that needs vacuuming dispersed randomly throughout or
> concentrated?
> 
> If it is concentrated and readahead would be useful, then maybe we
> need to increase read_ahead_kb. You mentioned off-list that the
> read_ahead_kb on this machine for this SSD was 128kB -- the same as
> io_combine_limit. If we want to read ahead, issuing 128 kB I/Os might
> be thwarting us and increasing latency.
> 

I haven't ran the new benchmark on the "xeon" machine, but I believe
this is the same regression that I mentioned above. I mean, it's the
same "area" where it happens, also for NVMe storage, so I guess it's has
the same cause. But I don't have any particular insight into this.


FWIW there's one more interesting thing - entirely unrelated to this
patch, but visible in the "eic vs. ioc" results, which are meant to show
how these two GUC interact. For (eic <= 1) the ioc doesn't seem to
matter very much, but for (eic > 1) it's clear higher ioc values are
better. Except that it "breaks" at 512kB, because I didn't realize we
allow ioc only up to 256kB. So 512kB does nothing, it just defaults to
the 128kB limit.

So this brings two questions:

* Does it still make sense to default to eic=1? For this particular test
increasing eic=4 often cuts the duration in half (especially on nvme
storage).

* Why are we limiting ioc to <= 256kB? Per the benchmark it seems it
might be beneficial to set even higher values.

regards

-- 
Tomas Vondra

Attachments:

  [application/pdf] ioc-eic.pdf (63.4K, ../../85696b8e-f1bf-459e-ba97-5608c644c185@vondra.me/2-ioc-eic.pdf)
  download

  [application/pdf] perc.pdf (55.0K, ../../85696b8e-f1bf-459e-ba97-5608c644c185@vondra.me/3-perc.pdf)
  download

  [application/gzip] results.csv.gz (293.0K, ../../85696b8e-f1bf-459e-ba97-5608c644c185@vondra.me/4-results.csv.gz)
  download

  [application/x-shellscript] run-vacuum-stream.sh (3.6K, ../../85696b8e-f1bf-459e-ba97-5608c644c185@vondra.me/5-run-vacuum-stream.sh)
  download

^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
@ 2025-01-18 21:31                                       ` Thomas Munro <thomas.munro@gmail.com>
  2025-01-18 21:45                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-01-18 22:04                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  1 sibling, 2 replies; 81+ messages in thread

From: Thomas Munro @ 2025-01-18 21:31 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Jan 19, 2025 at 5:51 AM Tomas Vondra <tomas@vondra.me> wrote:
> * Does it still make sense to default to eic=1? For this particular test
> increasing eic=4 often cuts the duration in half (especially on nvme
> storage).

Maybe it wasn't a bad choice for systems with one spinning disk, but
obviously typical hardware has changed completely since then.  Bruce
even changed the docs to recommend "hundreds" on SSDs (46eafc88).  We
could definitely consider changing the value, but this particular
thing is using the READ_STREAM_MAINTENANCE flag, so it uses
maintenance_io_concurrency, and that one defaults to 10.  That's also
arbitrary and quite small, but I think it means we can avoid choosing
new defaults for now :-)  For the non-maintenance one, we might want
to think about tweaking that in the context of bitmap heapscan?

(Interestingly, MySQL seems to have a related setting defaulting to
10k, but that may be a system-wide setting, IDK.  Our settings are
quite low level, per "operation", or really per stream.  In an
off-list chat with Robert and Andres, we bounced around some new
names, and the one I liked best was io_concurrency_per_stream.  It
would be accurate but bring a new implementation detail to the UX.  I
actually like that about it: it's like
max_parallel_workers_per_gather, and also just the way work_mem is
really work_mem_per_<something>: yes it is low level but is an honest
expression of how (un)sophisticated our resource usage controls are
today.  Perhaps we'll eventually figure out how to balance all
resources dynamically from global limits...)

> * Why are we limiting ioc to <= 256kB? Per the benchmark it seems it
> might be beneficial to set even higher values.

That comes from:

#define MAX_IO_COMBINE_LIMIT PG_IOV_MAX

... which comes from:

/* Define a reasonable maximum that is safe to use on the stack. */
#define PG_IOV_MAX Min(IOV_MAX, 32)

There are a few places that use either PG_IOV_MAX or
MAX_IO_COMBINE_LIMIT to size a stack array, but those should be OK
with a bigger number as the types are small: buffer, pointer, or
struct iovec (16 bytes).  For example, if it were 128 then we could do
1MB I/O, a nice round number, and arrays of those types would still
only be 2kB or less.  The other RDBMSes I googled seem to have max I/O
sizes of around 512kB or 1MB, some tunable explicitly, some derived
from other settings.

I picked 128kB as the default combine limit because it comes up in
lots of other places eg readahead size, and seemed to work pretty
well, and is definitely supportable on all POSIX systems (see POSIX
IOV_MAX, which is allowed to be as low as 16).  I chose a maximum that
was just a bit more, but not much more because I was also worried
about how many places would eventually finish up wasting a lot of
memory by having to multiply that by
number-of-possible-I/Os-in-progress or other similar ideas, but I was
expecting we'd want to increase it.  read_stream.c doesn't do that
sort of multiplication itself, but you can see a case like that in
Andres's AIO patchset here:

https://github.com/anarazel/postgres/blob/aio-2/src/backend/storage/aio/aio_init.c

So for example if io_max_concurrency defaults to 1024; you'd get 2MB
of iovecs in shared memory with PG_IOV_MAX of 128, instead of 512kB
today.  We can always discuss defaults separately but that case
doesn't seem like a problem from here...

Nice results, thanks!





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-18 21:31                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-01-18 21:45                                         ` Thomas Munro <thomas.munro@gmail.com>
  1 sibling, 0 replies; 81+ messages in thread

From: Thomas Munro @ 2025-01-18 21:45 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Jan 19, 2025 at 10:31 AM Thomas Munro <thomas.munro@gmail.com> wrote:
> read_stream.c doesn't do that
> sort of multiplication itself,

Actually for completeness there is a place where it allocates local
memory for max I/Os * 4, and that 4 is a not entirely unbogus and
should change to io_combine_limit for the AIO stuff.  Patches in
progress, more soon.  But that'd not be using MAX_IO_COMBINE_LIMIT or
the number of system-wide I/O, it'd be your (usually much smaller)
configured limits.  But I'll write about that with more details in a
new thread...





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-18 21:31                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-01-18 22:04                                         ` Tomas Vondra <tomas@vondra.me>
  1 sibling, 0 replies; 81+ messages in thread

From: Tomas Vondra @ 2025-01-18 22:04 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On 1/18/25 22:31, Thomas Munro wrote:
> On Sun, Jan 19, 2025 at 5:51 AM Tomas Vondra <tomas@vondra.me> wrote:
>> * Does it still make sense to default to eic=1? For this particular test
>> increasing eic=4 often cuts the duration in half (especially on nvme
>> storage).
> 
> Maybe it wasn't a bad choice for systems with one spinning disk, but
> obviously typical hardware has changed completely since then.  Bruce
> even changed the docs to recommend "hundreds" on SSDs (46eafc88).  We
> could definitely consider changing the value, but this particular
> thing is using the READ_STREAM_MAINTENANCE flag, so it uses
> maintenance_io_concurrency, and that one defaults to 10.  That's also
> arbitrary and quite small, but I think it means we can avoid choosing
> new defaults for now :-)

I completely lost track which hardware is supposed to be a good fit for
low/high values of these GUCs. But weren't old spinning drives what
needed fairly long queue to optimize the movement of heads? And IIRC
some of the newer SSD (e.g. Optane) were marketed as not requiring very
long queues ... anyway, it seems fairly difficult to formulate a rule
comprehensible for our users.

FWIW the benchmarking script tweaks both effective_io_concurrency and
maintenance_io_concurrency GUCs (sets them to the same value). But yeah,
10 seems like a much better default for this type of storage. So for
vacuum this is probably fine, but I was thinking more about the regular
effective_io_concurrency for queries.

> For the non-maintenance one, we might want
> to think about tweaking that in the context of bitmap heapscan?
> 

I'm not sure what you mean. How would we tweak it? You mean the GUC, or
some sort of adaptive heuristics?

> (Interestingly, MySQL seems to have a related setting defaulting to
> 10k, but that may be a system-wide setting, IDK.  Our settings are
> quite low level, per "operation", or really per stream.  In an
> off-list chat with Robert and Andres, we bounced around some new
> names, and the one I liked best was io_concurrency_per_stream.  It
> would be accurate but bring a new implementation detail to the UX.  I
> actually like that about it: it's like
> max_parallel_workers_per_gather, and also just the way work_mem is
> really work_mem_per_<something>: yes it is low level but is an honest
> expression of how (un)sophisticated our resource usage controls are
> today.  Perhaps we'll eventually figure out how to balance all
> resources dynamically from global limits...)
> 

Possibly, but I'd guess we're years from doing that. I'm not sure anyone
even proposed anything like that.

>> * Why are we limiting ioc to <= 256kB? Per the benchmark it seems it
>> might be beneficial to set even higher values.
> 
> That comes from:
> 
> #define MAX_IO_COMBINE_LIMIT PG_IOV_MAX
> 
> ... which comes from:
> 
> /* Define a reasonable maximum that is safe to use on the stack. */
> #define PG_IOV_MAX Min(IOV_MAX, 32)
> 
> There are a few places that use either PG_IOV_MAX or
> MAX_IO_COMBINE_LIMIT to size a stack array, but those should be OK
> with a bigger number as the types are small: buffer, pointer, or
> struct iovec (16 bytes).  For example, if it were 128 then we could do
> 1MB I/O, a nice round number, and arrays of those types would still
> only be 2kB or less.  The other RDBMSes I googled seem to have max I/O
> sizes of around 512kB or 1MB, some tunable explicitly, some derived
> from other settings.
> 
> I picked 128kB as the default combine limit because it comes up in
> lots of other places eg readahead size, and seemed to work pretty
> well, and is definitely supportable on all POSIX systems (see POSIX
> IOV_MAX, which is allowed to be as low as 16).

Not sure I follow. Surely if a system can't support values above some
limit, it would define IOV_MAX accordingly, and we'd just reject that
value. And as you point out, the IOV_MAX may be as low as 16, so it's
already possible to get a GUC value that gets rejected on some systems
(even if it's just a theoretical issue).

> I chose a maximum that
> was just a bit more, but not much more because I was also worried
> about how many places would eventually finish up wasting a lot of
> memory by having to multiply that by
> number-of-possible-I/Os-in-progress or other similar ideas, but I was
> expecting we'd want to increase it.  read_stream.c doesn't do that
> sort of multiplication itself, but you can see a case like that in
> Andres's AIO patchset here:
> 
> https://github.com/anarazel/postgres/blob/aio-2/src/backend/storage/aio/aio_init.c
> 
> So for example if io_max_concurrency defaults to 1024; you'd get 2MB
> of iovecs in shared memory with PG_IOV_MAX of 128, instead of 512kB
> today.  We can always discuss defaults separately but that case
> doesn't seem like a problem from here...
> 

Yeah, all of this makes sense. I don't doubt this is a tradeoff, and if
the GUC gets set to a high value it might have detrimental effect.
Still, 256kB seems a bit too conservative and "not round" ;-)


regards

-- 
Tomas Vondra






^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
@ 2025-02-05 22:26                                       ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-05 22:26 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sat, Jan 18, 2025 at 11:51 AM Tomas Vondra <tomas@vondra.me> wrote:
>
> Sure. I repeated the benchmark with v13, and it seems the behavior did
> change. I no longer see the "big" regression when most of the pages get
> updated (and need vacuuming).
>
> I can't be 100% sure this is due to changes in the patch, because I did
> some significant upgrades to the machine since that time - it has Ryzen
> 9900x instead of the ancient i5-2500k, new mobo/RAM/...  It's pretty
> much a new machine, I only kept the "old" SATA SSD RAID storage so that
> I can do some tests with non-NVMe.
>
> So there's a (small) chance the previous runs were hitting a bottleneck
> that does not exist on the new hardware.
>
> Anyway, just to make this information more complete, the machine now has
> this configuration:
>
> * Ryzen 9 9900x (12/24C), 64GB RAM
> * storage:
>   - data: Samsung SSD 990 PRO 4TB (NVMe)
>   - raid-nvme: RAID0 4x Samsung SSD 990 PRO 1TB (NVMe)
>   - raid-sata: RAID0 6x Intel DC3700 100GB (SATA)
>
> Attached is the script, raw results (CSV) and two PDFs summarizing the
> results as a pivot table for different test parameters. Compared to the
> earlier run I tweaked the script to also vary io_combine_limit (ioc), as
> I wanted to see how it interacts with effective_io_concurrency (eic).
>
> Looking at the new results, I don't see any regressions, except for two
> cases - data (single NVMe) and raid-nvme (4x NVMe). There's a small area
> of regression for eic=32 and perc=0.0005, but only with WAL-logging.
>
> I'm not sure this is worth worrying about too much. It's a heuristics
> and for every heuristics there's some combination parameters where it
> doesn't quite do the optimal thing. The area where the patch brings
> massive improvements (or does not regress) are much more significant.
>
> I personally am happy with this behavior, seems to be performing fine.

Yes, looking at these results, I also feel good about it. I've updated
the commit metadata in attached v14, but I could use a round of review
before pushing it.

- Melanie

Attachments:

  [text/x-patch] v14-0002-Use-streaming-I-O-in-VACUUM-s-third-phase.patch (3.6K, ../../CAAKRu_ZoOSZHexy=7YZ9W0CfeSHc1tGx7VCperZHWBxxz0gxzw@mail.gmail.com/2-v14-0002-Use-streaming-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From 2397c7fb4b91f907ebcec60d35067c5072a2ae8b Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 5 Feb 2025 17:23:05 -0500
Subject: [PATCH v14 2/2] Use streaming I/O in VACUUM's third phase

Now vacuum's third phase (its second pass over the heap), which removes
dead items referring to dead tuples collected in the first phase, uses a
read stream that looks ahead in the TidStore.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 42 ++++++++++++++++++++++++----
 1 file changed, 36 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 70351de403d..222ee01e1ad 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2250,6 +2250,27 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+/*
+ * Read stream callback for vacuum's third phase (second pass over the heap).
+ */
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/* Save the TidStoreIterResult for later, so we can extract the offsets. */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2270,6 +2291,8 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	Buffer		buf;
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2290,10 +2313,18 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (BufferIsValid(buf = read_stream_next_buffer(stream,
+													   (void **) &iter_result)))
 	{
 		BlockNumber blkno;
-		Buffer		buf;
 		Page		page;
 		Size		freespace;
 		OffsetNumber offsets[MaxOffsetNumber];
@@ -2301,8 +2332,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point();
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
 
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
@@ -2315,8 +2345,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2329,6 +2357,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



  [text/x-patch] v14-0001-Use-streaming-I-O-in-VACUUM-s-first-phase.patch (9.5K, ../../CAAKRu_ZoOSZHexy=7YZ9W0CfeSHc1tGx7VCperZHWBxxz0gxzw@mail.gmail.com/3-v14-0001-Use-streaming-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From 6d61028e0900d6b96bfe72cb0c262e22b8bde39a Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 5 Feb 2025 17:21:41 -0500
Subject: [PATCH v14 1/2] Use streaming I/O in VACUUM's first phase

Now vacuum's first phase, which HOT-prunes and records the TIDs of
non-removable dead tuples, uses the streaming read API by converting
heap_vac_scan_next_block() to a read stream callback.

Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 100 +++++++++++++++++----------
 1 file changed, 62 insertions(+), 38 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 075af385cd1..70351de403d 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -108,6 +108,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -296,8 +297,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -907,10 +909,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm = NULL;
 
 	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
@@ -926,26 +929,27 @@ lazy_scan_heap(LVRelState *vacrel)
 	initprog_val[2] = vacrel->dead_items_info->max_bytes;
 	pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
 
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(bool));
+
 	/* Initialize for the first heap_vac_scan_next_block() call */
 	vacrel->current_block = InvalidBlockNumber;
 	vacrel->next_unskippable_block = InvalidBlockNumber;
 	vacrel->next_unskippable_allvis = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point();
 
 		/*
@@ -986,7 +990,8 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages.  Note that blkno is the previously
+			 * processed block.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
 									blkno);
@@ -997,6 +1002,24 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, (void **) &all_visible_according_to_vm);
+
+		if (!BufferIsValid(buf))
+			break;
+
+		Assert(all_visible_according_to_vm);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+
+		vacrel->scanned_pages++;
+
+		blkno = BufferGetBlockNumber(buf);
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1004,10 +1027,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1063,7 +1082,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1117,7 +1136,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		ReleaseBuffer(vmbuffer);
 
 	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1132,6 +1151,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1143,11 +1164,11 @@ lazy_scan_heap(LVRelState *vacrel)
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1157,14 +1178,14 @@ lazy_scan_heap(LVRelState *vacrel)
 /*
  *	heap_vac_scan_next_block() -- get next block for vacuum to process
  *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
+ * The streaming read callback invokes heap_vac_scan_next_block() every time
+ * lazy_scan_heap() needs the next block to prune and vacuum.  The function
+ * uses the visibility map, vacuum options, and various thresholds to skip
+ * blocks which do not need to be processed and returns the next block to
+ * process or InvalidBlockNumber if there are no remaining blocks.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process.
+ * The visibility status of the next block to process is set in the
+ * per_buffer_data.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1172,11 +1193,14 @@ lazy_scan_heap(LVRelState *vacrel)
  * relfrozenxid in that case.  vacrel also holds information about the next
  * unskippable block, as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1189,8 +1213,8 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		vacrel->current_block = vacrel->rel_pages;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1239,9 +1263,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = true;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1251,9 +1275,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-06 18:06                                         ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-06 18:06 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Wed, Feb 5, 2025 at 5:26 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> Yes, looking at these results, I also feel good about it. I've updated
> the commit metadata in attached v14, but I could use a round of review
> before pushing it.

I've done a bit of self-review and updated these patches.

- Melanie

Attachments:

  [text/x-patch] v15-0002-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch (3.9K, ../../CAAKRu_Zb-zdDUug2ZUNcK43Fmk_eebqRFebSdshaP_iTusW93Q@mail.gmail.com/2-v15-0002-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From 0483495b5a3a35cf27672ad08901509b8c32d49d Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 5 Feb 2025 17:23:05 -0500
Subject: [PATCH v15 2/2] Use streaming read I/O in VACUUM's third phase

Make vacuum's third phase (its second pass over the heap), which reaps
dead items collected in the first phase and marks them as reusable, use
the read stream API. This commit adds a new read stream callback,
vacuum_reap_lp_read_stream_next(), that looks ahead in the TidStore and
returns the next block number to read for vacuum.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 49 +++++++++++++++++++++++++---
 1 file changed, 44 insertions(+), 5 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index b941158c645..740565b8379 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2261,6 +2261,29 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+/*
+ * Read stream callback for vacuum's third phase (second pass over the heap).
+ * Gets the next block from the TID store and returns it or InvalidBlockNumber
+ * if there are no further blocks to vacuum.
+ */
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/* Save the TidStoreIterResult for later, so we can extract the offsets. */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2281,6 +2304,7 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2301,7 +2325,17 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+
+	/* Set up the read stream */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (true)
 	{
 		BlockNumber blkno;
 		Buffer		buf;
@@ -2312,9 +2346,14 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point();
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		buf = read_stream_next_buffer(stream, (void **) &iter_result);
 
+		if (!BufferIsValid(buf))
+			break;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		Assert(iter_result);
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
 
@@ -2326,8 +2365,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2340,6 +2377,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



  [text/x-patch] v15-0001-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch (10.3K, ../../CAAKRu_Zb-zdDUug2ZUNcK43Fmk_eebqRFebSdshaP_iTusW93Q@mail.gmail.com/3-v15-0001-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From bc33c168c2799dd397b7b67f22e3d8fdf40bc043 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 5 Feb 2025 17:21:41 -0500
Subject: [PATCH v15 1/2] Use streaming read I/O in VACUUM's first phase

Make vacuum's first phase, which prunes and freezes tuples and records
dead TIDs, use the read stream API by by converting
heap_vac_scan_next_block() to a read stream callback.

Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 131 +++++++++++++++++----------
 1 file changed, 83 insertions(+), 48 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 075af385cd1..b941158c645 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -108,6 +108,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -296,8 +297,9 @@ typedef struct LVSavedErrInfo
 
 /* non-export function prototypes */
 static void lazy_scan_heap(LVRelState *vacrel);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -907,10 +909,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm;
+	bool	   *all_visible_according_to_vm = NULL;
 
 	Buffer		vmbuffer = InvalidBuffer;
 	const int	initprog_index[] = {
@@ -932,20 +935,22 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_allvis = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
+	/* Set up the read stream for vacuum's first pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(bool));
+
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
 		bool		has_lpdead_items;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point();
 
 		/*
@@ -986,7 +991,8 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages.  Note that blkno is the previously
+			 * processed block.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
 									blkno);
@@ -997,6 +1003,23 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, (void **) &all_visible_according_to_vm);
+
+		if (!BufferIsValid(buf))
+			break;
+
+		Assert(all_visible_according_to_vm);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+		blkno = BufferGetBlockNumber(buf);
+
+		vacrel->scanned_pages++;
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1004,10 +1027,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1063,7 +1082,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer, *all_visible_according_to_vm,
 							&has_lpdead_items);
 
 		/*
@@ -1116,8 +1135,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	if (BufferIsValid(vmbuffer))
 		ReleaseBuffer(vmbuffer);
 
-	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	/*
+	 * Report that everything is now scanned. We never skip scanning the last
+	 * block in the relation, so we can pass rel_pages here.
+	 */
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
+								 rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1132,6 +1155,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1142,12 +1167,14 @@ lazy_scan_heap(LVRelState *vacrel)
 	/*
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
+	 * We can pass rel_pages here because we never skip scanning the last
+	 * block of the relation.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1155,28 +1182,37 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	heap_vac_scan_next_block() -- get next block for vacuum to process
- *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
- *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process.
- *
- * vacrel is an in/out parameter here.  Vacuum options and information about
- * the relation are read.  vacrel->skippedallvis is set if we skip a block
- * that's all-visible but not all-frozen, to ensure that we don't update
- * relfrozenxid in that case.  vacrel also holds information about the next
- * unskippable block, as bookkeeping for this function.
+ *	heap_vac_scan_next_block() -- read stream callback to get the next block
+ *	for vacuum to process
+ *
+ * Every time lazy_scan_heap() needs a new block to process during its first
+ * phase, it invokes read_stream_next_buffer() with a stream set up to call
+ * heap_vac_scan_next_block() to get the next block.
+ *
+ * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
+ * various thresholds to skip blocks which do not need to be processed and
+ * returns the next block to process or InvalidBlockNumber if there are no
+ * remaining blocks.
+ *
+ * The visibility status of the next block to process is set in the
+ * per_buffer_data.
+ *
+ * callback_private_data contains a reference to the LVRelState, passed to the
+ * read stream API during stream setup. The LVRelState is an in/out parameter
+ * here (locally named `vacrel`). Vacuum options and information about the
+ * relation are read from it. vacrel->skippedallvis is set if we skip a block
+ * that's all-visible but not all-frozen (to ensure that we don't update
+ * relfrozenxid in that case). vacrel also holds information about the next
+ * unskippable block -- as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	bool	   *all_visible_according_to_vm = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1189,8 +1225,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1239,9 +1274,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = true;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1251,9 +1286,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-12 01:10                                           ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-13 23:11                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Melanie Plageman @ 2025-02-12 01:10 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Thu, Feb 6, 2025 at 1:06 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Wed, Feb 5, 2025 at 5:26 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> >
> > Yes, looking at these results, I also feel good about it. I've updated
> > the commit metadata in attached v14, but I could use a round of review
> > before pushing it.
>
> I've done a bit of self-review and updated these patches.

This needed a rebase in light of 052026c9b90.
v16 attached has an additional commit which converts the block
information parameters to heap_vac_scan_next_block() into flags
because we can only get one piece of information per block from the
read stream API. This seemed nicer than a cumbersome struct.

- Melanie

Attachments:

  [text/x-patch] v16-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch (3.9K, ../../CAAKRu_bmx33jTqATP5GKNFYwAg02a9dDtk4U_ciEjgBHZSVkOQ@mail.gmail.com/2-v16-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From 920b567a0afa77f1478f804dc934936a9e9e9ae8 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 5 Feb 2025 17:23:05 -0500
Subject: [PATCH v16 3/3] Use streaming read I/O in VACUUM's third phase

Make vacuum's third phase (its second pass over the heap), which reaps
dead items collected in the first phase and marks them as reusable, use
the read stream API. This commit adds a new read stream callback,
vacuum_reap_lp_read_stream_next(), that looks ahead in the TidStore and
returns the next block number to read for vacuum.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 49 +++++++++++++++++++++++++---
 1 file changed, 44 insertions(+), 5 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index f705f31f5e6..5b2d9c535c1 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2637,6 +2637,29 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+/*
+ * Read stream callback for vacuum's third phase (second pass over the heap).
+ * Gets the next block from the TID store and returns it or InvalidBlockNumber
+ * if there are no further blocks to vacuum.
+ */
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/* Save the TidStoreIterResult for later, so we can extract the offsets. */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2657,6 +2680,7 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2677,7 +2701,17 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+
+	/* Set up the read stream */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (true)
 	{
 		BlockNumber blkno;
 		Buffer		buf;
@@ -2688,9 +2722,14 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point();
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		buf = read_stream_next_buffer(stream, (void **) &iter_result);
 
+		if (!BufferIsValid(buf))
+			break;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		Assert(iter_result);
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
 
@@ -2702,8 +2741,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2716,6 +2753,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



  [text/x-patch] v16-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch (5.9K, ../../CAAKRu_bmx33jTqATP5GKNFYwAg02a9dDtk4U_ciEjgBHZSVkOQ@mail.gmail.com/3-v16-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch)
  download | inline diff:
From 4d6e90bd73dc185415d0278a19b22c691b6fa598 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Tue, 11 Feb 2025 19:02:13 -0500
Subject: [PATCH v16 1/3] Convert heap_vac_scan_next_block() boolean parameters
 to flags

The read stream API only allows one piece of extra per block state to be
passed back to the API user. Heap vacuum needs to know whether or not a
given block was all-visible in the visibility map and whether or not it
was eagerly scanned. Convert these two pieces of information to flags so
that they can be passed as a single argument to
heap_vac_scan_next_block() (which will become the read stream API
callback for heap phase I vacuuming).
---
 src/backend/access/heap/vacuumlazy.c | 47 ++++++++++++++++------------
 1 file changed, 27 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8c387ae557e..25aeb23aa30 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,6 +248,13 @@ typedef enum
  */
 #define EAGER_SCAN_REGION_SIZE 4096
 
+/*
+ * heap_vac_scan_next_block() sets these statuses to communicate per-block
+ * information to the caller.
+ */
+#define VAC_BLK_WAS_EAGER_SCANNED (1 << 0)
+#define VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM (1 << 1)
+
 typedef struct LVRelState
 {
 	/* Target heap relation and its indexes */
@@ -417,8 +424,7 @@ static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
 static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm,
-									 bool *was_eager_scanned);
+									 uint8 *blk_flags);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1171,8 +1177,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm,
-				was_eager_scanned = false;
+	uint8		blk_flags = 0;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1196,8 +1201,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm,
-									&was_eager_scanned))
+	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_flags))
 	{
 		Buffer		buf;
 		Page		page;
@@ -1206,7 +1210,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		got_cleanup_lock = false;
 
 		vacrel->scanned_pages++;
-		if (was_eager_scanned)
+		if (blk_flags & VAC_BLK_WAS_EAGER_SCANNED)
 			vacrel->eager_scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1331,7 +1335,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer,
+							blk_flags & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
 							&has_lpdead_items, &vm_page_frozen);
 
 		/*
@@ -1348,7 +1353,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * exclude pages skipped due to cleanup lock contention from eager
 		 * freeze algorithm caps.
 		 */
-		if (got_cleanup_lock && was_eager_scanned)
+		if (got_cleanup_lock &&
+			blk_flags & VAC_BLK_WAS_EAGER_SCANNED)
 		{
 			/* Aggressive vacuums do not eager scan. */
 			Assert(!vacrel->aggressive);
@@ -1479,11 +1485,11 @@ lazy_scan_heap(LVRelState *vacrel)
  * and various thresholds to skip blocks which do not need to be processed and
  * sets blkno to the next block to process.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process. If the block is being eagerly
- * scanned, was_eager_scanned is set so that the caller can count whether or
- * not an eagerly scanned page is successfully frozen.
+ * The block number of the next block to process is set in *blkno and its
+ * visibility status and whether or not it was eager scanned is set in
+ * *blk_flags.
+ *
+ * The return value is false if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1493,15 +1499,14 @@ lazy_scan_heap(LVRelState *vacrel)
  */
 static bool
 heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm,
-						 bool *was_eager_scanned)
+						 uint8 *blk_flags)
 {
 	BlockNumber next_block;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*was_eager_scanned = false;
+	*blk_flags = 0;
 
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
@@ -1562,7 +1567,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * otherwise they would've been unskippable.
 		 */
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = true;
+		*blk_flags |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		return true;
 	}
 	else
@@ -1574,8 +1579,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		Assert(next_block == vacrel->next_unskippable_block);
 
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		*was_eager_scanned = vacrel->next_unskippable_eager_scanned;
+		if (vacrel->next_unskippable_allvis)
+			*blk_flags |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		if (vacrel->next_unskippable_eager_scanned)
+			*blk_flags |= VAC_BLK_WAS_EAGER_SCANNED;
 		return true;
 	}
 }
-- 
2.34.1



  [text/x-patch] v16-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch (11.0K, ../../CAAKRu_bmx33jTqATP5GKNFYwAg02a9dDtk4U_ciEjgBHZSVkOQ@mail.gmail.com/4-v16-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From e321b5caacfc231b0cb64d99881d60a487fa3a8a Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Wed, 5 Feb 2025 17:21:41 -0500
Subject: [PATCH v16 2/3] Use streaming read I/O in VACUUM's first phase

Make vacuum's first phase, which prunes and freezes tuples and records
dead TIDs, use the read stream API by by converting
heap_vac_scan_next_block() to a read stream callback.

Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 139 +++++++++++++++++----------
 1 file changed, 86 insertions(+), 53 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 25aeb23aa30..f705f31f5e6 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -153,6 +153,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -423,8 +424,9 @@ typedef struct LVSavedErrInfo
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 uint8 *blk_flags);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1174,10 +1176,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
-	uint8		blk_flags = 0;
+	uint8	   *blk_flags = NULL;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1201,7 +1204,16 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_flags))
+	/* Set up the read stream for vacuum's first pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(bool));
+
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
@@ -1209,15 +1221,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		vm_page_frozen = false;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-		if (blk_flags & VAC_BLK_WAS_EAGER_SCANNED)
-			vacrel->eager_scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point();
 
 		/*
@@ -1258,7 +1261,8 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages.  Note that blkno is the previously
+			 * processed block.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
 									blkno);
@@ -1269,6 +1273,25 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, (void **) &blk_flags);
+
+		if (!BufferIsValid(buf))
+			break;
+
+		Assert(blk_flags);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+		blkno = BufferGetBlockNumber(buf);
+
+		vacrel->scanned_pages++;
+		if (*blk_flags & VAC_BLK_WAS_EAGER_SCANNED)
+			vacrel->eager_scanned_pages++;
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1276,10 +1299,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1336,7 +1355,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
 							vmbuffer,
-							blk_flags & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
+							*blk_flags & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
 							&has_lpdead_items, &vm_page_frozen);
 
 		/*
@@ -1354,7 +1373,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * freeze algorithm caps.
 		 */
 		if (got_cleanup_lock &&
-			blk_flags & VAC_BLK_WAS_EAGER_SCANNED)
+			*blk_flags & VAC_BLK_WAS_EAGER_SCANNED)
 		{
 			/* Aggressive vacuums do not eager scan. */
 			Assert(!vacrel->aggressive);
@@ -1439,8 +1458,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	if (BufferIsValid(vmbuffer))
 		ReleaseBuffer(vmbuffer);
 
-	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	/*
+	 * Report that everything is now scanned. We never skip scanning the last
+	 * block in the relation, so we can pass rel_pages here.
+	 */
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
+								 rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1455,6 +1478,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1465,12 +1490,14 @@ lazy_scan_heap(LVRelState *vacrel)
 	/*
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
+	 * We can pass rel_pages here because we never skip scanning the last
+	 * block of the relation.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1478,30 +1505,37 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	heap_vac_scan_next_block() -- get next block for vacuum to process
- *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
- *
- * The block number of the next block to process is set in *blkno and its
- * visibility status and whether or not it was eager scanned is set in
- * *blk_flags.
- *
- * The return value is false if there are no further blocks to process.
- *
- * vacrel is an in/out parameter here.  Vacuum options and information about
- * the relation are read.  vacrel->skippedallvis is set if we skip a block
- * that's all-visible but not all-frozen, to ensure that we don't update
- * relfrozenxid in that case.  vacrel also holds information about the next
- * unskippable block, as bookkeeping for this function.
+ *	heap_vac_scan_next_block() -- read stream callback to get the next block
+ *	for vacuum to process
+ *
+ * Every time lazy_scan_heap() needs a new block to process during its first
+ * phase, it invokes read_stream_next_buffer() with a stream set up to call
+ * heap_vac_scan_next_block() to get the next block.
+ *
+ * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
+ * various thresholds to skip blocks which do not need to be processed and
+ * returns the next block to process or InvalidBlockNumber if there are no
+ * remaining blocks.
+ *
+ * The visibility status of the next block to process and whether or not it
+ * was eager scanned is set in the per_buffer_data.
+ *
+ * callback_private_data contains a reference to the LVRelState, passed to the
+ * read stream API during stream setup. The LVRelState is an in/out parameter
+ * here (locally named `vacrel`). Vacuum options and information about the
+ * relation are read from it. vacrel->skippedallvis is set if we skip a block
+ * that's all-visible but not all-frozen (to ensure that we don't update
+ * relfrozenxid in that case). vacrel also holds information about the next
+ * unskippable block -- as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 uint8 *blk_flags)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	uint8	   *blk_flags = per_buffer_data;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
@@ -1516,8 +1550,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1566,9 +1599,9 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		*blk_flags |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
-		return true;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1578,12 +1611,12 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		if (vacrel->next_unskippable_allvis)
 			*blk_flags |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		if (vacrel->next_unskippable_eager_scanned)
 			*blk_flags |= VAC_BLK_WAS_EAGER_SCANNED;
-		return true;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-13 23:07                                             ` Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Masahiko Sawada @ 2025-02-13 23:07 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Tue, Feb 11, 2025 at 5:10 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Thu, Feb 6, 2025 at 1:06 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> >
> > On Wed, Feb 5, 2025 at 5:26 PM Melanie Plageman
> > <melanieplageman@gmail.com> wrote:
> > >
> > > Yes, looking at these results, I also feel good about it. I've updated
> > > the commit metadata in attached v14, but I could use a round of review
> > > before pushing it.
> >
> > I've done a bit of self-review and updated these patches.
>
> This needed a rebase in light of 052026c9b90.
> v16 attached has an additional commit which converts the block
> information parameters to heap_vac_scan_next_block() into flags
> because we can only get one piece of information per block from the
> read stream API. This seemed nicer than a cumbersome struct.
>

Sorry for the late chiming in. I've reviewed the v16 patch set, and
the patches mostly look good. Here are some comments mostly about
cosmetic things:

0001:

-   bool        all_visible_according_to_vm,
-               was_eager_scanned = false;
+   uint8       blk_flags = 0;

Can we probably declare blk_flags inside the main loop?


0002:

In lazy_scan_heap(), we have a failsafe check at the beginning of the
main loop, which is performed before reading the first block. Isn't it
better to move this check after scanning a block (especially after
incrementing scanned_pages)? Otherwise, we would end up calling
lazy_check_wraparound_failsafe() at the very first loop, which
previously didn't happen without the patch. Since we already called
lazy_check_wraparound_failsafe() just before calling lazy_scan_heap(),
the extra check would not make much sense.

---
+   /* Set up the read stream for vacuum's first pass through the heap */
+   stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+                                       vacrel->bstrategy,
+                                       vacrel->rel,
+                                       MAIN_FORKNUM,
+                                       heap_vac_scan_next_block,
+                                       vacrel,
+                                       sizeof(bool));

Is there any reason to use sizeof(bool) instead of sizeof(uint8) here?

---
            /*
             * Vacuum the Free Space Map to make newly-freed space visible on
-            * upper-level FSM pages.  Note we have not yet processed blkno.
+            * upper-level FSM pages.  Note that blkno is the previously
+            * processed block.
             */
            FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
                                    blkno);

Given the blkno is already processed, should we pass 'blkno + 1'
instead of blkno?


0003:

-   while ((iter_result = TidStoreIterateNext(iter)) != NULL)

I think we can declare iter_result in the main loop of lazy_vacuum_heap_rel().

Regards,


--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
@ 2025-02-14 00:54                                               ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-14 00:54 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Thanks for your review! I've made the changes in attached v18.

I do want to know what you think we should do about what you brought
up about lazy_check_wraparound_failsafe() -- given my reply (below).

On Thu, Feb 13, 2025 at 6:08 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> Sorry for the late chiming in. I've reviewed the v16 patch set, and
> the patches mostly look good. Here are some comments mostly about
> cosmetic things:
>
> 0001:
>
> -   bool        all_visible_according_to_vm,
> -               was_eager_scanned = false;
> +   uint8       blk_flags = 0;
>
> Can we probably declare blk_flags inside the main loop?

I've done this in 0002 (can't in 0001 because of it being used inside
the while loop itself).

> 0002:
>
> In lazy_scan_heap(), we have a failsafe check at the beginning of the
> main loop, which is performed before reading the first block. Isn't it
> better to move this check after scanning a block (especially after
> incrementing scanned_pages)? Otherwise, we would end up calling
> lazy_check_wraparound_failsafe() at the very first loop, which
> previously didn't happen without the patch. Since we already called
> lazy_check_wraparound_failsafe() just before calling lazy_scan_heap(),
> the extra check would not make much sense.

Yes, I agonized over this a bit. The problem with calling
lazy_check_wraparound_failsafe() (and vacuum_delay_point() especially)
after reading the first block is that read_stream_next_buffer()
returns the buffer pinned. We don't want to hang onto that pin for a
long time. But I can't move them to the bottom of the loop after we
release the buffer because some of the code paths don't make it that
far. I don't see a good way other than how I did it or special-casing
block 0. What do you think?

> ---
> +   /* Set up the read stream for vacuum's first pass through the heap */
> +   stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
> +                                       vacrel->bstrategy,
> +                                       vacrel->rel,
> +                                       MAIN_FORKNUM,
> +                                       heap_vac_scan_next_block,
> +                                       vacrel,
> +                                       sizeof(bool));
>
> Is there any reason to use sizeof(bool) instead of sizeof(uint8) here?

Nope. That was a buglet (fixed in my v17 but I'm glad you caught it
too). Thanks!

>             /*
>              * Vacuum the Free Space Map to make newly-freed space visible on
> -            * upper-level FSM pages.  Note we have not yet processed blkno.
> +            * upper-level FSM pages.  Note that blkno is the previously
> +            * processed block.
>              */
>             FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
>                                     blkno);
>
> Given the blkno is already processed, should we pass 'blkno + 1'
> instead of blkno?

Good idea! Done in attached v18.

> 0003:
>
> -   while ((iter_result = TidStoreIterateNext(iter)) != NULL)
>
> I think we can declare iter_result in the main loop of lazy_vacuum_heap_rel().

Done.

- Melanie

Attachments:

  [text/x-patch] v18-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch (4.3K, ../../CAAKRu_YP=-Mu9rG+q8CBGFMsurMMv-8T-=is80RMr0kR+VbAfA@mail.gmail.com/2-v18-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From 7cd9bd45b2e6a7da333b3f6c1ec46bc9fa90ba8b Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 17:34:18 -0500
Subject: [PATCH v18 3/3] Use streaming read I/O in VACUUM's third phase

Make vacuum's third phase (its second pass over the heap), which reaps
dead items collected in the first phase and marks them as reusable, use
the read stream API. This commit adds a new read stream callback,
vacuum_reap_lp_read_stream_next(), that looks ahead in the TidStore and
returns the next block number to read for vacuum.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 55 +++++++++++++++++++++++++---
 1 file changed, 49 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index ea19eed57bf..3c4aa17892e 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2638,6 +2638,32 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+/*
+ * Read stream callback for vacuum's third phase (second pass over the heap).
+ * Gets the next block from the TID store and returns it or InvalidBlockNumber
+ * if there are no further blocks to vacuum.
+ */
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/*
+	 * Save the TidStoreIterResult for later, so we can extract the offsets.
+	 * It is safe to copy the result, according to TidStoreIterateNext().
+	 */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2658,11 +2684,11 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
 	TidStoreIter *iter;
-	TidStoreIterResult *iter_result;
 
 	Assert(vacrel->do_index_vacuuming);
 	Assert(vacrel->do_index_cleanup);
@@ -2678,20 +2704,37 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+
+	/* Set up the read stream for vacuum's second pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (true)
 	{
 		BlockNumber blkno;
 		Buffer		buf;
 		Page		page;
+		TidStoreIterResult *iter_result;
 		Size		freespace;
 		OffsetNumber offsets[MaxOffsetNumber];
 		int			num_offsets;
 
 		vacuum_delay_point(false);
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		buf = read_stream_next_buffer(stream, (void **) &iter_result);
 
+		/* The relation is exhausted */
+		if (!BufferIsValid(buf))
+			break;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		Assert(iter_result);
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
 
@@ -2703,8 +2746,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2717,6 +2758,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



  [text/x-patch] v18-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch (11.0K, ../../CAAKRu_YP=-Mu9rG+q8CBGFMsurMMv-8T-=is80RMr0kR+VbAfA@mail.gmail.com/3-v18-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From 18a30acd22c0720e38d6e54873137eeb728f3a99 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 17:34:12 -0500
Subject: [PATCH v18 2/3] Use streaming read I/O in VACUUM's first phase

Make vacuum's first phase, which prunes and freezes tuples and records
dead TIDs, use the read stream API by by converting
heap_vac_scan_next_block() to a read stream callback.

Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CAAKRu_aLwANZpxHc0tC-6OT0OQT4TftDGkKAO5yigMUOv_Tcsw%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 148 ++++++++++++++++-----------
 1 file changed, 91 insertions(+), 57 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index c4d0f77ee2f..ea19eed57bf 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -153,6 +153,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -423,8 +424,9 @@ typedef struct LVSavedErrInfo
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 uint8 *blk_info);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1174,10 +1176,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
-	uint8		blk_info = 0;
+	void	   *per_buffer_data = NULL;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1201,23 +1204,24 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_info))
+	/* Set up the read stream for vacuum's first pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(uint8));
+
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
+		uint8		blk_info = 0;
 		bool		has_lpdead_items;
 		bool		vm_page_frozen = false;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
-			vacrel->eager_scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point(false);
 
 		/*
@@ -1258,10 +1262,10 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages. Note we have not yet processed blkno+1.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
-									blkno);
+									blkno + 1);
 			next_fsm_block_to_vacuum = blkno;
 
 			/* Report that we are once again scanning the heap */
@@ -1269,6 +1273,26 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, &per_buffer_data);
+
+		/* The relation is exhausted. */
+		if (!BufferIsValid(buf))
+			break;
+
+		blk_info = *((uint8 *) per_buffer_data);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+		blkno = BufferGetBlockNumber(buf);
+
+		vacrel->scanned_pages++;
+		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
+			vacrel->eager_scanned_pages++;
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1276,10 +1300,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1439,8 +1459,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	if (BufferIsValid(vmbuffer))
 		ReleaseBuffer(vmbuffer);
 
-	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	/*
+	 * Report that everything is now scanned. We never skip scanning the last
+	 * block in the relation, so we can pass rel_pages here.
+	 */
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
+								 rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1455,6 +1479,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1465,12 +1491,14 @@ lazy_scan_heap(LVRelState *vacrel)
 	/*
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
+	 * We can pass rel_pages here because we never skip scanning the last
+	 * block of the relation.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1478,36 +1506,41 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	heap_vac_scan_next_block() -- get next block for vacuum to process
- *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
- *
- * The block number of the next block to process is set in *blkno and its
- * visibility status and whether or not it was eager scanned is set in
- * *blk_info.
- *
- * The return value is false if there are no further blocks to process.
- *
- * vacrel is an in/out parameter here.  Vacuum options and information about
- * the relation are read.  vacrel->skippedallvis is set if we skip a block
- * that's all-visible but not all-frozen, to ensure that we don't update
- * relfrozenxid in that case.  vacrel also holds information about the next
- * unskippable block, as bookkeeping for this function.
+ *	heap_vac_scan_next_block() -- read stream callback to get the next block
+ *	for vacuum to process
+ *
+ * Every time lazy_scan_heap() needs a new block to process during its first
+ * phase, it invokes read_stream_next_buffer() with a stream set up to call
+ * heap_vac_scan_next_block() to get the next block.
+ *
+ * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
+ * various thresholds to skip blocks which do not need to be processed and
+ * returns the next block to process or InvalidBlockNumber if there are no
+ * remaining blocks.
+ *
+ * The visibility status of the next block to process and whether or not it
+ * was eager scanned is set in the per_buffer_data.
+ *
+ * callback_private_data contains a reference to the LVRelState, passed to the
+ * read stream API during stream setup. The LVRelState is an in/out parameter
+ * here (locally named `vacrel`). Vacuum options and information about the
+ * relation are read from it. vacrel->skippedallvis is set if we skip a block
+ * that's all-visible but not all-frozen (to ensure that we don't update
+ * relfrozenxid in that case). vacrel also holds information about the next
+ * unskippable block -- as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 uint8 *blk_info)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	uint8		blk_info = 0;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*blk_info = 0;
-
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
 	{
@@ -1516,8 +1549,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1566,9 +1598,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
-		*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
-		return true;
+		vacrel->current_block = next_block;
+		blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		*((uint8 *) per_buffer_data) = blk_info;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1578,12 +1611,13 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		if (vacrel->next_unskippable_allvis)
-			*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+			blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		if (vacrel->next_unskippable_eager_scanned)
-			*blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
-		return true;
+			blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
+		*((uint8 *) per_buffer_data) = blk_info;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



  [text/x-patch] v18-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch (6.1K, ../../CAAKRu_YP=-Mu9rG+q8CBGFMsurMMv-8T-=is80RMr0kR+VbAfA@mail.gmail.com/4-v18-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch)
  download | inline diff:
From 25140d2966d2f87a4a410fc92147f2d88e587920 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 16:49:10 -0500
Subject: [PATCH v18 1/3] Convert heap_vac_scan_next_block() boolean parameters
 to flags

The read stream API only allows one piece of extra per block state to be
passed back to the API user. lazy_scan_heap() needs to know whether or
not a given block was all-visible in the visibility map and whether or
not it was eagerly scanned. Convert these two pieces of information to
flags so that they can be passed as a single argument to
heap_vac_scan_next_block() (which will become the read stream API
callback for heap phase I vacuuming).

Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CAAKRu_bmx33jTqATP5GKNFYwAg02a9dDtk4U_ciEjgBHZSVkOQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 47 ++++++++++++++++------------
 1 file changed, 27 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3df5b92afb8..c4d0f77ee2f 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,6 +248,13 @@ typedef enum
  */
 #define EAGER_SCAN_REGION_SIZE 4096
 
+/*
+ * heap_vac_scan_next_block() sets these flags to communicate information
+ * about the block it read to the caller.
+ */
+#define VAC_BLK_WAS_EAGER_SCANNED (1 << 0)
+#define VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM (1 << 1)
+
 typedef struct LVRelState
 {
 	/* Target heap relation and its indexes */
@@ -417,8 +424,7 @@ static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
 static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm,
-									 bool *was_eager_scanned);
+									 uint8 *blk_info);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1171,8 +1177,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm,
-				was_eager_scanned = false;
+	uint8		blk_info = 0;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1196,8 +1201,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm,
-									&was_eager_scanned))
+	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_info))
 	{
 		Buffer		buf;
 		Page		page;
@@ -1206,7 +1210,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		got_cleanup_lock = false;
 
 		vacrel->scanned_pages++;
-		if (was_eager_scanned)
+		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
 			vacrel->eager_scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1331,7 +1335,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer,
+							blk_info & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
 							&has_lpdead_items, &vm_page_frozen);
 
 		/*
@@ -1348,7 +1353,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * exclude pages skipped due to cleanup lock contention from eager
 		 * freeze algorithm caps.
 		 */
-		if (got_cleanup_lock && was_eager_scanned)
+		if (got_cleanup_lock &&
+			(blk_info & VAC_BLK_WAS_EAGER_SCANNED))
 		{
 			/* Aggressive vacuums do not eager scan. */
 			Assert(!vacrel->aggressive);
@@ -1479,11 +1485,11 @@ lazy_scan_heap(LVRelState *vacrel)
  * and various thresholds to skip blocks which do not need to be processed and
  * sets blkno to the next block to process.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process. If the block is being eagerly
- * scanned, was_eager_scanned is set so that the caller can count whether or
- * not an eagerly scanned page is successfully frozen.
+ * The block number of the next block to process is set in *blkno and its
+ * visibility status and whether or not it was eager scanned is set in
+ * *blk_info.
+ *
+ * The return value is false if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1493,15 +1499,14 @@ lazy_scan_heap(LVRelState *vacrel)
  */
 static bool
 heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm,
-						 bool *was_eager_scanned)
+						 uint8 *blk_info)
 {
 	BlockNumber next_block;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*was_eager_scanned = false;
+	*blk_info = 0;
 
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
@@ -1562,7 +1567,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * otherwise they would've been unskippable.
 		 */
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = true;
+		*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		return true;
 	}
 	else
@@ -1574,8 +1579,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		Assert(next_block == vacrel->next_unskippable_block);
 
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		*was_eager_scanned = vacrel->next_unskippable_eager_scanned;
+		if (vacrel->next_unskippable_allvis)
+			*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		if (vacrel->next_unskippable_eager_scanned)
+			*blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
 		return true;
 	}
 }
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-14 01:29                                                 ` Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Masahiko Sawada @ 2025-02-14 01:29 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Thu, Feb 13, 2025 at 4:55 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> Thanks for your review! I've made the changes in attached v18.
>
> I do want to know what you think we should do about what you brought
> up about lazy_check_wraparound_failsafe() -- given my reply (below).
>
> On Thu, Feb 13, 2025 at 6:08 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> >
> > Sorry for the late chiming in. I've reviewed the v16 patch set, and
> > the patches mostly look good. Here are some comments mostly about
> > cosmetic things:
> >
> > 0001:
> >
> > -   bool        all_visible_according_to_vm,
> > -               was_eager_scanned = false;
> > +   uint8       blk_flags = 0;
> >
> > Can we probably declare blk_flags inside the main loop?
>
> I've done this in 0002 (can't in 0001 because of it being used inside
> the while loop itself).

You're right, thanks.

>
> > 0002:
> >
> > In lazy_scan_heap(), we have a failsafe check at the beginning of the
> > main loop, which is performed before reading the first block. Isn't it
> > better to move this check after scanning a block (especially after
> > incrementing scanned_pages)? Otherwise, we would end up calling
> > lazy_check_wraparound_failsafe() at the very first loop, which
> > previously didn't happen without the patch. Since we already called
> > lazy_check_wraparound_failsafe() just before calling lazy_scan_heap(),
> > the extra check would not make much sense.
>
> Yes, I agonized over this a bit. The problem with calling
> lazy_check_wraparound_failsafe() (and vacuum_delay_point() especially)
> after reading the first block is that read_stream_next_buffer()
> returns the buffer pinned.

Good point.

> We don't want to hang onto that pin for a
> long time. But I can't move them to the bottom of the loop after we
> release the buffer because some of the code paths don't make it that
> far. I don't see a good way other than how I did it or special-casing
> block 0. What do you think?

How about adding 'vacrel->scanned_pages > 0' to the if statement?
Which seems not odd to me.

Looking at the 0002 patch, it seems you reverted the change to the
following comment:

  /*
   * Vacuum the Free Space Map to make newly-freed space visible on
-  * upper-level FSM pages.  Note we have not yet processed blkno.
+ * upper-level FSM pages. Note we have not yet processed blkno+1.
   */

I feel that the previous change I saw in v17 is clearer:

  /*
  * Vacuum the Free Space Map to make newly-freed space visible on
- * upper-level FSM pages.  Note we have not yet processed blkno.
+ * upper-level FSM pages.  Note that blkno is the previously
+ * processed block.
  */

The rest looks good to me.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
@ 2025-02-14 02:06                                                   ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-14 02:06 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Thu, Feb 13, 2025 at 8:30 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>
> On Thu, Feb 13, 2025 at 4:55 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> >
> > We don't want to hang onto that pin for a
> > long time. But I can't move them to the bottom of the loop after we
> > release the buffer because some of the code paths don't make it that
> > far. I don't see a good way other than how I did it or special-casing
> > block 0. What do you think?
>
> How about adding 'vacrel->scanned_pages > 0' to the if statement?
> Which seems not odd to me.

Cool. I've done this in attached v19.

> Looking at the 0002 patch, it seems you reverted the change to the
> following comment:
>
>   /*
>    * Vacuum the Free Space Map to make newly-freed space visible on
> -  * upper-level FSM pages.  Note we have not yet processed blkno.
> + * upper-level FSM pages. Note we have not yet processed blkno+1.
>    */
>
> I feel that the previous change I saw in v17 is clearer:

I've reverted to the old comment. Thanks

> The rest looks good to me.

Cool! I'll plan to push this tomorrow barring any objections.

- Melanie

Attachments:

  [text/x-patch] v19-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch (6.1K, ../../CAAKRu_Zbay2UeANcg-X455Q10nZJ_XH31Qph2wM4qDrZVa28JQ@mail.gmail.com/2-v19-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch)
  download | inline diff:
From 25140d2966d2f87a4a410fc92147f2d88e587920 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 16:49:10 -0500
Subject: [PATCH v19 1/3] Convert heap_vac_scan_next_block() boolean parameters
 to flags

The read stream API only allows one piece of extra per block state to be
passed back to the API user. lazy_scan_heap() needs to know whether or
not a given block was all-visible in the visibility map and whether or
not it was eagerly scanned. Convert these two pieces of information to
flags so that they can be passed as a single argument to
heap_vac_scan_next_block() (which will become the read stream API
callback for heap phase I vacuuming).

Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CAAKRu_bmx33jTqATP5GKNFYwAg02a9dDtk4U_ciEjgBHZSVkOQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 47 ++++++++++++++++------------
 1 file changed, 27 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3df5b92afb8..c4d0f77ee2f 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,6 +248,13 @@ typedef enum
  */
 #define EAGER_SCAN_REGION_SIZE 4096
 
+/*
+ * heap_vac_scan_next_block() sets these flags to communicate information
+ * about the block it read to the caller.
+ */
+#define VAC_BLK_WAS_EAGER_SCANNED (1 << 0)
+#define VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM (1 << 1)
+
 typedef struct LVRelState
 {
 	/* Target heap relation and its indexes */
@@ -417,8 +424,7 @@ static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
 static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm,
-									 bool *was_eager_scanned);
+									 uint8 *blk_info);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1171,8 +1177,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm,
-				was_eager_scanned = false;
+	uint8		blk_info = 0;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1196,8 +1201,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm,
-									&was_eager_scanned))
+	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_info))
 	{
 		Buffer		buf;
 		Page		page;
@@ -1206,7 +1210,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		got_cleanup_lock = false;
 
 		vacrel->scanned_pages++;
-		if (was_eager_scanned)
+		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
 			vacrel->eager_scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1331,7 +1335,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer,
+							blk_info & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
 							&has_lpdead_items, &vm_page_frozen);
 
 		/*
@@ -1348,7 +1353,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * exclude pages skipped due to cleanup lock contention from eager
 		 * freeze algorithm caps.
 		 */
-		if (got_cleanup_lock && was_eager_scanned)
+		if (got_cleanup_lock &&
+			(blk_info & VAC_BLK_WAS_EAGER_SCANNED))
 		{
 			/* Aggressive vacuums do not eager scan. */
 			Assert(!vacrel->aggressive);
@@ -1479,11 +1485,11 @@ lazy_scan_heap(LVRelState *vacrel)
  * and various thresholds to skip blocks which do not need to be processed and
  * sets blkno to the next block to process.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process. If the block is being eagerly
- * scanned, was_eager_scanned is set so that the caller can count whether or
- * not an eagerly scanned page is successfully frozen.
+ * The block number of the next block to process is set in *blkno and its
+ * visibility status and whether or not it was eager scanned is set in
+ * *blk_info.
+ *
+ * The return value is false if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1493,15 +1499,14 @@ lazy_scan_heap(LVRelState *vacrel)
  */
 static bool
 heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm,
-						 bool *was_eager_scanned)
+						 uint8 *blk_info)
 {
 	BlockNumber next_block;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*was_eager_scanned = false;
+	*blk_info = 0;
 
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
@@ -1562,7 +1567,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * otherwise they would've been unskippable.
 		 */
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = true;
+		*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		return true;
 	}
 	else
@@ -1574,8 +1579,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		Assert(next_block == vacrel->next_unskippable_block);
 
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		*was_eager_scanned = vacrel->next_unskippable_eager_scanned;
+		if (vacrel->next_unskippable_allvis)
+			*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		if (vacrel->next_unskippable_eager_scanned)
+			*blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
 		return true;
 	}
 }
-- 
2.34.1



  [text/x-patch] v19-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch (4.3K, ../../CAAKRu_Zbay2UeANcg-X455Q10nZJ_XH31Qph2wM4qDrZVa28JQ@mail.gmail.com/3-v19-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From 1c980c266cb2c1e91c2a86688f7d2e39da0d264d Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 17:34:18 -0500
Subject: [PATCH v19 3/3] Use streaming read I/O in VACUUM's third phase

Make vacuum's third phase (its second pass over the heap), which reaps
dead items collected in the first phase and marks them as reusable, use
the read stream API. This commit adds a new read stream callback,
vacuum_reap_lp_read_stream_next(), that looks ahead in the TidStore and
returns the next block number to read for vacuum.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 55 +++++++++++++++++++++++++---
 1 file changed, 49 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 08d89ab2bcd..74175e00534 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2640,6 +2640,32 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+/*
+ * Read stream callback for vacuum's third phase (second pass over the heap).
+ * Gets the next block from the TID store and returns it or InvalidBlockNumber
+ * if there are no further blocks to vacuum.
+ */
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/*
+	 * Save the TidStoreIterResult for later, so we can extract the offsets.
+	 * It is safe to copy the result, according to TidStoreIterateNext().
+	 */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2660,11 +2686,11 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
 	TidStoreIter *iter;
-	TidStoreIterResult *iter_result;
 
 	Assert(vacrel->do_index_vacuuming);
 	Assert(vacrel->do_index_cleanup);
@@ -2680,20 +2706,37 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+
+	/* Set up the read stream for vacuum's second pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (true)
 	{
 		BlockNumber blkno;
 		Buffer		buf;
 		Page		page;
+		TidStoreIterResult *iter_result;
 		Size		freespace;
 		OffsetNumber offsets[MaxOffsetNumber];
 		int			num_offsets;
 
 		vacuum_delay_point(false);
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		buf = read_stream_next_buffer(stream, (void **) &iter_result);
 
+		/* The relation is exhausted */
+		if (!BufferIsValid(buf))
+			break;
+
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		Assert(iter_result);
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
 
@@ -2705,8 +2748,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2719,6 +2760,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



  [text/x-patch] v19-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch (11.4K, ../../CAAKRu_Zbay2UeANcg-X455Q10nZJ_XH31Qph2wM4qDrZVa28JQ@mail.gmail.com/4-v19-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From ba4b9d8dd13c02bddb6a1013e9a05b4aea688036 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 17:34:12 -0500
Subject: [PATCH v19 2/3] Use streaming read I/O in VACUUM's first phase

Make vacuum's first phase, which prunes and freezes tuples and records
dead TIDs, use the read stream API by by converting
heap_vac_scan_next_block() to a read stream callback.

Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CAAKRu_aLwANZpxHc0tC-6OT0OQT4TftDGkKAO5yigMUOv_Tcsw%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 152 +++++++++++++++++----------
 1 file changed, 94 insertions(+), 58 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index c4d0f77ee2f..08d89ab2bcd 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -153,6 +153,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -423,8 +424,9 @@ typedef struct LVSavedErrInfo
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 uint8 *blk_info);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1174,10 +1176,11 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
-	uint8		blk_info = 0;
+	void	   *per_buffer_data = NULL;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1201,23 +1204,24 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_info))
+	/* Set up the read stream for vacuum's first pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(uint8));
+
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
+		uint8		blk_info = 0;
 		bool		has_lpdead_items;
 		bool		vm_page_frozen = false;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
-			vacrel->eager_scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point(false);
 
 		/*
@@ -1229,7 +1233,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * one-pass strategy, and the two-pass strategy with the index_cleanup
 		 * param set to 'off'.
 		 */
-		if (vacrel->scanned_pages % FAILSAFE_EVERY_PAGES == 0)
+		if (vacrel->scanned_pages > 0 &&
+			vacrel->scanned_pages % FAILSAFE_EVERY_PAGES == 0)
 			lazy_check_wraparound_failsafe(vacrel);
 
 		/*
@@ -1258,10 +1263,11 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages. Note that blkno is the previously
+			 * processed block.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
-									blkno);
+									blkno + 1);
 			next_fsm_block_to_vacuum = blkno;
 
 			/* Report that we are once again scanning the heap */
@@ -1269,6 +1275,26 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, &per_buffer_data);
+
+		/* The relation is exhausted. */
+		if (!BufferIsValid(buf))
+			break;
+
+		blk_info = *((uint8 *) per_buffer_data);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+		blkno = BufferGetBlockNumber(buf);
+
+		vacrel->scanned_pages++;
+		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
+			vacrel->eager_scanned_pages++;
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1276,10 +1302,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1439,8 +1461,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	if (BufferIsValid(vmbuffer))
 		ReleaseBuffer(vmbuffer);
 
-	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	/*
+	 * Report that everything is now scanned. We never skip scanning the last
+	 * block in the relation, so we can pass rel_pages here.
+	 */
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
+								 rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1455,6 +1481,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1465,12 +1493,14 @@ lazy_scan_heap(LVRelState *vacrel)
 	/*
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
+	 * We can pass rel_pages here because we never skip scanning the last
+	 * block of the relation.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1478,36 +1508,41 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	heap_vac_scan_next_block() -- get next block for vacuum to process
- *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
- *
- * The block number of the next block to process is set in *blkno and its
- * visibility status and whether or not it was eager scanned is set in
- * *blk_info.
- *
- * The return value is false if there are no further blocks to process.
- *
- * vacrel is an in/out parameter here.  Vacuum options and information about
- * the relation are read.  vacrel->skippedallvis is set if we skip a block
- * that's all-visible but not all-frozen, to ensure that we don't update
- * relfrozenxid in that case.  vacrel also holds information about the next
- * unskippable block, as bookkeeping for this function.
+ *	heap_vac_scan_next_block() -- read stream callback to get the next block
+ *	for vacuum to process
+ *
+ * Every time lazy_scan_heap() needs a new block to process during its first
+ * phase, it invokes read_stream_next_buffer() with a stream set up to call
+ * heap_vac_scan_next_block() to get the next block.
+ *
+ * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
+ * various thresholds to skip blocks which do not need to be processed and
+ * returns the next block to process or InvalidBlockNumber if there are no
+ * remaining blocks.
+ *
+ * The visibility status of the next block to process and whether or not it
+ * was eager scanned is set in the per_buffer_data.
+ *
+ * callback_private_data contains a reference to the LVRelState, passed to the
+ * read stream API during stream setup. The LVRelState is an in/out parameter
+ * here (locally named `vacrel`). Vacuum options and information about the
+ * relation are read from it. vacrel->skippedallvis is set if we skip a block
+ * that's all-visible but not all-frozen (to ensure that we don't update
+ * relfrozenxid in that case). vacrel also holds information about the next
+ * unskippable block -- as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 uint8 *blk_info)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	uint8		blk_info = 0;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*blk_info = 0;
-
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
 	{
@@ -1516,8 +1551,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1566,9 +1600,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
-		*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
-		return true;
+		vacrel->current_block = next_block;
+		blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		*((uint8 *) per_buffer_data) = blk_info;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1578,12 +1613,13 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		if (vacrel->next_unskippable_allvis)
-			*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+			blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		if (vacrel->next_unskippable_eager_scanned)
-			*blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
-		return true;
+			blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
+		*((uint8 *) per_buffer_data) = blk_info;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-14 18:15                                                     ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-14 18:15 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Thu, Feb 13, 2025 at 9:06 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Thu, Feb 13, 2025 at 8:30 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > The rest looks good to me.
>
> Cool! I'll plan to push this tomorrow barring any objections.

I've committed this and marked it as such in the CF app.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-14 18:30                                                       ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-14 18:30 UTC (permalink / raw)
  To: Masahiko Sawada <sawada.mshk@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Fri, Feb 14, 2025 at 1:15 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Thu, Feb 13, 2025 at 9:06 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> >
> > On Thu, Feb 13, 2025 at 8:30 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
> > > The rest looks good to me.
> >
> > Cool! I'll plan to push this tomorrow barring any objections.
>
> I've committed this and marked it as such in the CF app.

Seems valgrind doesn't like this [1]. I'm looking into it.

- Melanie

[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2025-02-14%2018%3A00%3A12





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-14 21:50                                                         ` Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-14 21:50 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sat, Feb 15, 2025 at 7:30 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> Seems valgrind doesn't like this [1]. I'm looking into it.

Melanie was able to reproduce this on her local valgrind and
eventually we figured out that it's my fault.  I put code into
read_stream.c that calls wipe_mem(), thinking that that was our
standard way of scribbling 0x7f on memory that you shouldn't access
again until it's reused.  I didn't realise that wipe_mem() also tells
valgrind that the memory is now "no access".  That makes sense for
palloc/pfree because when that range is allocated again it'll clear
that.  The point is to help people discover that they have a dangling
reference to per-buffer data after they advance to the next buffer,
which wouldn't work because it's in a circular queue and could be
overwritten any time after that.

This fixes it, but is not yet my proposed change:

@@ -193,9 +193,12 @@ read_stream_get_block(ReadStream *stream, void
*per_buffer_data)
        if (blocknum != InvalidBlockNumber)
                stream->buffered_blocknum = InvalidBlockNumber;
        else
+       {
+               VALGRIND_MAKE_MEM_UNDEFINED(per_buffer_data,
stream->per_buffer_data_size);
                blocknum = stream->callback(stream,

 stream->callback_private_data,

 per_buffer_data);
+       }

Thinking about how to make it more symmetrical...





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-02-14 22:54                                                           ` Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-14 22:54 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sat, Feb 15, 2025 at 10:50 AM Thomas Munro <thomas.munro@gmail.com> wrote:
> On Sat, Feb 15, 2025 at 7:30 AM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> > Seems valgrind doesn't like this [1]. I'm looking into it.
>
> Melanie was able to reproduce this on her local valgrind and
> eventually we figured out that it's my fault.  I put code into
> read_stream.c that calls wipe_mem(), thinking that that was our
> standard way of scribbling 0x7f on memory that you shouldn't access
> again until it's reused.  I didn't realise that wipe_mem() also tells
> valgrind that the memory is now "no access".  That makes sense for
> palloc/pfree because when that range is allocated again it'll clear
> that.  The point is to help people discover that they have a dangling
> reference to per-buffer data after they advance to the next buffer,
> which wouldn't work because it's in a circular queue and could be
> overwritten any time after that.

Here's a patch.  Is there a tidier way to write this?

It should probably be back-patched to 17, because external code might
use per-buffer data (obviously v17 core doesn't or skink would have
told us this sooner).   It's not a good time to push to 17 today,
though.  Push to master now to cheer skink up and 17 some time later
when the coast is clear, or just wait?

Attachments:

  [text/x-patch] 0001-Fix-explicit-valgrind-interaction-in-read_stream.c.patch (3.4K, ../../CA+hUKGJ84L0yFD2S05WeCOXmBgBcYb2S5wMmzyohcMJeCwgksw@mail.gmail.com/2-0001-Fix-explicit-valgrind-interaction-in-read_stream.c.patch)
  download | inline diff:
From bf4ba8b334c7ea6fcd33e8e6a6a4628c88161624 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Sat, 15 Feb 2025 11:06:30 +1300
Subject: [PATCH] Fix explicit valgrind interaction in read_stream.c.

By calling wipe_mem() on per-buffer data memory that has been released,
we are also telling Valgrind that the memory is "noaccess".  We need to
set it to "undefined" before giving it to the registered callback to
fill in, when a slot is reused.

As discovered by build farm animal skink when the VACUUM streamification
patches landed (the first users of per-buffer data).

Back-patch to 17, where read streams landed.  There aren't any users of
per-buffer data in 17, but extension code might do that.

Reported-by: Melanie Plageman <melanieplageman@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKG%2Bg6aXpi2FEHqeLOzE%2BxYw%3DOV%2B-N5jhOEnnV%2BF0USM9xA%40mail.gmail.com
---
 src/backend/storage/aio/read_stream.c | 39 ++++++++++++++++++++++-----
 1 file changed, 33 insertions(+), 6 deletions(-)

diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index e4414b2e915..d722eda7d8e 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -193,9 +193,20 @@ read_stream_get_block(ReadStream *stream, void *per_buffer_data)
 	if (blocknum != InvalidBlockNumber)
 		stream->buffered_blocknum = InvalidBlockNumber;
 	else
+	{
+		/*
+		 * Tell Valgrind that the per-buffer data is undefined.  That replaces
+		 * the "noaccess" state that was set when the consumer moved past this
+		 * entry last time around the queue, and should also catch callbacks
+		 * that fail to initialize data that the buffer consumer later
+		 * accesses.  On the first go around, it is undefined already.
+		 */
+		VALGRIND_MAKE_MEM_UNDEFINED(per_buffer_data,
+									stream->per_buffer_data_size);
 		blocknum = stream->callback(stream,
 									stream->callback_private_data,
 									per_buffer_data);
+	}
 
 	return blocknum;
 }
@@ -752,8 +763,11 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	}
 
 #ifdef CLOBBER_FREED_MEMORY
-	/* Clobber old buffer and per-buffer data for debugging purposes. */
+	/* Clobber old buffer for debugging purposes. */
 	stream->buffers[oldest_buffer_index] = InvalidBuffer;
+#endif
+
+#if defined(CLOBBER_FREED_MEMORY) || defined(USE_VALGRIND)
 
 	/*
 	 * The caller will get access to the per-buffer data, until the next call.
@@ -762,11 +776,24 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 	 * that is holding a dangling pointer to it.
 	 */
 	if (stream->per_buffer_data)
-		wipe_mem(get_per_buffer_data(stream,
-									 oldest_buffer_index == 0 ?
-									 stream->queue_size - 1 :
-									 oldest_buffer_index - 1),
-				 stream->per_buffer_data_size);
+	{
+		void	   *per_buffer_data;
+
+		per_buffer_data = get_per_buffer_data(stream,
+											  oldest_buffer_index == 0 ?
+											  stream->queue_size - 1 :
+											  oldest_buffer_index - 1);
+
+#if defined(CLOBBER_FREED_MEMORY)
+		/* This also tells Valgrind the memory is "noaccess". */
+		wipe_mem(get_per_buffer_data(per_buffer_data,
+									 stream->per_buffer_data_size));
+#elif defined(USE_VALGRIND)
+		/* Tell it ourselves. */
+		VALGRIND_MAKE_MEM_NO_ACCESS(per_buffer_data,
+									stream->per_buffer_data_size);
+#endif
+	}
 #endif
 
 	/* Pin transferred to caller. */
-- 
2.48.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-02-14 23:03                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Tom Lane @ 2025-02-14 23:03 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Thomas Munro <thomas.munro@gmail.com> writes:
> Here's a patch.  Is there a tidier way to write this?

Hmm, I think not with the current set of primitives.  We could think
about refactoring them, but that's not a job for a band-aid patch.

> It should probably be back-patched to 17, because external code might
> use per-buffer data (obviously v17 core doesn't or skink would have
> told us this sooner).   It's not a good time to push to 17 today,
> though.  Push to master now to cheer skink up and 17 some time later
> when the coast is clear, or just wait?

Agreed that right now is a bad time to push this to v17 --- we need to
keep the risk factors as low as possible for the re-release.  Master
now and v17 after the re-wrap seems like the right compromise.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-02-14 23:08                                                               ` Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-14 23:08 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sat, Feb 15, 2025 at 12:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Thomas Munro <thomas.munro@gmail.com> writes:
> > Here's a patch.  Is there a tidier way to write this?
>
> Hmm, I think not with the current set of primitives.  We could think
> about refactoring them, but that's not a job for a band-aid patch.

Thanks for looking.

> > It should probably be back-patched to 17, because external code might
> > use per-buffer data (obviously v17 core doesn't or skink would have
> > told us this sooner).   It's not a good time to push to 17 today,
> > though.  Push to master now to cheer skink up and 17 some time later
> > when the coast is clear, or just wait?
>
> Agreed that right now is a bad time to push this to v17 --- we need to
> keep the risk factors as low as possible for the re-release.  Master
> now and v17 after the re-wrap seems like the right compromise.

Cool, will push to master.  Melanie, could you please confirm that
this patch works for you?  I haven't figured out what I'm doing wrong
but my local Valgrind doesn't seem to show the problem (USE_VALGRIND
defined, Debian's Valgrind v3.19.0).





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-02-14 23:50                                                                 ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-14 23:50 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Fri, Feb 14, 2025 at 6:09 PM Thomas Munro <thomas.munro@gmail.com> wrote:
>
> > Agreed that right now is a bad time to push this to v17 --- we need to
> > keep the risk factors as low as possible for the re-release.  Master
> > now and v17 after the re-wrap seems like the right compromise.
>
> Cool, will push to master.  Melanie, could you please confirm that
> this patch works for you?  I haven't figured out what I'm doing wrong
> but my local Valgrind doesn't seem to show the problem (USE_VALGRIND
> defined, Debian's Valgrind v3.19.0).

It fixed the issue (after an off-list correction to the patch by Thomas).

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-15 01:23                                                                   ` Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-15 01:23 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sat, Feb 15, 2025 at 12:50 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> It fixed the issue (after an off-list correction to the patch by Thomas).

Thanks!  It's green again.





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-02-16 18:12                                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Tom Lane @ 2025-02-16 18:12 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Thomas Munro <thomas.munro@gmail.com> writes:
> Thanks!  It's green again.

The security team's Coverity instance complained about this patch:

*** CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
/srv/coverity/git/pgsql-git/postgresql/src/backend/access/heap/vacuumlazy.c: 1295 in lazy_scan_heap()
1289     		buf = read_stream_next_buffer(stream, &per_buffer_data);
1290     
1291     		/* The relation is exhausted. */
1292     		if (!BufferIsValid(buf))
1293     			break;
1294     
>>>     CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
>>>     Dereferencing null pointer "per_buffer_data".
1295     		blk_info = *((uint8 *) per_buffer_data);
1296     		CheckBufferIsPinnedOnce(buf);
1297     		page = BufferGetPage(buf);
1298     		blkno = BufferGetBlockNumber(buf);
1299     
1300     		vacrel->scanned_pages++;

Basically, Coverity doesn't understand that a successful call to
read_stream_next_buffer must set per_buffer_data here.  I don't
think there's much chance of teaching it that, so we'll just
have to dismiss this item as "intentional, not a bug".  However,
I do have a suggestion: I think the "per_buffer_data" variable
should be declared inside the "while (true)" loop not outside.
That way there is no chance of a value being carried across
iterations, so that if for some reason read_stream_next_buffer
failed to do what we expect and did not set per_buffer_data,
we'd be certain to get a null-pointer core dump rather than
accessing data from a previous buffer.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-02-18 14:31                                                                       ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-18 15:52                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  0 siblings, 2 replies; 81+ messages in thread

From: Melanie Plageman @ 2025-02-18 14:31 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Sun, Feb 16, 2025 at 1:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Thomas Munro <thomas.munro@gmail.com> writes:
> > Thanks!  It's green again.
>
> The security team's Coverity instance complained about this patch:
>
> *** CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
> /srv/coverity/git/pgsql-git/postgresql/src/backend/access/heap/vacuumlazy.c: 1295 in lazy_scan_heap()
> 1289                    buf = read_stream_next_buffer(stream, &per_buffer_data);
> 1290
> 1291                    /* The relation is exhausted. */
> 1292                    if (!BufferIsValid(buf))
> 1293                            break;
> 1294
> >>>     CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
> >>>     Dereferencing null pointer "per_buffer_data".
> 1295                    blk_info = *((uint8 *) per_buffer_data);
> 1296                    CheckBufferIsPinnedOnce(buf);
> 1297                    page = BufferGetPage(buf);
> 1298                    blkno = BufferGetBlockNumber(buf);
> 1299
> 1300                    vacrel->scanned_pages++;
>
> Basically, Coverity doesn't understand that a successful call to
> read_stream_next_buffer must set per_buffer_data here.  I don't
> think there's much chance of teaching it that, so we'll just
> have to dismiss this item as "intentional, not a bug".

Is this easy to do? Like is there a list of things from coverity to ignore?

> I do have a suggestion: I think the "per_buffer_data" variable
> should be declared inside the "while (true)" loop not outside.
> That way there is no chance of a value being carried across
> iterations, so that if for some reason read_stream_next_buffer
> failed to do what we expect and did not set per_buffer_data,
> we'd be certain to get a null-pointer core dump rather than
> accessing data from a previous buffer.

Done and pushed. Thanks!

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-18 15:52                                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 81+ messages in thread

From: Tom Lane @ 2025-02-18 15:52 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Melanie Plageman <melanieplageman@gmail.com> writes:
> On Sun, Feb 16, 2025 at 1:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> Basically, Coverity doesn't understand that a successful call to
>> read_stream_next_buffer must set per_buffer_data here.  I don't
>> think there's much chance of teaching it that, so we'll just
>> have to dismiss this item as "intentional, not a bug".

> Is this easy to do? Like is there a list of things from coverity to ignore?

Their website has a table of live issues, and we can just mark this
one "dismissed".  I'm not entirely sure how they recognize dismissed
issues --- it's not perfect, because old complaints tend to get
resurrected after changes in nearby code.  But it's good enough.

>> I do have a suggestion: I think the "per_buffer_data" variable
>> should be declared inside the "while (true)" loop not outside.

> Done and pushed. Thanks!

Thanks, looks better now.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-27 17:32                                                                         ` Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  1 sibling, 1 reply; 81+ messages in thread

From: Ranier Vilela @ 2025-02-27 17:32 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Hi.

Em ter., 18 de fev. de 2025 às 11:31, Melanie Plageman <
melanieplageman@gmail.com> escreveu:

> On Sun, Feb 16, 2025 at 1:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> >
> > Thomas Munro <thomas.munro@gmail.com> writes:
> > > Thanks!  It's green again.
> >
> > The security team's Coverity instance complained about this patch:
> >
> > *** CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
> >
> /srv/coverity/git/pgsql-git/postgresql/src/backend/access/heap/vacuumlazy.c:
> 1295 in lazy_scan_heap()
> > 1289                    buf = read_stream_next_buffer(stream,
> &per_buffer_data);
> > 1290
> > 1291                    /* The relation is exhausted. */
> > 1292                    if (!BufferIsValid(buf))
> > 1293                            break;
> > 1294
> > >>>     CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
> > >>>     Dereferencing null pointer "per_buffer_data".
> > 1295                    blk_info = *((uint8 *) per_buffer_data);
> > 1296                    CheckBufferIsPinnedOnce(buf);
> > 1297                    page = BufferGetPage(buf);
> > 1298                    blkno = BufferGetBlockNumber(buf);
> > 1299
> > 1300                    vacrel->scanned_pages++;
> >
> > Basically, Coverity doesn't understand that a successful call to
> > read_stream_next_buffer must set per_buffer_data here.  I don't
> > think there's much chance of teaching it that, so we'll just
> > have to dismiss this item as "intentional, not a bug".
>
> Is this easy to do? Like is there a list of things from coverity to ignore?
>
> > I do have a suggestion: I think the "per_buffer_data" variable
> > should be declared inside the "while (true)" loop not outside.
> > That way there is no chance of a value being carried across
> > iterations, so that if for some reason read_stream_next_buffer
> > failed to do what we expect and did not set per_buffer_data,
> > we'd be certain to get a null-pointer core dump rather than
> > accessing data from a previous buffer.
>
> Done and pushed. Thanks!
>
Per Coverity.

CID 1592454: (#1 of 1): Explicit null dereferenced (FORWARD_NULL)
8. var_deref_op: Dereferencing null pointer per_buffer_data.

I think that function *read_stream_next_buffer* can return
a invalid per_buffer_data pointer, with a valid buffer.

Sorry if I'm wrong, but the function is very suspicious.

Attached a patch, which tries to fix.

best regards,
Ranier Vilela

Attachments:

  [application/octet-stream] fix-possible-invalid-pointer-read_stream.patch (935B, ../../CAEudQAr_QXGB2DaK+BhTHuzw76FZCFSp54mzT3MSDn0E5XbcTA@mail.gmail.com/3-fix-possible-invalid-pointer-read_stream.patch)
  download | inline diff:
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 04bdb5e6d4..18e9b4f3c4 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -666,6 +666,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 										READ_BUFFERS_ISSUE_ADVICE : 0)))
 			{
 				/* Fast return. */
+				if (per_buffer_data)
+					*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
 				return buffer;
 			}
 
@@ -682,9 +684,14 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
 			stream->distance = 0;
 			stream->oldest_buffer_index = stream->next_buffer_index;
 			stream->pinned_buffers = 0;
+			oldest_buffer_index = stream->next_buffer_index;
 		}
 
 		stream->fast_path = false;
+
+		if (per_buffer_data)
+			*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
+
 		return buffer;
 	}
 #endif


^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
@ 2025-02-27 17:44                                                                           ` Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 81+ messages in thread

From: Andres Freund @ 2025-02-27 17:44 UTC (permalink / raw)
  To: Ranier Vilela <ranier.vf@gmail.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Hi,

On 2025-02-27 14:32:28 -0300, Ranier Vilela wrote:
> Hi.
> 
> Em ter., 18 de fev. de 2025 às 11:31, Melanie Plageman <
> melanieplageman@gmail.com> escreveu:
> 
> > On Sun, Feb 16, 2025 at 1:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > >
> > > Thomas Munro <thomas.munro@gmail.com> writes:
> > > > Thanks!  It's green again.
> > >
> > > The security team's Coverity instance complained about this patch:
> > >
> > > *** CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
> > >
> > /srv/coverity/git/pgsql-git/postgresql/src/backend/access/heap/vacuumlazy.c:
> > 1295 in lazy_scan_heap()
> > > 1289                    buf = read_stream_next_buffer(stream,
> > &per_buffer_data);
> > > 1290
> > > 1291                    /* The relation is exhausted. */
> > > 1292                    if (!BufferIsValid(buf))
> > > 1293                            break;
> > > 1294
> > > >>>     CID 1642971:  Null pointer dereferences  (FORWARD_NULL)
> > > >>>     Dereferencing null pointer "per_buffer_data".
> > > 1295                    blk_info = *((uint8 *) per_buffer_data);
> > > 1296                    CheckBufferIsPinnedOnce(buf);
> > > 1297                    page = BufferGetPage(buf);
> > > 1298                    blkno = BufferGetBlockNumber(buf);
> > > 1299
> > > 1300                    vacrel->scanned_pages++;
> > >
> > > Basically, Coverity doesn't understand that a successful call to
> > > read_stream_next_buffer must set per_buffer_data here.  I don't
> > > think there's much chance of teaching it that, so we'll just
> > > have to dismiss this item as "intentional, not a bug".
> >
> > Is this easy to do? Like is there a list of things from coverity to ignore?
> >
> > > I do have a suggestion: I think the "per_buffer_data" variable
> > > should be declared inside the "while (true)" loop not outside.
> > > That way there is no chance of a value being carried across
> > > iterations, so that if for some reason read_stream_next_buffer
> > > failed to do what we expect and did not set per_buffer_data,
> > > we'd be certain to get a null-pointer core dump rather than
> > > accessing data from a previous buffer.
> >
> > Done and pushed. Thanks!
> >
> Per Coverity.
> 
> CID 1592454: (#1 of 1): Explicit null dereferenced (FORWARD_NULL)
> 8. var_deref_op: Dereferencing null pointer per_buffer_data.

That's exactly what the messages you quoted are discussing, no?


> Sorry if I'm wrong, but the function is very suspicious.

How so?



> diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
> index 04bdb5e6d4..18e9b4f3c4 100644
> --- a/src/backend/storage/aio/read_stream.c
> +++ b/src/backend/storage/aio/read_stream.c
> @@ -666,6 +666,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
>  										READ_BUFFERS_ISSUE_ADVICE : 0)))
>  			{
>  				/* Fast return. */
> +				if (per_buffer_data)
> +					*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
>  				return buffer;
>  			}

A few lines above:
		Assert(stream->per_buffer_data_size == 0);

The fast path isn't used when per buffer data is used.  Adding a check for
per_buffer_data and assigning something to it is nonsensical.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
@ 2025-02-27 17:49                                                                             ` Andres Freund <andres@anarazel.de>
  2025-02-27 18:07                                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 18:08                                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 81+ messages in thread

From: Andres Freund @ 2025-02-27 17:49 UTC (permalink / raw)
  To: Ranier Vilela <ranier.vf@gmail.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Hi,

On 2025-02-27 12:44:24 -0500, Andres Freund wrote:
> > CID 1592454: (#1 of 1): Explicit null dereferenced (FORWARD_NULL)
> > 8. var_deref_op: Dereferencing null pointer per_buffer_data.
> 
> That's exactly what the messages you quoted are discussing, no?

Ah, no, it isn't. But I still think the coverity alert and the patch don't
make sense, as per the below:

> > diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
> > index 04bdb5e6d4..18e9b4f3c4 100644
> > --- a/src/backend/storage/aio/read_stream.c
> > +++ b/src/backend/storage/aio/read_stream.c
> > @@ -666,6 +666,8 @@ read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
> >  										READ_BUFFERS_ISSUE_ADVICE : 0)))
> >  			{
> >  				/* Fast return. */
> > +				if (per_buffer_data)
> > +					*per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
> >  				return buffer;
> >  			}
> 
> A few lines above:
> 		Assert(stream->per_buffer_data_size == 0);
> 
> The fast path isn't used when per buffer data is used.  Adding a check for
> per_buffer_data and assigning something to it is nonsensical.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
@ 2025-02-27 18:07                                                                               ` Ranier Vilela <ranier.vf@gmail.com>
  1 sibling, 0 replies; 81+ messages in thread

From: Ranier Vilela @ 2025-02-27 18:07 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Em qui., 27 de fev. de 2025 às 14:49, Andres Freund <andres@anarazel.de>
escreveu:

> Hi,
>
> On 2025-02-27 12:44:24 -0500, Andres Freund wrote:
> > > CID 1592454: (#1 of 1): Explicit null dereferenced (FORWARD_NULL)
> > > 8. var_deref_op: Dereferencing null pointer per_buffer_data.
> >
> > That's exactly what the messages you quoted are discussing, no?
>
> Ah, no, it isn't. But I still think the coverity alert and the patch don't
> make sense, as per the below:
>
> > > diff --git a/src/backend/storage/aio/read_stream.c
> b/src/backend/storage/aio/read_stream.c
> > > index 04bdb5e6d4..18e9b4f3c4 100644
> > > --- a/src/backend/storage/aio/read_stream.c
> > > +++ b/src/backend/storage/aio/read_stream.c
> > > @@ -666,6 +666,8 @@ read_stream_next_buffer(ReadStream *stream, void
> **per_buffer_data)
> > >
>      READ_BUFFERS_ISSUE_ADVICE : 0)))
> > >                     {
> > >                             /* Fast return. */
> > > +                           if (per_buffer_data)
> > > +                                   *per_buffer_data =
> get_per_buffer_data(stream, oldest_buffer_index);
> > >                             return buffer;
> > >                     }
> >
> > A few lines above:
> >               Assert(stream->per_buffer_data_size == 0);
> >
> > The fast path isn't used when per buffer data is used.  Adding a check
> for
> > per_buffer_data and assigning something to it is nonsensical.
>
Perhaps.

But the fast path and the parameter void **per_buffer_data,
IMHO, is a serious risk in my opinion.
Of course, when in runtime.

best regards,
Ranier Vilela

^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
@ 2025-02-27 18:08                                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-27 22:57                                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Tom Lane @ 2025-02-27 18:08 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Ranier Vilela <ranier.vf@gmail.com>; Melanie Plageman <melanieplageman@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Andres Freund <andres@anarazel.de> writes:
> Ah, no, it isn't. But I still think the coverity alert and the patch don't
> make sense, as per the below:

Coverity's alert makes perfect sense if you posit that Coverity
doesn't assume that this read_stream_next_buffer call will
only be applied to a stream that has per_buffer_data_size > 0.
(Even if it did understand that, I wouldn't assume that it's
smart enough to see that the fast path will never be taken.)

I wonder if it'd be a good idea to add something like

		Assert(stream->distance == 1);
		Assert(stream->pending_read_nblocks == 0);
		Assert(stream->per_buffer_data_size == 0);
+		Assert(per_buffer_data == NULL);

in read_stream_next_buffer.  I doubt that this will shut Coverity
up, but it would help to catch caller coding errors, i.e. passing
a per_buffer_data pointer when there's no per-buffer data.

On the whole I doubt we can get rid of this warning without some
significant redesign of the read_stream API, and I don't think
it's worth the trouble.  Coverity is a tool not a requirement.
I'm content to just dismiss the warning.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 18:08                                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-02-27 22:57                                                                                 ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-28 01:29                                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-27 22:57 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Ranier Vilela <ranier.vf@gmail.com>; Thomas Munro <thomas.munro@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Thu, Feb 27, 2025 at 1:08 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> I wonder if it'd be a good idea to add something like
>
>                 Assert(stream->distance == 1);
>                 Assert(stream->pending_read_nblocks == 0);
>                 Assert(stream->per_buffer_data_size == 0);
> +               Assert(per_buffer_data == NULL);
>
> in read_stream_next_buffer.  I doubt that this will shut Coverity
> up, but it would help to catch caller coding errors, i.e. passing
> a per_buffer_data pointer when there's no per-buffer data.

I think this is a good stopgap. I was discussing adding this assert
off-list with Thomas and he wanted to detail his more ambitious plans
for type safety improvements in the read stream API. Less on the order
of a redesign and more like a separate read_stream_next_buffer()s for
when there is per buffer data and when there isn't. And a by-value and
by-reference version for the one where there is data.

I'll plan to add this assert tomorrow if that discussion doesn't materialize.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 18:08                                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-27 22:57                                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-28 01:29                                                                                   ` Thomas Munro <thomas.munro@gmail.com>
  2025-02-28 02:13                                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-28 01:29 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Ranier Vilela <ranier.vf@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Fri, Feb 28, 2025 at 11:58 AM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> On Thu, Feb 27, 2025 at 1:08 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > I wonder if it'd be a good idea to add something like
> >
> >                 Assert(stream->distance == 1);
> >                 Assert(stream->pending_read_nblocks == 0);
> >                 Assert(stream->per_buffer_data_size == 0);
> > +               Assert(per_buffer_data == NULL);
> >
> > in read_stream_next_buffer.  I doubt that this will shut Coverity
> > up, but it would help to catch caller coding errors, i.e. passing
> > a per_buffer_data pointer when there's no per-buffer data.
>
> I think this is a good stopgap. I was discussing adding this assert
> off-list with Thomas and he wanted to detail his more ambitious plans
> for type safety improvements in the read stream API. Less on the order
> of a redesign and more like a separate read_stream_next_buffer()s for
> when there is per buffer data and when there isn't. And a by-value and
> by-reference version for the one where there is data.

Here's what I had in mind.  Is it better?

Attachments:

  [text/x-patch] 0001-Improve-API-for-retrieving-data-from-read-streams.patch (10.1K, ../../CA+hUKG+SWMtu9D1eevnbdzf=vurfuDjdFVM5WnX28Fxp-H3mYg@mail.gmail.com/2-0001-Improve-API-for-retrieving-data-from-read-streams.patch)
  download | inline diff:
From 68e9424b590051959142917459eb4ea074589b79 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Fri, 28 Feb 2025 10:48:29 +1300
Subject: [PATCH 1/2] Improve API for retrieving data from read streams.

Dealing with the per_buffer_data argument to read_stream_next_buffer()
has proven a bit clunky.  Provide some new wrapper functions/macros:

    buffer = read_stream_get_buffer(rs);
    buffer = read_stream_get_buffer_and_value(rs, &my_int);
    buffer = read_stream_get_buffer_and_pointer(rs, &my_pointer_to_int);

These improve readability and type safety via assertions.
---
 contrib/pg_prewarm/pg_prewarm.c          |  4 +-
 contrib/pg_visibility/pg_visibility.c    |  6 +--
 src/backend/access/heap/heapam.c         |  2 +-
 src/backend/access/heap/heapam_handler.c |  2 +-
 src/backend/access/heap/vacuumlazy.c     |  6 +--
 src/backend/storage/aio/read_stream.c    | 12 +++++
 src/backend/storage/buffer/bufmgr.c      |  4 +-
 src/include/storage/read_stream.h        | 64 ++++++++++++++++++++++++
 8 files changed, 87 insertions(+), 13 deletions(-)

diff --git a/contrib/pg_prewarm/pg_prewarm.c b/contrib/pg_prewarm/pg_prewarm.c
index a2f0ac4af0c..f6ae266d7b0 100644
--- a/contrib/pg_prewarm/pg_prewarm.c
+++ b/contrib/pg_prewarm/pg_prewarm.c
@@ -208,11 +208,11 @@ pg_prewarm(PG_FUNCTION_ARGS)
 			Buffer		buf;
 
 			CHECK_FOR_INTERRUPTS();
-			buf = read_stream_next_buffer(stream, NULL);
+			buf = read_stream_get_buffer(stream);
 			ReleaseBuffer(buf);
 			++blocks_done;
 		}
-		Assert(read_stream_next_buffer(stream, NULL) == InvalidBuffer);
+		Assert(read_stream_get_buffer(stream) == InvalidBuffer);
 		read_stream_end(stream);
 	}
 
diff --git a/contrib/pg_visibility/pg_visibility.c b/contrib/pg_visibility/pg_visibility.c
index 7f268a18a74..e7187a46c9d 100644
--- a/contrib/pg_visibility/pg_visibility.c
+++ b/contrib/pg_visibility/pg_visibility.c
@@ -556,7 +556,7 @@ collect_visibility_data(Oid relid, bool include_pd)
 			Buffer		buffer;
 			Page		page;
 
-			buffer = read_stream_next_buffer(stream, NULL);
+			buffer = read_stream_get_buffer(stream);
 			LockBuffer(buffer, BUFFER_LOCK_SHARE);
 
 			page = BufferGetPage(buffer);
@@ -569,7 +569,7 @@ collect_visibility_data(Oid relid, bool include_pd)
 
 	if (include_pd)
 	{
-		Assert(read_stream_next_buffer(stream, NULL) == InvalidBuffer);
+		Assert(read_stream_get_buffer(stream) == InvalidBuffer);
 		read_stream_end(stream);
 	}
 
@@ -752,7 +752,7 @@ collect_corrupt_items(Oid relid, bool all_visible, bool all_frozen)
 										0);
 
 	/* Loop over every block in the relation. */
-	while ((buffer = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
+	while ((buffer = read_stream_get_buffer(stream)) != InvalidBuffer)
 	{
 		bool		check_frozen = all_frozen;
 		bool		check_visible = all_visible;
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index fa7935a0ed3..86f280069e0 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -609,7 +609,7 @@ heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
 
 	scan->rs_dir = dir;
 
-	scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
+	scan->rs_cbuf = read_stream_get_buffer(scan->rs_read_stream);
 	if (BufferIsValid(scan->rs_cbuf))
 		scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
 }
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index e78682c3cef..7487896b06c 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -1010,7 +1010,7 @@ heapam_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
 	 * re-acquire sharelock for each tuple, but since we aren't doing much
 	 * work per tuple, the extra lock traffic is probably better avoided.
 	 */
-	hscan->rs_cbuf = read_stream_next_buffer(stream, NULL);
+	hscan->rs_cbuf = read_stream_get_buffer(stream);
 	if (!BufferIsValid(hscan->rs_cbuf))
 		return false;
 
diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1af18a78a2b..ac7a4d8c21d 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1230,7 +1230,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		Page		page;
 		uint8		blk_info = 0;
 		bool		has_lpdead_items;
-		void	   *per_buffer_data = NULL;
 		bool		vm_page_frozen = false;
 		bool		got_cleanup_lock = false;
 
@@ -1287,13 +1286,12 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
-		buf = read_stream_next_buffer(stream, &per_buffer_data);
+		buf = read_stream_get_buffer_and_value(stream, &blk_info);
 
 		/* The relation is exhausted. */
 		if (!BufferIsValid(buf))
 			break;
 
-		blk_info = *((uint8 *) per_buffer_data);
 		CheckBufferIsPinnedOnce(buf);
 		page = BufferGetPage(buf);
 		blkno = BufferGetBlockNumber(buf);
@@ -2740,7 +2738,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point(false);
 
-		buf = read_stream_next_buffer(stream, (void **) &iter_result);
+		buf = read_stream_get_buffer_and_pointer(stream, &iter_result);
 
 		/* The relation is exhausted */
 		if (!BufferIsValid(buf))
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 04bdb5e6d4b..0f1332c46f6 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -615,6 +615,9 @@ read_stream_begin_smgr_relation(int flags,
  * valid until the next call to read_stream_next_buffer().  When the stream
  * runs out of data, InvalidBuffer is returned.  The caller may decide to end
  * the stream early at any time by calling read_stream_end().
+ *
+ * See read_stream.h for read_stream_get_buffer() and variants that provide
+ * some degree of type safety for the per_buffer_data argument.
  */
 Buffer
 read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
@@ -840,6 +843,15 @@ read_stream_next_block(ReadStream *stream, BufferAccessStrategy *strategy)
 	return read_stream_get_block(stream, NULL);
 }
 
+/*
+ * Return the configured per-buffer data size, for use in assertions.
+ */
+size_t
+read_stream_per_buffer_data_size(ReadStream *stream)
+{
+	return stream->per_buffer_data_size;
+}
+
 /*
  * Reset a read stream by releasing any queued up buffers, allowing the stream
  * to be used again for different blocks.  This can be used to clear an
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 7915ed624c1..f4cedd15109 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4690,7 +4690,7 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
 		CHECK_FOR_INTERRUPTS();
 
 		/* Read block from source relation. */
-		srcBuf = read_stream_next_buffer(src_stream, NULL);
+		srcBuf = read_stream_get_buffer(src_stream);
 		LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
 		srcPage = BufferGetPage(srcBuf);
 
@@ -4715,7 +4715,7 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
 		UnlockReleaseBuffer(dstBuf);
 		UnlockReleaseBuffer(srcBuf);
 	}
-	Assert(read_stream_next_buffer(src_stream, NULL) == InvalidBuffer);
+	Assert(read_stream_get_buffer(src_stream) == InvalidBuffer);
 	read_stream_end(src_stream);
 
 	FreeAccessStrategy(bstrategy_src);
diff --git a/src/include/storage/read_stream.h b/src/include/storage/read_stream.h
index c11d8ce3300..68c9340b0e3 100644
--- a/src/include/storage/read_stream.h
+++ b/src/include/storage/read_stream.h
@@ -70,6 +70,7 @@ extern ReadStream *read_stream_begin_relation(int flags,
 extern Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data);
 extern BlockNumber read_stream_next_block(ReadStream *stream,
 										  BufferAccessStrategy *strategy);
+extern size_t read_stream_per_buffer_data_size(ReadStream *stream);
 extern ReadStream *read_stream_begin_smgr_relation(int flags,
 												   BufferAccessStrategy strategy,
 												   SMgrRelation smgr,
@@ -81,4 +82,67 @@ extern ReadStream *read_stream_begin_smgr_relation(int flags,
 extern void read_stream_reset(ReadStream *stream);
 extern void read_stream_end(ReadStream *stream);
 
+/*
+ * Get the next buffer from a stream that is not using per-buffer data.
+ */
+static inline Buffer
+read_stream_get_buffer(ReadStream *stream)
+{
+	Assert(read_stream_per_buffer_data_size(stream) == 0);
+	return read_stream_next_buffer(stream, NULL);
+}
+
+/*
+ * Inlinable helper for read_stream_get_buffer_and_value() macro.
+ */
+static inline Buffer
+read_stream_get_buffer_and_value_with_size(ReadStream *stream,
+										   void *output_data,
+										   size_t output_data_size)
+{
+	Buffer		buffer;
+	void	   *per_buffer_data;
+
+	Assert(read_stream_per_buffer_data_size(stream) == output_data_size);
+	buffer = read_stream_next_buffer(stream, &per_buffer_data);
+	if (buffer != InvalidBuffer)
+		memcpy(output_data, per_buffer_data, output_data_size);
+
+	return buffer;
+}
+
+/*
+ * Get the next buffer and a copy of the associated per-buffer data.
+ * InvalidBuffer means end-of-stream, and in that case the per-buffer data is
+ * undefined.  Example of use:
+ *
+ * int my_int;
+ *
+ * buf = read_stream_get_buffer_and_value(stream, &my_int);
+ */
+#define read_stream_get_buffer_and_value(stream, vp) \
+	read_stream_get_buffer_and_value_with_size((stream), (vp), sizeof(*(vp)))
+
+/*
+ * Get the next buffer and a pointer to the associated per-buffer data.  This
+ * avoids casts, while still checking that we have the expected level of
+ * indirection.  InvalidBuffer means end-of-stream, and in that case the output
+ * pointer is undefined.  Otherwise the output pointer should only be
+ * dereferenced up until the next call.  For example:
+ *
+ * int *my_int_p;
+ *
+ * buf = read_stream_get_buffer_and_pointer(stream, &my_int_p);
+ */
+#if HAVE__BUILTIN_TYPES_COMPATIBLE_P
+#define read_stream_get_buffer_and_pointer(stream, pointer) \
+	(StaticAssertExpr(!__builtin_types_compatible_p(__typeof__(**(pointer)), \
+													void), \
+					  "expected pointer to pointer to non-void"), \
+	 read_stream_next_buffer((stream), ((void **) (pointer))))
+#else
+#define read_stream_get_buffer_and_pointer(stream, pointer) \
+	read_stream_next_buffer((stream), ((void **) (pointer)))
+#endif
+
 #endif							/* READ_STREAM_H */
-- 
2.48.1



  [text/x-patch] 0002-Improve-API-for-storing-data-in-read-streams.patch (2.9K, ../../CA+hUKG+SWMtu9D1eevnbdzf=vurfuDjdFVM5WnX28Fxp-H3mYg@mail.gmail.com/3-0002-Improve-API-for-storing-data-in-read-streams.patch)
  download | inline diff:
From 02bb13b80abc20cd8221287b4c908f9c7c0dde23 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Fri, 28 Feb 2025 12:53:23 +1300
Subject: [PATCH 2/2] Improve API for storing data in read streams.

Read stream callbacks receive a void pointer into the per-buffer data
queue so that can store data there for later retrieval by the buffer
consumer.  We can improve readability and safety a bit by changing
cast-and-assign or raw memcpy() to:

	read_stream_put_value(stream, per_buffer_data, my_int);

This form infers the size and asserts that the storage space matches,
generally mirroring the read_stream_get_buffer_and_value() call used for
retrieving the streamed data later.
---
 src/backend/access/heap/vacuumlazy.c | 6 +++---
 src/include/storage/read_stream.h    | 9 +++++++++
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index ac7a4d8c21d..9563906fb27 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1612,7 +1612,7 @@ heap_vac_scan_next_block(ReadStream *stream,
 		 */
 		vacrel->current_block = next_block;
 		blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
-		*((uint8 *) per_buffer_data) = blk_info;
+		read_stream_put_value(stream, per_buffer_data, blk_info);
 		return vacrel->current_block;
 	}
 	else
@@ -1628,7 +1628,7 @@ heap_vac_scan_next_block(ReadStream *stream,
 			blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		if (vacrel->next_unskippable_eager_scanned)
 			blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
-		*((uint8 *) per_buffer_data) = blk_info;
+		read_stream_put_value(stream, per_buffer_data, blk_info);
 		return vacrel->current_block;
 	}
 }
@@ -2671,7 +2671,7 @@ vacuum_reap_lp_read_stream_next(ReadStream *stream,
 	 * Save the TidStoreIterResult for later, so we can extract the offsets.
 	 * It is safe to copy the result, according to TidStoreIterateNext().
 	 */
-	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+	read_stream_put_value(stream, per_buffer_data, *iter_result);
 
 	return iter_result->blkno;
 }
diff --git a/src/include/storage/read_stream.h b/src/include/storage/read_stream.h
index 68c9340b0e3..673dd75ccaf 100644
--- a/src/include/storage/read_stream.h
+++ b/src/include/storage/read_stream.h
@@ -145,4 +145,13 @@ read_stream_get_buffer_and_value_with_size(ReadStream *stream,
 	read_stream_next_buffer((stream), ((void **) (pointer)))
 #endif
 
+/*
+ * Set the per-buffer data by value.  This can be called from inside a
+ * callback that is returning block numbers.  It asserts that the value's size
+ * matches the available space.
+ */
+#define read_stream_put_value(stream, per_buffer_data, value) \
+	(AssertMacro(sizeof(value) == read_stream_per_buffer_data_size(stream)), \
+	 memcpy((per_buffer_data), &(value), sizeof(value)))
+
 #endif							/* READ_STREAM_H */
-- 
2.48.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 18:08                                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-27 22:57                                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-28 01:29                                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-02-28 02:13                                                                                     ` Thomas Munro <thomas.munro@gmail.com>
  2025-08-06 17:39                                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-28 02:13 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Ranier Vilela <ranier.vf@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Fri, Feb 28, 2025 at 2:29 PM Thomas Munro <thomas.munro@gmail.com> wrote:
> On Fri, Feb 28, 2025 at 11:58 AM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> > On Thu, Feb 27, 2025 at 1:08 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > > I wonder if it'd be a good idea to add something like
> > >
> > >                 Assert(stream->distance == 1);
> > >                 Assert(stream->pending_read_nblocks == 0);
> > >                 Assert(stream->per_buffer_data_size == 0);
> > > +               Assert(per_buffer_data == NULL);
> > >
> > > in read_stream_next_buffer.  I doubt that this will shut Coverity
> > > up, but it would help to catch caller coding errors, i.e. passing
> > > a per_buffer_data pointer when there's no per-buffer data.
> >
> > I think this is a good stopgap. I was discussing adding this assert
> > off-list with Thomas and he wanted to detail his more ambitious plans
> > for type safety improvements in the read stream API. Less on the order
> > of a redesign and more like a separate read_stream_next_buffer()s for
> > when there is per buffer data and when there isn't. And a by-value and
> > by-reference version for the one where there is data.
>
> Here's what I had in mind.  Is it better?

Here's a slightly better one.  I think when you use
read_stream_get_buffer_and_value(stream, &value), or
read_stream_put_value(stream, space, value), then we should assert
that sizeof(value) strictly matches the available space, as shown.  But,
new in v2, if you use read_stream_get_buffer_and_pointer(stream,
&pointer), then sizeof(*pointer) should only have to  be <= the
storage space, not ==, because someone might plausibly want to make
per_buffer_data_size variable at runtime (ie decide when they
construct the stream), and then be able to retrieve a pointer to the
start of a struct with a flexible array or something like that.  In v1
I was just trying to assert that it was a
pointer-to-a-pointer-to-something and no more (in a confusing
compile-time assertion), but v2 is simpler, and is happy with a
pointer to a pointer to something that doesn't exceed the space
(run-time assertion).

Attachments:

  [application/x-patch] v2-0001-Improve-API-for-retrieving-data-from-read-streams.patch (9.7K, ../../CA+hUKGLa7ba7USyT+JR7uRiawWeCVJ96wyRsoEXk7r2gngPv=A@mail.gmail.com/2-v2-0001-Improve-API-for-retrieving-data-from-read-streams.patch)
  download | inline diff:
From b2dd9c90f970a889deea2c2e9e16097e4e06ece8 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Fri, 28 Feb 2025 10:48:29 +1300
Subject: [PATCH v2 1/2] Improve API for retrieving data from read streams.

Dealing with the per_buffer_data argument to read_stream_next_buffer()
has proven a bit clunky.  Provide some new wrapper functions/macros:

    buffer = read_stream_get_buffer(rs);
    buffer = read_stream_get_buffer_and_value(rs, &my_int);
    buffer = read_stream_get_buffer_and_pointer(rs, &my_pointer_to_int);

These improve readability and type safety via assertions.
---
 contrib/pg_prewarm/pg_prewarm.c          |  4 +-
 contrib/pg_visibility/pg_visibility.c    |  6 +--
 src/backend/access/heap/heapam.c         |  2 +-
 src/backend/access/heap/heapam_handler.c |  2 +-
 src/backend/access/heap/vacuumlazy.c     |  6 +--
 src/backend/storage/aio/read_stream.c    | 12 ++++++
 src/backend/storage/buffer/bufmgr.c      |  4 +-
 src/include/storage/read_stream.h        | 55 ++++++++++++++++++++++++
 8 files changed, 78 insertions(+), 13 deletions(-)

diff --git a/contrib/pg_prewarm/pg_prewarm.c b/contrib/pg_prewarm/pg_prewarm.c
index a2f0ac4af0c..f6ae266d7b0 100644
--- a/contrib/pg_prewarm/pg_prewarm.c
+++ b/contrib/pg_prewarm/pg_prewarm.c
@@ -208,11 +208,11 @@ pg_prewarm(PG_FUNCTION_ARGS)
 			Buffer		buf;
 
 			CHECK_FOR_INTERRUPTS();
-			buf = read_stream_next_buffer(stream, NULL);
+			buf = read_stream_get_buffer(stream);
 			ReleaseBuffer(buf);
 			++blocks_done;
 		}
-		Assert(read_stream_next_buffer(stream, NULL) == InvalidBuffer);
+		Assert(read_stream_get_buffer(stream) == InvalidBuffer);
 		read_stream_end(stream);
 	}
 
diff --git a/contrib/pg_visibility/pg_visibility.c b/contrib/pg_visibility/pg_visibility.c
index 7f268a18a74..e7187a46c9d 100644
--- a/contrib/pg_visibility/pg_visibility.c
+++ b/contrib/pg_visibility/pg_visibility.c
@@ -556,7 +556,7 @@ collect_visibility_data(Oid relid, bool include_pd)
 			Buffer		buffer;
 			Page		page;
 
-			buffer = read_stream_next_buffer(stream, NULL);
+			buffer = read_stream_get_buffer(stream);
 			LockBuffer(buffer, BUFFER_LOCK_SHARE);
 
 			page = BufferGetPage(buffer);
@@ -569,7 +569,7 @@ collect_visibility_data(Oid relid, bool include_pd)
 
 	if (include_pd)
 	{
-		Assert(read_stream_next_buffer(stream, NULL) == InvalidBuffer);
+		Assert(read_stream_get_buffer(stream) == InvalidBuffer);
 		read_stream_end(stream);
 	}
 
@@ -752,7 +752,7 @@ collect_corrupt_items(Oid relid, bool all_visible, bool all_frozen)
 										0);
 
 	/* Loop over every block in the relation. */
-	while ((buffer = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
+	while ((buffer = read_stream_get_buffer(stream)) != InvalidBuffer)
 	{
 		bool		check_frozen = all_frozen;
 		bool		check_visible = all_visible;
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index fa7935a0ed3..86f280069e0 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -609,7 +609,7 @@ heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
 
 	scan->rs_dir = dir;
 
-	scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
+	scan->rs_cbuf = read_stream_get_buffer(scan->rs_read_stream);
 	if (BufferIsValid(scan->rs_cbuf))
 		scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
 }
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index e78682c3cef..7487896b06c 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -1010,7 +1010,7 @@ heapam_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
 	 * re-acquire sharelock for each tuple, but since we aren't doing much
 	 * work per tuple, the extra lock traffic is probably better avoided.
 	 */
-	hscan->rs_cbuf = read_stream_next_buffer(stream, NULL);
+	hscan->rs_cbuf = read_stream_get_buffer(stream);
 	if (!BufferIsValid(hscan->rs_cbuf))
 		return false;
 
diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1af18a78a2b..ac7a4d8c21d 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1230,7 +1230,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		Page		page;
 		uint8		blk_info = 0;
 		bool		has_lpdead_items;
-		void	   *per_buffer_data = NULL;
 		bool		vm_page_frozen = false;
 		bool		got_cleanup_lock = false;
 
@@ -1287,13 +1286,12 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
-		buf = read_stream_next_buffer(stream, &per_buffer_data);
+		buf = read_stream_get_buffer_and_value(stream, &blk_info);
 
 		/* The relation is exhausted. */
 		if (!BufferIsValid(buf))
 			break;
 
-		blk_info = *((uint8 *) per_buffer_data);
 		CheckBufferIsPinnedOnce(buf);
 		page = BufferGetPage(buf);
 		blkno = BufferGetBlockNumber(buf);
@@ -2740,7 +2738,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point(false);
 
-		buf = read_stream_next_buffer(stream, (void **) &iter_result);
+		buf = read_stream_get_buffer_and_pointer(stream, &iter_result);
 
 		/* The relation is exhausted */
 		if (!BufferIsValid(buf))
diff --git a/src/backend/storage/aio/read_stream.c b/src/backend/storage/aio/read_stream.c
index 04bdb5e6d4b..0f1332c46f6 100644
--- a/src/backend/storage/aio/read_stream.c
+++ b/src/backend/storage/aio/read_stream.c
@@ -615,6 +615,9 @@ read_stream_begin_smgr_relation(int flags,
  * valid until the next call to read_stream_next_buffer().  When the stream
  * runs out of data, InvalidBuffer is returned.  The caller may decide to end
  * the stream early at any time by calling read_stream_end().
+ *
+ * See read_stream.h for read_stream_get_buffer() and variants that provide
+ * some degree of type safety for the per_buffer_data argument.
  */
 Buffer
 read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
@@ -840,6 +843,15 @@ read_stream_next_block(ReadStream *stream, BufferAccessStrategy *strategy)
 	return read_stream_get_block(stream, NULL);
 }
 
+/*
+ * Return the configured per-buffer data size, for use in assertions.
+ */
+size_t
+read_stream_per_buffer_data_size(ReadStream *stream)
+{
+	return stream->per_buffer_data_size;
+}
+
 /*
  * Reset a read stream by releasing any queued up buffers, allowing the stream
  * to be used again for different blocks.  This can be used to clear an
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 7915ed624c1..f4cedd15109 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4690,7 +4690,7 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
 		CHECK_FOR_INTERRUPTS();
 
 		/* Read block from source relation. */
-		srcBuf = read_stream_next_buffer(src_stream, NULL);
+		srcBuf = read_stream_get_buffer(src_stream);
 		LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
 		srcPage = BufferGetPage(srcBuf);
 
@@ -4715,7 +4715,7 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
 		UnlockReleaseBuffer(dstBuf);
 		UnlockReleaseBuffer(srcBuf);
 	}
-	Assert(read_stream_next_buffer(src_stream, NULL) == InvalidBuffer);
+	Assert(read_stream_get_buffer(src_stream) == InvalidBuffer);
 	read_stream_end(src_stream);
 
 	FreeAccessStrategy(bstrategy_src);
diff --git a/src/include/storage/read_stream.h b/src/include/storage/read_stream.h
index c11d8ce3300..c6066c0f296 100644
--- a/src/include/storage/read_stream.h
+++ b/src/include/storage/read_stream.h
@@ -70,6 +70,7 @@ extern ReadStream *read_stream_begin_relation(int flags,
 extern Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data);
 extern BlockNumber read_stream_next_block(ReadStream *stream,
 										  BufferAccessStrategy *strategy);
+extern size_t read_stream_per_buffer_data_size(ReadStream *stream);
 extern ReadStream *read_stream_begin_smgr_relation(int flags,
 												   BufferAccessStrategy strategy,
 												   SMgrRelation smgr,
@@ -81,4 +82,58 @@ extern ReadStream *read_stream_begin_smgr_relation(int flags,
 extern void read_stream_reset(ReadStream *stream);
 extern void read_stream_end(ReadStream *stream);
 
+/*
+ * Get the next buffer from a stream that is not using per-buffer data.
+ */
+static inline Buffer
+read_stream_get_buffer(ReadStream *stream)
+{
+	Assert(read_stream_per_buffer_data_size(stream) == 0);
+	return read_stream_next_buffer(stream, NULL);
+}
+
+/*
+ * Helper for read_stream_get_buffer_and_value().
+ */
+static inline Buffer
+read_stream_get_buffer_and_value_with_size(ReadStream *stream,
+										   void *output_data,
+										   size_t output_data_size)
+{
+	Buffer		buffer;
+	void	   *per_buffer_data;
+
+	Assert(read_stream_per_buffer_data_size(stream) == output_data_size);
+	buffer = read_stream_next_buffer(stream, &per_buffer_data);
+	if (buffer != InvalidBuffer)
+		memcpy(output_data, per_buffer_data, output_data_size);
+
+	return buffer;
+}
+
+/*
+ * Get the next buffer and a copy of the associated per-buffer data.
+ * InvalidBuffer means end-of-stream, and in that case the per-buffer data is
+ * undefined.  Example of use:
+ *
+ * int my_int;
+ *
+ * buf = read_stream_get_buffer_and_value(stream, &my_int);
+ */
+#define read_stream_get_buffer_and_value(stream, vp) \
+	read_stream_get_buffer_and_value_with_size((stream), (vp), sizeof(*(vp)))
+
+/*
+ * Get the next buffer and a pointer to the associated per-buffer data.  This
+ * avoids casts in the calling code, and asserts that we received a pointer to
+ * a pointer to a type that doesn't exceed the storage size.  For example:
+ *
+ * int *my_int_p;
+ *
+ * buf = read_stream_get_buffer_and_pointer(stream, &my_int_p);
+ */
+#define read_stream_get_buffer_and_pointer(stream, pointer) \
+	(AssertMacro(sizeof(**(pointer)) <= read_stream_per_buffer_data_size(stream)), \
+	 read_stream_next_buffer((stream), ((void **) (pointer))))
+
 #endif							/* READ_STREAM_H */
-- 
2.48.1



  [application/x-patch] v2-0002-Improve-API-for-storing-data-in-read-streams.patch (2.9K, ../../CA+hUKGLa7ba7USyT+JR7uRiawWeCVJ96wyRsoEXk7r2gngPv=A@mail.gmail.com/3-v2-0002-Improve-API-for-storing-data-in-read-streams.patch)
  download | inline diff:
From 2586d9c7321391168a40cb0f14e5a80182792b64 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Fri, 28 Feb 2025 12:53:23 +1300
Subject: [PATCH v2 2/2] Improve API for storing data in read streams.

Read stream callbacks receive a void pointer into the per-buffer data
queue so that can store data there for later retrieval by the buffer
consumer.  We can improve readability and safety a bit by changing
cast-and-assign or raw memcpy() to:

	read_stream_put_value(stream, per_buffer_data, my_int);

This form infers the size and asserts that the storage space matches,
generally mirroring the read_stream_get_buffer_and_value() call used for
retrieving the streamed data later.
---
 src/backend/access/heap/vacuumlazy.c | 6 +++---
 src/include/storage/read_stream.h    | 9 +++++++++
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index ac7a4d8c21d..9563906fb27 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1612,7 +1612,7 @@ heap_vac_scan_next_block(ReadStream *stream,
 		 */
 		vacrel->current_block = next_block;
 		blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
-		*((uint8 *) per_buffer_data) = blk_info;
+		read_stream_put_value(stream, per_buffer_data, blk_info);
 		return vacrel->current_block;
 	}
 	else
@@ -1628,7 +1628,7 @@ heap_vac_scan_next_block(ReadStream *stream,
 			blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		if (vacrel->next_unskippable_eager_scanned)
 			blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
-		*((uint8 *) per_buffer_data) = blk_info;
+		read_stream_put_value(stream, per_buffer_data, blk_info);
 		return vacrel->current_block;
 	}
 }
@@ -2671,7 +2671,7 @@ vacuum_reap_lp_read_stream_next(ReadStream *stream,
 	 * Save the TidStoreIterResult for later, so we can extract the offsets.
 	 * It is safe to copy the result, according to TidStoreIterateNext().
 	 */
-	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+	read_stream_put_value(stream, per_buffer_data, *iter_result);
 
 	return iter_result->blkno;
 }
diff --git a/src/include/storage/read_stream.h b/src/include/storage/read_stream.h
index c6066c0f296..5af801969b4 100644
--- a/src/include/storage/read_stream.h
+++ b/src/include/storage/read_stream.h
@@ -136,4 +136,13 @@ read_stream_get_buffer_and_value_with_size(ReadStream *stream,
 	(AssertMacro(sizeof(**(pointer)) <= read_stream_per_buffer_data_size(stream)), \
 	 read_stream_next_buffer((stream), ((void **) (pointer))))
 
+/*
+ * Set the per-buffer data by value.  This can be called from inside a
+ * callback that is returning block numbers.  It asserts that the value's size
+ * matches the available space.
+ */
+#define read_stream_put_value(stream, per_buffer_data, value) \
+	(AssertMacro(sizeof(value) == read_stream_per_buffer_data_size(stream)), \
+	 memcpy((per_buffer_data), &(value), sizeof(value)))
+
 #endif							/* READ_STREAM_H */
-- 
2.48.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:07                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 00:54                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 01:29                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Masahiko Sawada <sawada.mshk@gmail.com>
  2025-02-14 02:06                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:15                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 18:30                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-14 21:50                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 22:54                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:03                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-14 23:08                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 23:50                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-15 01:23                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-16 18:12                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-18 14:31                                                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-27 17:32                                                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Ranier Vilela <ranier.vf@gmail.com>
  2025-02-27 17:44                                                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 17:49                                                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2025-02-27 18:08                                                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-02-27 22:57                                                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-28 01:29                                                                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-02-28 02:13                                                                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-08-06 17:39                                                                                       ` Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 0 replies; 81+ messages in thread

From: Álvaro Herrera @ 2025-08-06 17:39 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Melanie Plageman <melanieplageman@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Ranier Vilela <ranier.vf@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

Moved this [1] to PG19-Drafts.  Feel free to put it back in a regular
commitfest when you want to return to it.

[1] https://commitfest.postgresql.org/patch/5617/

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"La virtud es el justo medio entre dos defectos" (Aristóteles)





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-13 23:11                                             ` Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:51                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-02-13 23:11 UTC (permalink / raw)
  To: Tomas Vondra <tomas@vondra.me>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Tue, Feb 11, 2025 at 8:10 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> On Thu, Feb 6, 2025 at 1:06 PM Melanie Plageman
> <melanieplageman@gmail.com> wrote:
> >
> > On Wed, Feb 5, 2025 at 5:26 PM Melanie Plageman
> > <melanieplageman@gmail.com> wrote:
> > >
> > > Yes, looking at these results, I also feel good about it. I've updated
> > > the commit metadata in attached v14, but I could use a round of review
> > > before pushing it.
> >
> > I've done a bit of self-review and updated these patches.
>
> This needed a rebase in light of 052026c9b90.
> v16 attached has an additional commit which converts the block
> information parameters to heap_vac_scan_next_block() into flags
> because we can only get one piece of information per block from the
> read stream API. This seemed nicer than a cumbersome struct.

I've done some clean-up including incorporating a few off-list pieces
of minor feedback from Andres.

- Melanie

Attachments:

  [text/x-patch] v17-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch (4.0K, ../../CAAKRu_YWFiXkOmk1FJc9=ia7eF+OPSHTFPnk=R0vtysMUJP2aw@mail.gmail.com/2-v17-0003-Use-streaming-read-I-O-in-VACUUM-s-third-phase.patch)
  download | inline diff:
From da251546b0e7a748884efc9fb6d27fab0b7a452d Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 17:34:18 -0500
Subject: [PATCH v17 3/3] Use streaming read I/O in VACUUM's third phase

Make vacuum's third phase (its second pass over the heap), which reaps
dead items collected in the first phase and marks them as reusable, use
the read stream API. This commit adds a new read stream callback,
vacuum_reap_lp_read_stream_next(), that looks ahead in the TidStore and
returns the next block number to read for vacuum.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGKN3oy0bN_3yv8hd78a4%2BM1tJC9z7mD8%2Bf%2ByA%2BGeoFUwQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 53 +++++++++++++++++++++++++---
 1 file changed, 48 insertions(+), 5 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 32083a92c31..f85530a28f3 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -2639,6 +2639,32 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 	return allindexes;
 }
 
+/*
+ * Read stream callback for vacuum's third phase (second pass over the heap).
+ * Gets the next block from the TID store and returns it or InvalidBlockNumber
+ * if there are no further blocks to vacuum.
+ */
+static BlockNumber
+vacuum_reap_lp_read_stream_next(ReadStream *stream,
+								void *callback_private_data,
+								void *per_buffer_data)
+{
+	TidStoreIter *iter = callback_private_data;
+	TidStoreIterResult *iter_result;
+
+	iter_result = TidStoreIterateNext(iter);
+	if (iter_result == NULL)
+		return InvalidBlockNumber;
+
+	/*
+	 * Save the TidStoreIterResult for later, so we can extract the offsets.
+	 * It is safe to copy the result, according to TidStoreIterateNext().
+	 */
+	memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
+
+	return iter_result->blkno;
+}
+
 /*
  *	lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
  *
@@ -2659,6 +2685,7 @@ lazy_vacuum_all_indexes(LVRelState *vacrel)
 static void
 lazy_vacuum_heap_rel(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber vacuumed_pages = 0;
 	Buffer		vmbuffer = InvalidBuffer;
 	LVSavedErrInfo saved_err_info;
@@ -2679,7 +2706,17 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 							 InvalidBlockNumber, InvalidOffsetNumber);
 
 	iter = TidStoreBeginIterate(vacrel->dead_items);
-	while ((iter_result = TidStoreIterateNext(iter)) != NULL)
+
+	/* Set up the read stream */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										vacuum_reap_lp_read_stream_next,
+										iter,
+										sizeof(TidStoreIterResult));
+
+	while (true)
 	{
 		BlockNumber blkno;
 		Buffer		buf;
@@ -2690,9 +2727,15 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 
 		vacuum_delay_point(false);
 
-		blkno = iter_result->blkno;
-		vacrel->blkno = blkno;
+		buf = read_stream_next_buffer(stream, (void **) &iter_result);
+
+		/* The relation is exhausted */
+		if (!BufferIsValid(buf))
+			break;
 
+		vacrel->blkno = blkno = BufferGetBlockNumber(buf);
+
+		Assert(iter_result);
 		num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
 		Assert(num_offsets <= lengthof(offsets));
 
@@ -2704,8 +2747,6 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
 		/* We need a non-cleanup exclusive lock to mark dead_items unused */
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
 		LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
 		lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
 							  num_offsets, vmbuffer);
@@ -2718,6 +2759,8 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
+
+	read_stream_end(stream);
 	TidStoreEndIterate(iter);
 
 	vacrel->blkno = InvalidBlockNumber;
-- 
2.34.1



  [text/x-patch] v17-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch (6.0K, ../../CAAKRu_YWFiXkOmk1FJc9=ia7eF+OPSHTFPnk=R0vtysMUJP2aw@mail.gmail.com/3-v17-0001-Convert-heap_vac_scan_next_block-boolean-paramet.patch)
  download | inline diff:
From 6abfb26af7cd2ff55c9b13cadcef2d56b6460a28 Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 16:49:10 -0500
Subject: [PATCH v17 1/3] Convert heap_vac_scan_next_block() boolean parameters
 to flags

The read stream API only allows one piece of extra per block state to be
passed back to the API user. lazy_scan_heap() needs to know whether or
not a given block was all-visible in the visibility map and whether or
not it was eagerly scanned. Convert these two pieces of information to
flags so that they can be passed as a single argument to
heap_vac_scan_next_block() (which will become the read stream API
callback for heap phase I vacuuming).

Discussion: https://postgr.es/m/CAAKRu_bmx33jTqATP5GKNFYwAg02a9dDtk4U_ciEjgBHZSVkOQ%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 47 ++++++++++++++++------------
 1 file changed, 27 insertions(+), 20 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 3df5b92afb8..c4d0f77ee2f 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -248,6 +248,13 @@ typedef enum
  */
 #define EAGER_SCAN_REGION_SIZE 4096
 
+/*
+ * heap_vac_scan_next_block() sets these flags to communicate information
+ * about the block it read to the caller.
+ */
+#define VAC_BLK_WAS_EAGER_SCANNED (1 << 0)
+#define VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM (1 << 1)
+
 typedef struct LVRelState
 {
 	/* Target heap relation and its indexes */
@@ -417,8 +424,7 @@ static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
 static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 bool *all_visible_according_to_vm,
-									 bool *was_eager_scanned);
+									 uint8 *blk_info);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1171,8 +1177,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	BlockNumber rel_pages = vacrel->rel_pages,
 				blkno,
 				next_fsm_block_to_vacuum = 0;
-	bool		all_visible_according_to_vm,
-				was_eager_scanned = false;
+	uint8		blk_info = 0;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1196,8 +1201,7 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm,
-									&was_eager_scanned))
+	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_info))
 	{
 		Buffer		buf;
 		Page		page;
@@ -1206,7 +1210,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		got_cleanup_lock = false;
 
 		vacrel->scanned_pages++;
-		if (was_eager_scanned)
+		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
 			vacrel->eager_scanned_pages++;
 
 		/* Report as block scanned, update error traceback information */
@@ -1331,7 +1335,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		if (got_cleanup_lock)
 			lazy_scan_prune(vacrel, buf, blkno, page,
-							vmbuffer, all_visible_according_to_vm,
+							vmbuffer,
+							blk_info & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
 							&has_lpdead_items, &vm_page_frozen);
 
 		/*
@@ -1348,7 +1353,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		 * exclude pages skipped due to cleanup lock contention from eager
 		 * freeze algorithm caps.
 		 */
-		if (got_cleanup_lock && was_eager_scanned)
+		if (got_cleanup_lock &&
+			(blk_info & VAC_BLK_WAS_EAGER_SCANNED))
 		{
 			/* Aggressive vacuums do not eager scan. */
 			Assert(!vacrel->aggressive);
@@ -1479,11 +1485,11 @@ lazy_scan_heap(LVRelState *vacrel)
  * and various thresholds to skip blocks which do not need to be processed and
  * sets blkno to the next block to process.
  *
- * The block number and visibility status of the next block to process are set
- * in *blkno and *all_visible_according_to_vm.  The return value is false if
- * there are no further blocks to process. If the block is being eagerly
- * scanned, was_eager_scanned is set so that the caller can count whether or
- * not an eagerly scanned page is successfully frozen.
+ * The block number of the next block to process is set in *blkno and its
+ * visibility status and whether or not it was eager scanned is set in
+ * *blk_info.
+ *
+ * The return value is false if there are no further blocks to process.
  *
  * vacrel is an in/out parameter here.  Vacuum options and information about
  * the relation are read.  vacrel->skippedallvis is set if we skip a block
@@ -1493,15 +1499,14 @@ lazy_scan_heap(LVRelState *vacrel)
  */
 static bool
 heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 bool *all_visible_according_to_vm,
-						 bool *was_eager_scanned)
+						 uint8 *blk_info)
 {
 	BlockNumber next_block;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*was_eager_scanned = false;
+	*blk_info = 0;
 
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
@@ -1562,7 +1567,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * otherwise they would've been unskippable.
 		 */
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = true;
+		*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		return true;
 	}
 	else
@@ -1574,8 +1579,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		Assert(next_block == vacrel->next_unskippable_block);
 
 		*blkno = vacrel->current_block = next_block;
-		*all_visible_according_to_vm = vacrel->next_unskippable_allvis;
-		*was_eager_scanned = vacrel->next_unskippable_eager_scanned;
+		if (vacrel->next_unskippable_allvis)
+			*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		if (vacrel->next_unskippable_eager_scanned)
+			*blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
 		return true;
 	}
 }
-- 
2.34.1



  [text/x-patch] v17-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch (10.8K, ../../CAAKRu_YWFiXkOmk1FJc9=ia7eF+OPSHTFPnk=R0vtysMUJP2aw@mail.gmail.com/4-v17-0002-Use-streaming-read-I-O-in-VACUUM-s-first-phase.patch)
  download | inline diff:
From def5659ded7b7f401ea8d9deffa44b10b73a4a5f Mon Sep 17 00:00:00 2001
From: Melanie Plageman <melanieplageman@gmail.com>
Date: Thu, 13 Feb 2025 17:34:12 -0500
Subject: [PATCH v17 2/3] Use streaming read I/O in VACUUM's first phase

Make vacuum's first phase, which prunes and freezes tuples and records
dead TIDs, use the read stream API by by converting
heap_vac_scan_next_block() to a read stream callback.

Discussion: https://postgr.es/m/CAAKRu_aLwANZpxHc0tC-6OT0OQT4TftDGkKAO5yigMUOv_Tcsw%40mail.gmail.com
---
 src/backend/access/heap/vacuumlazy.c | 145 +++++++++++++++++----------
 1 file changed, 90 insertions(+), 55 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index c4d0f77ee2f..32083a92c31 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -153,6 +153,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "storage/read_stream.h"
 #include "utils/lsyscache.h"
 #include "utils/pg_rusage.h"
 #include "utils/timestamp.h"
@@ -423,8 +424,9 @@ typedef struct LVSavedErrInfo
 static void lazy_scan_heap(LVRelState *vacrel);
 static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
 										 VacuumParams *params);
-static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-									 uint8 *blk_info);
+static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
+											void *callback_private_data,
+											void *per_buffer_data);
 static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
 static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
 								   BlockNumber blkno, Page page,
@@ -1174,10 +1176,12 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
 static void
 lazy_scan_heap(LVRelState *vacrel)
 {
+	ReadStream *stream;
 	BlockNumber rel_pages = vacrel->rel_pages,
-				blkno,
+				blkno = 0,
 				next_fsm_block_to_vacuum = 0;
 	uint8		blk_info = 0;
+	void	   *per_buffer_data = NULL;
 	BlockNumber orig_eager_scan_success_limit =
 		vacrel->eager_scan_remaining_successes; /* for logging */
 	Buffer		vmbuffer = InvalidBuffer;
@@ -1201,7 +1205,16 @@ lazy_scan_heap(LVRelState *vacrel)
 	vacrel->next_unskippable_eager_scanned = false;
 	vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 
-	while (heap_vac_scan_next_block(vacrel, &blkno, &blk_info))
+	/* Set up the read stream for vacuum's first pass through the heap */
+	stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
+										vacrel->bstrategy,
+										vacrel->rel,
+										MAIN_FORKNUM,
+										heap_vac_scan_next_block,
+										vacrel,
+										sizeof(uint8));
+
+	while (true)
 	{
 		Buffer		buf;
 		Page		page;
@@ -1209,15 +1222,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		bool		vm_page_frozen = false;
 		bool		got_cleanup_lock = false;
 
-		vacrel->scanned_pages++;
-		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
-			vacrel->eager_scanned_pages++;
-
-		/* Report as block scanned, update error traceback information */
-		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
-		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
-								 blkno, InvalidOffsetNumber);
-
 		vacuum_delay_point(false);
 
 		/*
@@ -1258,7 +1262,8 @@ lazy_scan_heap(LVRelState *vacrel)
 
 			/*
 			 * Vacuum the Free Space Map to make newly-freed space visible on
-			 * upper-level FSM pages.  Note we have not yet processed blkno.
+			 * upper-level FSM pages.  Note that blkno is the previously
+			 * processed block.
 			 */
 			FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
 									blkno);
@@ -1269,6 +1274,26 @@ lazy_scan_heap(LVRelState *vacrel)
 										 PROGRESS_VACUUM_PHASE_SCAN_HEAP);
 		}
 
+		buf = read_stream_next_buffer(stream, &per_buffer_data);
+
+		/* The relation is exhausted. */
+		if (!BufferIsValid(buf))
+			break;
+
+		blk_info = *((uint8 *) per_buffer_data);
+		CheckBufferIsPinnedOnce(buf);
+		page = BufferGetPage(buf);
+		blkno = BufferGetBlockNumber(buf);
+
+		vacrel->scanned_pages++;
+		if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
+			vacrel->eager_scanned_pages++;
+
+		/* Report as block scanned, update error traceback information */
+		pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+		update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
+								 blkno, InvalidOffsetNumber);
+
 		/*
 		 * Pin the visibility map page in case we need to mark the page
 		 * all-visible.  In most cases this will be very cheap, because we'll
@@ -1276,10 +1301,6 @@ lazy_scan_heap(LVRelState *vacrel)
 		 */
 		visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
 
-		buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
-								 vacrel->bstrategy);
-		page = BufferGetPage(buf);
-
 		/*
 		 * We need a buffer cleanup lock to prune HOT chains and defragment
 		 * the page in lazy_scan_prune.  But when it's not possible to acquire
@@ -1439,8 +1460,12 @@ lazy_scan_heap(LVRelState *vacrel)
 	if (BufferIsValid(vmbuffer))
 		ReleaseBuffer(vmbuffer);
 
-	/* report that everything is now scanned */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
+	/*
+	 * Report that everything is now scanned. We never skip scanning the last
+	 * block in the relation, so we can pass rel_pages here.
+	 */
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
+								 rel_pages);
 
 	/* now we can compute the new value for pg_class.reltuples */
 	vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
@@ -1455,6 +1480,8 @@ lazy_scan_heap(LVRelState *vacrel)
 		Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
 		vacrel->missed_dead_tuples;
 
+	read_stream_end(stream);
+
 	/*
 	 * Do index vacuuming (call each index's ambulkdelete routine), then do
 	 * related heap vacuuming
@@ -1465,12 +1492,14 @@ lazy_scan_heap(LVRelState *vacrel)
 	/*
 	 * Vacuum the remainder of the Free Space Map.  We must do this whether or
 	 * not there were indexes, and whether or not we bypassed index vacuuming.
+	 * We can pass rel_pages here because we never skip scanning the last
+	 * block of the relation.
 	 */
-	if (blkno > next_fsm_block_to_vacuum)
-		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
+	if (rel_pages > next_fsm_block_to_vacuum)
+		FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
 
 	/* report all blocks vacuumed */
-	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
+	pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
 
 	/* Do final index cleanup (call each index's amvacuumcleanup routine) */
 	if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
@@ -1478,36 +1507,41 @@ lazy_scan_heap(LVRelState *vacrel)
 }
 
 /*
- *	heap_vac_scan_next_block() -- get next block for vacuum to process
- *
- * lazy_scan_heap() calls here every time it needs to get the next block to
- * prune and vacuum.  The function uses the visibility map, vacuum options,
- * and various thresholds to skip blocks which do not need to be processed and
- * sets blkno to the next block to process.
- *
- * The block number of the next block to process is set in *blkno and its
- * visibility status and whether or not it was eager scanned is set in
- * *blk_info.
- *
- * The return value is false if there are no further blocks to process.
- *
- * vacrel is an in/out parameter here.  Vacuum options and information about
- * the relation are read.  vacrel->skippedallvis is set if we skip a block
- * that's all-visible but not all-frozen, to ensure that we don't update
- * relfrozenxid in that case.  vacrel also holds information about the next
- * unskippable block, as bookkeeping for this function.
+ *	heap_vac_scan_next_block() -- read stream callback to get the next block
+ *	for vacuum to process
+ *
+ * Every time lazy_scan_heap() needs a new block to process during its first
+ * phase, it invokes read_stream_next_buffer() with a stream set up to call
+ * heap_vac_scan_next_block() to get the next block.
+ *
+ * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
+ * various thresholds to skip blocks which do not need to be processed and
+ * returns the next block to process or InvalidBlockNumber if there are no
+ * remaining blocks.
+ *
+ * The visibility status of the next block to process and whether or not it
+ * was eager scanned is set in the per_buffer_data.
+ *
+ * callback_private_data contains a reference to the LVRelState, passed to the
+ * read stream API during stream setup. The LVRelState is an in/out parameter
+ * here (locally named `vacrel`). Vacuum options and information about the
+ * relation are read from it. vacrel->skippedallvis is set if we skip a block
+ * that's all-visible but not all-frozen (to ensure that we don't update
+ * relfrozenxid in that case). vacrel also holds information about the next
+ * unskippable block -- as bookkeeping for this function.
  */
-static bool
-heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
-						 uint8 *blk_info)
+static BlockNumber
+heap_vac_scan_next_block(ReadStream *stream,
+						 void *callback_private_data,
+						 void *per_buffer_data)
 {
 	BlockNumber next_block;
+	LVRelState *vacrel = callback_private_data;
+	uint8		blk_info = 0;
 
 	/* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
 	next_block = vacrel->current_block + 1;
 
-	*blk_info = 0;
-
 	/* Have we reached the end of the relation? */
 	if (next_block >= vacrel->rel_pages)
 	{
@@ -1516,8 +1550,7 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 			ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
 			vacrel->next_unskippable_vmbuffer = InvalidBuffer;
 		}
-		*blkno = vacrel->rel_pages;
-		return false;
+		return InvalidBlockNumber;
 	}
 
 	/*
@@ -1566,9 +1599,10 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 * but chose not to.  We know that they are all-visible in the VM,
 		 * otherwise they would've been unskippable.
 		 */
-		*blkno = vacrel->current_block = next_block;
-		*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
-		return true;
+		vacrel->current_block = next_block;
+		blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+		*((uint8 *) per_buffer_data) = blk_info;
+		return vacrel->current_block;
 	}
 	else
 	{
@@ -1578,12 +1612,13 @@ heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno,
 		 */
 		Assert(next_block == vacrel->next_unskippable_block);
 
-		*blkno = vacrel->current_block = next_block;
+		vacrel->current_block = next_block;
 		if (vacrel->next_unskippable_allvis)
-			*blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
+			blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
 		if (vacrel->next_unskippable_eager_scanned)
-			*blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
-		return true;
+			blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
+		*((uint8 *) per_buffer_data) = blk_info;
+		return vacrel->current_block;
 	}
 }
 
-- 
2.34.1



^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:11                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-02-13 23:51                                               ` Thomas Munro <thomas.munro@gmail.com>
  2025-02-14 00:56                                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Thomas Munro @ 2025-02-13 23:51 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Fri, Feb 14, 2025 at 12:11 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
> I've done some clean-up including incorporating a few off-list pieces
> of minor feedback from Andres.

I've been poking, reading, and trying out these patches.  They look good to me.

Tiny nit, maybe this comment could say something less obvious, cf the
similar comment near the other stream:

+       /* Set up the read stream */
+       stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,

I don't really love the cumbersome casting required around
per_buffer_data, but that's not your patches' fault (hmm, wonder what
we can do to improve that).





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-12-15 15:10                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-01-16 01:45                                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-01-18 16:51                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Tomas Vondra <tomas@vondra.me>
  2025-02-05 22:26                                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-06 18:06                                         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-12 01:10                                           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:11                                             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2025-02-13 23:51                                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-02-14 00:56                                                 ` Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 0 replies; 81+ messages in thread

From: Melanie Plageman @ 2025-02-14 00:56 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Tomas Vondra <tomas@vondra.me>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>; Masahiko Sawada <sawada.mshk@gmail.com>

On Thu, Feb 13, 2025 at 6:52 PM Thomas Munro <thomas.munro@gmail.com> wrote:
>
> I've been poking, reading, and trying out these patches.  They look good to me.

Thanks for the review.

> Tiny nit, maybe this comment could say something less obvious, cf the
> similar comment near the other stream:
>
> +       /* Set up the read stream */
> +       stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,

Done in upthread v18.

> I don't really love the cumbersome casting required around
> per_buffer_data, but that's not your patches' fault (hmm, wonder what
> we can do to improve that).

I don't know if you saw v17, but I tried to improve it a bit. The
casting still has to happen, but I at least use the variable as a
uint8 instead of a pointer to a uint8 (dunno if that makes it better
or worse). It is the same in v18.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
@ 2025-10-22 16:12                                 ` Tom Lane <tgl@sss.pgh.pa.us>
  2025-10-30 11:13                                   ` Re: Confine vacuum skip logic to lazy_scan_skip John Naylor <johncnaylorls@gmail.com>
  1 sibling, 1 reply; 81+ messages in thread

From: Tom Lane @ 2025-10-22 16:12 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

[ seizing on this old commit as being most closely related to the issue ]

Thomas Munro <thomas.munro@gmail.com> writes:
> On Tue, Jul 16, 2024 at 1:52 PM Noah Misch <noah@leadboat.com> wrote:
>> On Mon, Jul 15, 2024 at 03:26:32PM +1200, Thomas Munro wrote:
>> That's reasonable.  radixtree already forbids mutations concurrent with
>> iteration, so there's no new concurrency hazard.  One alternative is
>> per_buffer_data big enough for MaxOffsetNumber, but that might thrash caches
>> measurably.  That patch is good to go apart from these trivialities:

> Thanks!  I have pushed that patch, without those changes you didn't like.

The security team recently updated our Coverity instance to the latest
version, and it's started complaining as follows:


*** CID 1667418:         Memory - corruptions  (OVERRUN)
/srv/coverity/git/pgsql-git/postgresql/src/backend/access/heap/vacuumlazy.c: 2812             in lazy_vacuum_heap_rel()
2806              * already have the correct page pinned anyway.
2807              */
2808             visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
2809     
2810             /* We need a non-cleanup exclusive lock to mark dead_items unused */
2811             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
>>>     CID 1667418:         Memory - corruptions  (OVERRUN)
>>>     Overrunning callee's array of size 291 by passing argument "num_offsets" (which evaluates to 2048) in call to "lazy_vacuum_heap_page".
2812             lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
2813                                   num_offsets, vmbuffer);
2814     
2815             /* Now that we've vacuumed the page, record its available space */
2816             page = BufferGetPage(buf);
2817             freespace = PageGetHeapFreeSpace(page);


The reason it thinks that num_offsets could be as much as 2048 is
presumably the code a little bit above this:

        OffsetNumber offsets[MaxOffsetNumber];
        ...
        num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
        Assert(num_offsets <= lengthof(offsets));

However, lazy_vacuum_heap_page blindly assumes that the passed value
will be no more than MaxHeapTuplesPerPage.  It seems like we ought
to get these two functions in sync, either both using MaxOffsetNumber
or both using MaxHeapTuplesPerPage for their array sizes.

It looks to me like MaxHeapTuplesPerPage should be sufficient.
Also, after reading TidStoreGetBlockOffsets I wonder if we
should replace that Assert with

        num_offsets = Min(num_offsets, lengthof(offsets));

Thoughts?

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-10-22 16:12                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-10-30 11:13                                   ` John Naylor <johncnaylorls@gmail.com>
  2025-11-03 15:59                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: John Naylor @ 2025-10-30 11:13 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; Melanie Plageman <melanieplageman@gmail.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Wed, Oct 22, 2025 at 11:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> The reason it thinks that num_offsets could be as much as 2048 is
> presumably the code a little bit above this:
>
>         OffsetNumber offsets[MaxOffsetNumber];
>         ...
>         num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
>         Assert(num_offsets <= lengthof(offsets));
>
> However, lazy_vacuum_heap_page blindly assumes that the passed value
> will be no more than MaxHeapTuplesPerPage.  It seems like we ought
> to get these two functions in sync, either both using MaxOffsetNumber
> or both using MaxHeapTuplesPerPage for their array sizes.
>
> It looks to me like MaxHeapTuplesPerPage should be sufficient.

Seems right.

> Also, after reading TidStoreGetBlockOffsets I wonder if we
> should replace that Assert with
>
>         num_offsets = Min(num_offsets, lengthof(offsets));
>
> Thoughts?

Not sure. That changes the posture from "can't happen" to "shouldn't
happen, but if it does, don't cause a disaster". Even with the latter,
the assert still seems appropriate for catching developer mistakes.

--
John Naylor
Amazon Web Services





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-10-22 16:12                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-10-30 11:13                                   ` Re: Confine vacuum skip logic to lazy_scan_skip John Naylor <johncnaylorls@gmail.com>
@ 2025-11-03 15:59                                     ` Melanie Plageman <melanieplageman@gmail.com>
  2025-11-04 09:27                                       ` Re: Confine vacuum skip logic to lazy_scan_skip John Naylor <johncnaylorls@gmail.com>
  0 siblings, 1 reply; 81+ messages in thread

From: Melanie Plageman @ 2025-11-03 15:59 UTC (permalink / raw)
  To: John Naylor <johncnaylorls@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Thu, Oct 30, 2025 at 7:14 AM John Naylor <johncnaylorls@gmail.com> wrote:
>
> On Wed, Oct 22, 2025 at 11:12 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > The reason it thinks that num_offsets could be as much as 2048 is
> > presumably the code a little bit above this:
> >
> >         OffsetNumber offsets[MaxOffsetNumber];
> >         ...
> >         num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
> >         Assert(num_offsets <= lengthof(offsets));
> >
> > However, lazy_vacuum_heap_page blindly assumes that the passed value
> > will be no more than MaxHeapTuplesPerPage.  It seems like we ought
> > to get these two functions in sync, either both using MaxOffsetNumber
> > or both using MaxHeapTuplesPerPage for their array sizes.
> >
> > It looks to me like MaxHeapTuplesPerPage should be sufficient.
>
> Seems right.

Yes, it makes sense to me to make offsets size MaxHeapTuplesPerPage,
if that is what is being suggested. Doesn't hurt to take up a bit less
stack space too.

> > Also, after reading TidStoreGetBlockOffsets I wonder if we
> > should replace that Assert with
> >
> >         num_offsets = Min(num_offsets, lengthof(offsets));
> >
> > Thoughts?
>
> Not sure. That changes the posture from "can't happen" to "shouldn't
> happen, but if it does, don't cause a disaster". Even with the latter,
> the assert still seems appropriate for catching developer mistakes.

You are suggesting keeping the assert and this line after it?

num_offsets = Min(num_offsets, lengthof(offsets));

The current contract of TidStoreGetBlockOffsets() is that it won't
return a value larger than max_offsets passed in, so it is a good idea
to have an assert in case it changes. But, if we take the minimum,
then is the assert there to keep developers from changing
TidStoreGetBlockOffsets() from behaving differently? I don't know if I
like that, but I don't feel strongly enough to object. Anyway, I think
we should add the line Tom suggested.

- Melanie





^ permalink  raw  reply  [nested|flat] 81+ messages in thread

* Re: Confine vacuum skip logic to lazy_scan_skip
  2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-02 17:36 ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-04 20:23   ` Re: Confine vacuum skip logic to lazy_scan_skip Andres Freund <andres@anarazel.de>
  2024-01-11 23:41     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-01-26 13:28       ` Re: Confine vacuum skip logic to lazy_scan_skip vignesh C <vignesh21@gmail.com>
  2024-01-30 01:18         ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-02-27 19:47           ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-06 23:47             ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-10 16:31               ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-11 03:01                 ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-03-11 21:02                   ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-03-17 06:53                     ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-06-28 21:36                       ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
  2024-07-07 14:49                         ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-15 03:26                           ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2024-07-16 01:52                             ` Re: Confine vacuum skip logic to lazy_scan_skip Noah Misch <noah@leadboat.com>
  2024-07-24 05:40                               ` Re: Confine vacuum skip logic to lazy_scan_skip Thomas Munro <thomas.munro@gmail.com>
  2025-10-22 16:12                                 ` Re: Confine vacuum skip logic to lazy_scan_skip Tom Lane <tgl@sss.pgh.pa.us>
  2025-10-30 11:13                                   ` Re: Confine vacuum skip logic to lazy_scan_skip John Naylor <johncnaylorls@gmail.com>
  2025-11-03 15:59                                     ` Re: Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
@ 2025-11-04 09:27                                       ` John Naylor <johncnaylorls@gmail.com>
  0 siblings, 0 replies; 81+ messages in thread

From: John Naylor @ 2025-11-04 09:27 UTC (permalink / raw)
  To: Melanie Plageman <melanieplageman@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thomas Munro <thomas.munro@gmail.com>; Noah Misch <noah@leadboat.com>; vignesh C <vignesh21@gmail.com>; Andres Freund <andres@anarazel.de>; pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>; Nazir Bilal Yavuz <byavuz81@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Andrey M. Borodin <x4mmm@yandex-team.ru>

On Mon, Nov 3, 2025 at 10:59 PM Melanie Plageman
<melanieplageman@gmail.com> wrote:
>
> > Not sure. That changes the posture from "can't happen" to "shouldn't
> > happen, but if it does, don't cause a disaster". Even with the latter,
> > the assert still seems appropriate for catching developer mistakes.
>
> You are suggesting keeping the assert and this line after it?
>
> num_offsets = Min(num_offsets, lengthof(offsets));

My "not sure" was referring to this line.

> The current contract of TidStoreGetBlockOffsets() is that it won't
> return a value larger than max_offsets passed in, so it is a good idea
> to have an assert in case it changes.

I suspect the contract is the way it is in order to enable the assert to work.

> But, if we take the minimum,
> then is the assert there to keep developers from changing
> TidStoreGetBlockOffsets() from behaving differently? I don't know if I
> like that, but I don't feel strongly enough to object. Anyway, I think
> we should add the line Tom suggested.

This line seems strange to me (and maybe even stranger to have both
the min and the assert), but maybe I don't understand Tom's rationale
well enough. Do we need it to silence Coverity?

-- 
John Naylor
Amazon Web Services





^ permalink  raw  reply  [nested|flat] 81+ messages in thread


end of thread, other threads:[~2025-11-04 09:27 UTC | newest]

Thread overview: 81+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2023-12-31 18:28 Confine vacuum skip logic to lazy_scan_skip Melanie Plageman <melanieplageman@gmail.com>
2024-01-02 17:36 ` Melanie Plageman <melanieplageman@gmail.com>
2024-01-04 20:23   ` Andres Freund <andres@anarazel.de>
2024-01-04 23:25     ` Jim Nasby <jim.nasby@gmail.com>
2024-01-05 10:51       ` Nazir Bilal Yavuz <byavuz81@gmail.com>
2024-01-11 23:50         ` Melanie Plageman <melanieplageman@gmail.com>
2024-01-12 19:02           ` Jim Nasby <jim.nasby@gmail.com>
2024-01-12 19:09             ` Melanie Plageman <melanieplageman@gmail.com>
2024-01-11 23:41     ` Melanie Plageman <melanieplageman@gmail.com>
2024-01-26 13:28       ` vignesh C <vignesh21@gmail.com>
2024-01-30 01:18         ` Melanie Plageman <melanieplageman@gmail.com>
2024-02-27 19:47           ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-06 19:55             ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-07 03:00               ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 00:46                 ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 13:49                   ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-08 15:40                     ` Peter Geoghegan <pg@bowt.ie>
2024-03-08 15:48                       ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 16:00                         ` Peter Geoghegan <pg@bowt.ie>
2024-03-08 16:06                           ` Peter Geoghegan <pg@bowt.ie>
2024-03-08 16:31                           ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 16:41                             ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 15:44                     ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 16:07                   ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-08 17:34                     ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-08 18:21                       ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-11 09:29                       ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-11 16:15                         ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-11 18:47                           ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-11 20:41                             ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-06 23:47             ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-10 16:31               ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-11 03:01                 ` Thomas Munro <thomas.munro@gmail.com>
2024-03-11 21:02                   ` Melanie Plageman <melanieplageman@gmail.com>
2024-03-17 06:53                     ` Thomas Munro <thomas.munro@gmail.com>
2024-06-28 21:36                       ` Melanie Plageman <melanieplageman@gmail.com>
2024-07-07 14:49                         ` Noah Misch <noah@leadboat.com>
2024-07-08 18:16                           ` Melanie Plageman <melanieplageman@gmail.com>
2024-07-15 03:26                           ` Thomas Munro <thomas.munro@gmail.com>
2024-07-16 01:52                             ` Noah Misch <noah@leadboat.com>
2024-07-24 05:40                               ` Thomas Munro <thomas.munro@gmail.com>
2024-12-15 15:10                                 ` Tomas Vondra <tomas@vondra.me>
2025-01-16 01:45                                   ` Melanie Plageman <melanieplageman@gmail.com>
2025-01-18 16:51                                     ` Tomas Vondra <tomas@vondra.me>
2025-01-18 21:31                                       ` Thomas Munro <thomas.munro@gmail.com>
2025-01-18 21:45                                         ` Thomas Munro <thomas.munro@gmail.com>
2025-01-18 22:04                                         ` Tomas Vondra <tomas@vondra.me>
2025-02-05 22:26                                       ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-06 18:06                                         ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-12 01:10                                           ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-13 23:07                                             ` Masahiko Sawada <sawada.mshk@gmail.com>
2025-02-14 00:54                                               ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-14 01:29                                                 ` Masahiko Sawada <sawada.mshk@gmail.com>
2025-02-14 02:06                                                   ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-14 18:15                                                     ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-14 18:30                                                       ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-14 21:50                                                         ` Thomas Munro <thomas.munro@gmail.com>
2025-02-14 22:54                                                           ` Thomas Munro <thomas.munro@gmail.com>
2025-02-14 23:03                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2025-02-14 23:08                                                               ` Thomas Munro <thomas.munro@gmail.com>
2025-02-14 23:50                                                                 ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-15 01:23                                                                   ` Thomas Munro <thomas.munro@gmail.com>
2025-02-16 18:12                                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2025-02-18 14:31                                                                       ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-18 15:52                                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2025-02-27 17:32                                                                         ` Ranier Vilela <ranier.vf@gmail.com>
2025-02-27 17:44                                                                           ` Andres Freund <andres@anarazel.de>
2025-02-27 17:49                                                                             ` Andres Freund <andres@anarazel.de>
2025-02-27 18:07                                                                               ` Ranier Vilela <ranier.vf@gmail.com>
2025-02-27 18:08                                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2025-02-27 22:57                                                                                 ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-28 01:29                                                                                   ` Thomas Munro <thomas.munro@gmail.com>
2025-02-28 02:13                                                                                     ` Thomas Munro <thomas.munro@gmail.com>
2025-08-06 17:39                                                                                       ` Álvaro Herrera <alvherre@kurilemu.de>
2025-02-13 23:11                                             ` Melanie Plageman <melanieplageman@gmail.com>
2025-02-13 23:51                                               ` Thomas Munro <thomas.munro@gmail.com>
2025-02-14 00:56                                                 ` Melanie Plageman <melanieplageman@gmail.com>
2025-10-22 16:12                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-10-30 11:13                                   ` John Naylor <johncnaylorls@gmail.com>
2025-11-03 15:59                                     ` Melanie Plageman <melanieplageman@gmail.com>
2025-11-04 09:27                                       ` John Naylor <johncnaylorls@gmail.com>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox