TID Range Scans can return wrong results after scanning backwards

From: Jeff Davis <pgsql(at)j-davis(dot)com>
To: pgsql-bugs(at)postgresql(dot)org
Subject: TID Range Scans can return wrong results after scanning backwards
Date: 2026-09-16 20:07:35
Message-ID: 6b50233fcc0f7d6f4845f083777fa9702d9612e4.camel@j-davis.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

AI reported a bug (appended to this email) where TID Range Scans can
return the wrong results after changing the direction of the scan.

Regards,
Jeff Davis

SQL repro
---------

CREATE TABLE t (id int, data text) WITH (fillfactor = 10);
-- 5 rows per page, 20 pages: ctids (0,1) .. (19,5)
INSERT INTO t SELECT i, repeat('x', 100)
FROM generate_series(1, 100) i;
SET enable_seqscan = off;
BEGIN;
DECLARE c SCROLL CURSOR FOR
SELECT ctid FROM t WHERE ctid >= '(2,1)' AND ctid <= '(11,5)';
MOVE FORWARD 35 c; -- cursor is now on (8,5)
FETCH BACKWARD 2 c; -- (8,4), (8,3): correct
FETCH BACKWARD ALL c; -- should return 32 rows, returns 12
COMMIT;

Diagnosis
---------

heap_setscanlimits() stores the number of blocks to scan in
rs_numblocks. heapgettup_advance_block() then treats that field as a
remaining budget: it decrements it once for every block it hands out,
in either direction, and ends the scan when it reaches zero. That
model only holds for a scan that moves in one direction and consumes
exactly the blocks it requests. A change in direction breaks that.

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Jacob Champion 2026-09-16 22:16:23 Re: Postmaster crashes on SIGHUP when oauth_validator_libraries holds only whitespace
Previous Message Jürgen Schmidt 2026-09-16 15:42:21 Re: BUG #19691: Wrong configuration in .../Postgres/var-19/postgresql.auto.conf