Re: Tepid: selective index updates for heap relations

Started by Greg Burdabout 2 months ago15 messageshackers
Jump to latest
#1Greg Burd
greg@burd.me

On Mon, Jul 27, 2026, at 11:36 PM, Chao Li wrote:

On Jul 21, 2026, at 05:34, Greg Burd <greg@burd.me> wrote:

On Fri, Jul 17, 2026, at 4:12 PM, Bharath Rupireddy wrote:

Hi,

On Thu, Jul 16, 2026 at 3:05 AM Greg Burd <greg@burd.me> wrote:

Rebased onto 3cf5264557b to address conflicts, no other changes.

Thanks for working on this. I previously played around with PHOT and
WARM a bit and built some context, but I need to refresh my memory and
give things a re-read.

Thanks for looking at it!

The patches cover a lot. Reducing the diff to the core and posting the
stats, amcheck, and logical replication patches later would make
review easier. I managed to get through 0001 and 0002 so far.

Yes, the 0001 and 0002 work is really a direct re-posting of the same two patches on my cf-5556 work that moves HeapDetermineColumnsInfo() into the executor. That was necessary work for the "HOT for Expression Indexes" but even more so for this work because this involves changing the contract between the table AM and the index AM as goverened by the executor to allow for cases other than TU_All/Summarizing/None.

Yes, it is dense and I should try to chop it up a bit more. I think at this stage it the viability of the idea hinges on the format changes and their long term implications. If those aren't accepted (and I'm on the fence myself on the "bit14" idea) then I have to get other foundational changes in before this could fly so I wasn't super concerned about having the final patch layout.

The tight integration of the TID abstraction across the table AM, the index AM and the executor is something that is hard to ignore and hard to work around. The TID abstraction is a heap specific thing (IMO) that works very well but is a very leaky and at times a highly limiting one.

I would be more interested in focusing the initial discussion on the
key design decisions. Where to store the modified index bitmap (it is
per-row version). How we get vacuuming right. How bitmap scans and
index scans produce correct results. How on-disk row format changes
are acceptable. How upgrades work for migrating existing databases.
How replication (logical and streaming) works and any impact on
downstream systems (replicas, subscribers, etc.). How it impacts
tooling (in-core like amcheck, pg_upgrade, pageinspect, and external
ones).

Yes, all good topics.

Most importantly, the trade-offs. We are going to have more heap bloat
at the cost of less index bloat, which is fine since most OLTP
workloads go via indexes, but does it impact analytical workloads that
scan the heap? How does it impact vacuum performance? Do we know how
many customers in practice modify indexed columns (not exact numbers,
but some data points to keep the motivation up for this feature)? The
fact that the modified index column bitmap is now stored per tuple
version means fewer rows fit per page, which means more pages per
relation, and does it also mean fewer HOT updates because updated rows
cannot fit in the same page since some space is used for storing the
bitmap, causing more index maintenance in turn?

Yes, there are trade-offs to call out. The heap pages will a) have more meta-data on them in the form of the bitmaps on UPDATE that collapse into dead tuples and b) yes there will be longer redirect chains that are harder to fully collect during vacuum and they will prevent pages from being marked frozen more frequently. That is true, and that has a cost.

Also, the naming (SIU, Tepid, HOT-INDEXED, HEAP_INDEXED_UPDATED, and
previously PHOT, WARM) is a bit confusing to me. Could we simplify the
names and use them consistently?

I agree, and naming is hard. Happy to take on any ideas here. I've been calling it "tepid" and explaining it as "selective index updates" and in a way that is "partially HOT (PHOT)" but in other ways the tepid model isn't a "heap-only tuple (HOT)" at all, it's not heap-only it is heap and SOME indexes but not ALL. IDK what to call it, but maybe that's something to work out if/when the idea(s) and trade-offs are accepted and we're finalizing the code for commit?

Some quick comments on the patches.

0001:

1/ Can 0001 be discussed in a separate thread? It seems to provide
good coverage for HOT updates on its own and is worth discussing and
perhaps getting committed separately.

This was pre-amble for changes that I'd planned for the HOT for Expressions patches. It's not strictly necessary in tepid, I should just drop it.

2/

+SELECT id FROM hot_xml_test WHERE xpath('/person/name/text()', doc) =
ARRAY['Alice2'::text];
+ERROR:  operator does not exist: xml[] = text[]
+LINE 1: ..._xml_test WHERE xpath('/person/name/text()', doc) = ARRAY['A...
+                                                             ^
+DETAIL:  No operator of that name accepts the given argument types.
+HINT:  You might need to add explicit type casts.
+INSERT INTO hot_xml_test VALUES
+    (1, '<person><name>Alice</name><age>30</age></person>'),
+    (2, '<person><name>Bob</name><age>25</age></person>');
+ERROR:  could not identify a comparison function for type xml
+SELECT * FROM get_hot_count('hot_xml_test');

Are these expected?

Yeah no, my mistake. The more I looked at the XML tests the more they didn't really add value so I've removed them.

0002:

1/
-SELECT * FROM base_tbl;
+SELECT * FROM base_tbl ORDER BY a;
ERROR:  cannot insert a non-DEFAULT value into column "b"
DETAIL:  Column "b" is a generated column.
-SELECT * FROM gtest1v;
+SELECT * FROM gtest1v ORDER BY a;
-DELETE FROM main_view WHERE a IN (20,21);
+DELETE FROM main_view WHERE a = 20 AND b = 31;
NOTICE:  main_view BEFORE DELETE STATEMENT (before_view_del_stmt)
NOTICE:  main_view INSTEAD OF DELETE ROW (instead_of_del)
-NOTICE:  OLD: (21,10)
-NOTICE:  main_view INSTEAD OF DELETE ROW (instead_of_del)
NOTICE:  OLD: (20,31)
+NOTICE:  main_view AFTER DELETE STATEMENT (after_view_del_stmt)
+DELETE 1

The commit message says this fixes nondeterministic behavior in
existing tests due to row ordering. I think these are unrelated to
this work and could be discussed and committed separately.

Sure, possibly. The instability became apparent when working on the first two patches.

2/ ExecUpdateModifiedIdxAttrs() replaces HeapDetermineColumnsInfo().
Why do we need to move modified index attribute computation to the
executor and make every TTS and table AM pay that cost? HOT and
modified index attributes are purely heap AM specific. If the executor
ever needs the list of modified index attributes, why not let the AMs
provide it as an out parameter (similar to how we pass the HOT hint in
TU_UpdateIndexes format)?

The contract between the index and table AMs is governed by the the executor, or it should be (IMO), and the TU_All/Summarizing/None model that exists now is very much a heap-ism (leaky, too heap-MVCC specific) and so breaks down in the face of any table AM that has a different MVCC model. IMO the executor should be defaulting to only updating the indexes that are impacted by an update as a rule but allow for table AMs to influence that. Why? Because a table-agnostic executor should have as a goal not updating indexes unless those updates are required by the modifications underway. Doing more than that amount of work as a rule is assuming things the executor shouldn't know about in the table and/or index implementations. So, the executor (after patch 0002) will only update indexes that overlap with the modified attributes.

I read the commit message saying that finding this set of attributes
is not heap-specific but more general to all table AMs and could
inform other decisions about when index inserts are required. But is
it needed for this feature? If not, I think it can be discussed
separately.

Yes, how else is the heap supposed to be able to communicate which subset of indexes to update in a generic manner? I tried other methods and they all felt (to me) like they were working around a leaky abstraction rather than fixing the root cause. Your view may differ.

3/
- SELECT FROM injection_points_detach('heap_update-before-pin');
- SELECT FROM injection_points_wakeup('heap_update-before-pin');
+ SELECT FROM injection_points_detach('simple_heap_update-before-pin');
+ SELECT FROM injection_points_wakeup('simple_heap_update-before-pin');

Once we find the need for 0002, can we just leave the injection point
name as-is to reduce the mechanical diff?

I can re-try and find out if it matters.

4/ Nits.
Typos.
+ * are in the UPDATE statment and are known to be referenced by at least one
+ * ExecGetAllUpdatedCols().  Desipte the name it provides the set of

Fixed.

No need to specify test names in the comments, because they can change anytime.

I disagree this time because the comment calls out a very very subtle hidden issue that is induced by that test and I felt should be documented so the next hacker could understand and avoid it earlier in the process than I did.

* heap_modifiy_tuple(). There is one test in tsearch.sql that does just
+ * that, modifies an indexed attribute that isn't specified in the SQL and

5/
+ /* attidx is zero-based, attrnum is the normal attribute number */
+ AttrNumber attrnum = attidx + FirstLowInvalidHeapAttributeNumber;

Is every TTS implementer expected to support all system columns that
FirstLowInvalidHeapAttributeNumber implies? Asking because 0002 moved
this code to the executor in ExecCompareSlotAttrs.

Interesting point. Yes, I did move a heap-ism into the executor (facepalm), something I claim to be against. :)

I'm going to take the abstraction critique seriously and move the mechanism of "which attributes changed" behind the slot/table-AM boundary, while keeping the policy "only maintain indexes whose attributes overlap the change" in the executor.

Concretely: ExecCompareSlotAttrs() as written leaks heap assumptions upward (it enumerates over FirstLowInvalidHeapAttributeNumber and hand-handles system columns like tableoid), which is fair to call out. The comparison of two versions of a row is something the AM should answer for its own attributes and its own notion of "a version changed"; the executor should only collect that changed-set and intersect it with each index's attribute set to decide which indexes need fresh entries. That split is the honest form of "the executor governs the table-AM/index-AM contract, the table AM owns its storage mechanics."

The reason I can't instead adopt the suggested out-parameter model, have the AM return modified_attrs from table_tuple_update(), is a matter of ordering, and I think it's the same ordering that a couple of the concurrency questions in the thread are also tripping on, so it's worth stating plainly:

modified_attrs is an input to table_tuple_update(), not a byproduct of it. The heap AM reads it during the update to decide, before it writes anything, (a) whether the update can stay HOT / selectively-indexed vs. must update all indexes (HeapUpdateHotAllowable), (b) the tuple lock mode (HeapUpdateDetermineLockmode), and (c) whether the replica-identity key changed. The executor then uses the same set after the update to drive which indexes get fresh entries. A value returned from the update call would arrive after every one of those decisions had already been made it's structurally too late to inform them. So the changed-attribute set has to be available to, and passed into, the table AM, not produced by it.

The clean way to satisfy both constraints that comes to mind is a slot/AM-level comparison the executor calls to build the set (AM owns "what changed"), then passes into the update (executor owns "which indexes"). That keeps the decision points in the right order and removes the heap-ism from the executor. To that end I've added to the table AM: table_modified_attrs() callback in an updated 0002 and in heap heapam_modified_attrs() in a new 0003 patch.

(Separately and related to that: this is also why the "reduces buffer-lock hold time" line in the 0002 commit message is both wrong and misleading the computation was always pre-lock and I'm dropping it.)

6/ The commit message says that having ExecUpdateModifiedIdxAttrs() in
the executor reduces the time the buffer lock is held by computing
modified index columns before table_tuple_update(). How is this
correct from a concurrency perspective? If another transaction
modifies the same tuple between when the executor compares columns and
when heap_update acquires the buffer lock, what happens? The executor
locks the old tuple explicitly only when it detects concurrent updates
or deletes to the same tuple, but does not hold the tuple lock the
first time.

Good catch, and the commit message is misleading here I'll reword it. The "reduces the time the buffer lock is held" line oversells a benefit that isn't real and, worse, invites exactly the concurrency worry you raised. In today's tree HeapDetermineColumnsInfo() already runs before heap_update() takes the buffer lock (it's computed up front from oldtup/newtup), so moving the computation into the executor doesn't change when, relative to the buffer lock, the comparison happens. The motivation for the move is the table-AM/index-AM contract, not lock-hold latency; I'll drop that paragraph so it stops implying otherwise.

On the concurrency correctness itself, there's no window to exploit:

- ExecUpdateAct() computes modified_attrs from (oldSlot, newSlot) and immediately calls table_tuple_update() in the same function, with no lock dropped and no yield between the two. There is no "compare, then later acquire the buffer lock" gap — the comparison is not protected by, nor waiting on, any buffer lock, in either the old or new arrangement.

- Concurrency is still detected exactly where it always was: inside heap_update(), under the buffer lock, via the xmax/visibility check. If another transaction updated the row first, heap_update() returns TM_Updated (unchanged by this patch).

- On TM_Updated, ExecUpdate() runs the normal EPQ path: table_tuple_lock() the latest version, EvalPlanQual(), re-fetch the latest oldSlot and rebuild the new slot, then goto redo_act — which re-enters ExecUpdateAct() and recomputes modified_attrs against the fresh versions.

- modified_attrs is consumed only in ExecUpdateEpilogue() (the index-insert step), which runs only on the TM_Ok path. A modified_attrs computed against a version that lost the race is discarded and recomputed before any index maintenance happens.

So the set of indexes we maintain is always derived from the same (old, new) pair the update was actually applied to; a concurrent update forces a re-read and recompute before index inserts, identical in effect to how HeapDetermineColumnsInfo() behaves today. The executor doesn't need to hold a tuple lock across the comparison for the same reason it doesn't today — the AM's TM_Updated/EPQ protocol is the serialization point.

I'll fix the injection-point/comment nits and drop the misleading commit-message paragraph in the next revision.

I will continue reading the other patches in the coming weeks.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

best.

-greg<v67-tepid.tgz>

Thanks for the patch.

I have spent some time reviewing v67 0001-0009. git am failed at 0010,
so a rebase is needed.

Hello Chao, thank you for investing time to review this work.

Apologies for the delay responding. It has been a long time since I've updated this patch set due to /reasons/ that don't matter but here. I'm back at it and hope you appreciate these changes in approach and in code.

I think I have only got a rough idea of what this feature does and how
it works so far. I believe I will still need much more time to
understand the details.

I just want to raise a few design comments I have so far:

* Does it make sense to add a table-level option to make this feature
opt-in? From my understanding, this feature will benefit tables that
have many indexes across multiple fields. Although benchmarks are
attached, I am afraid they may not be able to simulate all users' data
models. Making it opt-in would allow users to easily evaluate the
feature with their own tables and enable it only on tables that really
benefit from it. I realize that turning it on is easy, but turning it
off may require table rewritten and index rebuilds. However, I think
that is acceptable, as many other ALTER TABLE operations may also
require so.

I appreciate your point of view on this, it is a behavior change for heap and that means basically everyone. This feature benefits UPDATEs that modify some, but not all, of a relation's indexed columns: today those force a new entry in every index; with this change only the indexes whose columns changed are maintained. In those cases, where some but not all indexes on a relation intersect, the benefit is avoiding the index write and the overhead that "index bloat" creates for vacuum and index scans. Avoiding those writes avoids index "bloat" and the I/O and storage costs during the operation. This is measurable in terms of TPS for UPDATEs that fall into that pattern and also in terms of WAL volume, index size, and vacuum time and frequency.

I'm personally against a GUC or reloption or other gating because the feature is safe and beneficial by default, and a knob adds permanent surface area, we didn't gate the initial HOT feature so why do so now? That said, it's a good idea to explore the idea and answer your questions about it. I don't believe there would be any index corruption or issues if we had a knob to enable/disable the feature even after operating in one mode or the other for a while as long as the chain walking logic remained on, that is to say that the read side (chain walk + crossed-attribute recheck) is stateless w.r.t. the knob; only creation of new HOT-indexed updates would be gated. If that was also gated by the knob then existing chains age out through normal prune/vacuum; a VACUUM FULL or CLUSTER normalizes immediately but wouldn't be required.

* When an index entry points to a stale tuple chain, it still returns
the entry and sets xs_hot_indexed_stale, which means callers of
index_getnext_slot() need to check this new state. This seems to weaken
the current index scan API contract. Is there any thought behind
exposing this state to callers instead of filtering stale entries
internally?

This is a good question, I'll try to dive in and provide my thoughts which I don't pretend are the final/correct answer just where I am on this trade-off right now.

I need to stop here to handle some other work. I will come back with
more comments later.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

After much thought about the implicit contracts between the HEAP table AM, index AMs (mostly nbtree), and the executor I felt that I should try to untie a bit of the Gordian knot rather than add another thread to it. By that I mean I've tried hard in v68 to call out what was implicit before and make it explicit.

In this v68 series we have:

0001 - a table AM contract (or what I might like to call a "trait") similar to those found on indexes but the first of its kind for tables. This contract defines what a "locator" is, which in today's world is always a TID, and pull back into the table AM what enables a locator to do its job and interact with the executor and any number of index AMs.

0002 - this is a simple rename of "traversed" to retargeted in TM_FailureData to, in my mind, make it more clear what that boolean is communicating. Some might say this isn't required, and they'd be right, but I felt this change made it clearer to me and I hope others what this field means in practice so I've left it in this series.

0003 - now that we've defined a "locator" let's make it possible for the bytes that define the location to be a variable length so some table AM in the future (not introduced here in this series) could in theory store something other than a TID in an index that supports such behavior. Imagine a table that wants to provide the primary key as the "locator" (read: OrioleDB) or something somewhat TID-like but not entirely (see: Zedstore)

0004 - and while we're at it, let's stretch our minds a bit and consider that some table AMs might want to update in-place and manage MVCC differently from the model in HEAP. Again, nothing like that is introduced in this commit, but if we're going to define how an index and executor reference items stored in tables this feels like a case worth covering.

0005 - in this patch we get to the core issue that forced me to rethink and redesign Tepid a bit and bring to light the locator contract; the BitmapAnd/Or operations in the executor. Were it not for them this patch set could have sailed through months ago. But we have this nifty optimization whereby an index and executor can avoid pulling table (heap) pages under certain circumstances and so we need to continue to support that. To do that in the previous patch set I'd been co-opt'ing the 14th bit of a TID to signal a need to do something different when performing these bitmap scans, that left me feeling very dirty so I've found a new way to work around this which has different (hopefully lesser) trade-offs (you'll be the judge on that I'm sure). I had to find another method to address this issue head on. So, I've widened the VM map 2 bits to 4 bits in total (2x in size, say it isn't so!) and now track per-page in the VM with the third bit of those four if an indexes' entries for a row on the page may name different line pointers, which is the case where a bitmap AND scan must jump through hoops. BitmapOr turns out to be a non-issue for HEAP and TIDs, but there is room in the contract for table AMs that have other shapes to own that as well.

0006 - here is where we return to the earlier patch set which began by adding more tests as a way to baseline the existing HOT functionality more precisely than we've done so far, this commit is largely what it was before with some cleanup.

0007 - this is the commit that has traveled far from it's start in the thread on supporting expression indexes in the HOT update path, it is largely unchanged and still moves the logic of HeapDetermineColumnsInfo() from the HEAP into the executor while calling into the table AM for the AM's specific needs/layout so as not to leak HEAP-isms into the executor (well, not add more of those leaks).

0008 - here I borrow bits form the infomask for selective index updates (SIU) on the HOT path as in previous versions of these patches

0009 - this is the meat of the Tepid selective index updates (SIU) patch and the largest change set in this series, also mostly unchanged from before

0010 - update the prune/vacuum process to reclaim SIU chains

0011 - update statistics to include new useful metrics for observing SIU in action

0012 - update amcheck so it's not confused by the changes we've made thus far

0013 - enable some new choices on logical replication stemming from SIU

0014 - and the benchmark I'm using to measure for transparency sake, but not proposed for merge into core (just for you to tell me how I'm doing it wrong, lol)

And so there you have it, another in the long line of attempts at expanding the concepts and advantages of the HOT update path for HEAP but in a way that furthers other important goals as well. I hope you enjoy reading and reviewing this as much as I have enjoyed coding it. Also attached is my draft of a wiki page on this and you will also find a new README.HOT-INDEXED to (hopefully) shed some light on these changes. I have reviewed all of this code myself, I have at times also used LLMs to review and or adjust patches (split them, re-order them, etc.). This code will, I hope spark a debate on the merits of my approach to opening the door to a world where only modified indexes are updated, not ALL/NONE/SUMMARIZING, and I look forward to your thoughtful reviews and feedback on it.

best.

-greg

Attachments:

v68-tepid.tgzapplication/x-compressed-tar; name=v68-tepid.tgzDownload+6-7
HOT-Indexed-Updates-Design.mediawikiapplication/octet-stream; name=HOT-Indexed-Updates-Design.mediawikiDownload
#2Greg Burd
greg@burd.me
In reply to: Greg Burd (#1)

Hello, v69 attached and rebased onto e5d25959 to appease the cfbot.

-greg

Attachments:

tepid-v69.tgzapplication/x-compressed-tar; name=tepid-v69.tgzDownload+4-5
#3Greg Burd
greg@burd.me
In reply to: Greg Burd (#2)

Hello, v70 attached and rebased onto d4c15309 to appease the cfbot.

-greg

Attachments:

tepid-v70.tgzapplication/x-compressed-tar; name=tepid-v70.tgzDownload
#4Greg Burd
greg@burd.me
In reply to: Greg Burd (#3)

From: Greg Burd <greg@burd.me>
To: pgsql-hackers@postgresql.org
Subject: Re: Tepid: selective index updates for heap relations
In-Reply-To: <af02b486-6adc-494c-a357-1dd72f655dcf@app.fastmail.com>
References: <af02b486-6adc-494c-a357-1dd72f655dcf@app.fastmail.com>

Attached is v71, rebased on master through f58ab18a.

I took the time to split the table/index AM contract and executor
changes out from the heap implementation. This makes the series longer,
but should make it easier to review the interface without first
reviewing the other changes for Tepid.

In thinking this through I might pull out the locator contract into
a new thread to discuss separately along with the other changes to
core, but for now they live here.

Each of these have their own patch near the beginning so that we can
discuss them separately:

* BitmapAnd now learns the table relation from each bitmap index scan,
including scans nested under BitmapOr. For a group where entries for
the same row can name different slots (as can happen with Tepid due to
mid-chain references in indexes), the AM's callback requests a union
and recheck instead of an exact intersection. The locator contract
also has an optional BitmapOr recheck hook.

* The locator descriptor states width, maximum offset, locator stability
and whether an UPDATE preserves the old version. A stable locator does
not imply unchanged contents. The LOCKED_VERSION flags distinguish a
snapshot-visible version from one the command has already locked;
retargeted tells callers when they must re-evaluate a newer version.

* For AMs that overwrite rows (none of which exist in core today, but
many have experimented with this including me in the UNDO[1] proposal
with the FLUX table AM), the executor preserves OLD before the
write. AFTER ROW events can carry OLD and event-time NEW, with spill
and subtransaction cleanup. Foreign-key checks and unique rechecks
still fetch the current version. The contract requires a deleted row
to remain fetchable with SnapshotAny until the deleting transaction
ends.

* Index creation and rebuilds check locator width. The amcanvarlocator
capability remains, but this does not add variable-width transport to
the existing ItemPointerData interfaces. max_offset also bounds the
planner's bitmap paths and GIN's supported offsets.

In the v68 patch set I overloaded the meaning of bit 14 in a TID as a
signal used during BitmapAnd, I never felt that was a good idea and it
was that struggle that forced my hand to either a) give up or b) write
the locator contract. I did (b), but that meant that I needed somewhere
else to hide the hint I'd burried in bit 14 before. In this series I've
done that via the visibility map and I feel a bit less dirty, but I do
have a sense of guilt for doubling its size.

I moved heap's locator-split visibility-map bit and pg_upgrade rewrite
into the heap portion. This widens the visibility map from two to four
bits per heap block, as I said before doubling its size, and requires
rewriting old _vm forks during upgrade which isn't great, but we're
living in a world of not-great trade-offs if we want to solve this so
help me find a better trade-off, get comfortable with this one, or we
put a pin in this idea alltogether and call it a day.

Heap's update and prune/vacuum changes now land together, so no
intermediate patch creates chains that pruning cannot handle. I also
fixed index-only-scan identification in the common scan constructor so
btree retains its leaf pin for genuine index-only scans.

The patch order is:
01-07 Locator contract, version naming, triggers and bitmap hooks
08 Capturing/codifying the existing HOT behavior in tests
09-12 Attribute comparison and generic selective index maintenance
13-15 Heap format, visibility map, update and prune/vacuum support
16-18 Statistics, amcheck and logical-replication apply option
19-20 [DO NOT MERGE] Test AMs and benchmark harness

The test AMs exercise contract properties that heap does not normally
use. They do not validate LOCKED_VERSION semantics for a real in-place
AM; they still use heap's lock and update implementation.

I need to re-benchmark this version and also measure the impact on the
visibility map.

There remains many things that need to be quantified, reviewed, and
deemed "acceptable trade-offs" including:
* the visibility map 2->4 bits
* rewriting old _vm forks during upgrade
* the overhead of additional tuples in longer chains on heap pages
* making it harder to declare a heap page all visible
* the negative impact of 01-07 patches on performance
* the positive impact of 09-18 on performance, table and index bloat
* I'm surely missing something...

At this point, I'd particularly appreciate review of the locator
contract, the rest of the 01-07 changes, and the visibility-map
trade-off. TM_FailureData still exposes cmax, xmax and ctid to callers
outside heap; I have left abstracting those fields for follow-up work
(because I think they fall into the same bucket of "heap-specific leak
into the surrounding code" or "leaky abstraction" or whatever you'd like
to call it) rather than adding it to this (ever growing, now 20 patches)
series.

best.

-greg

Attachments:

tepid-v71.tar.gzapplication/gzip; name=tepid-v71.tar.gzDownload+2-5
#5Greg Burd
greg@burd.me
In reply to: Greg Burd (#4)

Hello,

Attached is v72, rebased onto 9e7d1524. The series now has 26 patches,
more than I'd anticipated and hard for anyone to commit to a review at
that scale. Apologies, perhapes I'll break out the locator contract
into a separate thread next.

I ran the benchmarks I promised in the v71 email which turned up a few
bugs, which I've fixed. It's always good idea to test at scale to find
issues.

TL;DR
-----

The anticipated wins are in this series, the other shapes showed almost
no change of significance.

Mixed 80/20 read/update +32.26%
Update one of eight indexed columns +51.56%

The worst impact:
Plain-index scan after churn -5.94%

Changes since v71
-----------------

The first addition is the TM_FailureData abstraction I deferred
in v71. Patch 03 moves ctid, xmax and cmax into HeapTupleFailureData.
Table-AM callers instead receive same-command, current-transaction and
partition-move results. The adapter initializes the semantic outputs on
each call and reads heap fields only for results that define them.
retargeted accumulates across retries within one lock call. Executor,
trigger and replication callers no longer interpret raw heap metadata.
Tests cover the command/transaction distinctions, including MERGE and
subtransactions.

The other five additions fix problems found during testing:

* Repeated pruning could bypass a preserved changed-attribute bitmap
stub. An old index entry then looked valid for the current tuple. A
20-row example returned 24 rows through a unique index, and WHERE u=1
could return a row whose current value was -1. Pruning now preserves
the hop information and forwarding links. Tests cover repeated and
opportunistic pruning, ordering, offset reuse and WAL replay.

* amcheck's heapallindexed check confused a valid old chain anchor with
the live tuple's own TID. It now compares coverage through the visible
tuple while retaining the stored index key and rejecting stale anchors
for that index. It validates physical chain structure before using the
heap visibility walker, so corrupt links do not turn the checker into
an assertion failure. This is separate from the wrong-query fix.

* HOT-indexed redo did not initialize a new visibility-map page when no
applicable full-page image existed. It now initializes the page before
setting the locator-split bit. Recovery tests cover full_page_writes
settings and VM tail truncation. I kept the existing WAL consistency
masking rules; strict bitmap comparison would reject legitimate
unlogged truncation changes.

* Concurrent index validation could insert a second entry for a tuple
that already had a valid per-index chain anchor. Validation now checks
those anchors under its snapshot before adding an entry. The tests
include REINDEX CONCURRENTLY and changed, unchanged and A-to-B-to-A
keys.

* Unique checks requested a key recheck after any indexed-attribute hop,
even when the arriving index's attributes had not changed. That could
hit an assertion on an unchanged expression index. The existing
fetch-check interface now accepts the index relation and reports
possible staleness for that index. This avoids evaluating expressions
while holding a btree leaf lock.

The patch order is:

01-08 Locator contract, semantic failures, version naming, triggers
and bitmap hooks
09 Existing HOT behavior tests
10-13 Attribute comparison and selective index maintenance
14-16 Heap format, visibility map, update and prune/vacuum support
17-19 Statistics, amcheck and replication apply option
20-21 [DO NOT MERGE] Test AMs and in-tree benchmark harness
22-26 The five correctness fixes described above

I have left the fixes as separate patches to make the differences from
v71 reviewable. The complete testable series includes all 26 patches;
the two [DO NOT MERGE] patches are not the end of this version's series.
The VM remains four bits per heap block. This version does not add
native variable-width locator transport or an in-place table AM.

Testing
-------

The final rebased tip, 40e568cb, passed a build with assertions,
injection points and -Werror, then fresh test setup and world testing:
405 passed, 0 failed, 36 skipped. The extra pass versus the earlier
404-test result is the new upstream hash-index regression suite.
I also reran the original wrong-results reproducer and strict amcheck
on the final installation.

Each of the 26 submitted commits passed a warning-free build, fresh
setup and 239 core regression tests. Isolation counts were 134 for the
first 16 patches and 135 thereafter. I rebuilt and retested the five
rewritten tail commits after folding the test dependencies below.

I fixed two missing GNU Make recovery-test dependencies during export:
pageinspect in patch 22 and pg_buffercache in patch 24. Fresh temporary
installs first reproduced each missing-extension failure, then passed
all 125 assertions with the dependencies present. Those two Makefile
lines are the only changes beyond replaying the existing series onto
the new base.

Before the rebase, the integrated repair build passed the local default
world suite: 404 passed, 0 failed, 36 skipped. The original reproducer
returned 20 rows through each of sequential, plain-index and bitmap
scans, with no obsolete-key match. Two 65536-row, 160-step stress runs,
with checksums on and off, passed result comparisons and strict amcheck
checks before and after crash recovery.

On FreeBSD the default world suite recorded 401 passed, 1 failed and 31
skipped. The failure was psql filename completion; I reproduced the same
timeout on the baseline. I am not counting that run as a world pass.
All four native database gates and all completed benchmark correctness
checks passed. Those checks include exact row multisets, plan checks,
feature counters and heapallindexed verification. The first FreeBSD
harness attempt failed before timing because it checked feature counters
after a deliberate crash reset; I corrected it to check before the crash
and retained that failed attempt.

Performance
-----------

I ran separate Debian 13 and FreeBSD 15.1-p4 campaigns on EC2
m6id.metal: two sockets, 64 cores/128 threads, 512 GiB RAM and four
local NVMe drives. The FreeBSD run used UFS over a GEOM stripe and
eight physical cores on one NUMA domain. CPU pinning is not a claim of
memory binding. Builds, durability settings and placement matched within
each campaign. Each trial used a fresh fixture, and only one workload
ran on the host at a time.

I compared the branch base, the foundations through the bitmap hooks,
and the full series. The FreeBSD measurements used repaired commit
23b76c05, baseline 5fc25dec and foundations 7e5ef84e. They precede this
rebase. I have not rerun throughput on the new base, and I am not
comparing FreeBSD TPS directly with Debian TPS.

FreeBSD paired-median TPS changes for full versus baseline were:

Workload Change
------------------------------------- -------
No-op update, eight secondary indexes -0.99%
Ordinary HOT update -0.46%
Update all eight indexed columns +0.74%
Pristine plain-index scan -1.78%
Pristine index-only scan -1.93%
Mixed 80/20 read/update +32.26%
Exact bitmap scan -2.01%
Lossy bitmap scan +0.31%
Update one of eight indexed columns +51.56%
Plain-index scan after churn -5.94%
Lossy bitmap scan after churn +3.54%

These are medians of three matched-repeat ratios, with 60-second
comparison runs and alternating arms. The two phases completed 78 and 33
trials, including their A/A controls. Maximum absolute A/A paired biases
were 0.634% and 0.092%. That does not establish precision for all of the
small differences above.

The one-column update gain ranged from 51.29% to 52.26%. About 83% of
its timed updates were HOT-indexed. The churned plain-index scan was
slower in all three pairs, from 3.57% to 7.21%. Churn produced different
index layouts between arms, so this measures the resulting feature
state, not equal-layout scan overhead. I did not complete a five-repeat
confirmation of that read regression. After the five-update churn, index
main-fork bytes were 47.5 MB baseline versus 38.4 MB full, with equal
heap main-fork sizes.

For the one-column update, median WAL bytes per transaction fell from
884.86 to 384.20 (LSN delta, including any background WAL). Full ended
with larger heap and index forks because it performed more updates in
the fixed interval. I do not have an equal-work bloat conclusion.

The foundations-only core results ranged from about -1.01% to +0.58%
versus baseline. This addresses part of the interface-overhead question
from v71, but does not establish zero overhead for other workloads.

CLUSTER shows a larger cost. With 300k rows and four balanced repeats,
full/baseline statement time increased 61.9% for pristine multi-index
fixtures and 54.4% after churn. Single-index increases were 2.7% and
3.0%. These were short, instrumented warm-cache statements; I have not
profiled the remaining cost into a source-level attribution.

I also ran 128 CLUSTER/trigger/relation-context cases, 32 warm PG17
upgrade cells and eight separate upgrade cells containing VM states 0, 1
and 3. All passed their checks. At 256 relations I measured about 2.4 kB
more backend context memory per relation after commit in full. That
includes catalog and index state, not just locator descriptors. The
wrapper AM tests exercise image/spill/rollback machinery, not a real
overwriting AM. With work_mem=64kB the deferred wrapper case held about
7.1 MB of used backend context and 23.0 MB of live temp storage before
commit. At 64MB it held about 38.2 MB in memory without spill; after
commit, used context was about 2.8 MB and live temp storage was
zero. work_mem does not bound total event/backend memory, and logical
rollback need not shrink a physical temp file. I did not sum backend RSS
or infer a memory leak.

The upgrade cells cover link/copy, checksums on/off, few/many relations
and dense/sparse VM layouts. Exact rows and logical VM maps survived.
Total upgrade times were about 1.73-2.33 seconds. One pair per
configuration and roughly 50 ms timing granularity are not enough to
claim an upgrade performance difference. Cold-cache FreeBSD upgrades
remain untested.

The earlier Debian run used the unfixed candidate 85e75674. I retained
its failures and results, but do not offer its active-update timings as
safe gains. Its five-repeat pristine-index confirmation showed a -3.25%
paired median. A separate 12 GiB fixture measured VM growth from 49 to
97 pages, or 393216 bytes, with other captured forks unchanged. That
follow-up did not retroactively fix the original I/O run's failed size
comparison gate. In those 18 pristine read-only trials, warm median TPS
was 130770 baseline versus 130949 full; under memory pressure it was
18700 versus 18705. Pressure trials recorded about 144 GB of device
reads per 60 seconds, while warm trials recorded none. These remain
descriptive observations with a failed publication gate.

Debian also completed 192 PG17 upgrade cells with three matched pairs
per configuration. All passed their integrity checks. All 12
cold-VM/many-relations/link full trials took longer, by 0.050-0.151
seconds (median 0.100 seconds; configuration paired medians about 6%).
The roughly 50 ms timing granularity and 1.416-2.218 second total calls
do not isolate VM conversion cost. Cold here means verified VM-page
residency, not a cold whole cluster. Conversion also pads allocated VM
forks: 128 small tables grew from 1 MiB of VM storage to 2 MiB even
though each table's entries fit within one page in either format.

The unfixed Debian multi-index CLUSTER runs took 39.4% longer pristine
and 35.4% longer after churn, by ratios of arm medians, with an extra
spilling tuple sort of about 86.6 MiB. Four full CLUSTER executions had
failed correctness status; completed statements do not make those runs
green. The repaired FreeBSD results above provide the separate checked
comparison. The attached reports also retain the Debian foundations
controls, trigger/resource measurements and initial performance screen;
I have not pooled those repeats with the later confirmation.

I would appreciate review of the semantic failure interface and the heap
anchor/pruning rules. The VM trade-off, slower churned reads and
multi-index CLUSTER cost still need scrutiny. I think the update results
justify continuing, but they do not settle those trade-offs.

best.

-greg

Attachments:

tepid-v72.tar.gzapplication/gzip; name=tepid-v72.tar.gzDownload+8-10
#6Greg Burd
greg@burd.me
In reply to: Greg Burd (#5)

Attached is v73 that (hopefully!) fixes the cf-bot failures.

-greg

Attachments:

tepid-v73.tar.gzapplication/gzip; name=tepid-v73.tar.gzDownload+7-2
#7Greg Burd
greg@burd.me
In reply to: Greg Burd (#6)

Hello,

Attached is v74: 21 patches against aa7b9cf13. Changes since posted v73:

In v74 I've folded the five repair patches into their introducing commits.
Dependent pageinspect and recovery tests move into amcheck patch18.
Statistics remain patch17. Patches 1-19 are the production series;
patches 20/21 are separate [DO NOT MERGE] test-AM and benchmark patches.

01. Name the locator contract between table and index access methods
02. Rename TM_FailureData.traversed to retargeted
03. Report table AM tuple failures without heap metadata
04. Let the executor say which version of a row it names
05. Let an index AM store a variable-width locator
06. Carry row copies in after-trigger events
07. Support table AMs that update rows in place
08. Let a table AM flag bitmap groups that do not combine exactly
09. Improve test coverage for heap-only tuple (HOT) update behavior
10. Let table AMs compare candidate attributes before an update
11. Implement the heap AM's modified-attrs comparison callback
12. Identify modified indexed attributes in the executor on UPDATE
13. Prepare index maintenance for selective updates.
14. Add the selective-indexed on-disk format: inline attr bitmap and stubs
15. Add a per-block locator-split bit to the visibility map
16. Implement heap HOT with selective index updates.
17. Extend heap statistics to include selective-indexed updates
18. Teach amcheck to verify HOT-indexed chains and index coverage
19. Add a subscription option for HOT-indexed updates
20. [DO NOT MERGE] Add test table AMs for the locator contract
21. [DO NOT MERGE] Add a HOT-indexed benchmark harness

best.

-greg

Attachments:

tepid-v74.tar.gzapplication/gzip; name=tepid-v74.tar.gzDownload+5-3
#8Greg Burd
greg@burd.me
In reply to: Greg Burd (#7)

Here is v79, rebased on 1910daf98. It is the same 21 patches, but I'd like to
stop presenting them as one thing. They are two groups, and the first can be
reviewed and committed without the second.

First, some numbers. These are paired TPS medians against the merge base on a
FreeBSD m6id.metal, with all of 0001-0019 applied, from the v72 code:

updating 1 of 8 indexed columns +51.6% TPS
mixed 80/20 read/update +32.3%
plain index scan after churn -5.9% (more/longer unresolved chains)
index scan, untouched table -1.8%
index-only scan, untouched -1.9%
BitmapAnd, exact, untouched -2.0%
CLUSTER, 2 indexes, 300k rows +54% to +62% time
CLUSTER, 1 index +3%

With only 0001-0008 applied, every case was within 1.2% of baseline. I believe
the scan costs come from walking chains that may hold stale entries, but I
haven't profiled them, and I haven't found what makes multi-index CLUSTER
slower.

On-disk costs:
- one infomask2 bit (0x0800),
- a bitmap of ceil(natts/8) bytes on each HOT-indexed tuple,
- two new WAL flag bits,
- and a visibility map widened from 2 to 4 bits per heap page,
which pg_upgrade rewrites.

But the cost I most want to surface and work on mitigating in a later version
of this is: a page holding a HOT-indexed tuple, live or reduced to a stub by
prune, is never marked all-visible or all-frozen, because an index-only scan
there could return a stale entry's values. Those pages cost every vacuum a
visit and every index-only scan a heap fetch. In a quick test, updating an
indexed column in 10% of the rows kept all 11 pages out of the VM through four
vacuums and a later plain HOT update of those rows; only deleting them brought
the pages back. None of the benchmarks above measure this.

So there are trade-offs to discuss or creatively work around if we'd like to
someday commit this series or something like it.

0001-0008: making the table AM contract less heap-specific

Today the executor, index AMs and TM_FailureData assume heap: a TID names one
version, a row changes TID when updated, and failures are reported as
ctid/xmax/cmax. These patches name that contract (LocatorDesc) so a table AM
can declare something else: in-place updates, a wider locator, or blocks where
a BitmapAnd must union rather than intersect. TM_FailureData now carries the
facts the executor actually uses (modified_by_same_command and so on), with
heap's physical fields moving to a heap-private struct. Heap's behavior is
unchanged. The consumers I have in mind are undo-based and in-place AMs
(OrioleDB, zheap-style designs, my UNDO work in CF 7389) and indirect indexes,
not this feature.

0009-0019: HOT with selective index updates for heap

When an UPDATE changes some indexed columns, the new version stays on the page
as a HOT chain member, and only the indexes on changed columns get new entries.
The aim is the write amplification on wide, many-index tables where one or two
indexed columns churn.

0009 is just tests for existing HOT behavior, something I added to make all the
subtle cases more apparent before and after the changes; it can go in on its
own, as Bharath suggested. 0020 and 0021 (test AMs, benchmark harness) are not
for commit.

Bharath, Chao: answers to your open questions, in order.

where to store the modified index bitmap

On the tuple, trailing its data, sized by the tuple's own natts so ADD COLUMN
doesn't break it. When prune collapses a chain, dead members whose columns
later hops don't cover become small xid-free stubs that keep only the bitmap
and a forward link; the rest are reclaimed.

how bitmap scans and index scans produce correct results

An index scan unions the bitmaps of the hops it crosses and drops the entry if
any of them changed one of that index's columns; the entry for the current
value returns the row.

For BitmapAnd, the update sets a per-page bit in the visibility map, and on
such pages BitmapAnd unions the two pages and forces a recheck instead of
intersecting. That is Alexander's false negative; contrib/bloom and
pageinspect have tests for it.

vacuum cost, heap vs index bloat, fewer rows per page

See above; I don't have a vacuum-time comparison yet, and the visibility map
problem is the part I expect to matter most. Index size after churn was 19%
smaller (47.5 MB to 38.4 MB) with equal heaps; WAL per updating transaction
fell from 885 to 384 bytes. The bitmap is one byte per eight columns, only on
HOT-indexed versions. An update that can't fit on the page falls back to a
normal update, as HOT does.

upgrade, replication, tooling

pg_upgrade rewrites VM forks; --swap refuses when that's needed. Physical
replication uses the existing heap update and prune records, with new flag
bits; catversion and XLOG_PAGE_MAGIC bumps are left for commit time. Logical
apply is gated by a subscription option (patch 19). amcheck verifies chains
and index coverage; pageinspect understands the new tuples.

why compute modified indexed attributes in the executor (and the
concurrency question)

So the executor, not heap, decides which indexes get entries which is logically
a component of any table AM, not just heap. heap, or any other table AM, only
supplies the comparison. It runs before table_tuple_update(), on the version
the executor has, as heap_update() itself does today. If someone updates the
row first, table_tuple_update() fails, EPQ re-fetches the old version and
ExecUpdateAct() recomputes from it.

the 0001/0002 test changes and the injection point rename

Those changes are now in 0012, the patch that needs them: deleting through
main_view and reading gtest1v and base_tbl came back in a different order once
the executor drives index maintenance. I'll drop them if someone shows they
can be avoided. The injection point didn't move: heap_update() keeps
heap_update-before-pin, and simple_heap_update() gets its own point before its
new fetch, which the syscache test now waits on.

Chao: opt-in per table

Not now, I'm hopeful not ever. There is no reloption or GUC today, I feel this
is something that either works and is the default or doesn't go in.
Half-measures leave users confused, either you've solved the selective index
update problem or you haven't.

Chao: exposing staleness to index_getnext_slot() callers

Agreed it's a contract change, but it's small: one boolean,
xs_entry_needs_recheck, set by the table AM. IndexScan, CLUSTER and
replica-identity lookup drop the entry; unique and exclusion checks need to see
it, since a stale entry can resolve to the row being checked. Filtering inside
the AM would hide it from them.

Changes since v74:

- VM counts no longer include the new bit;
- the pg_upgrade VM rewrite is now correct across segments, with a new test;
- pg_dump and pg_upgrade of a v19 cluster with subscriptions work again;
- pageinspect's tuple_data_split() no longer errors on the new tuples;
- CLUSTER drops the bitmap bytes;

and smaller fixes from review (prune assertions, a leaked bitmap, buffile error
handling, tests that could pass without testing anything). Every patch is
pgindented and perltidied, and passes regression and isolation on its own.

cfbot's last failure, a 009_twophase timeout on Windows, also showed up on CF
6854 and looks like the walreceiver reconnect hang Alexander Lakhin reported
[0]: /messages/by-id/93515d62-edce-9041-ec6e-7122f6e92bea@gmail.com

best,

-greg

[0]: /messages/by-id/93515d62-edce-9041-ec6e-7122f6e92bea@gmail.com

Attachments:

tepid-v79.tgzapplication/x-compressed-tar; name=tepid-v79.tgzDownload+6-7
#9Greg Burd
greg@burd.me
In reply to: Greg Burd (#8)

Hey Peter,

In v79 I said 0001-0008 could be reviewed without the rest. Nobody has
commented on them (yet), which I put down to their sitting in front of
eleven heap patches and two test-only ones. So here is what they cover
and who needs them.

In 2021 you asked that we "have a generalized definition that accounts
for what variation is acceptable, and (most importantly) what variation
*isn't* acceptable" [1]/messages/by-id/CAH2-Wzmee=VKQ7DbgZY4AcacWSoWTw0yyLdnvtn6kyH0nzg+pw@mail.gmail.com, and Tom said we'd "need some interlocks on
which index AMs could be used with which table AMs", and that
tidbitmap.c is "quite specific to heap-style TIDs" [2]/messages/by-id/3268871.1619800534@sss.pgh.pa.us. amgetbatch is
about to make the index-to-table interface new again [3]/messages/by-id/auOon54DuG2A6ll4@floki. 0001 is my
answer to that for the row locator. A table AM returns a LocatorDesc:

width exact size, or a bound when negative; index builds
refuse anything wider than ItemPointerData unless the
index AM opts in (0005)
max_offset the largest offset; bounds bitmap scans and GIN
(Jeff's 2021 problem)
stable does UPDATE keep the row's locator?
old_version_retained
can the pre-update version still be fetched by locator?

amlocator.h also writes down what every locator must satisfy, which
no field relaxes: it travels as an ItemPointerData, it is the row's
ctid, certain values are reserved, and locators sort in (block,
offset) order, which nbtree, ANALYZE and BRIN depend on. Peter's
2021 view was that TIDs should stay fixed size and correlate with
physical layout [4]/messages/by-id/CAH2-Wzk6FHes6H-cCN=1pxoVauza4Rm5c0RC1dyB6qBfdPPYDQ@mail.gmail.com. 0001 keeps that as the rule. 0005 is an opt-in
for an out-of-core index AM and table AM pair that agree on something
wider. No in-core AM uses it.

0002-0004 change interfaces that carried heap's answers. 0005-0008
are gated on the descriptor. Heap's behavior is unchanged, and with
all eight applied every case in v79's benchmark was within 1.2% of
master.

0002-0003 TM_FailureData without ctid/xmax/cmax; "traversed" becomes
"retargeted", which is what callers act on
0004 flags for when the executor names a version it has already
locked: after a BEFORE ROW trigger or EvalPlanQual, in ON
CONFLICT, MERGE and logical replication apply
0005 amcanvarlocator
0006-0007 RETURNING OLD, AFTER ROW triggers, transition tables and
EvalPlanQual stop re-fetching old rows by locator when
old_version_retained is false
0008 per-group BitmapAnd/BitmapOr inexactness callbacks, for
Tom's tidbitmap point; 0015 uses them for Alexander's
false negative

FLUX (CF 7389) is an in-place table AM, and it shows the cost of not
having this. It carries its own versions of 0006-0007 behind a single
am_inplace_update_keeps_tid flag. It also needs 0004. Without it FLUX
relaxes two assertions and infers "already locked" from per-command
bookkeeping and which lock flags the caller passed. That inference has
already produced a MERGE loop and an ON CONFLICT crash that FLUX had to
fix one at a time. I'd rather FLUX used this contract than add a second
set of hooks for the same things. The test module in 0020
(test_locator_tableam, not for commit) runs heap variants that declare
different width, max_offset, old_version_retained and bitmap_or_inexact
values. stable has no reader in core yet; it's there for the lock and
update callbacks' documented contract. If reviewers would rather it
wait for a consumer, I'll drop it.

If it helps, I'll post 0001-0008 as their own thread and CF entry,
rebased on master without the heap patches, and keep this thread for
0009-0019.

Objections? Thoughts? Thoughts? Thoughts? Thoughts?

-greg

[1]: /messages/by-id/CAH2-Wzmee=VKQ7DbgZY4AcacWSoWTw0yyLdnvtn6kyH0nzg+pw@mail.gmail.com
[2]: /messages/by-id/3268871.1619800534@sss.pgh.pa.us
[3]: /messages/by-id/auOon54DuG2A6ll4@floki
[4]: /messages/by-id/CAH2-Wzk6FHes6H-cCN=1pxoVauza4Rm5c0RC1dyB6qBfdPPYDQ@mail.gmail.com

#10Greg Burd
greg@burd.me
In reply to: Greg Burd (#9)

On Thu, 29 Oct 2026 20:53:33 +0000, Greg Burd <greg@burd.me> wrote:

Objections? Thoughts? Thoughts? Thoughts? Thoughts?

lol, that bit of repetition may look LLM-generated but it is my own
fat-fingering as I re-learn vi (leaving my 30+ years of emacs history
behind is hard) and neomutt. Not sure why I felt compelled to point
that out really...

oh well. :)

-greg

#11Greg Burd
greg@burd.me
In reply to: Greg Burd (#10)

Here is v80, rebased on f8cabd1f175. It fixes two bugs I found in v79,
both in 0013.

A HOT-indexed update leaves the old index entry in place, and that entry
still leads to the updated row. The table AM flags such an entry
(xs_entry_needs_recheck) and every consumer has to drop it. Two
consumers did not:

- The foreign key fast path (ri_FastPathProbeOne) took the first row
the index returned. After UPDATE parent SET k = 5000 WHERE k = 5, an
INSERT into the child with k = 5 succeeded and left an orphan row.
That happened for a referenced primary key and for a unique key. The
SPI path, which ALTER TABLE ... ADD FOREIGN KEY uses, was correct.

- REPACK (CONCURRENTLY) finds the row to change through the same kind
of entry when it replays concurrent changes. If a key moved and was
then reused, the replay matched the wrong row and REPACK failed with
a duplicate key error. Master runs the same sequence without error.

Both now skip flagged entries and keep scanning, as IndexScan and the
logical replication lookups already did. 0018 adds an FK test (old
primary and unique key values are rejected, new values are found, and a
key changed away and back is still found), and 0016 adds an isolation
test for the REPACK case.

I went through the other index scan callers. Catalog scans
(systable_getnext) never see these entries, since catalogs never take
HOT-indexed updates, and get_actual_variable_endpoint() only feeds
estimates. If I've missed a caller, that is the review I most need
here. Every caller has to opt in to the check, which is Chao's point
from July, and so far my only answer is auditing them.

Only 0013, 0016 and 0018 changed since v79; the rest differ only by the
rebase. 0013 and 0016 also lost a duplicated #include and two stale
comments, and 0016's comments on index_delete_check_htid() now say what
the code does: the relaxed corruption checks apply to every non-catalog
relation, since nothing records whether a table has ever taken a
HOT-indexed update. Narrowing that would need such a record, and I'd
like opinions on whether losing those checks is acceptable.

cfbot had one failure on v79, on Oct 31: an ecpg TIMEOUT on Windows (VS
slice 1; the other 200 tests passed). Four other CF entries hit the
same ecpg timeout on Windows that week, and the Nov 3 retest of v79
passed everywhere, so I don't think it is this series.

0001-0008 still stand on their own,

-greg

Attachments:

tepid-v80.tgzapplication/gzip; name=tepid-v80.tgzDownload+3-3
#12Greg Burd
greg@burd.me
In reply to: Greg Burd (#11)

Hello, me again. :)

Here is v81, rebased on 6a3da13d376. It fixes a bug in 0019 and
resolves rebase conflicts in 0006, 0015, 0018 and 0019.

hot_indexed_on_apply = off did not turn the feature off on the apply
path. The check compared the indexed attributes to the primary key's
with bms_equal(), but every primary key column is also in the indexed
set, so that test was the same as subset_only's bms_is_subset(). With a
primary key on (a, b) and another index on (b), a replicated UPDATE of a
still went HOT-indexed under off. Nothing was lost, since off only
allowed what subset_only already allows, but the docs promise the old
behaviour. off now always takes the non-HOT path, and 039 has a table
that fails without the fix (20 of 20 updates went HOT-indexed).

The rebase conflicts:

- 0006: 398eb35f001 made the original insert tuple an explicit argument
to ExecARInsertTriggers() and ExecARUpdateTriggers(). 0006 adds the
old row image to ExecARUpdateTriggers(), so its callers now pass
both.

- 0015, 0018, 0019: test lists in Makefiles and meson.build. Upstream
added pg_upgrade's t/009_composite_types.pl, so 0018's
t/009_hot_indexed.pl is now t/011_hot_indexed.pl.

0006 and 0013 also have one-line comment fixes, 0015's 010_vm_conversion
no longer fails when run with PG_TEST_PG_UPGRADE_MODE=--swap, and the
two DO NOT MERGE patches got small cleanups. In 0021's A/A control, the
second arm queried the master server with the tepid client binaries; it
now uses the master build for both. 0001-0005, 0007-0012, 0014, 0016
and 0017 differ from v80 only by the rebase.

Attribute versioning (245eb832f88, 6a3da13d376) marks composite datums
with HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID. Nothing in the series
builds tuples with both bits set, and amcheck's new "tuple marked as
datum tuple in table" check passes on the HOT-indexed tests.

I'd still be interested to hear opinions on whether losing the
index_delete_check_htid() corruption checks on non-catalog tables is
acceptable, and whether there are index scan callers I've missed that
need to skip flagged entries.

best.

-greg

Attachments:

tepid-v81.tgzapplication/gzip; name=tepid-v81.tgzDownload+7-11
#13Greg Burd
greg@burd.me
In reply to: Greg Burd (#12)

I appreciate the careful read; here is v83, rebased on 70c4a57b64d.

An index build put its entry for a live HOT-indexed row at that row's
own TID, for every index, while pruning assumes the only entries at a
heap-only member are the ones its own UPDATE planted. So a member could
be reclaimed with a live entry pointing at it. CREATE INDEX on b
reproduces it as you said, and so do REINDEX INDEX, REINDEX TABLE and
both CONCURRENTLY forms on any index the chain did not change. REINDEX
of the changed index lost rows another way: when the live member's own
update changed no indexed column, that member was reclaimed outright and
took the rebuilt entry with it. In every case an index scan stopped
returning the row and amcheck's heapallindexed check failed. Every
posted version had this.

0016 now anchors each live row, per index, at the latest chain member
that changed one of that index's attributes, or at the root if none
did.

That is where an UPDATE would have put the entry, so pruning's rule
holds for built entries too and for readers. CIC's validate pass uses
the same anchor. 0018 adds the three cases to pageinspect's
hot_indexed_updates test; they fail without the fix.

I also wrote a small fuzzer that mixes updates of different columns with
VACUUM, CREATE/DROP/REINDEX [CONCURRENTLY], and compares every index
against a seqscan after each step and that's helped find a few more
issues.

On the stale-entry flag, I agree that auditing callers doesn't scale so
I'm flipping the default. The heap AM now skips flagged entries
inside its index scan, and a caller sees one only if it asks with a
new scan option, SO_INDEX_KEEP_STALE.

Only check_exclusion_or_unique_constraint() asks: with a dirty snapshot,
an in-progress update's row can be reachable through its old entry
before its new entry is inserted, so it has to see that entry and
compare the row's current key. The checks in IndexScan, CLUSTER,
REPACK, the FK fast path and the replication lookups are gone, and new
callers get the safe behavior without knowing about any of this.

On index_delete_check_htid() upon further review I agree that relaxing
all three checks for every table was too broad. So v83 restores
master's three checks for every relation, with one exception: an entry
may point at a heap-only tuple that carries HEAP_INDEXED_UPDATED. That
is narrower than tracking it per table, and a table that never takes one
of these updates keeps every check.

On the visibility map, I agree but I'm stuck, and I have no fix in v83.

I measured it on 100,000 rows across 1,924 pages, with a HOT-indexed
update of one row in fifty. After three vacuums, no page is
all-visible, and an index-only scan over all rows does 102,000 heap
fetches. Deleting those rows and vacuuming brings all 1,924 pages back.

The stale entry keeps the root's TID live, so VACUUM can't remove it,
and the page stays out of the map. I think the fix is the one you
suggest, VACUUM removing a stale entry from just the index it is stale
in, but that is a significant new piece of work. Until something like
that exists this is a trade I don't expect anyone to accept as a
default.

I'll consider posting 0001-0008 on their own in a new thread, as you
suggest. I'd been thinking about that as well.

best.

-greg

Attachments:

tepid-v83.tgzapplication/gzip; name=tepid-v83.tgzDownload+3-4
#14Greg Burd
greg@burd.me
In reply to: Greg Burd (#13)

Here is v84, rebased on 45047c51aab. It fixes one more problem in
the unique-index path; the rest are small cleanups.

While checking a unique index, _bt_check_unique() rechecks a flagged
entry by comparing its stored key with the live row's key, and it does
that while holding the leaf page lock. If the row kept that key column
out of line, the comparison fetched it from the TOAST table under the
lock: a TOAST index scan and possibly I/O on two more relations, which
core never does while holding a btree page lock. Results were correct;
the locking was not. I reproduced it with a 2400-byte unique text key
stored EXTERNAL and confirmed the fetch in gdb under bttextcmp().

v84 makes the rule part of the fetch_tid_check() contract: when it asks
for a recheck, the slot's unique key columns must not be stored out of
line. Heap meets that by falling back to a regular update when a
HOT-indexed update would store a unique key column out of line, and
nbtree asserts it. Only unique indexes are affected, so a large column
with a GIN index, say, still gets HOT-indexed updates. The new test in
0018 trips the assertion without the heap change.

The cleanups:

- 0013: ri_FastPathProbeOne() is back to master's code, since the AM
now skips flagged entries itself. RelationGetIndexedAttrs() no
longer leaks its parsed expression trees. nbtinsert.c drops an
unused include.
- 0016: removed the prefix_all_dead out-parameter of
heap_hot_search_buffer(), whose only output nothing read.
- 0006: AfterTriggerSaveImage() errors out instead of wrapping its
image count.
- 0012, 0013, 0018, 0019: comment fixes, a skip guard in
001_concurrent_hot.pl, and a redundant check removed from 039.

The other patches differ from v83 only by the rebase.

-greg

Attachments:

tepid-v84.tgzapplication/gzip; name=tepid-v84.tgzDownload+7-3
#15Greg Burd
greg@burd.me
In reply to: Greg Burd (#14)

Here is v85, rebased on 0cb41ee8070. Nothing in it changes the
design; it follows two upstream changes and fixes a few small things
found in review of v84.

Rebase:

- 0006: 1e676702cac (MERGE transition tables for cross-partition
UPDATEs) restructured the two ExecARUpdateTriggers() calls in
ExecInsert() and ExecDeleteEpilogue() that 0006 had changed; they
keep upstream's shape and gain 0006's old-row argument.
- 0018: upstream added recovery/t/061_recovery_target_prefetch.pl, so
061_hot_indexed_vm.pl and 062_hot_indexed_recovery.pl are now 062
and 063.

Fixes:

- 0017: pg_relation_hot_indexed_stats() stopped walking a chain at
the first collapse-survivor stub, since a stub carries no
HEAP_HOT_UPDATED bit, so avg_chain_len and max_chain_len were too
small for any chain that VACUUM had collapsed. It now follows the
stub's forward link. 0018 adds a root, stub and live-member chain
to hot_indexed_updates, which reported length 1 before.
- 0018: amcheck reports a stub whose forward link points at a line
pointer that is not normal; it skipped those silently.
- 0015: static_assert() instead of StaticAssertDecl() in pg_upgrade.
- 0016: a prune comment still called stubs "PHOT-style key tuples".

The other patches differ from v84 only by the rebase.

-greg

Attachments:

tepid-v85.tgzapplication/gzip; name=tepid-v85.tgzDownload+3-5