Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

Поиск
Список
Период
Сортировка
Искать

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
"Burd, Greg" <greg@burd.me>
Дата:


> On Sep 14, 2026, at 8:10 AM, Virender Singla  wrote:
> 
> Just a quick ping on this patch.
> It appears the `tts_tid` assignment was inadvertently omitted from the
> BufferHeapTupleTableSlot path in ExecForceStoreHeapTuple() when the
> function was first introduced during the PG12 TupleTableSlot
> refactoring [1].

I ran into this myself and posted a patch [1] as well.  I had not noticed your
patch.  Looks like both patches are essentially identical with different tests
we could combine those into one and then possibly get the attention of a
committer.

> This was subsequently exposed when the GiST index scan reorder queue
> was updated to route popped tuples through this same function [2]. The
> relevant code hasn't changed since those commits.
> 
> Thanks,
> Virender
> [1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=4da597edf1b
> [2] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=b8b94ea129f

I agree, it's a bug/oversight that has lingered since v12 and should be fixed.

best.

-greg

[1] https://pg.ddx.io/m/pgsql-hackers/0498c10f-839b-4f68-9994-c29b454e55a4@app.fastmail.com/

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
On Sep 14, 2026, Greg Burd  wrote:
> Done, so both checks now read zero when correct:

My AI harness noticed that v4-0001 still has the old ctid_matches join
returning 5, in both gist.sql and gist.out.  It looks like the email and
attachment got out of sync.

> That is 0003. I put the check in table_tuple_lock() rather than
> heap_lock_tuple(), because heap_lock_tuple() is only reachable through
> the AM callback in heapam_handler.c, so one check at the boundary covers
> every AM and rejects the TID before any AM code runs.

This catches the reported (InvalidBlockNumber, 0), but
ItemPointerIsValid() only checks for a non-NULL pointer and ip_posid != 0.
For example, (InvalidBlockNumber, 1) still reaches the AM.

If the intended protection is specifically against passing P_NEW to
heap's ReadBuffer(), should this check be heap-side?  A stronger generic
check would need a clearly stated table-AM invariant; the moved-partitions
marker is also an InvalidBlockNumber encoding with a nonzero offset.

Thanks,
Nik


Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:

On Monday, September 21st, 2026 at 12:24 AM, Nikolay Samokhvalov  wrote:

Hi Nik,

Thanks for reviewing, both of your points are correct. Thanks, and sorry for
the slow reply.

> My AI harness noticed that v4-0001 still has the old ctid_matches join
> returning 5, in both gist.sql and gist.out.  It looks like the email and
> attachment got out of sync.

Right, and the email was the thing that was wrong. I did the format() and
temp-table changes, wrote up all three, and never actually made the
NOT EXISTS change before generating the patch. Fixed in v5-0001:

  select count(*) as ctid_not_found
  from gist_knn_ctid_res r
  where not exists (select 1 from gist_knn_ctid t
                    where t.ctid = r.c and t.id = r.id);

So both checks now read zero when correct, which is what I claimed last
time.

> This catches the reported (InvalidBlockNumber, 0), but
> ItemPointerIsValid() only checks for a non-NULL pointer and ip_posid != 0.
> For example, (InvalidBlockNumber, 1) still reaches the AM.

Yes. ItemPointerIsValid() is just

  return pointer && pointer->ip_posid != 0;

So my check tested the offset and called it a block-number guard. Anything
with InvalidBlockNumber and a nonzero offset went straight through to
ReadBuffer() as P_NEW, which is exactly the case I said I was preventing.

> If the intended protection is specifically against passing P_NEW to
> heap's ReadBuffer(), should this check be heap-side?  A stronger generic
> check would need a clearly stated table-AM invariant; the moved-partitions
> marker is also an InvalidBlockNumber encoding with a nonzero offset.

Agreed on both halves, and I've moved it. v5-0003 checks the block number
in heapam_tuple_lock() instead of table_tuple_lock(). That covers every
caller of the heap AM's lock callback, since heap_lock_tuple() is only
reachable through it, and it leaves other AMs to state their own rules
rather than my inventing an invariant for them.

Your moved-partitions point turned out to matter in a second way I hadn't
anticipated. MovedPartitionsBlockNumber is InvalidBlockNumber with offset
0xfffd, so it has to be allowed through to the existing report in
heapam_tuple_lock()'s retry loop. But the obvious spelling,

  if (ItemPointerGetBlockNumberNoCheck(tid) == InvalidBlockNumber &&
      !ItemPointerIndicatesMovedPartitions(tid))

crashes before it can reject anything: ItemPointerIndicatesMovedPartitions()
reads the offset through the checked accessor, which asserts on offset 0,
which is the case we're here to catch. The offset has to be tested first.
I only found that because the assert fired; reading the code I had
convinced myself it was fine.

v5 attached, rebased on master (6a93535798a).

  0001  the fix, plus the regression test. This is the piece that wants
        backpatching.
  0002  the reorder-case assertion Andres asked for. master only.
  0003  the invalid-TID rejection, now heap-side. master only.

On backpatching 0001: it applies as-is to 18, 17, 16 and 15. On 14 the C
hunk applies (with an offset) but the test hunks do not, because gist.sql
has grown since, the block ahead of the insertion point in master does not
exist on 14. The test block itself is self-contained, its own table, its
own set/reset of enable_seqscan, its own cleanup, no dependency on
gist_tbl, so appending it to the end of 14's gist.sql and gist.out is all
that is needed.

I built that assembled 14 tree with --enable-cassert to check I wasn't
just asserting this. The gist test passes with the fix, and with only the
execTuples.c hunk reverted it fails the way it should:
  invalid_ctids    0 -> 4
  ctid_not_found   0 -> 4
  FOR UPDATE       5 rows -> assert

So the test gates the fix on 14 as well, it just needs placing by hand.
Happy to send a separate 14-specific 0001 if that's easier for whoever
commits it.

Verified on an assert-enabled build:

  - 0003 alone, with 0001 and 0002 reverted: the FOR UPDATE case gives
    ERROR: cannot lock tuple with invalid TID (4294967295,0) in relation
    "tri", pg_relation_size() is 8192 before and after, and the backend
    stays up. Without 0003 the same build asserts in
    ItemPointerGetOffsetNumber() under heapam_tuple_lock().
  - (4294967295,65533), the moved-partitions encoding, still reaches its
    own path rather than the new error.
  - All three applied: regression suite green, 239 tests.

I have still not built without assertions, so the production
relation-extension behavior remains Virender's report rather than
something I've reproduced. The commit message says so.

One loose end: there's no commitfest entry for this thread. I'll create
one so it doesn't get lost, unless Virender would rather do it as the
original reporter.

best.

-greg

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Virender Singla <virender.cse@gmail.com>
Дата:
> One loose end: there's no commitfest entry for this thread. I'll create
> one so it doesn't get lost, unless Virender would rather do it as the
> original reporter.

Thanks Greg!!
Here is the commitfest entry: https://commitfest.postgresql.org/patch/7371/

Regards,
Virender

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,

On 2026-09-29 16:31:39 +0000, Greg Burd wrote:
> From 057189b13e905377766f0e6c667c23849241708c Mon Sep 17 00:00:00 2001
> From: Greg Burd 
> Date: Mon, 14 Sep 2026 12:58:22 -0400
> Subject: [PATCH v5 1/3] Restore tts_tid in ExecForceStoreHeapTuple()
> 
> The TTS_IS_BUFFERTUPLE branch calls ExecClearTuple(), which resets
> tts_tid via tts_buffer_heap_clear(), then copies the tuple in without
> restoring tts_tid.  Both tts_heap_store_tuple() and
> tts_buffer_heap_store_tuple() assign slot->tts_tid = tuple->t_self, so
> this reads as an omission rather than an intentional choice.
> 
> It is user-visible because slot_getsysattr() answers
> SelfItemPointerAttributeNumber straight out of tts_tid.  The reorder
> queue in nodeIndexscan.c reaches this path for any index AM that sets
> xs_recheckorderby, so an ORDER BY-op scan over such an AM projects
> (4294967295,0) as ctid.  Feeding that sentinel to heap_lock_tuple()
> extends the relation, because InvalidBlockNumber equals P_NEW, leaving
> an uninitialized block that later breaks sequential scans.
> 
> The bug dates to b8d71745eac, which added tts_tid and set it in both
> store callbacks while missing this branch.  It only became observable
> at ff11e7f4b9a, which made tts_buffer_heap_clear() invalidate tts_tid;
> before that the slot retained a stale TID instead of the sentinel.
> 
> The test uses thin diagonal triangles so that poly_ops' bounding-box
> distance is strictly below the true distance, which forces the requeue
> path, and materializes the ordered result before checking it so that
> the planner cannot push the checks' quals into the scan.
> 
> Reported-by: Virender Singla
> Reported-by: Greg Burd

We normally include email addresses as well. Also would be good to add
Discussion links for the (at least?) two threads.  Adding Reviewed-By also
helps eventual committers.


> @@ -1768,6 +1768,12 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
>  		slot->tts_flags |= TTS_FLAG_SHOULDFREE;
>  		MemoryContextSwitchTo(oldContext);
>  
> +		/*
> +		 * ExecClearTuple() above reset tts_tid, so restore it from the tuple
> +		 * we just stored, the same way the tts_*_store_tuple() callbacks do.
> +		 */
> +		slot->tts_tid = tuple->t_self;
> +
>  		if (shouldFree)
>  			pfree(tuple);
>  	}

So one thing that's weird is that this does not modify the subsequent else
block:

	else
	{
		ExecClearTuple(slot);
		heap_deform_tuple(tuple, slot->tts_tupleDescriptor,
						  slot->tts_values, slot->tts_isnull);
		ExecStoreVirtualTuple(slot);

		if (shouldFree)
		{
			ExecMaterializeSlot(slot);
			pfree(tuple);
		}
	}

If we decide to maintain the tid in ExecForceStoreHeapTuple() - I suspect the
right call - we really should actually do it consistently.


The lock path itself can't be reached with a virtual slot (c.f. assertion in
heapam_tuple_lock()), but it might be possible to have a virtual slot in the
path towards it. But even if it can't be today, it'll likely be soon.



> From 7ed9738b2a8d2471673fbff88418fcfe411842f2 Mon Sep 17 00:00:00 2001
> From: Greg Burd 
> Date: Mon, 14 Sep 2026 12:58:42 -0400
> Subject: [PATCH v5 2/3] Assert the reorder queue keeps a tuple's TID in the
>  slot
> 
> IndexNextWithReorder() re-stores a queued tuple with
> ExecForceStoreHeapTuple(), and slot_getsysattr() answers
> SelfItemPointerAttributeNumber out of tts_tid alone, so a slot that
> loses the TID silently projects a different ctid than the row it
> returned.  Assert that the slot advertises the TID the tuple was
> fetched from.
> 
> The invariant does not hold for slots in general, since HOT can
> legitimately make tts_tid and the stored tuple's t_self differ, so the
> check is confined to this path, where a divergence changes query
> results.
> 
> The TID is captured before the store, which frees the tuple, and the
> comparison uses the NoCheck accessors so that the sentinel trips this
> assertion rather than the validity check inside ItemPointerEquals().

Maybe I'm slow, but who cares whether an earlier assert trips it? I think
flagging that the ctid is invalid, rather than unequal, seems perfectly fine?
Certainly doesn't seem worth to me to quadruple the size of the assertion for.


> From 1431683a3df66187dac74ededaf613f3d4ecaea6 Mon Sep 17 00:00:00 2001
> From: Greg Burd 
> Date: Mon, 14 Sep 2026 13:01:10 -0400
> Subject: [PATCH v5 3/3] Reject an invalid TID before heap_lock_tuple() reads
>  it
> 
> An invalid TID reaching heap_lock_tuple() is handed to ReadBuffer() as
> InvalidBlockNumber, which is P_NEW, so the relation is extended by a
> block before the lock attempt fails.  The uninitialized block is left
> behind and later breaks sequential scans with "invalid page in block".
> A caller that gets this far with such a TID has a bug, so fail cleanly
> instead.
> 
> An earlier version of this check sat in table_tuple_lock(), but that was
> both too weak and in the wrong place.  ItemPointerIsValid() only tests
> for a non-NULL pointer and a nonzero offset, so a TID like
> (InvalidBlockNumber, 1) passed it and still reached ReadBuffer().  And
> the hazard being guarded against is specific to heap's use of P_NEW,
> not a documented table AM invariant, so the generic layer is not the
> right place to enforce it.  Checking the block number in
> heapam_tuple_lock() covers every caller of the heap AM's lock callback
> and leaves other AMs to state their own rules.

I don't think I buy the "specific to heap's use of P_NEW", given that

a) Stuff like ItemPointerGetBlockNumber() asserts out if P_NEW is used
b) P_NEW is a ReadBuffer() thing, not a heap thing


> The moved-partitions marker also encodes InvalidBlockNumber, with
> offset MovedPartitionsOffsetNumber, and is a legitimate value that the
> retry loop in heapam_tuple_lock() reports on its own terms, so it is
> allowed through.

I'm not sure I buy that? I don't think it'd be valid to call
heapam_tuple_lock() with something indicating a moved partition? That's
different than reaching that during the retry loop!

(not yet done thinking about this, but have to run into a meeting, and this
seemed enough)

Greetings,

Andres Freund


Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Andres Freund <andres@anarazel.de>
Дата:
Вложения:
Hi,

On 2026-10-01 10:16:05 -0400, Andres Freund wrote:
> On 2026-09-29 16:31:39 +0000, Greg Burd wrote:
> > @@ -1768,6 +1768,12 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
> >  		slot->tts_flags |= TTS_FLAG_SHOULDFREE;
> >  		MemoryContextSwitchTo(oldContext);
> >  
> > +		/*
> > +		 * ExecClearTuple() above reset tts_tid, so restore it from the tuple
> > +		 * we just stored, the same way the tts_*_store_tuple() callbacks do.
> > +		 */
> > +		slot->tts_tid = tuple->t_self;
> > +
> >  		if (shouldFree)
> >  			pfree(tuple);
> >  	}
> 
> So one thing that's weird is that this does not modify the subsequent else
> block:
> 
> 	else
> 	{
> 		ExecClearTuple(slot);
> 		heap_deform_tuple(tuple, slot->tts_tupleDescriptor,
> 						  slot->tts_values, slot->tts_isnull);
> 		ExecStoreVirtualTuple(slot);
> 
> 		if (shouldFree)
> 		{
> 			ExecMaterializeSlot(slot);
> 			pfree(tuple);
> 		}
> 	}
> 
> If we decide to maintain the tid in ExecForceStoreHeapTuple() - I suspect the
> right call - we really should actually do it consistently.

None of the copyslots maintains it properly either. Some just don't set it,
others will *sometimes* infer it from the source tuple
(e.g. tts_buffer_heap_copyslot, if the source slot is a buffer slot). Nor is
tts_tableOid consistently maintained as part of a copy.

That seems to currently not really be observable, because afaict we always
push down the projection of ctid, tableoid accesses down to the scan level,
where the slot is populated "originally" (if you assume nodeModifyTable.c is a
scan node, at least).

Which I guess is an argument to not consider that aspect a bug.


> The lock path itself can't be reached with a virtual slot (c.f. assertion in
> heapam_tuple_lock()), but it might be possible to have a virtual slot in the
> path towards it. But even if it can't be today, it'll likely be soon.

AI did find a path, see attached tid2.sql, note the wrong tid for
    INSERT INTO parent_rows VALUES (2) RETURNING a, ctid;

Seems we should just move
    slot->tts_tid = tuple->t_self;
to the end of ExecForceStoreHeapTuple()?


After looking at tid2.sql I played around trying to see whether it'd make it
possible to get an invalid tid for an update and was rather horrified to find
out that cross-partition updates involving ctids just silently cause data to
be inconsistent with the partition constraints :(.


Greetings,

Andres Freund

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Thursday, October 1st, 2026 at 12:58 PM, Andres Freund  wrote:

> Hi,

Hello Andres, thanks for looking into this.

> We normally include email addresses as well. Also would be good to add
> Discussion links for the (at least?) two threads.  Adding Reviewed-By also
> helps eventual committers.

Yep, done, addresses on everything, both Discussion links, and Reviewed-by for
you, Dilip, Nik and Virender in v7 attached.  What's the convention when someone
both reports an issue and co-authors the patch?  I added myself and Virender
as reporters, but maybe we're also co-authors too?  Still learning this... :)

I'm dropping the attempts at adding asserts in other paths mainly because I'm
not sure of the value but also because while testing I ran into b8b94ea129f:

  For amcanreorderby scans the nodeIndexscan.c's reorder queue holds
  heap tuples, but the underlying table likely does not.

For such an AM the scan slot isn't a buffer slot, so reorderqueue_push() goes
ExecCopySlotHeapTuple() -> tts_virtual_copy_heap_tuple() -> heap_form_tuple(),
which does ItemPointerSetInvalid(&tuple->t_self). The queued tuple therefore
has no TID to begin with. 0001 stores that invalid TID and the assertion then
fires on a slot that is behaving correctly. heap_copytuple() preserves t_self,
which is why heap never hits this.

> On 2026-10-01 10:16:05 -0400, Andres Freund wrote:
> > On 2026-09-29 16:31:39 +0000, Greg Burd wrote:
> > > @@ -1768,6 +1768,12 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
> > >		slot->tts_flags |= TTS_FLAG_SHOULDFREE;
> > >		MemoryContextSwitchTo(oldContext);
> > >
> > > +		/*
> > > +		 * ExecClearTuple() above reset tts_tid, so restore it from the tuple
> > > +		 * we just stored, the same way the tts_*_store_tuple() callbacks do.
> > > +		 */
> > > +		slot->tts_tid = tuple->t_self;
> > > +
> > >		if (shouldFree)
> > >			pfree(tuple);
> > >	}
> >
> > So one thing that's weird is that this does not modify the subsequent else
> > block:
> >
> >	else
> >	{
> >		ExecClearTuple(slot);
> >		heap_deform_tuple(tuple, slot->tts_tupleDescriptor,
> >						  slot->tts_values, slot->tts_isnull);
> >		ExecStoreVirtualTuple(slot);
> >
> >		if (shouldFree)
> >		{
> >			ExecMaterializeSlot(slot);
> >			pfree(tuple);
> >		}
> >	}
> >
> > If we decide to maintain the tid in ExecForceStoreHeapTuple() - I suspect the
> > right call - we really should actually do it consistently.
>
> None of the copyslots maintains it properly either. Some just don't set it,
> others will *sometimes* infer it from the source tuple
> (e.g. tts_buffer_heap_copyslot, if the source slot is a buffer slot). Nor is
> tts_tableOid consistently maintained as part of a copy.
>
> That seems to currently not really be observable, because afaict we always
> push down the projection of ctid, tableoid accesses down to the scan level,
> where the slot is populated "originally" (if you assume nodeModifyTable.c is a
> scan node, at least).
>
> Which I guess is an argument to not consider that aspect a bug.

Agreed.

> > The lock path itself can't be reached with a virtual slot (c.f. assertion in
> > heapam_tuple_lock()), but it might be possible to have a virtual slot in the
> > path towards it. But even if it can't be today, it'll likely be soon.
>
> AI did find a path, see attached tid2.sql, note the wrong tid for
>     INSERT INTO parent_rows VALUES (2) RETURNING a, ctid;
>
> Seems we should just move
>     slot->tts_tid = tuple->t_self;
> to the end of ExecForceStoreHeapTuple()?

I took a copy of the TID at function start and use that later to avoid a case
where the tuple might have bee free'd.

> After looking at tid2.sql I played around trying to see whether it'd make it
> possible to get an invalid tid for an update and was rather horrified to find
> out that cross-partition updates involving ctids just silently cause data to
> be inconsistent with the partition constraints :(.

Yikes, good find that sounds worse than anything in this thread. The
postgres_fdw side looks like a separate patch, and I don't think it
should hold up the backpatchable fix. I'll take a look at it
separately if nobody else is already on it and start a new thread.

> Greetings,
>
> Andres Freund

v7/0001  the fix, now maintaining the TID for all slot types, plus the
         regression test. This is the piece that wants backpatching.

On backpatching 0001: applies as-is to 18, 17, 16 and 15. On 14 the C
hunk applies with an offset but the test hunks don't, gist.sql has grown
since. The test block is self-contained, so appending it to the end of
14's gist.sql and gist.out is enough IMO.

best.

-greg

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello.

v8 attached, code/fix is unchanged from v7 but just some cleanup of things
I'd overlooked or misunderstood so a new commit message and some additional
tests.

First, the tid2.sql case *is* fixed by this patch. I said otherwise, and
I'm sorry for the confusion. I'd tested against the wrong build, and then
misread EXPLAIN VERBOSE: the routed INSERT shows no "Remote SQL ...
RETURNING", which I took to mean ctid wasn't being requested. That remote
statement is built at execution time in postgresBeginForeignInsert(),
which passes ri_returningList through to deparseReturningList(), so ctid
is requested and make_tuple_from_result_row() does fill in t_self. What
lost it was the else (virtual-slot) branch of ExecForceStoreHeapTuple()
not setting tts_tid, which is exactly what moving the assignment to the
end (as you had suggested Andres) fixes.

Testing against a fresh build:

  INSERT INTO parent_rows VALUES (2) RETURNING a, ctid;
    v8:                     2 | (0,2)fixes
    execTuples.c reverted:  2 | (4294967295,0)

v8 drops the paragraph in v7's commit message that claimed this was a
separate postgres_fdw problem, and adds your case as a regression test
in postgres_fdw.sql, next to the existing insert tuple routing tests.
It inserts into itrtest and checks every returned ctid against
loct1/loct2, so as not to depend on page layout.

While writing it I found that only one of the two partitions in that
test shows the bug: remp1, whose columns match the parent, gets a virtual
result slot. remp2 declares (b, a), so its insert goes through a tuple
conversion map and a heap slot, which was already correct. The test
therefore reports one missing ctid rather than two without the fix.

Second, in my last mail I answered your cross-partition update comment
with "The postgres_fdw side looks like a separate patch". That attached
the FDW case to the wrong issue. As far as I can tell they're unrelated:
the FDW case was this bug, while

> cross-partition updates involving ctids just silently cause data to be
> inconsistent with the partition constraints :(.

is something else. I tried a few obvious shapes, a ctid-keyed UPDATE that
moves the row, a ctid-only predicate that matches (0,1) in two
partitions, and a ctid taken from a subquery against another partition,
and they all came out consistent with the partition constraints. So I
haven't found your case. Could you share what you ran? I'm happy to work
on it in a new thread.

On attribution, I'll answer my own question from last time, I've used
Co-authored-by: me and Virender, and Reported-by: you for the FDW
path. Tell me if you'd rather it were different.

Backpatching: v8 applies as-is to master and 15 through 18. On 14 the
execTuples.c hunk applies, but both test hunks need placing by hand
because gist.sql and postgres_fdw.sql have grown since. Both blocks are
self-contained and go in unchanged. I built 14 with --enable-cassert and
the placed postgres_fdw test passes with the fix and fails without it
(ctid_not_found 0 -> 1), the same as on master.

Apologies for rushing out the last email.

best.

-greg

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Greg,

The thread only tested the FOR UPDATE case with asserts, so I tried
it on a normal build. After the FOR UPDATE and a restart, the table
cannot be read or vacuumed:

  create table tri (id int, p polygon);
  insert into tri select i, format('((%s,0),(%s,9),(%s,0))',
    i * 10, i * 10 + 9, i * 10 + 9)::polygon
    from generate_series(1, 20) i;
  create index on tri using gist (p);
  vacuum analyze tri;
  set enable_seqscan = off;
  begin;
  select id from tri order by p <-> point(100,4) limit 5 for update;
  rollback;
  checkpoint;

Then restart the server and run

  select count(*) from tri;
  ERROR:  invalid page in block 1 of relation "base/5/16384"

With v8 the FOR UPDATE returns 5 rows and the count is 20. I think
it is ready for committer.

Thanks,
Shihao

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Sun, 18 Oct 2026 23:55:36 -0400, shihao zhong  wrote:
> Hi Greg,
> 
> The thread only tested the FOR UPDATE case with asserts, so I tried
> it on a normal build. After the FOR UPDATE and a restart, the table
> cannot be read or vacuumed:
> 
>   create table tri (id int, p polygon);
>   insert into tri select i, format('((%s,0),(%s,9),(%s,0))',
>     i * 10, i * 10 + 9, i * 10 + 9)::polygon
>     from generate_series(1, 20) i;
>   create index on tri using gist (p);
>   vacuum analyze tri;
>   set enable_seqscan = off;
>   begin;
>   select id from tri order by p <-> point(100,4) limit 5 for update;
>   rollback;
>   checkpoint;
> 
> Then restart the server and run
> 
>   select count(*) from tri;
>   ERROR:  invalid page in block 1 of relation "base/5/16384"
> 
> With v8 the FOR UPDATE returns 5 rows and the count is 20. I think
> it is ready for committer.
> 
> Thanks,
> Shihao

Hi Shihao,

Thanks for testing this. v9 is attached. The code is unchanged from v8.
The commit message now describes the damage as above, and I've added you
as Tested-by.

There are two patches this time:

   v9-0001         master, and applies as-is to REL_18 down to REL_15
   v9-REL_14-0001  the same fix, with both test blocks placed where 14's
                   gist.sql and postgres_fdw.sql need them

For each of the six branches, without the fix the new tests fail on
exactly their own hunk (gist ctid_not_found 0 -> 4, postgres_fdw 0 -> 1)
and nothing else, and with the fix they pass. On master the full meson
suite passes, 359 tests and none failing.

best.

-greg

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Nathan Bossart <nathandbossart@gmail.com>
Дата:
Вложения:
Here is what I have staged for commit, which I'm planning to do early next
week barring additional feedback or objections.  I've left out the tests
and extra checks for now.  Those might be worth adding, but I'd like to
make sure we at least get the main fix into November's releases.

-- 
nathan

Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:

On Friday, October 30th, 2026 at 12:11 PM, Nathan Bossart  wrote:

> Here is what I have staged for commit, which I'm planning to do early next
> week barring additional feedback or objections.  I've left out the tests
> and extra checks for now.  Those might be worth adding, but I'd like to
> make sure we at least get the main fix into November's releases.
> 
> --
> nathan

Thanks Nathan, +1.

-greg


Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 30/10/2026 18:11, Nathan Bossart wrote:
> --- a/src/backend/executor/execTuples.c
> +++ b/src/backend/executor/execTuples.c
> @@ -1752,6 +1752,8 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
>  						TupleTableSlot *slot,
>  						bool shouldFree)
>  {
> +	ItemPointerData tid = tuple->t_self;
> +
>  	if (TTS_IS_HEAPTUPLE(slot))
>  	{
>  		ExecStoreHeapTuple(tuple, slot, shouldFree);
> @@ -1784,6 +1786,13 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
>  			pfree(tuple);
>  		}
>  	}
> +
> +	/*
> +	 * ExecClearTuple() invalidated the slot's TID, so we need to set it again
> +	 * here.  Note that the tuple might have already been freed, so we use the
> +	 * copy of its TID that we saved above.
> +	 */
> +	slot->tts_tid = tid;
>  }
>  
>  /*
The comment sounds wrong to me. This isn't restoring the old TID that 
was in the slot previously, it's setting the new TID from 'tuple'. Or am 
I missing something?

For same reason, the local variable seems pointless; you could just do:

     slot->tts_tid = tuple->t_self;

The comment in Greg's earlier version (v9) said:

> +	/*
> +	 * Store the TID from the local copy taken on entry since the stores above
> +	 * may have freed the tuple.
> +	 */
> +	slot->tts_tid = tid;

But I don't see how the store might've free'd the tuple. If it did, we'd 
have trouble anyway.

- Heikki



Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:
On Sat, 31 Oct 2026 10:50:46 +0200, Heikki Linnakangas  wrote:
> On 30/10/2026 18:11, Nathan Bossart wrote:
> > --- a/src/backend/executor/execTuples.c
> > +++ b/src/backend/executor/execTuples.c
> > @@ -1752,6 +1752,8 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
> >  						TupleTableSlot *slot,
> >  						bool shouldFree)
> >  {
> > +	ItemPointerData tid = tuple->t_self;
> > +
> >  	if (TTS_IS_HEAPTUPLE(slot))
> >  	{
> >  		ExecStoreHeapTuple(tuple, slot, shouldFree);
> > @@ -1784,6 +1786,13 @@ ExecForceStoreHeapTuple(HeapTuple tuple,
> >  			pfree(tuple);
> >  		}
> >  	}
> > +
> > +	/*
> > +	 * ExecClearTuple() invalidated the slot's TID, so we need to set it again
> > +	 * here.  Note that the tuple might have already been freed, so we use the
> > +	 * copy of its TID that we saved above.
> > +	 */
> > +	slot->tts_tid = tid;
> >  }
> >  
> >  /*
>

Hey Heikki, thanks for taking a look at this.  I appreciate it.

> The comment sounds wrong to me. This isn't restoring the old TID that 
> was in the slot previously, it's setting the new TID from 'tuple'. Or am 
> I missing something?

No, you're right. ExecClearTuple() resets the slot's previous TID, and
what goes in afterwards is the incoming tuple's t_self, which has no
relation to the old value. "set it again" reads as restoring it.

> 
> For same reason, the local variable seems pointless; you could just do:
> 
>      slot->tts_tid = tuple->t_self;

That's the form I tried first, at Andres's suggestion, and it's why the
local is there. The tuple is gone by the end of the function. Both the
buffer and the virtual branches finish with

     if (shouldFree)
         pfree(tuple);

and the only two callers that pass shouldFree = true are the ones this
patch is about:

     nodeIndexscan.c:257   ExecForceStoreHeapTuple(tuple, slot, true);
     postgres_fdw.c:4660   ExecForceStoreHeapTuple(newtup, slot, true);

the reorder queue, and Andres's tid2.sql routed insert. So reading
tuple->t_self after the if/else reads freed memory.

I re-ran it this morning on Debian 13, master at 77705d1e5a, with the
GiST reorder-queue case from the thread (20 thin triangles, ORDER BY p
<-> point(100,4) LIMIT 5). With your form, an assert-enabled build gives

      ctid               | id
     --------------------+----
      (0,9)              |  9
      (0,32639)          | 10
      (0,32639)          | 11
      (1437663232,32639) |  8
      (0,32639)          | 12

32639 is 0x7F7F, the CLOBBER_FREED_MEMORY fill, and the row with the
huge block number has picked up a pointer from whatever reused the
chunk. Without assertions it doesn't fail cleanly either: four rows come
out right, and one gets a different random block each time,
(1432158208,8) on one run and (1440808960,8) on the next. With the local
copy (v10) all five rows are (0,9) (0,10) (0,11) (0,8) (0,12), on both
builds and over three runs each.

> 
> The comment in Greg's earlier version (v9) said:
> 
> > +	/*
> > +	 * Store the TID from the local copy taken on entry since the stores above
> > +	 * may have freed the tuple.
> > +	 */
> > +	slot->tts_tid = tid;
> 
> But I don't see how the store might've free'd the tuple. If it did, we'd 
> have trouble anyway.

That comment was badly worded, and I think it's what sent you down this
path. The stores don't free it; the explicit pfree() after each store
does. And we don't have trouble anyway, because each branch copies the
data out before freeing it: heap_copytuple() in the buffer branch and
ExecMaterializeSlot() in the virtual one. The slot is fine. Only the
original tuple is gone, and t_self is the one thing we still read from
it.

So I'd keep the local copy and fix the comment so it gives the actual
reason, something like:

     /*
      * Set the slot's TID from the tuple.  ExecClearTuple() reset it, and
      * only the heap-slot branch above stores a new one.  Use the copy taken
      * on entry, because the branches above free the tuple when
      * shouldFree is true.
      */
     slot->tts_tid = tid;

> - Heikki

Nathan, please adjust the wording however you like when you commit.

best.

-greg




Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Nathan Bossart <nathandbossart@gmail.com>
Дата:
On Sat, Oct 31, 2026 at 01:34:16PM +0000, Greg Burd wrote:
> That comment was badly worded, and I think it's what sent you down this
> path. The stores don't free it; the explicit pfree() after each store
> does. And we don't have trouble anyway, because each branch copies the
> data out before freeing it: heap_copytuple() in the buffer branch and
> ExecMaterializeSlot() in the virtual one. The slot is fine. Only the
> original tuple is gone, and t_self is the one thing we still read from
> it.
> 
> So I'd keep the local copy and fix the comment so it gives the actual
> reason, something like:
> 
>      /*
>       * Set the slot's TID from the tuple.  ExecClearTuple() reset it, and
>       * only the heap-slot branch above stores a new one.  Use the copy taken
>       * on entry, because the branches above free the tuple when
>       * shouldFree is true.
>       */
>      slot->tts_tid = tid;
> 
> Nathan, please adjust the wording however you like when you commit.

Heikki, WDYT?  I was similarly confused by the comment, and my attempts at
better phrasing obviously fell short.

-- 
nathan


Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Nathan Bossart <nathandbossart@gmail.com>
Дата:
On Mon, Nov 02, 2026 at 08:20:42AM -0600, Nathan Bossart wrote:
> On Sat, Oct 31, 2026 at 01:34:16PM +0000, Greg Burd wrote:
>> Nathan, please adjust the wording however you like when you commit.
> 
> Heikki, WDYT?  I was similarly confused by the comment, and my attempts at
> better phrasing obviously fell short.

Eh, I decided to just add the assignments in the branches where it was
missing and omit the comment.  But the fix is now committed.

-- 
nathan


Re: [PATCH] Corruption Issue: Fix missing tts_tid in ExecForceStoreHeapTuple

От:
Greg Burd <greg@burd.me>
Дата:

On Monday, November 2nd, 2026 at 11:18 AM, Nathan Bossart  wrote:

> On Mon, Nov 02, 2026 at 08:20:42AM -0600, Nathan Bossart wrote:
> > On Sat, Oct 31, 2026 at 01:34:16PM +0000, Greg Burd wrote:
> >> Nathan, please adjust the wording however you like when you commit.
> >
> > Heikki, WDYT?  I was similarly confused by the comment, and my attempts at
> > better phrasing obviously fell short.
> 
> Eh, I decided to just add the assignments in the branches where it was
> missing and omit the comment.  But the fix is now committed.

That was the other option, and now the code is the documentation (and this
discussion thread).

> --
> nathan

thank you.

-greg


FAQ