More speedups for tuple deformation
More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
Around this time last year I worked on a series of patches for v18 to
speed up tuple deformation. That involved about 5 separate patches,
the main 3 of which were 5983a4cff (CompactAttribute), db448ce5a
(faster offset aligning), and 58a359e58 (inline various deforming
loops). The latter of those 3 changed slot_deform_heap_tuple() to add
dedicated deforming loops for !slow mode and for tuples that don't
have the HEAP_HASNULL bit set.
When I was working on that, I wondered if it might be better to
precalculate the attcacheoff rather than doing it in the deforming
loop. I've finally written some code to do this, and I'm now ready to
share some results.
0001:
This introduces a function named TupleDescFinalize(), which must be
called after a TupleDesc has been created or changed. This function
pre-calculates the attcacheoff for all fixed-width attributes and
records the attnum of the first attribute without a cached offset (the
first varlena or cstring attribute). This allows the code in the
deforming loops which was setting CompactAttribute's attcacheoff to be
removed and allows a dedicated loop to process all attributes with an
attcacheoff before falling through to the loop that handles
non-attcacheoff attributes, which has to calculate the offset and
alignment manually. If the tuple has a NULL value before the last
attribute with a cached offset, then we can only use the attcacheoff
until the NULL attribute.
The expectation here is that knowing the offset beforehand is faster
than calculating it each time. Calculating the offset requires first
aligning the current offset according to the attributes attalign
value, then once we've called fetch_att() to get the Datum value, we
need to add the length of the attribute to skip forward to the next
attribute. There's not much opportunity for instruction-level
parallelism there due to the dependency on the previous calculation.
The primary optimisation in 0001 is that it adds a dedicated tight
loop to deform as many attributes with a cache offset as possible
before breaking out that loop to deform any remaining attributes
without using any cached offset.
0002:
After thinking about 0001 for a while, I wondered if we could do
better than resorting to having to check att_isnull() for every
attribute after we find the first NULL. What if the tuple has a NULL
quite early on, then no NULLs after that. It would be good if we
looked ahead in the tuple's NULL bitmap to identify exactly if and
when the next NULL attribute occurs and loop without checking
att_isnull() until that attribute.
Effectively, what I came up with was something like:
for (;;)
{
for(; attnum < nextNullAttr; attnum++)
{
// do fetch_att() without checking for NULLs
}
if (attnum >= natts)
break;
for(; attnum < nextNullSeqEnd; attnum++)
isnull[attnum] = true;
next_null_until(bp, attnum, natts, &nextNullAttr, &nextNullSeqEnd);
}
The next_null_until() function looks at the NULL bitmap starting at
attnum and sets nextNullAttr to the next NULL and nextNullSeqEnd to
the first attribute to the first non-NULL after the NULL. If there are
no more NULLs, then nextNullAttr is set to natts, which allows the
outer loop to complete.
Test #5 seems to do well with this code, but I wasn't impressed with
most of the other results. I'd have expected test #3 to improve with
this change, but it didn't.
0003:
In 0002 I added a dedicated loop that handles tuples without
HEAP_HASNULL. To see if it would make the performance any better I
made 0003, which gets rid of that dedicated loop. I hoped that
shrinking the code down might help performance. It didn't quite have
the effect I hoped for.
In each version, I experimented with having a dedicated deforming loop
which can only handle attbyval == true columns. If we know there are
no byref attributes, then fetch_att() can be inlined without the
branch that handles pointer types. That removes some branching
overhead and makes for a tighter loop with fewer instructions. When
this optimisation doesn't apply, there's a bit of extra overhead of
having to check for "attnum < firstByRefAttr".
Benchmarking:
To get an idea if doing this is a win performance-wise, I designed a
benchmark with various numbers of columns and various combinations of
fixed vs varlena types along with NULLs and no NULLs. There are 8
tests in total. For each of those 8 tests, I ran it with between 0
and 40 extra INT NOT NULL columns.
The tests are:
1. first col int not null, last col int not null
2. first col text not null, last col int not null
3. first col int null, last col int not null
4. first col text null, last col int not null
5. first col int not null, last col int null
6. first col text not null, last col int null
7. first col int null, last col int null
8. first col text null, last col int null
So, for example #1 would look like:
CREATE TABLE t1 (
c INT NOT NULL DEFAULT 0,
a INT NOT NULL,
b INT NOT NULL DEFAULT 0
);
and #8 would be:
CREATE TABLE t1 (
c TEXT DEFAULT NULL,
a INT NOT NULL,
b INT DEFAULT NULL
);
For each of the 8 tests, I ran with 0, 10, 20, 30 and 40 extra
columns, so 40 tests in total (8 tests * 5 for each variation of extra
columns).
Another benefit of 0001, besides using the fixed attcacheoff is that
since we know where the first NULL attribute is, we can keep deforming
without calling att_isnull() until we get to the first NULL attribute.
Currently in master, if the tuple has the HEAP_HASNULL bit set, then
the deforming code will call att_isnull for every attribute in the
tuple. Test #5 should highlight this (you may notice the orange bar in
the attached graphs is commonly the test with the biggest speedup)
Now, not every query is bottlenecked on tuple deforming, so to try to
maximise the amount of tuple deforming that occurs relative to other
work, the query I ran was: SELECT sum(a) FROM t1; since the "a"
column is almost last, all prior attributes need to be deformed before
"a" can be.
I've tried to make the benchmark represent a large variety of
scenarios to see if there are any performance regressions. I've
benchmarked each patch with and without OPTIMIZE_BYVAL defined (the
additional byval-only attribute deformer loop). I tried with gcc and
with clang on my Zen 2 machine and also an Apple M2. Please see the
attached graphs which show the results of the SUM(a) query on a table
with 1 million rows.
Analysing the results, it's not really that clear which patch is best.
Which version works fastest seems to depend on the hardware. The AMD
Zen 2 machine with gcc does really well with 0001+OPTIMIZE_BYVAL as it
comes out an average of 21% faster and some tests are more than 44%
faster than master, and there are no performance regressions. With
clang on the same Zen2 machine the performance isn't the same. There
are a few regressions with the 0 extra column tests. On the Apple M2
tests #1 and #5 improve massively. The other tests don't improve
nearly as much and with certain patches a few regress slightly.
Please see the attached gifs which show 6 graphs each. Top is the
results of 0001, the middle row is 0001+0002 and the bottom row
0001+0002+0003. The left column is without OPTIMIZE_BYVAL and the
right column is with. The percentage shown is the query time speedup
the patched version gives over master.
Things still to do:
* More benchmarking is needed. I've not yet completed the benchmarks
on my Zen4 machine. No Intel hardware has been tested at all. I don't
really have any good Intel hardware to test with. Maybe someone else
would like to help? Script is attached.
* I've not looked at the JIT deforming code. At the moment the code
won't even compile with LLVM enabled because I've removed the
TTS_FLAG_SLOW flag. It's possible I'll have to adjust the JIT
deforming code or consider keeping TTS_FLAG_SLOW.
I'll add this patch to the January commitfest.
David
Re: More speedups for tuple deformation
On Sun, 28 Dec 2025 at 22:04, David Rowley wrote: > Things still to do: > > * More benchmarking is needed. I've not yet completed the benchmarks > on my Zen4 machine. No Intel hardware has been tested at all. I don't > really have any good Intel hardware to test with. Maybe someone else > would like to help? Script is attached. Please find attached an updated set of patches. A rebase was needed, plus 0003 had a problem with an Assert not handling the bitmap being a NULL pointer. I've done some more performance tests after upgrading my Zen2 machine to use newer versions of gcc and clang. I've also tested on an Intel machine now. All the results are attached in a spreadsheet form in the bzip file. There's also a pg_dump of the results and analysis_schema.sql, which has an SQL function to extract the data in a form that's compatible with the spreadsheet's format. I'd say things are looking generally good for 0001 without the OPTIMIZE_BYVAL stuff, but the results I got from clang on the AMD7945hx don't look good at all. I'll run the tests on that again tonight. The machine is a laptop and I did run the benchmarks on master first to establish the baseline. I want to ensure there's no thermal throttling going on. Aside from clang on the 7945hx, there are a few cases where there's a slight regression in the 0 extra column tests when a NULL is present. I wonder how much we should care about this as 1) the regression is small; and, 2) IMO, there's less chance of there being a NULL in a table with very few columns, in this case, the table has 3 columns. The "AMD3990x clang 20.1.8" results in the spreadsheet also look strange for 0001. It looks good up to 20 columns, then the performance trend breaks for 30 and 40 columns. I don't have an explanation for this yet. I've also attached an updated script to run the tests and output the results in csv format so that it can be easily imported into Postgres for analysis or processing. > * I've not looked at the JIT deforming code. At the moment the code > won't even compile with LLVM enabled because I've removed the > TTS_FLAG_SLOW flag. It's possible I'll have to adjust the JIT > deforming code or consider keeping TTS_FLAG_SLOW. This part turned out to be easy. The JIT deformer does not pay attention to the TTS_FLAG_SLOW flag, it just unconditionally turns it on to force the non-jit deformer into using slow mode. I've deleted the code that was setting it since slow mode no longer exists in the patched code. David
Re: More speedups for tuple deformation
On Fri, 2 Jan 2026 at 18:58, David Rowley wrote: > Please find attached an updated set of patches. A rebase was needed, > plus 0003 had a problem with an Assert not handling the bitmap being a > NULL pointer. Another rebase and updates to some newly created missing calls to TupleDescFinalize(). I've also attached another round of benchmarks after dipping into some Azure machines to cover my lack of any Intel benchmark results. I think these are somewhat noisy as I opted for low core-count instances which will have L3 shared with workloads running for other people. This is most evident in Xeon_E5-2673 with gcc where the patched run was nearly twice as fast as unpatched for test 2 on 20 extra columns. If you look at the raw results from that, you can see the times are quite unstable between the 3 runs of each test, which makes me believe that the machine was busy with other work when that test ran on master. The AMD3990x and M2 machines are all sitting next to me and were otherwise idle, so they should be much more stable. Quite a few machines have a small regression for the 0 extra column tests. There is a small amount of extra work being done in the deforming function to check if the attnum < the first attribute without an attcacheoff. This mostly only affects the tests that don't do any deforming with a cached attcacheoff, e.g due to NULLs or varlena types. The only way I've thought about to possibly reduce that is to invent a new TupleTableSlotOps and pick the one that applies when creating the TupleTableSlot. This doesn't appeal to me very much as it requires modifying many callsites. But I do wonder if we should try to come up with something here as technically we could use this to eliminate alignment padding out of some MinimalTuples in some cases where these were not directly derived from pre-formed HeapTuples. That could allow a more compact tuple representation for sorting and hashing, allowing us to do more with less memory in some cases. The benchmark results also indicated that there wasn't much advantage to the 0002+0003 patches, so I've removed those from the set. That reduces some complexity around the benchmarks. I did still keep the OPTIMIZE_BYVAL loop as separate results. It's not quite clear what's best there as machines seem to vary on which they prefer. Benchmark results attached in the bz2 file both in spreadsheet form and the raw results pg_dumped. David
Re: More speedups for tuple deformation
От:
Chao Li <li.evan.chao@gmail.com>
Дата:
> On Jan 19, 2026, at 06:13, David Rowley wrote:
>
> On Fri, 2 Jan 2026 at 18:58, David Rowley wrote:
>> Please find attached an updated set of patches. A rebase was needed,
>> plus 0003 had a problem with an Assert not handling the bitmap being a
>> NULL pointer.
>
> Another rebase and updates to some newly created missing calls to
> TupleDescFinalize().
>
> I've also attached another round of benchmarks after dipping into some
> Azure machines to cover my lack of any Intel benchmark results. I
> think these are somewhat noisy as I opted for low core-count instances
> which will have L3 shared with workloads running for other people.
> This is most evident in Xeon_E5-2673 with gcc where the patched run
> was nearly twice as fast as unpatched for test 2 on 20 extra columns.
> If you look at the raw results from that, you can see the times are
> quite unstable between the 3 runs of each test, which makes me believe
> that the machine was busy with other work when that test ran on
> master. The AMD3990x and M2 machines are all sitting next to me and
> were otherwise idle, so they should be much more stable.
>
> Quite a few machines have a small regression for the 0 extra column
> tests. There is a small amount of extra work being done in the
> deforming function to check if the attnum < the first attribute
> without an attcacheoff. This mostly only affects the tests that don't
> do any deforming with a cached attcacheoff, e.g due to NULLs or
> varlena types. The only way I've thought about to possibly reduce that
> is to invent a new TupleTableSlotOps and pick the one that applies
> when creating the TupleTableSlot. This doesn't appeal to me very much
> as it requires modifying many callsites. But I do wonder if we should
> try to come up with something here as technically we could use this to
> eliminate alignment padding out of some MinimalTuples in some cases
> where these were not directly derived from pre-formed HeapTuples. That
> could allow a more compact tuple representation for sorting and
> hashing, allowing us to do more with less memory in some cases.
>
> The benchmark results also indicated that there wasn't much advantage
> to the 0002+0003 patches, so I've removed those from the set. That
> reduces some complexity around the benchmarks. I did still keep the
> OPTIMIZE_BYVAL loop as separate results. It's not quite clear what's
> best there as machines seem to vary on which they prefer.
>
> Benchmark results attached in the bz2 file both in spreadsheet form
> and the raw results pg_dumped.
>
> David
>
Hi David,
I reviewed the patch and traced some basic workflows. But I haven’t done a load test to compare performance differences with and without this patch, I will do that if I get some bandwidth later. Here comes some review comments:
1 - tupmacs.h
```
+ /* Create a mask with all bits beyond natts's bit set to off */
+ mask = 0xFF & ((((uint8) 1) << (natts & 7)) - 1);
+ byte = (~bits[lastByte]) & mask;
```
When I read the code, I got an impression bits[lastByte] might overflow when natts % 8 == 0, so I traced the code, then I realized that, this function is only called when a row has null values, so that, when reaching here, natts % 8 != 0, otherwise it should return earlier within the for loop.
So, to avoid future reader’s same confusion, can we add a brief comment to explain that no overflow should happen here.
2 - After this patch, nocachegetattr() and nocache_index_getattr() strictly rely on tupleDesc->firstNonCachedOffAttr to work:
```
if (tupleDesc->firstNonCachedOffAttr >= 0)
{
startAttr = Min(tupleDesc->firstNonCachedOffAttr - 1, firstnullattr);
off = TupleDescCompactAttr(tupleDesc, startAttr)->attcacheoff;
}
else
{
startAttr = 0;
off = 0;
}
```
And tupleDesc->firstNonCachedOffAttr is only set by TupleDescFinalize(). So, assuming some code misses to call TupleDescFinalize(), looking at how TupleDesc is created, for example CreateTemplateTupleDesc():
```
desc = (TupleDesc) palloc(offsetof(struct TupleDescData, compact_attrs) +
natts * sizeof(CompactAttribute) +
natts * sizeof(FormData_pg_attribute));
/*
* Initialize other fields of the tupdesc.
*/
desc->natts = natts;
desc->constr = NULL;
desc->tdtypeid = RECORDOID;
desc->tdtypmod = -1;
desc->tdrefcount = -1; /* assume not reference-counted */
return desc;
```
It’s palloc and not palloc0, so desc->firstNonCachedOffAttr will initially hold a random value. As long as TupleDescFinalize() is missed, then that’s a bug.
From this perspective, I think we can set firstNonCachedOffAttr to -2 when in CreateTemplateTupleDesc() as well as other functions that create a TupleDesc. Then in nocachegetattr() and nocache_index_getattr(), we can Assert(desc->firstNonCachedOffAttr > -2).
3
```
+ firstNonCachedOffAttr = i + 1;
```
In TupleDescFinalize(), given firstNonCachedOffAttr = i + 1, firstNonCachedOffAttr will never be 0.
But in nocachegetattr(), it checks firstNonCachedOffAttr >= 0:
```
if (tupleDesc->firstNonCachedOffAttr >= 0)
{
startAttr = Min(tupleDesc->firstNonCachedOffAttr - 1, firstnullattr);
off = TupleDescCompactAttr(tupleDesc, startAttr)->attcacheoff;
}
```
This is kinda inconsistent, and may potentially lead to some confusion to code readers.
From the meaning of the variable name “firstNonCachedOffAttr”, when there is no cached attribute, firstNonCachedOffAttr feels better to be 0 rather than-1. From this perspective, TupleDescFinalize() can initialize desc->firstNonCachedOffAttr to 0. And for my comment 2, we can use -1 instead of -2, so that -1 indicates TupleDescFinalize() is not called, 0 means no cached attribute, >0 means some cached attributes.
4
```
+ * possibily could cache the first attlen == -2 attr. Worthwhile?
```
Typo: possibily -> possibly
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: More speedups for tuple deformation
On Mon, 19 Jan 2026 at 18:48, Chao Li wrote: > I reviewed the patch and traced some basic workflows. But I haven’t done a load test to compare performance differences with and without this patch, I will do that if I get some bandwidth later. Here comes some review comments: > > 1 - tupmacs.h > ``` > + /* Create a mask with all bits beyond natts's bit set to off */ > + mask = 0xFF & ((((uint8) 1) << (natts & 7)) - 1); > + byte = (~bits[lastByte]) & mask; > ``` > > When I read the code, I got an impression bits[lastByte] might overflow when natts % 8 == 0, so I traced the code, then I realized that, this function is only called when a row has null values, so that, when reaching here, natts % 8 != 0, otherwise it should return earlier within the for loop. It certainly is possible to get to that part of the code when natts is a multiple of 8 and the tuple contains NULLs after that (we may not be deforming the entire tuple). The code you quoted that's setting "mask" in that case will produce a zero mask, resulting in not finding any NULLs. I don't quite see any risk of overflowing any of the types here. If natts is 16 then effectively the code does 0xFF & ((1 << 0) - 1); so no overflow. Just left shift by 0 bits and bitwise AND with zero, resulting in the mask becoming zero. How about if I write the comment as follows? /* * Create a mask with all bits beyond natts's bit set to off. The code * below will generate a zero mask when natts & 7 == 0. When that happens * all bytes that need to be checked were done so in the loop above. The * code below will create an empty mask and end up returning natts. This * has been done to avoid having to write a special case to check if we've * covered all bytes already. */ > In TupleDescFinalize(), given firstNonCachedOffAttr = i + 1, firstNonCachedOffAttr will never be 0. > But in nocachegetattr(), it checks firstNonCachedOffAttr >= 0: > This is kinda inconsistent, and may potentially lead to some confusion to code readers. I've changed things around so that firstNonCachedOffAttr == 0 means there are no attributes with cached offsets. -1 becomes uninitialised. I've added Asserts to check for firstNonCachedOffAttr >= 0 with a comment directing anyone who's facing debugging one of those failing to add the missing call to TupleDescFinalize(). Thanks for reviewing. I've attached the v4 patch, which also fixes the LLVM compiler warning that I introduced. David
Re: More speedups for tuple deformation
От:
Chao Li <li.evan.chao@gmail.com>
Дата:
> On Jan 20, 2026, at 08:11, David Rowley wrote: > > On Mon, 19 Jan 2026 at 18:48, Chao Li wrote: >> I reviewed the patch and traced some basic workflows. But I haven’t done a load test to compare performance differences with and without this patch, I will do that if I get some bandwidth later. Here comes some review comments: >> >> 1 - tupmacs.h >> ``` >> + /* Create a mask with all bits beyond natts's bit set to off */ >> + mask = 0xFF & ((((uint8) 1) << (natts & 7)) - 1); >> + byte = (~bits[lastByte]) & mask; >> ``` >> >> When I read the code, I got an impression bits[lastByte] might overflow when natts % 8 == 0, so I traced the code, then I realized that, this function is only called when a row has null values, so that, when reaching here, natts % 8 != 0, otherwise it should return earlier within the for loop. > > It certainly is possible to get to that part of the code when natts is > a multiple of 8 and the tuple contains NULLs after that (we may not be > deforming the entire tuple). The code you quoted that's setting "mask" > in that case will produce a zero mask, resulting in not finding any > NULLs. I don't quite see any risk of overflowing any of the types > here. If natts is 16 then effectively the code does 0xFF & ((1 << 0) > - 1); so no overflow. Just left shift by 0 bits and bitwise AND with > zero, resulting in the mask becoming zero. > > How about if I write the comment as follows? > > /* > * Create a mask with all bits beyond natts's bit set to off. The code > * below will generate a zero mask when natts & 7 == 0. When that happens > * all bytes that need to be checked were done so in the loop above. The > * code below will create an empty mask and end up returning natts. This > * has been done to avoid having to write a special case to check if we've > * covered all bytes already. > */ > I’m sorry I didn’t express myself clearly, maybe I should have used “OOB” rather than “overflow". My real concern is about out-of-boundary read of bits[lastByte] when natts&7==0. Say, natts is 16, then bits is 2 bytes long; lastByte = 16>>3 = 2, so bits[2] is a OOB read. If first_null_attr() is only called when hasnulls==true, then it will never hit the OOB point, because it will return early from the “for” loop. In the current patch, which is true, so the OOB should never happen. However, I don’t see any comment mentions something like “first_null_attr() should only be called when hasnulls is true. If in future one calls first_null_attr() in a situation where hasnulls == false, then the OOB will be triggered. The comment you added explains that even if OOB happens, no matter what value is hold by bits[lastByte], because mask is 0, the final result is still correct, which is true, but OOB is still a concern. If the bits array happens to end exactly at the edge of a memory page, the OOB read bits[lastByte] may trigger a segment fault; and valgrind may detect the OOB and complain about it. So, my original comment was that, we should at least add something to the header comment to mention “first_null_attr() should only be called when hasnulls is true. If we can add an Assert to ensure hasnulls is true, that would be even better. But if we want first_null_attr() to be safe no matter hasnulls is true or false, I think we should avoid the OOB. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: More speedups for tuple deformation
От:
Chao Li <li.evan.chao@gmail.com>
Дата:
> On Jan 20, 2026, at 12:32, Chao Li wrote: > > > >> On Jan 20, 2026, at 08:11, David Rowley wrote: >> >> On Mon, 19 Jan 2026 at 18:48, Chao Li wrote: >>> I reviewed the patch and traced some basic workflows. But I haven’t done a load test to compare performance differences with and without this patch, I will do that if I get some bandwidth later. Here comes some review comments: >>> >>> 1 - tupmacs.h >>> ``` >>> + /* Create a mask with all bits beyond natts's bit set to off */ >>> + mask = 0xFF & ((((uint8) 1) << (natts & 7)) - 1); >>> + byte = (~bits[lastByte]) & mask; >>> ``` >>> >>> When I read the code, I got an impression bits[lastByte] might overflow when natts % 8 == 0, so I traced the code, then I realized that, this function is only called when a row has null values, so that, when reaching here, natts % 8 != 0, otherwise it should return earlier within the for loop. >> >> It certainly is possible to get to that part of the code when natts is >> a multiple of 8 and the tuple contains NULLs after that (we may not be >> deforming the entire tuple). The code you quoted that's setting "mask" >> in that case will produce a zero mask, resulting in not finding any >> NULLs. I don't quite see any risk of overflowing any of the types >> here. If natts is 16 then effectively the code does 0xFF & ((1 << 0) >> - 1); so no overflow. Just left shift by 0 bits and bitwise AND with >> zero, resulting in the mask becoming zero. >> >> How about if I write the comment as follows? >> >> /* >> * Create a mask with all bits beyond natts's bit set to off. The code >> * below will generate a zero mask when natts & 7 == 0. When that happens >> * all bytes that need to be checked were done so in the loop above. The >> * code below will create an empty mask and end up returning natts. This >> * has been done to avoid having to write a special case to check if we've >> * covered all bytes already. >> */ >> > > I’m sorry I didn’t express myself clearly, maybe I should have used “OOB” rather than “overflow". My real concern is about out-of-boundary read of bits[lastByte] when natts&7==0. > > Say, natts is 16, then bits is 2 bytes long; lastByte = 16>>3 = 2, so bits[2] is a OOB read. > > If first_null_attr() is only called when hasnulls==true, then it will never hit the OOB point, because it will return early from the “for” loop. In the current patch, which is true, so the OOB should never happen. > > However, I don’t see any comment mentions something like “first_null_attr() should only be called when hasnulls is true. If in future one calls first_null_attr() in a situation where hasnulls == false, then the OOB will be triggered. > > The comment you added explains that even if OOB happens, no matter what value is hold by bits[lastByte], because mask is 0, the final result is still correct, which is true, but OOB is still a concern. If the bits array happens to end exactly at the edge of a memory page, the OOB read bits[lastByte] may trigger a segment fault; and valgrind may detect the OOB and complain about it. > > So, my original comment was that, we should at least add something to the header comment to mention “first_null_attr() should only be called when hasnulls is true. If we can add an Assert to ensure hasnulls is true, that would be even better. > > But if we want first_null_attr() to be safe no matter hasnulls is true or false, I think we should avoid the OOB. > I also noticed one thing that, with running an arbitrary SQL statement, first_null_attr() might be called with natts=0, so maybe it can have a fast path to return 0 directly if natts==0. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-01-20 13:11:55 +1300, David Rowley wrote:
> I've attached the v4 patch, which also fixes the LLVM compiler warning
> that I introduced.
I wonder if it's possible to split the patch - it's big enough to be
nontrivial to review... Perhaps the finalization could be introduced
separately from the patch actually making use of it?
I wonder if we should somehow change the API of tupledesc creation, to make
old code that doesn't have TupleDescFinalize() fail to compile, instead of
just warn...
> diff --git a/contrib/pg_buffercache/pg_buffercache_pages.c b/contrib/pg_buffercache/pg_buffercache_pages.c
> index dcba3fb5473..2fdf5a341f6 100644
> --- a/contrib/pg_buffercache/pg_buffercache_pages.c
> +++ b/contrib/pg_buffercache/pg_buffercache_pages.c
> @@ -174,6 +174,7 @@ pg_buffercache_pages(PG_FUNCTION_ARGS)
> TupleDescInitEntry(tupledesc, (AttrNumber) 9, "pinning_backends",
> INT4OID, -1, 0);
>
> + TupleDescFinalize(tupledesc);
> fctx->tupdesc = BlessTupleDesc(tupledesc);
>
Think it'd be worth adding an assertion to BlessTupleDesc that
TupleDescFinalize has been called, I think that'll lead to easier to
understand backtraces in a lot of cases. Particularly if you consider cases
where BlessTupleDesc() will create a tupdesc in shared memory, that could then
trigger an assertion failure in a parallel worker or such.
> /*
> * slot_deform_heap_tuple
> * Given a TupleTableSlot, extract data from the slot's physical tuple
> @@ -1122,78 +1010,167 @@ static pg_attribute_always_inline void
> slot_deform_heap_tuple(TupleTableSlot *slot, HeapTuple tuple, uint32 *offp,
> int natts)
> {
> + CompactAttribute *cattr;
> + TupleDesc tupleDesc = slot->tts_tupleDescriptor;
> bool hasnulls = HeapTupleHasNulls(tuple);
> + HeapTupleHeader tup = tuple->t_data;
> + bits8 *bp; /* ptr to null bitmap in tuple */
> int attnum;
> + int firstNonCacheOffsetAttr;
> +
> +#ifdef OPTIMIZE_BYVAL
> + int firstByRefAttr;
> +#endif
> + int firstNullAttr;
> + Datum *values;
> + bool *isnull;
> + char *tp; /* ptr to tuple data */
> uint32 off; /* offset in tuple data */
> - bool slow; /* can we use/set attcacheoff? */
> +
> + /* Did someone forget to call TupleDescFinalize()? */
> + Assert(tupleDesc->firstNonCachedOffAttr >= 0);
>
> /* We can only fetch as many attributes as the tuple has. */
> - natts = Min(HeapTupleHeaderGetNatts(tuple->t_data), natts);
> + natts = Min(HeapTupleHeaderGetNatts(tup), natts);
> + attnum = slot->tts_nvalid;
> + firstNonCacheOffsetAttr = Min(tupleDesc->firstNonCachedOffAttr, natts);
> +
> + if (hasnulls)
> + {
> + bp = tup->t_bits;
> + firstNullAttr = first_null_attr(bp, natts);
> + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, firstNullAttr);
> + }
> + else
> + {
> + bp = NULL;
> + firstNullAttr = natts;
> + }
> +
> +#ifdef OPTIMIZE_BYVAL
> + firstByRefAttr = Min(firstNonCacheOffsetAttr, tupleDesc->firstByRefAttr);
> +#endif
> + values = slot->tts_values;
> + isnull = slot->tts_isnull;
> + tp = (char *) tup + tup->t_hoff;
> +
> +#ifdef OPTIMIZE_BYVAL
>
> /*
> - * Check whether the first call for this tuple, and initialize or restore
> - * loop state.
> + * Many tuples have leading byval attributes, try and process as many of
> + * those as possible with a special loop that can't handle byref types.
> */
> - attnum = slot->tts_nvalid;
> - if (attnum == 0)
> + if (attnum < firstByRefAttr)
> + {
> + /* Use do/while as we already know we need to loop at least once. */
> + do
> + {
> + cattr = TupleDescCompactAttr(tupleDesc, attnum);
> +
> + Assert(cattr->attcacheoff >= 0);
> +
> + /*
> + * Hard code byval == true to allow the compiler to remove the
> + * byval check when inlining fetch_att().
> + */
Maybe add an assert for cattr->attbyval? Just to avoid a bad debugging
experience if somebody tries to extend this logic to
e.g. non-null-fixed-width-byref columns?
I also wonder if we could have assert-only crosschecking of the "real" offsets
against the cached ones?
Greetings,
Andres Freund
Re: More speedups for tuple deformation
On Wed, 21 Jan 2026 at 07:38, Andres Freund wrote: > I wonder if it's possible to split the patch - it's big enough to be > nontrivial to review... Perhaps the finalization could be introduced > separately from the patch actually making use of it? Seems reasonable. I've done that in the attached 0001, which contains a dummy macro for TupleDescFinalize() and all the required calls to it. > I wonder if we should somehow change the API of tupledesc creation, to make > old code that doesn't have TupleDescFinalize() fail to compile, instead of > just warn... I don't have any ideas on how to do that. I could maybe imagine some preprocessor magic if we always expected a CreateTupleDesc() and TupleDescFinalize() in the same function, but the TupleDescFinalize() may be required after any modification to the TupleDesc that could invalidate the processing that's done within that function. > Think it'd be worth adding an assertion to BlessTupleDesc that > TupleDescFinalize has been called, I think that'll lead to easier to > understand backtraces in a lot of cases. Particularly if you consider cases > where BlessTupleDesc() will create a tupdesc in shared memory, that could then > trigger an assertion failure in a parallel worker or such. Modified. > Maybe add an assert for cattr->attbyval? Just to avoid a bad debugging > experience if somebody tries to extend this logic to > e.g. non-null-fixed-width-byref columns? I ended up removing the OPTIMIZE_BYVAL code in the attached. Over all the machines I tested on, with the benchmark results I previously shared, it seemed to cause a slowdown rather than a speedup. Perhaps it can be refined and tried again later, but I've removed it for now to reduce complexity. > I also wonder if we could have assert-only crosschecking of the "real" offsets > against the cached ones? I've modified the code to do that. v5 patches attached. Thanks for reviewing. David
Re: More speedups for tuple deformation
Hi, I haven't yet looked at the new version of the patch, but I ran your benchmark from upthread (fwiw, I removed the sleep 10 to reduce runtimes, the results seem stable enough anyway) on two intel machines, as you mentioned that you saw a lot variation in Azure. For both I disabled turbo boost, cpu idling and pinned the backend to a single CPU core. There's a bit of noise on "awork3" (basically an editor and an idle browser window), but everything is pinned to the other socket. "awork4" is entirely idle. Looks like overall the results are quite impressive! Some of the extra_cols=0 runs saphire rapids are a bit slower, but the losses are much smaller than the gains in other cases. I think it'd be good to add a few test cases of "incremental deforming" to the benchmark. E.g. a qual that accesses column 10, but projection then deforms up to 20. I'm a bit worried that e.g. the repeated first_null_attr() computations could cause regressions. Greetings, Andres Freund
Re: More speedups for tuple deformation
> On Jan 23, 2026, at 09:18, Andres Freund wrote: > > Hi, > > I haven't yet looked at the new version of the patch, but I ran your benchmark > from upthread (fwiw, I removed the sleep 10 to reduce runtimes, the results > seem stable enough anyway) on two intel machines, as you mentioned that you > saw a lot variation in Azure. > > For both I disabled turbo boost, cpu idling and pinned the backend to a single > CPU core. > > There's a bit of noise on "awork3" (basically an editor and an idle browser > window), but everything is pinned to the other socket. "awork4" is entirely > idle. > > > Looks like overall the results are quite impressive! Some of the extra_cols=0 > runs saphire rapids are a bit slower, but the losses are much smaller than the > gains in other cases. > > > I think it'd be good to add a few test cases of "incremental deforming" to the > benchmark. E.g. a qual that accesses column 10, but projection then deforms up > to 20. I'm a bit worried that e.g. the repeated first_null_attr() > computations could cause regressions. > > > Greetings, > > Andres Freund > Today I ran the benchmark on my MacBook M4 against 3 versions (all without assert and with -O2): 1) Master (f9a468c664a) 2) Master + v4 3) Master + v4 + My tweak (first_null_attr immediately returns 0 when natts == 0) Overall, v4 shows significant improvements across most configuration combinations. In the best case, v4 is about 43% faster than master. The tweak version is only slightly faster than v4. In the best case, the tweak achieves an additional ~3.5% improvement over v4. Note that the MacBook is my working laptop. I didn’t actively work on it while the tests were running, but it was still not fully idle, as some other applications (Email, VScode, etc.) were running in the background. That said, I suppose this is still fair for the three rounds of test runs. See the attached Excel sheet for details. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-01-22 20:18:21 -0500, Andres Freund wrote:
> I haven't yet looked at the new version of the patch, but I ran your benchmark
> from upthread (fwiw, I removed the sleep 10 to reduce runtimes, the results
> seem stable enough anyway) on two intel machines, as you mentioned that you
> saw a lot variation in Azure.
>
> For both I disabled turbo boost, cpu idling and pinned the backend to a single
> CPU core.
>
> There's a bit of noise on "awork3" (basically an editor and an idle browser
> window), but everything is pinned to the other socket. "awork4" is entirely
> idle.
>
>
> Looks like overall the results are quite impressive! Some of the extra_cols=0
> runs saphire rapids are a bit slower, but the losses are much smaller than the
> gains in other cases.
>
>
> I think it'd be good to add a few test cases of "incremental deforming" to the
> benchmark. E.g. a qual that accesses column 10, but projection then deforms up
> to 20. I'm a bit worried that e.g. the repeated first_null_attr()
> computations could cause regressions.
The overhead of the aggregation etc makes it harder to see efficiency changes
in deformation speed:
I think it'd be worth replacing the SUM(a) with WHERE a < 0 (filtering all
rows), to reduce the cost of the executor dispatch.
Here's a profile of the SUM(a):
- 99.90% 0.00% postgres postgres [.] standard_ExecutorRun
- standard_ExecutorRun
- 96.83% ExecAgg
- 49.86% ExecInterpExpr
- 28.30% slot_getsomeattrs_int
tts_buffer_heap_getsomeattrs
0.67% tts_buffer_heap_getsomeattrs
+ 0.02% asm_sysvec_apic_timer_interrupt
- 37.44% fetch_input_tuple
- 31.42% ExecSeqScan
+ 20.58% heap_getnextslot
3.58% MemoryContextReset
0.52% heapgettup_pagemode
0.32% ExecStoreBufferHeapTuple
0.99% heap_getnextslot
0.79% MemoryContextReset
2.81% int4_sum
1.39% MemoryContextReset
Which takes ~93ms on average for the first generated bench.sql
- 99.88% 0.00% postgres postgres [.] standard_ExecutorRun
- standard_ExecutorRun
- 95.78% ExecSeqScanWithQual
- 57.65% ExecInterpExpr
- 29.08% slot_getsomeattrs_int
tts_buffer_heap_getsomeattrs
0.49% tts_buffer_heap_getsomeattrs
- 25.40% heap_getnextslot
+ 15.00% heapgettup_pagemode
+ 4.71% ExecStoreBufferHeapTuple
0.05% UnlockBuffer
1.80% MemoryContextReset
0.77% int4lt
0.52% heapgettup_pagemode
0.47% ExecStoreBufferHeapTuple
0.37% slot_getsomeattrs_int
2.11% heap_getnextslot
1.49% ExecInterpExpr
0.50% MemoryContextReset
Same data, but with a WHERE a < 0, takes on average ~74m.
I wonder if it's worth writing a C helper to test deformation in a bit more
targeted way.
Looking at the profile of ExecSeqScanWithQual() made me a bit sad, turns out
that some of the generated code isn't great :(. I'll start a separate thread
about that.
Greetings,
Andres Freund
Re: More speedups for tuple deformation
On Sat, 24 Jan 2026 at 05:33, Andres Freund wrote:
> I wonder if it's worth writing a C helper to test deformation in a bit more
> targeted way.
Good idea. I've written a test module called "deform_bench". You can
do: "select deform_bench('tablename'::regclass, '{10,20}');" which
will deform up to attnum=10, then in a 2nd pass deform up to
attnum=20. This is in the 0003 patch. (Requires "ninja
install-test-files"). 0003 is intended for testing, not commit.
There are also 2 scripts attached, one which sets up all the tables
for the benchmark, and one to run it. This saves creating the same
tables again when trying other branches or compilers.
I've also included a slightly revised patch. I made a small change to
the first_null_attr() to get rid of the masking of higher attnums and
also now making use of __builtin_ctz to find the first NULL attnum in
the byte. For compilers that don't support that, I've included a
pg_rightmost_*zero*_pos table. I didn't want to use the pg_bitutils
table for the rightmost *one* pos as it meant having to special-case
what happens when using index 255, as that would return 0, and I want
8. I'll make the MSVC version use _BitScanForward() in the next patch.
Using __builtin_ctz() seems to help reduce the small regression I was
seeing with the 0 extra column test. It's still there, but it is very
small. It's more pronounced because of the deform_bench module due to
the reduction of the other execution overheads.
Technically, the first_null_attr() function *could* contain slightly
fewer checks. It should be guaranteed that we'll find a byte not set
to 255, as there wouldn't be a bitmask there if there were no 0s. So
technically, the first for loop could be a while (byte[bytenum] ==
0xFF) bytenum++;. I just felt that might be too dangerous to do that
as the code would walk off the end of the bitmask if the tuple was
corrupted in the right way.
With the reduced overhead using deform_bench, the Apple M2 results are
looking quite good. Test 5 with 20 extra columns is 128% faster than
master and averages ~25% faster than master over all tests. My results
are in the attached spreadsheet.
David
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-01-28 02:34:26 +1300, David Rowley wrote:
> On Sat, 24 Jan 2026 at 05:33, Andres Freund wrote:
> > I wonder if it's worth writing a C helper to test deformation in a bit more
> > targeted way.
>
> Good idea. I've written a test module called "deform_bench". You can
> do: "select deform_bench('tablename'::regclass, '{10,20}');" which
> will deform up to attnum=10, then in a 2nd pass deform up to
> attnum=20. This is in the 0003 patch. (Requires "ninja
> install-test-files"). 0003 is intended for testing, not commit.
Nice! I am trying very hard to restrain myself from playing with it right
now, because I really need to get some other things done first...
> /*
> * slot_deform_heap_tuple
> * Given a TupleTableSlot, extract data from the slot's physical tuple
> @@ -1122,78 +1010,140 @@ static pg_attribute_always_inline void
> slot_deform_heap_tuple(TupleTableSlot *slot, HeapTuple tuple, uint32 *offp,
> int natts)
> {
> + CompactAttribute *cattr;
> + TupleDesc tupleDesc = slot->tts_tupleDescriptor;
> bool hasnulls = HeapTupleHasNulls(tuple);
> + HeapTupleHeader tup = tuple->t_data;
> + bits8 *bp; /* ptr to null bitmap in tuple */
> int attnum;
> + int firstNonCacheOffsetAttr;
> + int firstNullAttr;
> + Datum *values;
> + bool *isnull;
> + char *tp; /* ptr to tuple data */
> uint32 off; /* offset in tuple data */
> - bool slow; /* can we use/set attcacheoff? */
> +
> + /* Did someone forget to call TupleDescFinalize()? */
> + Assert(tupleDesc->firstNonCachedOffAttr >= 0);
>
> /* We can only fetch as many attributes as the tuple has. */
> - natts = Min(HeapTupleHeaderGetNatts(tuple->t_data), natts);
> + natts = Min(HeapTupleHeaderGetNatts(tup), natts);
> + attnum = slot->tts_nvalid;
> + firstNonCacheOffsetAttr = Min(tupleDesc->firstNonCachedOffAttr, natts);
FWIW, in a few experiments on my cascade lake systems, this branch (well, it
ends up as a cmov) ends up causing a surprisingly large performance
bottleneck. I don't really see a way around that, but I thought I'd mention it.
On the topic of tupleDesc->firstNonCachedOffAttr - shouldn't that be an
AttrNumber? Not that it'll make a difference perf or space wise, just for
clarity.
Hm, I guess natts isn't an AttrNumber either. Not sure why?
> + if (hasnulls)
> + {
> + bp = tup->t_bits;
> + firstNullAttr = first_null_attr(bp, natts);
> + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, firstNullAttr);
> + }
> + else
> + {
> + bp = NULL;
> + firstNullAttr = natts;
> + }
> +
> + values = slot->tts_values;
> + isnull = slot->tts_isnull;
> + tp = (char *) tup + tup->t_hoff;
Another stall I see is due to the t_hoff computation - which makes sense, it's
in the tuple header and none of the deforming can happen without knowing the
address. I think in the !hasnulls case, the only influence on it is
MAXALIGN(offsetof(HeapTupleHeaderData, t_bits)), so we could just hardcode
that?
Separately, sometimes - I haven't figured out when - gcc seems to think it's
smart to actually compute the `tp + cattr->attcacheoff` below using tup and
tup->t_hoff stored in registers (i.e. doing multiple adds). When the code is
generated that way, I see substantially worse performance. Have you seen
that?
> + else if (attnum == 0)
> {
> /* Start from the first attribute */
> off = 0;
> - slow = false;
> }
> else
> {
> /* Restore state from previous execution */
> off = *offp;
> - slow = TTS_SLOW(slot);
> }
Do we actually need both of these branches? Shouldn't *offp be set to 0 in the
attnum == 0 case?
> - if (!slow)
> + for (; attnum < firstNullAttr; attnum++)
> {
> [...]
> + cattr = TupleDescCompactAttr(tupleDesc, attnum);
> +
> + /* align the offset for this attribute */
> + off = att_pointer_alignby(off,
> + cattr->attalignby,
> + cattr->attlen,
> + tp + off);
> +
> + values[attnum] = fetchatt(cattr, tp + off);
> + isnull[attnum] = false;
> +
> + /* move the offset beyond this attribute */
> + off = att_addlength_pointer(off, cattr->attlen, tp + off);
> }
A few thoughts / suggestions:
1) We should not update values[]/isnull[] between fetchatt() and
att_addlength_pointer(). The compiler can't figure out that no fields in
cattr or *(tp + off) are being affected by those stores.
Changing this on master improves performance quite noticeably. I see a 13%
improvement in a test with deforming 5 not-null byval columns.
2) I sometime see performance benefits due to moving the isnull[attnum] =
false; to the beginning of the loop. Which makes some sense, starting the
store earlier allows it to complete earlier, and it doesn't depend on
fetching cattr, aligning the pointer, fetching the attribute and adjusting
the offset.
3) I briefly experimented with this code, and I think we may be able to
optimize the combination of att_pointer_alignby(), fetch_att() and
att_addlength_pointer(). They all do quite related work, and for byvalue
types, we know at compile time what the alignment requirement for each of
the supported attlen is.
> + /*
> + * Now handle any remaining tuples, this time include NULL checks as we're
> + * now at the first NULL attribute.
> + */
> + for (; attnum < natts; attnum++)
> {
> - /* XXX is it worth adding a separate call when hasnulls is false? */
> - attnum = slot_deform_heap_tuple_internal(slot,
> - tuple,
> - attnum,
> - natts,
> - true, /* slow */
> - hasnulls,
> - &off,
> - &slow);
> + if (att_isnull(attnum, bp))
> + {
> + values[attnum] = (Datum) 0;
> + isnull[attnum] = true;
> + continue;
> + }
Have you experimented setting isnull[] in a dedicated loop if there are nulls
and then in this loop just checking isnull[attnum]? Seems like that could
perhaps be combined with the work in first_null_attr() and be more efficient
than doing an att_isnull() separately for each column.
Greetings,
Andres Freund
Re: More speedups for tuple deformation
Thank you for looking at this again.
On Thu, 29 Jan 2026 at 05:26, Andres Freund wrote:
> On 2026-01-28 02:34:26 +1300, David Rowley wrote:
> > + firstNonCacheOffsetAttr = Min(tupleDesc->firstNonCachedOffAttr, natts);
>
> FWIW, in a few experiments on my cascade lake systems, this branch (well, it
> ends up as a cmov) ends up causing a surprisingly large performance
> bottleneck. I don't really see a way around that, but I thought I'd mention it.
Yeah, I believe this is the primary reason that I'm fighting the small
regression on the 0 extra column test. I thought it might be because
the mov has a dependency and wait on natts being calculated, which
needs to access fields in the tuple header. I wonder if there's some
reason the compiler to CPU can't defer calculating
firstNonCacheOffsetAttr until later. Maybe I should try moving it
later in the code to see if that helps.
> On the topic of tupleDesc->firstNonCachedOffAttr - shouldn't that be an
> AttrNumber? Not that it'll make a difference perf or space wise, just for
> clarity.
>
> Hm, I guess natts isn't an AttrNumber either. Not sure why?
I noticed that too, but took the path of least resistance and made
firstNonCachedOffAttr an int too. I did wonder why natts wasn't an
AttrNumber. If they both were AttrNumbers, I wouldn't need to make the
TupleDesc struct bigger. Right now, I've enlarged it by 8 bytes by
adding firstNonCachedOffAttr.
One problem is that a bunch of functions that accept int;
CreateTemplateTupleDesc(int natts), CreateTupleDesc(int natts,
Form_pg_attribute *attrs). Then BuildDescFromLists() sets natts based
on list_length(). Maybe CreateTemplateTupleDesc() could Assert or
throw an error if natts does not fit in 16-bits.
>
> > + if (hasnulls)
> > + {
> > + bp = tup->t_bits;
> > + firstNullAttr = first_null_attr(bp, natts);
> > + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, firstNullAttr);
> > + }
> > + else
> > + {
> > + bp = NULL;
> > + firstNullAttr = natts;
> > + }
> > +
> > + values = slot->tts_values;
> > + isnull = slot->tts_isnull;
> > + tp = (char *) tup + tup->t_hoff;
>
> Another stall I see is due to the t_hoff computation - which makes sense, it's
> in the tuple header and none of the deforming can happen without knowing the
> address. I think in the !hasnulls case, the only influence on it is
> MAXALIGN(offsetof(HeapTupleHeaderData, t_bits)), so we could just hardcode
> that?
hmm. I wonder why it even needs to exist. If the null bitmap is there,
you can calculate how many bytes from natts. I tried doing "tp = (char
*) tup + MAXALIGN(offsetof(HeapTupleHeaderData, t_bits));" for the
!hasnulls case and it's hard to tell if it helps. See the 0004 patch.
I'm somewhat hesitant to go against the grain here on how to calculate
where the tuple data starts.
> Separately, sometimes - I haven't figured out when - gcc seems to think it's
> smart to actually compute the `tp + cattr->attcacheoff` below using tup and
> tup->t_hoff stored in registers (i.e. doing multiple adds). When the code is
> generated that way, I see substantially worse performance. Have you seen
> that?
I've not noticed that.
> > + else if (attnum == 0)
> > {
> > /* Start from the first attribute */
> > off = 0;
> > - slow = false;
> > }
> > else
> > {
> > /* Restore state from previous execution */
> > off = *offp;
> > - slow = TTS_SLOW(slot);
> > }
>
> Do we actually need both of these branches? Shouldn't *offp be set to 0 in the
> attnum == 0 case?
I see tts_heap_clear() zeros it, so I think it should be ok. Doesn't
feel quite as robust, however.
> A few thoughts / suggestions:
>
> 1) We should not update values[]/isnull[] between fetchatt() and
> att_addlength_pointer(). The compiler can't figure out that no fields in
> cattr or *(tp + off) are being affected by those stores.
>
> Changing this on master improves performance quite noticeably. I see a 13%
> improvement in a test with deforming 5 not-null byval columns.
That's easy enough. I've moved it up in the v7 patch before the cattr
assignment.
> 2) I sometime see performance benefits due to moving the isnull[attnum] =
> false; to the beginning of the loop. Which makes some sense, starting the
> store earlier allows it to complete earlier, and it doesn't depend on
> fetching cattr, aligning the pointer, fetching the attribute and adjusting
> the offset.
> 3) I briefly experimented with this code, and I think we may be able to
> optimize the combination of att_pointer_alignby(), fetch_att() and
> att_addlength_pointer(). They all do quite related work, and for byvalue
> types, we know at compile time what the alignment requirement for each of
> the supported attlen is.
Is this true? Isn't there some nearby discussion about AIX having
4-byte double alignment?
I've taken a go at implementing a function called
align_fetch_then_add(), which rolls all the macros into one (See
0004). I just can't see any improvements with it. Maybe I've missed
something that could be more optimal. I did even ditch one of the
cases from the switch(attlen). It might be ok to do that now as we can
check for invalid attlens for byval types when we populate the
CompactAttribute.
> Have you experimented setting isnull[] in a dedicated loop if there are nulls
> and then in this loop just checking isnull[attnum]? Seems like that could
> perhaps be combined with the work in first_null_attr() and be more efficient
> than doing an att_isnull() separately for each column.
Yes. I experiment with that quite a bit. I wasn't able to make it any
faster than setting the isnull element in the same loop as the
tts_values element. What I did try was having a dedicated tight loop
like; for (int i = attnum; i < firstNullAttr; i++) isnull[i] = false;,
but the compiler would always try to optimise that into an inlined
memset which would result in poorly performing code in cases with a
small number of columns due to the size and alignment prechecks. I had
given up on it as I was already fighting some performance regressions
for the 0 extra column test and this made those worse. However...
In the attached 0004 patch I've experimented with this again. This
time, I wrote a function that converts the null bitmap into the isnull
array using a lookup table. I spent a bit of time trying to figure out
a way to do this without the lookup table and only came up with a
method that requires AVX512 instructions. I coded that up, but it
requires building with -march=x86-64-v4, which will likely cause many
other reasons for the performance to vary.
The machine that likes 0004 the most (using the lookup table method of
setting the isnull array) is the Apple M2. All the tests apart from
the 0 extra column test became 30-90% faster. Previously the tests
that had to do att_isnull didn't improve very much. The 0 extra column
test regressed quite a bit. 50% slower on all but test 1 and 5 (the
ones without NULLs). See the attached graph. The Zen2 machine also
perhaps quite likes it, but not for the 0 extra column test. I'm
struggling to get stable performance results from that machine right
now. My Zen 4 laptop isn't a fan of it, but also not getting very
stable performance results from that either.
I'm curious to see what your Intel machines think of 0004 vs not having it.
Right now, I'm really only getting stable performance out of my Apple
M2 machine, so I'm not too sure what parts of 0004 I should include in
0002 and which ones I should throw away.
David
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-01-31 00:10:42 +1300, David Rowley wrote:
> Thank you for looking at this again.
>
> On Thu, 29 Jan 2026 at 05:26, Andres Freund wrote:
> > On 2026-01-28 02:34:26 +1300, David Rowley wrote:
> > > + firstNonCacheOffsetAttr = Min(tupleDesc->firstNonCachedOffAttr, natts);
> >
> > FWIW, in a few experiments on my cascade lake systems, this branch (well, it
> > ends up as a cmov) ends up causing a surprisingly large performance
> > bottleneck. I don't really see a way around that, but I thought I'd mention it.
>
> Yeah, I believe this is the primary reason that I'm fighting the small
> regression on the 0 extra column test. I thought it might be because
> the mov has a dependency and wait on natts being calculated, which
> needs to access fields in the tuple header.
I agree that it's related to that. You have a chain of multiple computations
that lead to a higher aggregate latency.
natts depends on HeapTupleHeaderGetNatts(tup), firstNonCachedOffsetAttr
depends on both tupleDesc->firstNonCachedOffAttr and natts.
Afaict the dependencies are like the following:
0) a memory load (for tuple->t_data), likely to be cached
1) a memory load (for HeapTupleHeaderGetNatts(tup)), likely to miss memory,
depends on 0)
2) some bit-shiftery to compute natts, depends on 1)
3) a conditional move (the Min()), depends on 3)
4) a memory load (for slot->tupdesc), no dependencies, likely cached
5) a memory load (for tupdesc->firstNonCachedOfAttr), depends on 4), cached
6) a conditional move (the Min()), depends on 3) and 5)
7) a memory load (for HeapTupleHasNulls()), likely to miss memory, but can
piggy back on the cacheline load from 1), depends on 0)
8) a conditional branch (if (hasnulls), depends on 7)
And that's without even taking the hasnulls == true case into account.
Before all of those are completely executed ("retired"), none of the
speculatively executed instructions, e.g. the contents of the if (attnum <
firstNonCacheOffsetAttr) branch, can be retired.
This is why I like the idea of keeping track of whether we can rely on NOT
NULL columns to be present (I think that means we're evaluating expressions
other than constraint checks for new rows). It allows the leading NOT NULL
fixed-width columns to be decoded without having to wait for a good chunk of
the computations above. That's a performance boon even if we later have
nullable or varlength columns.
> I wonder if there's some reason the compiler to CPU can't defer calculating
> firstNonCacheOffsetAttr until later. Maybe I should try moving it later in
> the code to see if that helps.
I think it's the opposite, you want to have it as early as possible so it has
the lowest latency impact by the time the value is required, by starting the
first elements in the dependency chain before the rest.
> > On the topic of tupleDesc->firstNonCachedOffAttr - shouldn't that be an
> > AttrNumber? Not that it'll make a difference perf or space wise, just for
> > clarity.
> >
> > Hm, I guess natts isn't an AttrNumber either. Not sure why?
>
> I noticed that too, but took the path of least resistance and made
> firstNonCachedOffAttr an int too.
Probably reasonable.
> I did wonder why natts wasn't an AttrNumber. If they both were AttrNumbers,
> I wouldn't need to make the TupleDesc struct bigger. Right now, I've
> enlarged it by 8 bytes by adding firstNonCachedOffAttr.
One related thing: I noticed a speedup a few days ago when making sure that
both the slot and the descriptor are aligned to a cacheline boundary,
presumably because it reduces the number of cachelines that need to be in L1
for good performance. But the results were somewhat inconsistent.
Separately I was seeing performance changes in cases where I shouldn't really
see then on the cascade lake system. After a while I noticed that the
differences I was seeing were due to differences in how effective the uop
cache is. A bunch of searching lead to information about the "jcc eratum",
which in turn can be mitigated via "-Wa,-mbranches-within-32B-boundaries". I
am not actually clear whether my CPU is directly affected by that eratum, but
nonetheless, it improved performance quite substantially.
> One problem is that a bunch of functions that accept int;
> CreateTemplateTupleDesc(int natts), CreateTupleDesc(int natts,
> Form_pg_attribute *attrs). Then BuildDescFromLists() sets natts based on
> list_length(). Maybe CreateTemplateTupleDesc() could Assert or throw an
> error if natts does not fit in 16-bits.
We'd probably fail with larger values anyway, so it might be a good idea to
detect that regardless of changing the argument type.
> >
> > > + if (hasnulls)
> > > + {
> > > + bp = tup->t_bits;
> > > + firstNullAttr = first_null_attr(bp, natts);
> > > + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, firstNullAttr);
> > > + }
> > > + else
> > > + {
> > > + bp = NULL;
> > > + firstNullAttr = natts;
> > > + }
> > > +
> > > + values = slot->tts_values;
> > > + isnull = slot->tts_isnull;
> > > + tp = (char *) tup + tup->t_hoff;
> >
> > Another stall I see is due to the t_hoff computation - which makes sense, it's
> > in the tuple header and none of the deforming can happen without knowing the
> > address. I think in the !hasnulls case, the only influence on it is
> > MAXALIGN(offsetof(HeapTupleHeaderData, t_bits)), so we could just hardcode
> > that?
>
> hmm. I wonder why it even needs to exist.
There are a lot of questions like that in our on-disk format. There's a lot of
decisions in there that make fast decoding way harder than it has to be...
> If the null bitmap is there,
> you can calculate how many bytes from natts. I tried doing "tp = (char
> *) tup + MAXALIGN(offsetof(HeapTupleHeaderData, t_bits));" for the
> !hasnulls case and it's hard to tell if it helps. See the 0004 patch.
It helps here quite measurably interestingly.
> I'm somewhat hesitant to go against the grain here on how to calculate where
> the tuple data starts.
Hm. I don't think it's particularly risky. We could even add an error branch
for that assumption being violated - as long as the other computations don't
depend on the result of the conditional branch, the impact on performance
should be quite minimal.
> > > + else if (attnum == 0)
> > > {
> > > /* Start from the first attribute */
> > > off = 0;
> > > - slow = false;
> > > }
> > > else
> > > {
> > > /* Restore state from previous execution */
> > > off = *offp;
> > > - slow = TTS_SLOW(slot);
> > > }
> >
> > Do we actually need both of these branches? Shouldn't *offp be set to 0 in the
> > attnum == 0 case?
>
> I see tts_heap_clear() zeros it, so I think it should be ok. Doesn't
> feel quite as robust, however.
Should be easy enough to assert that it's correct. I don't think it's very
likely we'd just forget resetting it. It's already catastrophic if we set it
wrongly.
> > 3) I briefly experimented with this code, and I think we may be able to
> > optimize the combination of att_pointer_alignby(), fetch_att() and
> > att_addlength_pointer(). They all do quite related work, and for byvalue
> > types, we know at compile time what the alignment requirement for each of
> > the supported attlen is.
>
> Is this true? Isn't there some nearby discussion about AIX having
> 4-byte double alignment?
The AIX stuff is just bonkers. Having different alignment based on where in an
aggregate a double is is just insane.
We could probably just accomodate that with a compile-time ifdef.
> I've taken a go at implementing a function called align_fetch_then_add(),
> which rolls all the macros into one (See 0004). I just can't see any
> improvements with it. Maybe I've missed something that could be more
> optimal. I did even ditch one of the cases from the switch(attlen). It might
> be ok to do that now as we can check for invalid attlens for byval types
> when we populate the CompactAttribute.
You could move the TYPEALIGN(attalignby, *off) calls into the attlen switch
and call it with a constant argument.
> > Have you experimented setting isnull[] in a dedicated loop if there are nulls
> > and then in this loop just checking isnull[attnum]? Seems like that could
> > perhaps be combined with the work in first_null_attr() and be more efficient
> > than doing an att_isnull() separately for each column.
>
> Yes. I experiment with that quite a bit. I wasn't able to make it any
> faster than setting the isnull element in the same loop as the
> tts_values element. What I did try was having a dedicated tight loop
> like; for (int i = attnum; i < firstNullAttr; i++) isnull[i] = false;,
> but the compiler would always try to optimise that into an inlined
> memset which would result in poorly performing code in cases with a
> small number of columns due to the size and alignment prechecks.
Yea, that kind of transformation is pretty annoying and makes little sense
here :(.
I was thinking of actually computing the value of isnull[] based on the null
bitmap (as you also try below).
> In the attached 0004 patch I've experimented with this again. This
> time, I wrote a function that converts the null bitmap into the isnull
> array using a lookup table.
Oh. I was just thinking of something roughly like
int i nullbyte_i = attnum >> 3;
for (int nullcol = attnum; nullcol < natts; nullcol += 8)
{
bits8 nullbyte = bp[nullbyte_i++];
for (int onebyte = 0; onebyte < 8; onebyte++)
{
if (nullcol < natts)
tts_isnull[nullcol] = nullbyte & 0x01;
nullbyte >>= 1;
nullcol++;
}
}
This isn't quite right, as we'd need to deal with starting to deform at a
attribute that's not % 8 = 0 (I'd probably just do the whole byte even if we'd
redo a few column)). And probably lots of other stuff.
With a bit of care the inner loop should be unrollable with all the moves as
conditional moves depending on nullcol < natts. Or such.
Or we could just make sure tts_isnull is always sized to be divisible by 8,
that'd presumably allow considerably better code to be generated.
I'd hope this would be more efficient than doing
static inline bool
att_isnull(int ATT, const bits8 *BITS)
{
return !(BITS[ATT >> 3] & (1 << (ATT & 0x07)));
}
for each column.
> I spent a bit of time trying to figure out a way to do this without the
> lookup table and only came up with a method that requires AVX512
> instructions. I coded that up, but it requires building with
> -march=x86-64-v4, which will likely cause many other reasons for the
> performance to vary.
Yea, I doubt we want that... Too many tuples will be too short to benefit.
> The machine that likes 0004 the most (using the lookup table method of
> setting the isnull array) is the Apple M2. All the tests apart from
> the 0 extra column test became 30-90% faster. Previously the tests
> that had to do att_isnull didn't improve very much. The 0 extra column
> test regressed quite a bit. 50% slower on all but test 1 and 5 (the
> ones without NULLs). See the attached graph. The Zen2 machine also
> perhaps quite likes it, but not for the 0 extra column test. I'm
> struggling to get stable performance results from that machine right
> now. My Zen 4 laptop isn't a fan of it, but also not getting very
> stable performance results from that either.
Hm. A 2kB lookup table in the middle of deforming is probably not great for
L1...
> I'm curious to see what your Intel machines think of 0004 vs not having it.
Scheduling an experiment with it.
Greetings,
Andres Freund
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-01-30 12:11:44 -0500, Andres Freund wrote:
> > In the attached 0004 patch I've experimented with this again. This
> > time, I wrote a function that converts the null bitmap into the isnull
> > array using a lookup table.
>
> Oh. I was just thinking of something roughly like
>
> int i nullbyte_i = attnum >> 3;
> for (int nullcol = attnum; nullcol < natts; nullcol += 8)
> {
> bits8 nullbyte = bp[nullbyte_i++];
>
> for (int onebyte = 0; onebyte < 8; onebyte++)
> {
> if (nullcol < natts)
> tts_isnull[nullcol] = nullbyte & 0x01;
> nullbyte >>= 1;
> nullcol++;
> }
> }
>
> This isn't quite right, as we'd need to deal with starting to deform at a
> attribute that's not % 8 = 0 (I'd probably just do the whole byte even if we'd
> redo a few column)). And probably lots of other stuff.
>
> With a bit of care the inner loop should be unrollable with all the moves as
> conditional moves depending on nullcol < natts. Or such.
>
> Or we could just make sure tts_isnull is always sized to be divisible by 8,
> that'd presumably allow considerably better code to be generated.
>
>
> I'd hope this would be more efficient than doing
>
> static inline bool
> att_isnull(int ATT, const bits8 *BITS)
> {
> return !(BITS[ATT >> 3] & (1 << (ATT & 0x07)));
> }
>
> for each column.
I couldn't quite let go of this, thinking there had to be a non-simd way to do
this efficiently (by basically doing SWAR). And I think there is:
We can multiply one byte of the null bitmap with a carefully chosen value that
spreads each bit into the higher bytes. E.g.
0b111 * (1 << 0) = 0b 111
0b111 * (1 << 7) = 0b 11_10000000
0b111 * ((1 << 0) | (1 << 7))
= 0b 11_10000111
0b111 * (1 << 14) = 0b1_11000000_00000000
0b111 * ((1 << 0) | (1 << 7) | ( << 14))
= 0b1_11000011_10000111
...
Then, we can fairly easily mask out the unnecessary bits.
However, as maybe apparent above, this won't work for the input 0xff, as the
carry from each byte's multiplications will "overflow its byte" and flip the
next bit to 0. But that's not hard to handle:
a) A single branch would probably be fine?
b) Compute the low 4 bits and high 4 bits of the bitmap in parallel and or
the result together. By just looking at 4 null bits, no carry overflow is
possible. Due to being branchless, that's propbably better.
Something like
/*
* The bits array has 1s for values and 0s for NULLs. Bit-flip that to
* get 1s for NULLs.
*/
uint8_t nullbyte = ~bp[nullbyte_i++];
/* 8 bytes where each byte is 0 or 1 depending on whether null bitmap is set */
uint64_t isnull_8;
/*
* Multiplier ensuring that input bit 0 is reflected in output bit 0, input bit 1 at output bit 8, etc.
* Other bits also will often be set and need to be masked away.
*/
uint32_t spread_bits_32 = (1U << 0) | (1U << 7) | (1U << 14) | (1U << 21);
uint64_t mask_bits_64 = 0x0101010101010101ULL;
/* convert the lower 4 bits of null bitmap word into 32 bit int */
isnull_8 = (nullbyte & 0xf) * spread_bits_32;
/* convert the upper 4 bits of null bitmap word into 32 bit int, shift into the upper 32 bit */
isnull_8 |= ((uint64_t)((nullbyte >> 4) * spread_bits_32)) << 32;
/* mask out all the bogus bits (could also be done as a 32bit op?)*/
isnull_8 &= mask_bits_64;
memcpy(&tts_isnull[nullcol], &isnull_8, sizeof(isnull_8));
should, I think, be better than a 2kB array. Perhaps not quite as fast as the
AVX512 method, but it should be decent on most hardware...
Greetings,
Andres Freund
Re: More speedups for tuple deformation
От:
John Naylor <johncnaylorls@gmail.com>
Дата:
On Tue, Jan 27, 2026 at 8:34 PM David Rowley wrote:
> I've also included a slightly revised patch. I made a small change to
> the first_null_attr() to get rid of the masking of higher attnums and
> also now making use of __builtin_ctz to find the first NULL attnum in
> the byte. For compilers that don't support that, I've included a
> pg_rightmost_*zero*_pos table. I didn't want to use the pg_bitutils
> table for the rightmost *one* pos as it meant having to special-case
> what happens when using index 255, as that would return 0, and I want
> 8. I'll make the MSVC version use _BitScanForward() in the next patch.
I don't get why we'd need to special-case 255 in only one place.
+ /* Process all bytes up to just before the byte for the natts index */
+ for (bytenum = 0; bytenum < lastByte; bytenum++)
+ {
+ /* break if there's any NULL attrs (a 0 bit) */
+ if (bits[bytenum] != 0xFF)
+ break;
+ }
+
+ res = bytenum << 3;
+
+#ifdef HAVE__BUILTIN_CTZ
+ res += __builtin_ctz(~bits[bytenum]);
+#else
+ res += pg_rightmost_zero_pos[bits[bytenum]];
+#endif
If bits[bytenum] is 255, then __builtin_ctz(0) is undefined. The top
of the function says
+ * We expect that 'bits' contains at least one 0 bit somewhere in the mask,
+ * not necessarily < natts.
...in which case it should be well defined everywhere. Am I missing
something? If we need to handle the 255 case, this should work:
pg_rightmost_one_pos32(~((uint32) bits[bytenum]))
--
John Naylor
Amazon Web Services
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Sat, 31 Jan 2026 at 15:48, John Naylor wrote: > + res += __builtin_ctz(~bits[bytenum]); > If bits[bytenum] is 255, then __builtin_ctz(0) is undefined. The top > of the function says Oops, I forgot to cast the byte to uint32 before the bitwise-not. I've fixed locally. Still processing Andres' comments. > + * We expect that 'bits' contains at least one 0 bit somewhere in the mask, > + * not necessarily < natts. > > ...in which case it should be well defined everywhere. Am I missing > something? If we need to handle the 255 case, this should work: > > pg_rightmost_one_pos32(~((uint32) bits[bytenum])) I'd rather handle that in a single byte as the fallback path in that function requires byte-at-a-time processing. David
Re: More speedups for tuple deformation
От:
John Naylor <johncnaylorls@gmail.com>
Дата:
On Sat, Jan 31, 2026 at 10:45 AM David Rowley wrote: > On Sat, 31 Jan 2026 at 15:48, John Naylor wrote: > > pg_rightmost_one_pos32(~((uint32) bits[bytenum])) > > I'd rather handle that in a single byte as the fallback path in that > function requires byte-at-a-time processing. I spot checked some less common animals in the buildfarm and i686, ppc64le, riscv64, loongarch64, and s390x all have the builtin. Of these, only riscv64 seems to lack a single instruction implementation. It's good to keep the old fallback path around just in case, but I doubt a new fallback would get any coverage at all. -- John Naylor Amazon Web Services
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
On Sat, 31 Jan 2026 at 06:11, Andres Freund wrote: > This is why I like the idea of keeping track of whether we can rely on NOT > NULL columns to be present (I think that means we're evaluating expressions > other than constraint checks for new rows). It allows the leading NOT NULL > fixed-width columns to be decoded without having to wait for a good chunk of > the computations above. That's a performance boon even if we later have > nullable or varlength columns. I can look into this. As we both know, we can't apply this optimisation in every case as there are places in the code which form then deform tuples before NOT NULL constraints are checked. Perhaps the slot can store a flag to mention if the optimisation is valid to apply or not. It doesn't look like the flag can be part of the TupleDesc since we cache those in relcache. I'm imagining that TupleDescFinalize() calculates another field which could be the max cached offset that's got a NOT NULL constraint and isn't attmissing. I think this will need another dedicated loop in slot_deform_heap_tuple() to loop up to that attribute before doing the firstNonCacheOffsetAttr loop. Maybe it's worth making that new loop only handle byval types so that we can get rid of the byval branch from fetch_att(). That should make it a bit faster at the expense of not being able to handle fixed-width types that have a attlen > 8, which I don't think are excessively common... It's hard to know. UUIDs do get used as primary key columns, and making the PK column the first column in the table is a common pattern to follow. Overall, I agree that this will likely speed up some of the tests, but it will also likely further increase the overheads for the 0 extra column tests. > > > 3) I briefly experimented with this code, and I think we may be able to > > > optimize the combination of att_pointer_alignby(), fetch_att() and > > > att_addlength_pointer(). They all do quite related work, and for byvalue > > > types, we know at compile time what the alignment requirement for each of > > > the supported attlen is. > > > > Is this true? Isn't there some nearby discussion about AIX having > > 4-byte double alignment? > > The AIX stuff is just bonkers. Having different alignment based on where in an > aggregate a double is is just insane. > > We could probably just accomodate that with a compile-time ifdef. I've not tried this yet. There's probably more than align_fetch_then_add() that could benefit from the knowledge that attalign is the same as attlen for byval types. align_fetch_then_add() is the only one I'm currently aware of, and that only saves doing attalign - 1, which only saves 1 cycle. > > I've taken a go at implementing a function called align_fetch_then_add(), > > which rolls all the macros into one (See 0004). I just can't see any > > improvements with it. Maybe I've missed something that could be more > > optimal. I did even ditch one of the cases from the switch(attlen). It might > > be ok to do that now as we can check for invalid attlens for byval types > > when we populate the CompactAttribute. > > You could move the TYPEALIGN(attalignby, *off) calls into the attlen switch > and call it with a constant argument. I think that would need the assumption you mentioned above that the byval type's attlen defines the alignment requirements. > > > Have you experimented setting isnull[] in a dedicated loop if there are nulls > > > and then in this loop just checking isnull[attnum]? Seems like that could > > > perhaps be combined with the work in first_null_attr() and be more efficient > > > than doing an att_isnull() separately for each column. > > > > Yes. I experiment with that quite a bit. I wasn't able to make it any > > faster than setting the isnull element in the same loop as the > > tts_values element. What I did try was having a dedicated tight loop > > like; for (int i = attnum; i < firstNullAttr; i++) isnull[i] = false;, > > but the compiler would always try to optimise that into an inlined > > memset which would result in poorly performing code in cases with a > > small number of columns due to the size and alignment prechecks. > > Yea, that kind of transformation is pretty annoying and makes little sense > here :(. > > I was thinking of actually computing the value of isnull[] based on the null > bitmap (as you also try below). I've taken the code you posted in [1] to do this. Thanks for that. It works very well. I made it so the tts_isnull array size is rounded up to the next multiple of 8. Without that we'll overwrite the sentinel byte in the palloc'd chunk if we assume we can always write to tts_isnull in multiples of 8 elements. Because I've made tts_isnull round up to the next 8 elements, I can make the !hasnulls loop zero the memory 8 bytes at a time. That solves the annoying memset inlining I was getting. That seems to mostly fix the regression in the zero extra column test. The t_hoff calculation replacement maybe helped a bit too. I didn't test individually. > > I spent a bit of time trying to figure out a way to do this without the > > lookup table and only came up with a method that requires AVX512 > > instructions. I coded that up, but it requires building with > > -march=x86-64-v4, which will likely cause many other reasons for the > > performance to vary. > > Yea, I doubt we want that... Too many tuples will be too short to benefit. It was only doing 8 columns at once, not 64. I think it's irrelevant now with your 0x204081 trick. I've revised the 0004 patch to use the 0x204081 trick. I also added fetch_att_noerr() gets rid of the elog and assumes the default switch case must be attlen == 8. I didn't modify the existing function as that will be used for attlen values that don't come from CompactAttribute. Also got rid of the t_hoff usage. With those and the new code that zeros the tts_isnull array 8 bytes at a time, things are looking pretty good. I've attached 3 graphs, which are now looking a bit better. The gcc results are not quite as good. There's still a small regression with 0 extra column test, and overall, the results are not as impressive as clang's. I've not yet studied why. The Apple M2 machine averaged over 53% faster than master over all tests, or ~63% if you exclude the 0 extra column tests. I'll look into adding another optional optimisation for the NOT NULL columns. Attaching the updated patch in the meantime. This includes the fix for the __builtin_ctz() issue mentioned by John. David
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-02-01 00:27:02 +1300, David Rowley wrote:
> On Sat, 31 Jan 2026 at 06:11, Andres Freund wrote:
> > This is why I like the idea of keeping track of whether we can rely on NOT
> > NULL columns to be present (I think that means we're evaluating expressions
> > other than constraint checks for new rows). It allows the leading NOT NULL
> > fixed-width columns to be decoded without having to wait for a good chunk of
> > the computations above. That's a performance boon even if we later have
> > nullable or varlength columns.
>
> I can look into this. As we both know, we can't apply this
> optimisation in every case as there are places in the code which form
> then deform tuples before NOT NULL constraints are checked.
Right.
> Perhaps the slot can store a flag to mention if the optimisation is valid to
> apply or not. It doesn't look like the flag can be part of the TupleDesc
> since we cache those in relcache.
I wonder if we should do it the other way round - use a special flag (and
perhaps tuple descriptor) iff we are evaluating "unsanitizes" tuples,
i.e. ones where the NOT NULLness might not yet be correct.
> I'm imagining that TupleDescFinalize() calculates another field which could
> be the max cached offset that's got a NOT NULL constraint and isn't
> attmissing. I think this will need another dedicated loop in
> slot_deform_heap_tuple() to loop up to that attribute before doing the
> firstNonCacheOffsetAttr loop.
I was imagining that we'd use the new value to enter the
firstNonCacheOffsetAttr loop without having to depend on
HeapTupleHeaderGetNatts() & HeapTupleHasNulls(). I.e. just use it to avoid the
dependency on having to have completed the memory fetch for the header.
> > > > Have you experimented setting isnull[] in a dedicated loop if there are nulls
> > > > and then in this loop just checking isnull[attnum]? Seems like that could
> > > > perhaps be combined with the work in first_null_attr() and be more efficient
> > > > than doing an att_isnull() separately for each column.
> > >
> > > Yes. I experiment with that quite a bit. I wasn't able to make it any
> > > faster than setting the isnull element in the same loop as the
> > > tts_values element. What I did try was having a dedicated tight loop
> > > like; for (int i = attnum; i < firstNullAttr; i++) isnull[i] = false;,
> > > but the compiler would always try to optimise that into an inlined
> > > memset which would result in poorly performing code in cases with a
> > > small number of columns due to the size and alignment prechecks.
> >
> > Yea, that kind of transformation is pretty annoying and makes little sense
> > here :(.
> >
> > I was thinking of actually computing the value of isnull[] based on the null
> > bitmap (as you also try below).
>
> I've taken the code you posted in [1] to do this. Thanks for that. It
> works very well.
Nice!
> I made it so the tts_isnull array size is rounded up to the next multiple of
> 8.
Right, that's what I assumed we'd need.
> I've attached 3 graphs, which are now looking a bit better. The gcc
> results are not quite as good. There's still a small regression with 0
> extra column test, and overall, the results are not as impressive as
> clang's. I've not yet studied why.
I suspect it's due to gcc thinking it'd be a good idea to vectorize the
loop. I saw that happening on godbolt.
Are your results better if you use
#if defined(__clang__)
#define pg_nounroll _Pragma("clang loop unroll(disable)")
#define pg_novector _Pragma("clang loop vectorize(disable)")
#elif defined(__GNUC__)
#define pg_nounroll _Pragma("GCC unroll 0")
#define pg_novector _Pragma("GCC novector")
#else
#define pg_nounroll
#define pg_novector _Pragma("loop( no_vector )")
#endif
and put "pg_nounroll pg_novector" before the loop in populate_isnull_array()?
That improves both gcc and clang code generation substantially for me, but
with a considerably bigger improvement for gcc.
Compiler Opt Isns
gcc -O2 165
clang -O2 135
gcc -O3 532
clang -O3 135
Preventing vectorization & unrolling:
gcc -O2 26
clang -O2 25
gcc -O3 26
clang -O3 25
It's somewhat scary to see this level of code size increase in a case where
the compiler really has no information to think vectorizing really is
beneficial...
I'd expect it makes sense to combine the loop for first_null_attr() with the
one for populate_isnull_array(). It might also prevent gcc from trying to
vectorize the loop...
Greetings,
Andres Freund
Re: More speedups for tuple deformation
От:
John Naylor <johncnaylorls@gmail.com>
Дата:
On Tue, Feb 3, 2026 at 7:33 AM Andres Freund wrote: > It's somewhat scary to see this level of code size increase in a case where > the compiler really has no information to think vectorizing really is > beneficial... I tried building on gcc 15.2 with -fno-tree-loop-vectorize, and the server .text segment was only 5kB smaller, but that may understate the impact on the decisions that get made. Maybe it's better to opt in for unrolling and vectorization? I think this option also controls whether to turn loops into libc memset/memmove etc calls. -- John Naylor Amazon Web Services
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-02-03 12:24:39 +0700, John Naylor wrote: > On Tue, Feb 3, 2026 at 7:33 AM Andres Freund wrote: > > It's somewhat scary to see this level of code size increase in a case where > > the compiler really has no information to think vectorizing really is > > beneficial... > > I tried building on gcc 15.2 with -fno-tree-loop-vectorize, and the > server .text segment was only 5kB smaller, but that may understate the > impact on the decisions that get made. 5kB of instructions isn't nothing. But I guess the fact that most of our loops are too complicated might be protecting us :) > Maybe it's better to opt in for unrolling and vectorization? I think I'd go for opting out. There's too many cases where it's going to be hard to see the optimization potential, e.g. due to inlining etc. I do think we probably should add an evolved version of those pragma macros I showed (including perhaps also ones hinting the other way), and use them in the places we manually analyzed... Greetings, Andres Freund
Re: More speedups for tuple deformation
I've attached an updated version of the patch (v9). This includes some changes to the main patch so that we no longer access the tuple's natts when we're only fetching <= maximum guaranteed column. I've also included what John mentioned about using pg_rightmost_one_pos32() directly rather than trying to reinvent it in a slightly more optimal way. The changes in 0004 and 0005 are new. 0004 makes calling slot_getmissingattrs() the responsibility of the TupleTableSlotOps.getsomeattrs() function. Doing this allows getsomeattrs() to be called with the sibling call optimisation in slot_getsomeattrs_int() and since slot_getsomeattrs_int() is such a trivial function now, I ended up just modifying slot_getsomeattrs() to call getsomeattrs() in a way that allows the compiler to apply the sibling call optimisation. This seems to help reduce some overheads and makes the 0 extra column tests look better. I've also modified slot_getmissingattrs() replacing the memsets with a for loop to zero the tts_values and set the nulls in the tts_isnull array. Other experimentations showed that doing this in a loop is faster than memset, so I applied those learnings there too. I've moved the elog(ERROR) that checks for invalid attnums into there too. That does mean we'll deform a tuple before raising that error, but I don't see the issue with that given that it's a "can't happen" error anyway. Moving it there saves a compare and jump. 0005 reduces the size of CompactAttribute. It shrinks the struct down to 8 bytes from 16 by using some bitflags for some lesser-used booleans and by shrinking attcacheoff down to int16. The idea is that we just don't cache any offsets larger than 2^15. It's likely if we get a tuple that big that there's a variable-length attribute anyway, which caching the offset of isn't possible. I'm not getting great results from benchmarking the 0005 patch. I verified that gcc does access the array without calculating the element address from scratch each time and calculates it once, then increments the pointer by sizeof(CompactAttribute). See the attached .csv for the results on the 3 machines I tested on. I've also resequenced the patches to make the deform_bench test module part of the 0001 patch. This makes it easier to test the performance of master. I've not yet made it so the TTS_FLAG_OBEYS_NOT_NULL_CONSTRAINTS tts_flag gets set in all places it currently could be set. There are a few more scan types where it could be set. I understand you mentioned that you thought the flag should disable the optimisation rather than enable it, but I've not yet looked to check all the places that it needs to be disabled. David
Re: More speedups for tuple deformation
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
Hi David,
On Tue, Feb 24, 2026 at 11:23 AM David Rowley wrote:
> I've attached an updated version of the patch (v9).
I noticed what looks like some rebase noise in TupleDescFinalize():
off = att_nominal_alignby(off, cattr->attalignby);
/*
* attcacheoff is an int16, so don't try and cache any offsets larger
* than will fit in that type.
*/
if (off > PG_INT16_MAX)
break;
cattr->attcacheoff = off;
/*
* attcacheoff is an int16, so don't try and cache any offsets larger
* than will fit in that type.
*/
if (off > PG_INT16_MAX)
break;
cattr->attcacheoff = off;
--
Thanks, Amit Langote
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Tue, 24 Feb 2026 at 21:46, Amit Langote wrote: > I noticed what looks like some rebase noise in TupleDescFinalize(): Thanks. Fixed locally. That must have happened during a rebase when I renamed offp to off. David
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-02-24 15:23:17 +1300, David Rowley wrote: > The changes in 0004 and 0005 are new. 0004 makes calling > slot_getmissingattrs() the responsibility of the > TupleTableSlotOps.getsomeattrs() function. Doing this allows > getsomeattrs() to be called with the sibling call optimisation in > slot_getsomeattrs_int() and since slot_getsomeattrs_int() is such a > trivial function now, I ended up just modifying slot_getsomeattrs() to > call getsomeattrs() in a way that allows the compiler to apply the > sibling call optimisation. This seems to help reduce some overheads > and makes the 0 extra column tests look better. ISTM we should just merge 0004. In my testing it's a very clear win, without, afaict, any downsides. > 0005 reduces the size of CompactAttribute. It shrinks the struct down > to 8 bytes from 16 by using some bitflags for some lesser-used > booleans and by shrinking attcacheoff down to int16. The idea is that > we just don't cache any offsets larger than 2^15. It's likely if we > get a tuple that big that there's a variable-length attribute anyway, > which caching the offset of isn't possible. > > I'm not getting great results from benchmarking the 0005 patch. I > verified that gcc does access the array without calculating the > element address from scratch each time and calculates it once, then > increments the pointer by sizeof(CompactAttribute). See the attached > .csv for the results on the 3 machines I tested on. FWIW, where I had seen that be rather beneficial is the TupleDescCompactAttr() at the start of the various loops, where the compiler has little choice to compute the address of the tupdesc->compact_attrs[firstNeededCol]. That matters only when only deforming a small number of columns, of course. > I've also resequenced the patches to make the deform_bench test module > part of the 0001 patch. This makes it easier to test the performance > of master. What are your thoughts about merging the deform_bench tooling? I wonder if we should have src/test/modules/benchmark_tools or such, so we can add a few more micro-benchmarky tools over time? Greetings, Andres Freund
Re: More speedups for tuple deformation
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello + * We expect that 'bits' contains at least one 0 bit somewhere in the mask, + * not necessarily < natts. + */ Is this precondition really enough? Let's say we have 20 attributes, only attribute 20 is NULL Caller requests natts=8 That sets lastByte = 1, loop only checks bits[0], which is 0xFF, exits with bytenum=1, bits[1] is also 0xFF Then we execute + res += pg_rightmost_one_pos32(~bits[bytenum]); where ~0xFF = 0 + /* convert the lower 4 bits of null bitmap word into 32 bit int */ + isnull_8 = (nullbyte & 0xf) * SPREAD_BITS_MULTIPLIER_32; + + /* + * convert the upper 4 bits of null bitmap word into 32 bit int, shift + * into the upper 32 bit + */ + isnull_8 |= ((uint64) ((nullbyte >> 4) * SPREAD_BITS_MULTIPLIER_32)) << 32; + + /* mask out all other bits apart from the lowest bit of each byte */ + isnull_8 &= UINT64CONST(0x0101010101010101); + memcpy(isnull, &isnull_8, sizeof(uint64)); Won't this mix up column numbers on big-endian systems? Subject: [PATCH v9 1/5] Introduce deform_bench test module For benchmaring tuple deformation. --- Typo: should be benchmarking + * firstNonGuaranteedAttr stores the index to info the compact_attrs array for to info should be "into"?
Re: More speedups for tuple deformation
Thanks for having a look at this.
On Wed, 25 Feb 2026 at 07:33, Zsolt Parragi wrote:
> + * We expect that 'bits' contains at least one 0 bit somewhere in the mask,
> + * not necessarily < natts.
> + */
>
> Is this precondition really enough?
>
> Let's say we have 20 attributes, only attribute 20 is NULL
> Caller requests natts=8
>
> That sets lastByte = 1, loop only checks bits[0], which is 0xFF, exits
> with bytenum=1, bits[1] is also 0xFF
>
> Then we execute
>
> + res += pg_rightmost_one_pos32(~bits[bytenum]);
>
> where ~0xFF = 0
I think this works ok in v9, but in v10 I've added a cast so that line becomes:
res += pg_rightmost_one_pos32(~((uint32) bits[bytenum]));
For the case you describe, 0xFF becomes 0xFFFFFF00 and
pg_rightmost_one_pos32() returns 8, the lowest bit of the 2nd byte.
> + /* convert the lower 4 bits of null bitmap word into 32 bit int */
> + isnull_8 = (nullbyte & 0xf) * SPREAD_BITS_MULTIPLIER_32;
> +
> + /*
> + * convert the upper 4 bits of null bitmap word into 32 bit int, shift
> + * into the upper 32 bit
> + */
> + isnull_8 |= ((uint64) ((nullbyte >> 4) * SPREAD_BITS_MULTIPLIER_32)) << 32;
> +
> + /* mask out all other bits apart from the lowest bit of each byte */
> + isnull_8 &= UINT64CONST(0x0101010101010101);
> + memcpy(isnull, &isnull_8, sizeof(uint64));
>
>
> Won't this mix up column numbers on big-endian systems?
Yes, I believe you're right. I've added the following before the memcpy().
#ifdef WORDS_BIGENDIAN
/*
* Fix byte order on big-endian machines before copying to the array.
*/
isnull_8 = pg_bswap64(isnull_8);
#endif
>
> Subject: [PATCH v9 1/5] Introduce deform_bench test module
>
> For benchmaring tuple deformation.
> ---
>
> Typo: should be benchmarking
Fixed.
> + * firstNonGuaranteedAttr stores the index to info the compact_attrs array for
>
> to info should be "into"?
Also fixed.
I've attached a revised set of patches.
David
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Thanks for looking.
On Wed, 25 Feb 2026 at 03:39, Andres Freund wrote:
> ISTM we should just merge 0004. In my testing it's a very clear win, without,
> afaict, any downsides.
I'd like to get them in in sequence as I believe 0004 buys back some
extra overheads such as the Min()s in slot_deform_heap_tuple(). If I
were to do 0004 first, then wait a while, it might look more like I'm
introducing a small regression.
> > I'm not getting great results from benchmarking the 0005 patch. I
> > verified that gcc does access the array without calculating the
> > element address from scratch each time and calculates it once, then
> > increments the pointer by sizeof(CompactAttribute). See the attached
> > .csv for the results on the 3 machines I tested on.
>
> FWIW, where I had seen that be rather beneficial is the TupleDescCompactAttr()
> at the start of the various loops, where the compiler has little choice to
> compute the address of the tupdesc->compact_attrs[firstNeededCol]. That
> matters only when only deforming a small number of columns, of course.
oh ok. I wasn't aware that LEA's scaling factor can only be 1,2 4 or
8. With the 8-byte struct, the compiler should be able to do the shift
and add as one operation, whereas with the 16-byte struct would
require a separate shift and add.
Looking at the generated code, with 0004, I see:
1c79: 48 c1 e2 04 shl rdx,0x4
1c7d: 48 8d 4c 15 20 lea rcx,[rbp+rdx*1+0x20]
whereas with 0005 I see:
1c6b: 4a 8d 1c dd 00 00 00 lea rbx,[r11*8+0x0]
Is that what you meant?
> > I've also resequenced the patches to make the deform_bench test module
> > part of the 0001 patch. This makes it easier to test the performance
> > of master.
>
> What are your thoughts about merging the deform_bench tooling? I wonder if we
> should have src/test/modules/benchmark_tools or such, so we can add a few more
> micro-benchmarky tools over time?
I'd like to see us give these tools a proper home. It helps lower the
bar for anyone else who'd like to experiment at some future date, and
also allows people to more easily test for performance regressions if
they're forced to change related code. I've also got a tool that
benchmarks the MemoryContext code which I keep in some local repo that
I dig out from time to time. Given that, it's probably unlikely
deform_bench would be the only extension in there if we did make a
directory for these.
On the otherhand, it does add some maintenance overhead, but IMO,
helping to ensure various key routines are optimal is a worthy enough
cause to make the maintenance overhead worthwhile.
David
Re: More speedups for tuple deformation
От:
John Naylor <johncnaylorls@gmail.com>
Дата:
On Wed, Feb 25, 2026 at 7:40 AM David Rowley wrote: > On Wed, 25 Feb 2026 at 07:33, Zsolt Parragi wrote: > > Won't this mix up column numbers on big-endian systems? > > Yes, I believe you're right. I've added the following before the memcpy(). > > #ifdef WORDS_BIGENDIAN > > /* > * Fix byte order on big-endian machines before copying to the array. > */ > isnull_8 = pg_bswap64(isnull_8); > #endif I confirmed regression tests bail out early on a big-endian machine with v9 and pass with v10. -- John Naylor Amazon Web Services
Re: More speedups for tuple deformation
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
Hello,
With all these patches applied, I get this from pahole for
CompactAttribute,
struct CompactAttribute {
int16 attcacheoff; /* 0 2 */
int16 attlen; /* 2 2 */
_Bool attbyval; /* 4 1 */
uint8 attalignby; /* 5 1 */
_Bool attispackable:1; /* 6: 0 1 */
_Bool atthasmissing:1; /* 6: 1 1 */
_Bool attisdropped:1; /* 6: 2 1 */
_Bool attgenerated:1; /* 6: 3 1 */
/* XXX 4 bits hole, try to pack */
char attnullability; /* 7 1 */
/* size: 8, cachelines: 1, members: 9 */
/* sum members: 7 */
/* sum bitfield members: 4 bits, bit holes: 1, sum bit holes: 4 bits */
/* last cacheline: 8 bytes */
};
The 'attnullability' thing stands out. It probably doesn't make much of
a difference -- considering that it's down to 8 bytes already and I
doubt anything will change if it's instead 6 -- but given these
definitions
/* Valid values for CompactAttribute->attnullability */
#define ATTNULLABLE_UNRESTRICTED 'f' /* No constraint exists */
#define ATTNULLABLE_UNKNOWN 'u' /* constraint exists, validity unknown */
#define ATTNULLABLE_VALID 'v' /* valid constraint exists */
#define ATTNULLABLE_INVALID 'i' /* constraint exists, marked invalid */
it looks like you could reduce that to 3 bits with flags that say "does
a constraint exist", "is the constraint validity known", and "is it
valid or invalid", respectively. (Or you could use just 2 bits and
encode the four states there, but that's inconsequential).
But as I said, I'd bet this doesn't make any performance difference.
Looking at populate_isnull_array(), it says caller must ensure *isnull
is of a certain size. However, looking at its caller, it's not clear to
me how have we ensure that this happened. In MakeTupleTableSlot() we do
MAXALIGN() of natts, which I think should make a reference to
populate_isnull_array() so that we know *why* we MAXALIGN() there; and
ExecSetSlotDescriptor() the MAXALIGN() looks very mysterious compared to
the non-maxaligned size used to allocate tts_values in the line just
above. I just think, there should be a comment in those places. (And
anywhere tts_isnull is allocated; didn't find other places, but didn't
look too hard either).
Regarding deform_bench, I wonder if we shouldn't start a proper
benchmarking suite (of which this would the first participant) by
putting this in src/benchmark/tuple_deform instead (or something like
that) instead of relegating it to src/test/modules. It doesn't make
much of a technical difference, but it is a bit of a statement that more
tools are welcome.
--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
"People get annoyed when you try to debug them." (Larry Wall)
Re: More speedups for tuple deformation
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
> I think this works ok in v9, but in v10 I've added a cast so that line becomes:
Maybe I missed something in my logic there, I didn't try to actually
break the function, but the new one with the additional comment is
definitely clearer about this.
+/*
+ * first_null_attr
+ * Inspect a NULL bitmask from a tuple and return the 0-based attnum of the
+ * first NULL attribute. Returns natts if no NULLs were found.
+ */
+static inline int
+first_null_attr(const bits8 *bits, int natts)
The previous version of this function had an explanation that there
has to be at least one NULL in bits - now it's not part of the
description.
Is it a requirement or not? I think it is currently true for all call
sites, but the comment now allows all fields to be not null.
Because if it is valid for bits to not have any NULLs, we might do an
out of bounds read if natts == tupnatts, and bits is exactly allocated
to the proper size. MAXALIGN usually hides this situation, but the
possibility seems to be there.
+ /* use attrmiss to set the missing values */
+ for (int attnum = startAttNum; attnum < lastAttNum; attnum++)
{
- slot->tts_values[missattnum] = attrmiss[missattnum].am_value;
- slot->tts_isnull[missattnum] = !attrmiss[missattnum].am_present;
+ slot->tts_values[attnum] = attrmiss[attnum].am_value;
+ slot->tts_isnull[attnum] = !attrmiss[attnum].am_present;
}
}
+
+ if (unlikely(lastAttNum > slot->tts_tupleDescriptor->natts))
+ elog(ERROR, "invalid attribute number %d", lastAttNum);
Is it okay to do this error check at the end? If we hit that unlikely
error condition, we already performed a write past the end of the
arrays in the loop before (and also a read from attrmiss).
(in nocachegetattr)
- off += att->attlen;
+ off = att_pointer_alignby(off, cattr->attalignby, cattr->attlen,
+ tp + off);
+ off += cattr->attlen;
Shouldn't this be att_nominal_alignby, like above in the previous loop?
There's one more typo in "This loops only differs"
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-02-25 13:59:53 +1300, David Rowley wrote:
> On Wed, 25 Feb 2026 at 03:39, Andres Freund wrote:
> > ISTM we should just merge 0004. In my testing it's a very clear win, without,
> > afaict, any downsides.
>
> I'd like to get them in in sequence as I believe 0004 buys back some
> extra overheads such as the Min()s in slot_deform_heap_tuple(). If I
> were to do 0004 first, then wait a while, it might look more like I'm
> introducing a small regression.
I'd rather get more stuff merged out of the way. We can handle a small
regression by comparing to 18 instead. I think we tend to be too worried
about intra-master regressions, and not worried enough about intra branch
regressions.
But FWIW, I don't actually see any regressions due to the Min() on my hardware
as the patches stand.
I do actually see a small regression in some cases due to 0004, but that's
easy to fix:
/* Fetch any missing attrs and raise an error if reqnatts is invalid */
if (unlikely(attnum < reqnatts))
slot_getmissingattrs(slot, attnum, reqnatts);
done:
/* Save current offset for next execution */
*offp = off;
This forces pushing a bunch of stack state before the call to
slot_getmissingattrs, doing the call, returning, restoring state from the
stack, just to then jump to the end of the function to set *offp which then
again does a bunch of stack restoring and returns.
If you instead make it something like:
/* Fetch any missing attrs and raise an error if reqnatts is invalid */
if (unlikely(attnum < reqnatts))
{
*offp = off;
slot_getmissingattrs(slot, attnum, reqnatts);
return;
}
(or just duplicate the *offp = off in the goto done; case)
the overhead seems to be removed.
At least gcc is doing some truly weird shit in the
firstNonGuaranteed/firstNonCachedOffsetAttr loop "header" (i.e. just before
the first entrance to the loop) , which leads to the register pressure being
high, which leads to spilling on the stack, making the few-tuples case slower:
r9 is tts_nvalid, r11 is firstNonGuaranteedAttr, r15 is
slot->tts_tupleDescriptor, rbx is tts_values, -0x10(%rsp) is tts_isnull, rax
is tup.
if (attnum < firstNonGuaranteedAttr)
cmp %r9d,%r11d
jle
lea 0x0(,%r9,8),%r12
multiply r9/tts_nvalid by 8, store in r12
sub %r9d,%r11d
r11=firstNonGuaranteedAttr-tts_nvalid
xor %ecx,%ecx
Set ecx to 0
lea 0x20(%r15,%r12,1),%rdx
compute (char *) tupleDesc->compact_attrs + r12, i.e. the address of the first
needed compact attribute
add %rbx,%r12
compute (char*) tts_values + tts_nvalid * sizeof(Datum)
mov -0x10(%rsp),%rbx
restore tts_isnull from stack
lea (%rbx,%r9,1),%rsi
compute tts_isnull[tts_nvalid]
jmp
Then the loop body:
...
movb $0x0,(%rsi,%rcx,1)
set (tts_isnull + tts_nvalid)[i] = 0
mov %rdx,%r13
movswl (%rdx),%edi
load cattr->attcacheoff into rdi/edi
movzwl 0x2(%rdx),%r10d
load attlen into r10
mov %rdi,%rbx
add %rax,%rdi
rdi = tup + attcacheoff
[bunch of attlen related branches omitted]
movslq (%rdi),%rdi
store *(tup + off) in rdi
mov %rdi,(%r12,%rcx,8)
store rdi in tts_values[i]
lea 0x1(%rcx),%rdi
increment i by one, in a weird way, store in rdi
add $0x8,%rdx
increment cattr by 8
cmp %rdi,%r11
check if i < (firstNonGuaranteedAttr-tts_nvalid)
I.e. the compiler creates an offset version of tts_values[tts_nvalid],
tts_isnull[tts_nvalid], which then creates register allocation pressure,
because later the original tts_values/tts_isnulll etc are accessed again and
thus the underlying registers are preserved. And this is all for zero gain,
from what I can tell, because the acceses are still done with indexed
addressing (like mov %rdi,(%r12,%rcx,8)), which would work just as
well if rcx were indexed based on attnum, not zero indexed within the loop.
I see about a 10% improvement if I dissuade the compiler from doing that by
adding
__asm__ volatile ("" : "+r"(attnum) : :);
In the loop body.
I'm getting to the point where I'd like to just hand write the assembler for
this stupid function. Gah.
> > > I'm not getting great results from benchmarking the 0005 patch. I
> > > verified that gcc does access the array without calculating the
> > > element address from scratch each time and calculates it once, then
> > > increments the pointer by sizeof(CompactAttribute). See the attached
> > > .csv for the results on the 3 machines I tested on.
> >
> > FWIW, where I had seen that be rather beneficial is the TupleDescCompactAttr()
> > at the start of the various loops, where the compiler has little choice to
> > compute the address of the tupdesc->compact_attrs[firstNeededCol]. That
> > matters only when only deforming a small number of columns, of course.
>
> oh ok. I wasn't aware that LEA's scaling factor can only be 1,2 4 or
> 8. With the 8-byte struct, the compiler should be able to do the shift
> and add as one operation, whereas with the 16-byte struct would
> require a separate shift and add.
>
> Looking at the generated code, with 0004, I see:
>
> 1c79: 48 c1 e2 04 shl rdx,0x4
> 1c7d: 48 8d 4c 15 20 lea rcx,[rbp+rdx*1+0x20]
>
> whereas with 0005 I see:
>
> 1c6b: 4a 8d 1c dd 00 00 00 lea rbx,[r11*8+0x0]
>
> Is that what you meant?
Yep.
> > > I've also resequenced the patches to make the deform_bench test module
> > > part of the 0001 patch. This makes it easier to test the performance
> > > of master.
> >
> > What are your thoughts about merging the deform_bench tooling? I wonder if we
> > should have src/test/modules/benchmark_tools or such, so we can add a few more
> > micro-benchmarky tools over time?
>
> I'd like to see us give these tools a proper home. It helps lower the
> bar for anyone else who'd like to experiment at some future date, and
> also allows people to more easily test for performance regressions if
> they're forced to change related code. I've also got a tool that
> benchmarks the MemoryContext code which I keep in some local repo that
> I dig out from time to time. Given that, it's probably unlikely
> deform_bench would be the only extension in there if we did make a
> directory for these.
I'd probably lean towards one extensions with different functions for
different purposes, but that's boring details.
> On the otherhand, it does add some maintenance overhead, but IMO,
> helping to ensure various key routines are optimal is a worthy enough
> cause to make the maintenance overhead worthwhile.
Agreed.
Greetings,
Andres Freund
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-02-25 13:05:14 -0500, Andres Freund wrote:
> At least gcc is doing some truly weird shit in the
> firstNonGuaranteed/firstNonCachedOffsetAttr loop "header" (i.e. just before
> the first entrance to the loop) , which leads to the register pressure being
> high, which leads to spilling on the stack, making the few-tuples case slower:
>
> [ lots of stuff trimmed ]
>
> I.e. the compiler creates an offset version of tts_values[tts_nvalid],
> tts_isnull[tts_nvalid], which then creates register allocation pressure,
> because later the original tts_values/tts_isnulll etc are accessed again and
> thus the underlying registers are preserved. And this is all for zero gain,
> from what I can tell, because the acceses are still done with indexed
> addressing (like mov %rdi,(%r12,%rcx,8)), which would work just as
> well if rcx were indexed based on attnum, not zero indexed within the loop.
>
> I see about a 10% improvement if I dissuade the compiler from doing that by
> adding
> __asm__ volatile ("" : "+r"(attnum) : :);
>
> In the loop body.
>
>
> I'm getting to the point where I'd like to just hand write the assembler for
> this stupid function. Gah.
Huh. It, at least partially, seems to be related to using an integer for
attnum et al. Due to us using -fwrapv, the compiler can't actually assume that
an attnum++ won't overflow. An overflow would make the loop trip counts a lot
more complicated. Even with that I don't understand how it ends up
generating such crappy code, but since using size_t fixes it...
Greetings,
Andres Freund
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Thanks for having a look at this.
On Wed, 25 Feb 2026 at 22:49, Álvaro Herrera wrote:
> With all these patches applied, I get this from pahole for
> CompactAttribute,
> The 'attnullability' thing stands out. It probably doesn't make much of
> a difference -- considering that it's down to 8 bytes already and I
> doubt anything will change if it's instead 6 -- but given these
> definitions
We could get it to 6 bytes. The alignment is 2, so there's certainly a
memory saving there. I think the primary reason to make it 8 was that
the LEA instruction can be used without any other instructions to
calculate the address of the first CompactAttribute element to use.
LEA can shift the array index to multiply it by 1,2,4 or 8, and
because it can do shift and add concurrently, it can utilise the add
to add the offset of compact_attrs in the TupleDesc struct.
I see gcc doing this when I make attnum a size_t. This is effectively
what I described above:
1c46: 48 8d 74 c2 20 lea rsi,[rdx+rax*8+0x20]
The 0x20 is the offset to the start of compact_attrs in TupleDescData.
rax is attnum. rdx is the tupledesc. Effectively, that's:
rsi = ((char *) tupledesc) + (attnum << 3) + offsetof(TupleDescData,
compact_attrs);
If I make the CompactAttribute 6 bytes, I see gcc producing two LEA
instructions instead of one:
1c80: 48 8d 34 40 lea rsi,[rax+rax*2]
1c89: 49 8d 74 74 20 lea rsi,[r12+rsi*2+0x20]
rax is attnum again. r12 is the tupledesc. Effectively that's:
/* multiply attnum by 3, store in rdi */
rsi = attnum + (attnum << 1);
/* multiply rdi by 2 to make multiply by 6 and at that plus 32 to the
tupledesc's addr. */
rsi = ((char *) tupledesc) + (rsi << 1) + offsetof(TupleDescData,
compact_attrs);
I expect that the extra address calculation costs plus the extra
bitwise-AND for checking attbyval will cost more than it will save.
> Regarding deform_bench, I wonder if we shouldn't start a proper
> benchmarking suite (of which this would the first participant) by
> putting this in src/benchmark/tuple_deform instead (or something like
> that) instead of relegating it to src/test/modules. It doesn't make
> much of a technical difference, but it is a bit of a statement that more
> tools are welcome.
Yeah. Andres was talking about this in [1]. I'd originally not planned
on committing deform_bench at all and only put it in the current
location in the patch as that seemed like the best location for it
that we have today. Andres mentioned just having 1 extension and
adding functions to it. That seems fine to me. I have some other
things that could go in there. If it's just one extension, then
there's likely no need to make a special directory for it. Maybe
src/test/modules is fine. For now, I don't want to focus too much as
I'd rather get the deformation speedups ready and in.
David
[1] https://postgr.es/m/rbxc2qqhsvzxpukgd36caoa4ydgn5r22fxktxanrkn6nobg7j6%4027b4vogohgu2
Re: More speedups for tuple deformation
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Feb-27, David Rowley wrote: > > The 'attnullability' thing stands out. It probably doesn't make much of > > a difference -- considering that it's down to 8 bytes already and I > > doubt anything will change if it's instead 6 -- but given these > > definitions > > We could get it to 6 bytes. [...] > If I make the CompactAttribute 6 bytes, I see gcc producing two LEA > instructions instead of one: [...] > I expect that the extra address calculation costs plus the extra > bitwise-AND for checking attbyval will cost more than it will save. Ah, that makes sense. Interesting, thanks for explaining. > > Regarding deform_bench, I wonder if we shouldn't start a proper > > benchmarking suite [...] > > Yeah. Andres was talking about this in [1]. I'd originally not planned > on committing deform_bench at all and only put it in the current > location in the patch as that seemed like the best location for it > that we have today. Andres mentioned just having 1 extension and > adding functions to it. That seems fine to me. I have some other > things that could go in there. If it's just one extension, then > there's likely no need to make a special directory for it. Maybe > src/test/modules is fine. For now, I don't want to focus too much as > I'd rather get the deformation speedups ready and in. Hmm, ok. I'd rather not get it in the tree at all for now, and see what else can we get in there later. Then we might have better ideas of what to do; if we do get it in src/test/modules now, we might not want to move it elsewhere later as it might be more painful. As you say, if it's just one extension then it doesn't matter much where it is. But we might get other ideas that require more than one extension, or more than one benchmarking suite, and then src/test/modules doesn't sound so great a location. -- Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-02-26 16:01:26 +0100, Álvaro Herrera wrote: > On 2026-Feb-27, David Rowley wrote: > > > Regarding deform_bench, I wonder if we shouldn't start a proper > > > benchmarking suite [...] > > > > Yeah. Andres was talking about this in [1]. I'd originally not planned > > on committing deform_bench at all and only put it in the current > > location in the patch as that seemed like the best location for it > > that we have today. Andres mentioned just having 1 extension and > > adding functions to it. That seems fine to me. I have some other > > things that could go in there. If it's just one extension, then > > there's likely no need to make a special directory for it. Maybe > > src/test/modules is fine. For now, I don't want to focus too much as > > I'd rather get the deformation speedups ready and in. > > Hmm, ok. I'd rather not get it in the tree at all for now, and see what > else can we get in there later. Then we might have better ideas of what > to do; if we do get it in src/test/modules now, we might not want to > move it elsewhere later as it might be more painful. As you say, if > it's just one extension then it doesn't matter much where it is. But we > might get other ideas that require more than one extension, or more than > one benchmarking suite, and then src/test/modules doesn't sound so great > a location. I don't get this. We'll approximately never have a full suite of benchmark tools that make sense to integrate at once. The reason we're here is because over and over we've not actually merged quite useful tools, making do with benchmarking-by-proxy and one off tools. This seems like a recipe for never getting anywhere better. Greetings, Andres Freund
Re: More speedups for tuple deformation
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Feb-26, Andres Freund wrote:
> I don't get this. We'll approximately never have a full suite of benchmark
> tools that make sense to integrate at once. The reason we're here is because
> over and over we've not actually merged quite useful tools, making do with
> benchmarking-by-proxy and one off tools. This seems like a recipe for never
> getting anywhere better.
Eh, my first suggestion was to start the benchmark suite as a top-level
thing, so put this module under src/benchmark rather than hide it with
the bunch of smelly dudes in src/test/modules.
--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
"Ed is the standard text editor."
http://groups.google.com/group/alt.religion.emacs/msg/8d94ddab6a9b0ad3
Re: More speedups for tuple deformation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-02-26 17:01:57 +0100, Álvaro Herrera wrote: > On 2026-Feb-26, Andres Freund wrote: > > > I don't get this. We'll approximately never have a full suite of benchmark > > tools that make sense to integrate at once. The reason we're here is because > > over and over we've not actually merged quite useful tools, making do with > > benchmarking-by-proxy and one off tools. This seems like a recipe for never > > getting anywhere better. > > Eh, my first suggestion was to start the benchmark suite as a top-level > thing, so put this module under src/benchmark rather than hide it with > the bunch of smelly dudes in src/test/modules. I don't particularly care about whether we put it in src/benchmark or src/test/modules. I don't love either, so whatever. But I think it's reasonably important that we don't go for "one extension for every single C benchmark function", because that'll just make the overhead for adding another benchmark function too high. And I think we shouldn't install anything in there by default (like with src/test/modules), as otherwise we'll have to care about the benchmark module being perfectly safe, which I don't think we want to. Greetings, Andres Freund
Re: More speedups for tuple deformation
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Feb-26, Andres Freund wrote: > But I think it's reasonably important that we don't go for "one extension for > every single C benchmark function", because that'll just make the overhead for > adding another benchmark function too high. Absolutely. I just don't think we should think that one extension is going to be enough forever. > And I think we shouldn't install anything in there by default (like with > src/test/modules), as otherwise we'll have to care about the benchmark module > being perfectly safe, which I don't think we want to. Agreed. -- Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/ "Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end." (2nd Commandment for C programmers)
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Wed, 25 Feb 2026 at 23:54, Zsolt Parragi wrote:
> +/*
> + * first_null_attr
> + * Inspect a NULL bitmask from a tuple and return the 0-based attnum of the
> + * first NULL attribute. Returns natts if no NULLs were found.
> + */
> +static inline int
> +first_null_attr(const bits8 *bits, int natts)
>
> The previous version of this function had an explanation that there
> has to be at least one NULL in bits - now it's not part of the
> description.
> Is it a requirement or not? I think it is currently true for all call
> sites, but the comment now allows all fields to be not null.
I mistakenly removed that comment thinking that it was no longer a
requirement. I've now put a more comprehensive comment there so that I
don't forget the reason for this again.
> + /* use attrmiss to set the missing values */
> + for (int attnum = startAttNum; attnum < lastAttNum; attnum++)
> {
> - slot->tts_values[missattnum] = attrmiss[missattnum].am_value;
> - slot->tts_isnull[missattnum] = !attrmiss[missattnum].am_present;
> + slot->tts_values[attnum] = attrmiss[attnum].am_value;
> + slot->tts_isnull[attnum] = !attrmiss[attnum].am_present;
> }
> }
> +
> + if (unlikely(lastAttNum > slot->tts_tupleDescriptor->natts))
> + elog(ERROR, "invalid attribute number %d", lastAttNum);
>
>
> Is it okay to do this error check at the end? If we hit that unlikely
> error condition, we already performed a write past the end of the
> arrays in the loop before (and also a read from attrmiss).
It's not. I've moved it to the start of that function.
> (in nocachegetattr)
>
> - off += att->attlen;
> + off = att_pointer_alignby(off, cattr->attalignby, cattr->attlen,
> + tp + off);
> + off += cattr->attlen;
>
> Shouldn't this be att_nominal_alignby, like above in the previous loop?
>
> There's one more typo in "This loops only differs"
Fixed both. I'll send an updated set of patches shortly.
Many thanks for reviewing.
David
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
On Thu, 26 Feb 2026 at 09:29, Andres Freund wrote:
> Huh. It, at least partially, seems to be related to using an integer for
> attnum et al. Due to us using -fwrapv, the compiler can't actually assume that
> an attnum++ won't overflow. An overflow would make the loop trip counts a lot
> more complicated. Even with that I don't understand how it ends up
> generating such crappy code, but since using size_t fixes it...
Thanks. That seems to make the gcc compiled version quite a bit better.
I am still seeing a bit of register overflow as the TupleDesc is
written to the stack and reloaded back into a register a couple of
times. I've attached the objdump in question.
if (attnum < firstNonGuaranteedAttr)
1c3c: 48 39 e8 cmp rax,rbp
1c3f: 73 7f jae 1cc0
1c41: 48 89 54 24 f0 mov QWORD PTR [rsp-0x10],rdx
1c46: 48 8d 74 c2 20 lea rsi,[rdx+rax*8+0x20]
the tupledesc is put back into the register in:
off += cattr->attlen;
1f88: 48 8b 54 24 f0 mov rdx,QWORD PTR [rsp-0x10]
I've not found a way to have gcc not do this.
I've also resequenced the patches so 0002 contains the sibling call
optimisation for slot_getmissingattrs() and I've applied that tail
call optimisation that you mentioned for slot_getmissingattrs() in
0004.
I've attached benchmark results in the attached spreadsheet.
David
Re: More speedups for tuple deformation
One of my goals for proactively populating
CompactAttribute.attcacheoff is to make it so we're able to support
deforming only a subset of columns. If we only need a small number of
columns from the tuple and all those columns have a known attcacheoff
and no NULLs come prior, then we can quite efficiently just go to
those cached offsets and fetch only the attributes that we need. To
do this, we'll need an extra array to store which attnums we're
interested in, rather than deforming all attrs up to the highest
attnum that we need, as we do today. I expect that looking at this
new array will slow things down a bit when we're accessing either most
or all columns in, say, a SELECT * query. So, IMO, it'd be bad to
*replace* the current deforming code with code which does this.
Instead, I propose we add an additional deform operator and have some
heuristic which decides which one is best to use. I expect
ExecPushExprSetupSteps() could make that choice fairly easily. Perhaps
something cheap like bms_num_members(scan_attrs) is less than half the
bms_prev_member(scan_attrs, -1) (the highest member).
There's going to be many cases where the attcacheoff isn't known in
the attributes being selected. So that we still get some gains when
that's the case, I've coded it up so that we start walking the tuple
at the last attribute that has an attcacheoff. In many cases, that'll
mean we don't need to walk the entire tuple. Often, leading columns
are fixed-width, so this means that there's likely some benefit to
most cases. There might need to be a bit more education or
documentation about best column ordering practises.
There are a few hurdles to make this work, and one is the physical
tlist optimization. If the planner replaces the targetlist with a
physical tlist, the executor is going to think we need all columns,
which would have it likely choose not to do the selective deforming.
To make this work, I've added some code in createplan.c to extract the
attnums we need from the qual and tlist before the physical tlist is
installed. That's recorded in a Bitmapset and passed down to the
executor and to the code which sets up the ExprStates. Currently,
mostly to exercise this code as much as possible, I've coded it to
always do the selective deforming when the Bitmapset isn't empty. So
far, I've only done this for Seq Scan, but I expect all the scans that
deform tuples could use this.
I've attached the code which does all this in the 0006 patch.
Ideally, I'd have had this at least to the current state about 2-3
months ago, so I don't intend that 0006 is v19 material, but I wanted
to share to show where I intend this work to go.
Performance:
Using the t_1_40 table from the deform_test_setup.sh script I sent in
[1], running "select a from t_1_40 where a = 0;" ("a" is the 43rd
column in that table), on my Zen2 machine, I get the following from
perf top and pgbench:
master:
75.57% postgres [.] tts_buffer_heap_getsomeattrs
4.70% postgres [.] ExecInterpExpr
2.85% postgres [.] ExecSeqScanWithQualProject
1.94% postgres [.] heapgettup_pagemode
1.21% postgres [.] UnlockBuffer
1.15% postgres [.] slot_getsomeattrs_int
$ for i in {1..3}; do pgbench -n -f bench.sql -M prepared -T 10
postgres | grep latency; done
latency average = 154.175 ms
latency average = 156.780 ms
latency average = 157.599 ms
0001-0005:
64.24% postgres [.] tts_buffer_heap_getsomeattrs
15.01% postgres [.] ExecInterpExpr
3.22% postgres [.] ExecSeqScanWithQualProject
3.01% postgres [.] heapgettup_pagemode
1.57% postgres [.] ExecStoreBufferHeapTuple
1.53% postgres [.] heap_prepare_pagescan
$ for i in {1..3}; do pgbench -n -f bench.sql -M prepared -T 10
postgres | grep latency; done
latency average = 130.981 ms
latency average = 134.700 ms
latency average = 134.898 ms
0001-0006:
42.28% postgres [.] heapgettup_pagemode
11.38% postgres [.] ExecInterpExpr
7.13% postgres [.] ExecSeqScanWithQualProject
5.92% postgres [.] tts_buffer_heap_selectattrs <-- it's down here.
5.69% postgres [.] ExecStoreBufferHeapTuple
5.11% postgres [.] heap_getnextslot
3.87% postgres [.] heap_prepare_pagescan
$ for i in {1..3}; do pgbench -n -f bench.sql -M prepared -T 10
postgres | grep latency; done
latency average = 71.689 ms
latency average = 75.638 ms
latency average = 75.149 ms
Keep in mind that this is one of the best cases as t_1_40 has no NULLs
and only has fixed-width columns. The only slightly better case would
be to add more columns and fetch only the final one. 40 doesn't seem
excessively unrealistic, to get an idea of the gains that someone
*could* see.
You can see that perf top report that tts_buffer_heap_getsomeattrs
dropped from taking 75.57% down to 64.24% with 0001-0005. Adding 0006
sees that replaced with tts_buffer_heap_selectattrs which takes less
than 6% of the CPU time. It also highlights the next most interesting
thing we should probably make faster, heapgettup_pagemode().
I've attached v12 of the patch. There are a few changes in 0001-0005
that should help make things a bit faster than v11. I've also attached
the new selective deforming code in 0006. There's no JIT support for
0006 yet, I don't need to be told about that :-)
I'm planning on starting to go through 0002-0005 in much more detail
from mid next week with my committer hat on. If anyone wants to relook
at any of the 0002-0005 patches, there's still time. I'm also happy to
receive feedback on 0006, but I will address concerns with that at a
lower priority. One thing that's still left todo in the 0004 patch is
enable the TTS_FLAG_OBEYS_NOT_NULL_CONSTRAINTS optimisation for a few
other scan types.
Thanks for reading
David
[1] https://postgr.es/m/CAApHDvo1i-ycAcWnK3L7ZASTuM8mW46kvRqMaUHD46HSuJmx7A@mail.gmail.com
Re: More speedups for tuple deformation
От:
Junwang Zhao <zhjwpku@gmail.com>
Дата:
Hi David,
On Fri, Mar 6, 2026 at 12:10 PM David Rowley wrote:
>
> One of my goals for proactively populating
> CompactAttribute.attcacheoff is to make it so we're able to support
> deforming only a subset of columns. If we only need a small number of
> columns from the tuple and all those columns have a known attcacheoff
> and no NULLs come prior, then we can quite efficiently just go to
> those cached offsets and fetch only the attributes that we need. To
> do this, we'll need an extra array to store which attnums we're
> interested in, rather than deforming all attrs up to the highest
> attnum that we need, as we do today. I expect that looking at this
> new array will slow things down a bit when we're accessing either most
> or all columns in, say, a SELECT * query. So, IMO, it'd be bad to
> *replace* the current deforming code with code which does this.
> Instead, I propose we add an additional deform operator and have some
> heuristic which decides which one is best to use. I expect
> ExecPushExprSetupSteps() could make that choice fairly easily. Perhaps
> something cheap like bms_num_members(scan_attrs) is less than half the
> bms_prev_member(scan_attrs, -1) (the highest member).
>
> There's going to be many cases where the attcacheoff isn't known in
> the attributes being selected. So that we still get some gains when
> that's the case, I've coded it up so that we start walking the tuple
> at the last attribute that has an attcacheoff. In many cases, that'll
> mean we don't need to walk the entire tuple. Often, leading columns
> are fixed-width, so this means that there's likely some benefit to
> most cases. There might need to be a bit more education or
> documentation about best column ordering practises.
>
> There are a few hurdles to make this work, and one is the physical
> tlist optimization. If the planner replaces the targetlist with a
> physical tlist, the executor is going to think we need all columns,
> which would have it likely choose not to do the selective deforming.
> To make this work, I've added some code in createplan.c to extract the
> attnums we need from the qual and tlist before the physical tlist is
> installed. That's recorded in a Bitmapset and passed down to the
> executor and to the code which sets up the ExprStates. Currently,
> mostly to exercise this code as much as possible, I've coded it to
> always do the selective deforming when the Bitmapset isn't empty. So
> far, I've only done this for Seq Scan, but I expect all the scans that
> deform tuples could use this.
>
> I've attached the code which does all this in the 0006 patch.
> Ideally, I'd have had this at least to the current state about 2-3
> months ago, so I don't intend that 0006 is v19 material, but I wanted
> to share to show where I intend this work to go.
>
> Performance:
>
> Using the t_1_40 table from the deform_test_setup.sh script I sent in
> [1], running "select a from t_1_40 where a = 0;" ("a" is the 43rd
> column in that table), on my Zen2 machine, I get the following from
> perf top and pgbench:
>
> master:
> 75.57% postgres [.] tts_buffer_heap_getsomeattrs
> 4.70% postgres [.] ExecInterpExpr
> 2.85% postgres [.] ExecSeqScanWithQualProject
> 1.94% postgres [.] heapgettup_pagemode
> 1.21% postgres [.] UnlockBuffer
> 1.15% postgres [.] slot_getsomeattrs_int
>
> $ for i in {1..3}; do pgbench -n -f bench.sql -M prepared -T 10
> postgres | grep latency; done
> latency average = 154.175 ms
> latency average = 156.780 ms
> latency average = 157.599 ms
>
> 0001-0005:
> 64.24% postgres [.] tts_buffer_heap_getsomeattrs
> 15.01% postgres [.] ExecInterpExpr
> 3.22% postgres [.] ExecSeqScanWithQualProject
> 3.01% postgres [.] heapgettup_pagemode
> 1.57% postgres [.] ExecStoreBufferHeapTuple
> 1.53% postgres [.] heap_prepare_pagescan
>
> $ for i in {1..3}; do pgbench -n -f bench.sql -M prepared -T 10
> postgres | grep latency; done
> latency average = 130.981 ms
> latency average = 134.700 ms
> latency average = 134.898 ms
>
> 0001-0006:
> 42.28% postgres [.] heapgettup_pagemode
> 11.38% postgres [.] ExecInterpExpr
> 7.13% postgres [.] ExecSeqScanWithQualProject
> 5.92% postgres [.] tts_buffer_heap_selectattrs <-- it's down here.
> 5.69% postgres [.] ExecStoreBufferHeapTuple
> 5.11% postgres [.] heap_getnextslot
> 3.87% postgres [.] heap_prepare_pagescan
>
> $ for i in {1..3}; do pgbench -n -f bench.sql -M prepared -T 10
> postgres | grep latency; done
> latency average = 71.689 ms
> latency average = 75.638 ms
> latency average = 75.149 ms
>
> Keep in mind that this is one of the best cases as t_1_40 has no NULLs
> and only has fixed-width columns. The only slightly better case would
> be to add more columns and fetch only the final one. 40 doesn't seem
> excessively unrealistic, to get an idea of the gains that someone
> *could* see.
>
> You can see that perf top report that tts_buffer_heap_getsomeattrs
> dropped from taking 75.57% down to 64.24% with 0001-0005. Adding 0006
> sees that replaced with tts_buffer_heap_selectattrs which takes less
> than 6% of the CPU time. It also highlights the next most interesting
> thing we should probably make faster, heapgettup_pagemode().
>
> I've attached v12 of the patch. There are a few changes in 0001-0005
> that should help make things a bit faster than v11. I've also attached
> the new selective deforming code in 0006. There's no JIT support for
> 0006 yet, I don't need to be told about that :-)
>
> I'm planning on starting to go through 0002-0005 in much more detail
> from mid next week with my committer hat on. If anyone wants to relook
> at any of the 0002-0005 patches, there's still time. I'm also happy to
I have some comments on v12-0004.
1.
+ off += cattr->attlen;
+ firstNonCachedOffsetAttr = i + 1;
+ }
+
+ tupdesc->firstNonCachedOffsetAttr = firstNonCachedOffsetAttr;
+ tupdesc->firstNonGuaranteedAttr = firstNonGuaranteedAttr;
+}
The firstNonCachedOffsetAttr seems to be the first variable width
attribute, but it seems that the offset of this attribute can be cached,
for example, in a table defined as (int, text), the offset of
firstNonCachedOffsetAttr should be 4, is that correct?
If TupleDescFinalize records the offset firstNonCachedOffsetAttr,
it might save one iterator of the deforming loop. For example,
add something like the following after the above mentioned code.
if (firstNonCachedOffsetAttr < tupdesc->natts)
{
cattr = TupleDescCompactAttr(tupdesc, firstNonCachedOffsetAttr);
cattr->attcacheoff = off;
}
2.
in slot_deform_heap_tuple, there are multiple statements setting
firstNonCacheOffsetAttr,
+ firstNonCacheOffsetAttr = tupleDesc->firstNonCachedOffsetAttr;
+ /* We can only use any cached offsets until the first NULL attr */
+ firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr,
+ firstNullAttr);
+ /* We can only fetch as many attributes as the tuple has. */
+ firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, natts);
Based on the logic, it seems the second one could be moved
to the third position, and the third one could then be safely
removed?
> receive feedback on 0006, but I will address concerns with that at a
> lower priority. One thing that's still left todo in the 0004 patch is
> enable the TTS_FLAG_OBEYS_NOT_NULL_CONSTRAINTS optimisation for a few
> other scan types.
>
> Thanks for reading
>
> David
>
> [1] https://postgr.es/m/CAApHDvo1i-ycAcWnK3L7ZASTuM8mW46kvRqMaUHD46HSuJmx7A@mail.gmail.com
--
Regards
Junwang Zhao
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
Thanks for having a look.
On Sun, 8 Mar 2026 at 05:36, Junwang Zhao wrote:
> I have some comments on v12-0004.
>
> 1.
>
> + off += cattr->attlen;
> + firstNonCachedOffsetAttr = i + 1;
> + }
> +
> + tupdesc->firstNonCachedOffsetAttr = firstNonCachedOffsetAttr;
> + tupdesc->firstNonGuaranteedAttr = firstNonGuaranteedAttr;
> +}
>
> The firstNonCachedOffsetAttr seems to be the first variable width
> attribute, but it seems that the offset of this attribute can be cached,
> for example, in a table defined as (int, text), the offset of
> firstNonCachedOffsetAttr should be 4, is that correct?
Yes.
> If TupleDescFinalize records the offset firstNonCachedOffsetAttr,
> it might save one iterator of the deforming loop. For example,
> add something like the following after the above mentioned code.
>
> if (firstNonCachedOffsetAttr < tupdesc->natts)
> {
> cattr = TupleDescCompactAttr(tupdesc, firstNonCachedOffsetAttr);
> cattr->attcacheoff = off;
> }
The problem is that short varlenas have 1 byte alignment and normal
varlenas have 4 byte alignment. It might be possible to do something
if the previous column is 4-byte aligned and has a length of 4 or 8,
since that means the offset must also be 1-byte aligned. The main
reason I don't want to do this is that the only positive is that
*maybe* 1 extra column can be deformed with a fixed offset. The
drawback is that the following code *has* to use
att_addlength_pointer(), *regardless* instead of "off += attlen;".
This means more deforming code and more complexity in
TupleDescFinalize(). I'd rather not do this.
> 2.
>
> in slot_deform_heap_tuple, there are multiple statements setting
> firstNonCacheOffsetAttr,
>
> + firstNonCacheOffsetAttr = tupleDesc->firstNonCachedOffsetAttr;
>
> + /* We can only use any cached offsets until the first NULL attr */
> + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr,
> + firstNullAttr);
>
> + /* We can only fetch as many attributes as the tuple has. */
> + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, natts);
>
> Based on the logic, it seems the second one could be moved
> to the third position, and the third one could then be safely
> removed?
Yeah. Well spotted. I've done that in the attached.
I've also modified the 0006 patch to add a new deform_bench_select()
function which allows the benchmark to call the new selective deform
function. See the attached graphs comparing master to v13-0001-0005
and master to v13-0001-0006. It's good to see that there's still quite
a large speedup even from the tests that don't have an attcacheoff for
the column being deformed. Tests 1 and 5 do have a attcacheoff for the
column deformed, so they're a good bit faster again. To get the
0001-0006 results, I used the deform_test_run.sh script from [1] and
modified it to call deform_bench_select() instead of deform_bench().
I also noticed that when building with older gcc versions, I was
getting warnings about attlen and 'off' not being initialised. I ended
up switching back to the do/while loops to fix that rather than adding
needless initialisation, which would add overhead. 1 loop is
guaranteed, and the older compiler is not clever enough to work that
out.
David
[1] https://postgr.es/m/CAApHDvo1i-ycAcWnK3L7ZASTuM8mW46kvRqMaUHD46HSuJmx7A@mail.gmail.com
Re: More speedups for tuple deformation
От:
Junwang Zhao <zhjwpku@gmail.com>
Дата:
On Fri, Mar 13, 2026 at 8:19 PM David Rowley wrote:
>
> Thanks for having a look.
>
>
> On Sun, 8 Mar 2026 at 05:36, Junwang Zhao wrote:
> > I have some comments on v12-0004.
> >
> > 1.
> >
> > + off += cattr->attlen;
> > + firstNonCachedOffsetAttr = i + 1;
> > + }
> > +
> > + tupdesc->firstNonCachedOffsetAttr = firstNonCachedOffsetAttr;
> > + tupdesc->firstNonGuaranteedAttr = firstNonGuaranteedAttr;
> > +}
> >
> > The firstNonCachedOffsetAttr seems to be the first variable width
> > attribute, but it seems that the offset of this attribute can be cached,
> > for example, in a table defined as (int, text), the offset of
> > firstNonCachedOffsetAttr should be 4, is that correct?
>
> Yes.
>
> > If TupleDescFinalize records the offset firstNonCachedOffsetAttr,
> > it might save one iterator of the deforming loop. For example,
> > add something like the following after the above mentioned code.
> >
> > if (firstNonCachedOffsetAttr < tupdesc->natts)
> > {
> > cattr = TupleDescCompactAttr(tupdesc, firstNonCachedOffsetAttr);
> > cattr->attcacheoff = off;
> > }
>
> The problem is that short varlenas have 1 byte alignment and normal
> varlenas have 4 byte alignment. It might be possible to do something
> if the previous column is 4-byte aligned and has a length of 4 or 8,
> since that means the offset must also be 1-byte aligned. The main
> reason I don't want to do this is that the only positive is that
> *maybe* 1 extra column can be deformed with a fixed offset. The
> drawback is that the following code *has* to use
> att_addlength_pointer(), *regardless* instead of "off += attlen;".
> This means more deforming code and more complexity in
> TupleDescFinalize(). I'd rather not do this.
That explains, thanks.
>
> > 2.
> >
> > in slot_deform_heap_tuple, there are multiple statements setting
> > firstNonCacheOffsetAttr,
> >
> > + firstNonCacheOffsetAttr = tupleDesc->firstNonCachedOffsetAttr;
> >
> > + /* We can only use any cached offsets until the first NULL attr */
> > + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr,
> > + firstNullAttr);
> >
> > + /* We can only fetch as many attributes as the tuple has. */
> > + firstNonCacheOffsetAttr = Min(firstNonCacheOffsetAttr, natts);
> >
> > Based on the logic, it seems the second one could be moved
> > to the third position, and the third one could then be safely
> > removed?
>
> Yeah. Well spotted. I've done that in the attached.
>
> I've also modified the 0006 patch to add a new deform_bench_select()
> function which allows the benchmark to call the new selective deform
> function. See the attached graphs comparing master to v13-0001-0005
> and master to v13-0001-0006. It's good to see that there's still quite
> a large speedup even from the tests that don't have an attcacheoff for
> the column being deformed. Tests 1 and 5 do have a attcacheoff for the
> column deformed, so they're a good bit faster again. To get the
> 0001-0006 results, I used the deform_test_run.sh script from [1] and
> modified it to call deform_bench_select() instead of deform_bench().
>
> I also noticed that when building with older gcc versions, I was
> getting warnings about attlen and 'off' not being initialised. I ended
> up switching back to the do/while loops to fix that rather than adding
> needless initialisation, which would add overhead. 1 loop is
> guaranteed, and the older compiler is not clever enough to work that
> out.
>
> David
>
> [1] https://postgr.es/m/CAApHDvo1i-ycAcWnK3L7ZASTuM8mW46kvRqMaUHD46HSuJmx7A@mail.gmail.com
--
Regards
Junwang Zhao
Re: More speedups for tuple deformation
От:
Tender Wang <tndrwang@gmail.com>
Дата:
Hi David,
After c456e391138, I found a crash.
How to reproduce:
psql (19devel)
Type "help" for help.
postgres=# CREATE TABLE t0 (
c0 double precision,
c1 int4range
);
INSERT INTO public.t0 VALUES (0.013077308, '[160364071,527006655)');
INSERT INTO public.t0 VALUES (0.2488792, NULL);
INSERT INTO public.t0 VALUES ('Infinity', '[-477016999,529396556)');
INSERT INTO public.t0 VALUES (0.2687647, '[-1356493040,71686839)');
INSERT INTO public.t0 VALUES (-2019956220, NULL);
INSERT INTO public.t0 VALUES (NULL, '[-1645797683,476242219)');
INSERT INTO public.t0 VALUES (0.64798653, NULL);
INSERT INTO public.t0 VALUES (0.70265657, NULL);
INSERT INTO public.t0 VALUES (0.31205487, NULL);
INSERT INTO public.t0 VALUES (0.43003803, '[-1973503943,635641598)');
INSERT INTO public.t0 VALUES (0.7500011, '[516760684,870974126)');
INSERT INTO public.t0 VALUES (0, '[-1666589420,-456062869)');
INSERT INTO public.t0 VALUES (NULL, '[-1328295821,1687052919)');
INSERT INTO public.t0 VALUES (NULL, '[-81427373,1340586611)');
INSERT INTO public.t0 VALUES (NULL, '[1469060470,1895771979)');
CREATE TABLE t2 (
c0 bigint,
c1 bigint CONSTRAINT t1_c1_not_null NOT NULL
);
INSERT INTO public.t2 VALUES (NULL, 23);
INSERT INTO public.t2 VALUES (622289345, 15);
CREATE TABLE t4 (
c0 boolean,
c1 boolean,
CONSTRAINT t4_c0_check CHECK (c0)
);
INSERT INTO public.t4 VALUES (true, true);
SELECT * FROM t2, t4 RIGHT OUTER JOIN t0 ON t4.c0 WHERE t4.c1 ORDER BY
t4.c0, t0.c1;
CREATE TABLE
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
CREATE TABLE
INSERT 0 1
INSERT 0 1
CREATE TABLE
INSERT 0 1
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Succeeded.
postgres=# \q
git bisect shows c456e391138 is the first bad commit.
Please take a look.
--
Thanks,
Tender Wang
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Mon, 16 Mar 2026 at 20:01, Tender Wang wrote: > SELECT * FROM t2, t4 RIGHT OUTER JOIN t0 ON t4.c0 WHERE t4.c1 ORDER BY > server closed the connection unexpectedly Thanks. Looks like I didn't get the startAttr logic correct in nocachegetattr(). Starting by using the attcacheoff of the first NULL attribute isn't valid. It should be the attribute prior to that one. I'm just verifying some code locally now. David
Re: More speedups for tuple deformation
Hi David and Tender, On Mon, Mar 16, 2026 at 5:17 PM David Rowley wrote: > > On Mon, 16 Mar 2026 at 20:01, Tender Wang wrote: > > SELECT * FROM t2, t4 RIGHT OUTER JOIN t0 ON t4.c0 WHERE t4.c1 ORDER BY > > > server closed the connection unexpectedly > > Thanks. Looks like I didn't get the startAttr logic correct in > nocachegetattr(). Starting by using the attcacheoff of the first NULL > attribute isn't valid. It should be the attribute prior to that one. > > I'm just verifying some code locally now. > > David > > The following case is more simpler: drop table if exists ty; create table ty(c0 int not null, c1 double precision, c2 int4range); insert into ty values (1, 1.0, '[1469060470,1895771979)'); insert into ty values(2, null, '[-1973503943,635641598)'); select * from ty order by c2; In this case, firstNonCachedOffsetAttr is 2 and firstNullAttr is 1. If we start from 1, the cached offset becomes 8 due to double's alignby, and deforming int4range from offset 8 will lead to corrupted data. Therefore, as David said, we should start from the attribute prior to that one. PFA is a trivial fix, I think we should add the test but I haven't found a proper regress test file for it. -- Regards Junwang Zhao
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Mon, 16 Mar 2026 at 22:17, David Rowley wrote:
>
> On Mon, 16 Mar 2026 at 20:01, Tender Wang wrote:
> > SELECT * FROM t2, t4 RIGHT OUTER JOIN t0 ON t4.c0 WHERE t4.c1 ORDER BY
>
> > server closed the connection unexpectedly
>
> Thanks. Looks like I didn't get the startAttr logic correct in
> nocachegetattr(). Starting by using the attcacheoff of the first NULL
> attribute isn't valid. It should be the attribute prior to that one.
>
> I'm just verifying some code locally now.
Now pushed. Some concerns about the lack of exercise in the tests for
fastgetattr() for user tables. I ended up testing by injecting the
following into slot_deform_heap_tuple()
- attnum = slot->tts_nvalid;
+ attnum2 = attnum = slot->tts_nvalid;
[...]
+ for (attnum = attnum2; attnum < natts; attnum++)
+ {
+ Datum v = values[attnum];
+ bool b = isnull[attnum];
+ values[attnum] = fastgetattr(tuple, attnum + 1, tupleDesc,
&isnull[attnum]);
+ Assert(v == values[attnum]);
+ Assert(b == isnull[attnum]);
+ }
+
/* Fetch any missing attrs and raise an error if reqnatts is invalid */
if (unlikely(attnum < reqnatts))
Still considering the best way to get a bit more coverage more permanently.
David
Re: More speedups for tuple deformation
От:
Tender Wang <tndrwang@gmail.com>
Дата:
Hi David,
David Rowley 于2026年3月17日周二 05:15写道:
>
> On Mon, 16 Mar 2026 at 22:17, David Rowley wrote:
> >
> > On Mon, 16 Mar 2026 at 20:01, Tender Wang wrote:
> > > SELECT * FROM t2, t4 RIGHT OUTER JOIN t0 ON t4.c0 WHERE t4.c1 ORDER BY
> >
> > > server closed the connection unexpectedly
> >
> > Thanks. Looks like I didn't get the startAttr logic correct in
> > nocachegetattr(). Starting by using the attcacheoff of the first NULL
> > attribute isn't valid. It should be the attribute prior to that one.
> >
> > I'm just verifying some code locally now.
>
> Now pushed. Some concerns about the lack of exercise in the tests for
> fastgetattr() for user tables. I ended up testing by injecting the
> following into slot_deform_heap_tuple()
I encountered a crash when doing SQLSmith on TPCH (s=1) test.
How to reproduce:
1. prepare TPCH s =1 data.
2. Execute the following query
postgres=# update public.region set
r_comment = public.region.r_comment
returning
5 as c0,
pg_catalog.bittypmodout(
cast(public.region.r_regionkey as int4)) as c1;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Succeeded.
(gdb) bt
#0 __pthread_kill_implementation (no_tid=0, signo=6,
threadid=140696004203456) at ./nptl/pthread_kill.c:44
#1 __pthread_kill_internal (signo=6, threadid=140696004203456) at
./nptl/pthread_kill.c:78
#2 __GI___pthread_kill (threadid=140696004203456,
signo=signo@entry=6) at ./nptl/pthread_kill.c:89
#3 0x00007ff659450476 in __GI_raise (sig=sig@entry=6) at
../sysdeps/posix/raise.c:26
#4 0x00007ff6594367f3 in __GI_abort () at ./stdlib/abort.c:79
#5 0x000055d8ae8cad94 in ExceptionalCondition
(conditionName=0x55d8aeac5beb "attlen > 0 || attlen == -1",
fileName=0x55d8aeac5a18 "execTuples.c", lineNumber=1197) at
assert.c:65
#6 0x000055d8ae3afa2e in slot_deform_heap_tuple (slot=0x55d8cabf1a58,
tuple=0x55d8cabf1ab0, offp=0x55d8cabf1ac8, reqnatts=2) at
execTuples.c:1197
#7 0x000055d8ae3ae853 in tts_minimal_getsomeattrs
(slot=0x55d8cabf1a58, natts=2) at execTuples.c:550
#8 0x000055d8ae06ac3b in slot_getsomeattrs (slot=0x55d8cabf1a58,
attnum=2) at ../../../../src/include/executor/tuptable.h:380
#9 0x000055d8ae06ac62 in slot_getallattrs (slot=0x55d8cabf1a58) at
../../../../src/include/executor/tuptable.h:392
#10 0x000055d8ae06b5f5 in printtup (slot=0x55d8cabf1a58,
self=0x55d8cab11828) at printtup.c:319
#11 0x000055d8ae6bfd82 in RunFromStore (portal=0x55d8cab860a0,
direction=ForwardScanDirection, count=0, dest=0x55d8cab11828) at
pquery.c:1089
#12 0x000055d8ae6bf88b in PortalRunSelect (portal=0x55d8cab860a0,
forward=true, count=0, dest=0x55d8cab11828) at pquery.c:912
#13 0x000055d8ae6bf4ea in PortalRun (portal=0x55d8cab860a0,
count=9223372036854775807, isTopLevel=true, dest=0x55d8cab11828,
altdest=0x55d8cab11828, qc=0x7ffe1b92e4f0) at pquery.c:760
#14 0x000055d8ae6b7c2b in exec_simple_query (
query_string=0x55d8caadb4b0 "update public.region set \n
r_comment = public.region.r_comment\n returning \n 5
as c0, \n pg_catalog.bittypmodout(\n", ' ' , "cast(public.region.r_regionkey as int4)) a"...)
at postgres.c:1278
#15 0x000055d8ae6bd47b in PostgresMain (dbname=0x55d8cab218d0
"postgres", username=0x55d8cab218b8 "ubuntu") at postgres.c:4810
#16 0x000055d8ae6b3068 in BackendMain (startup_data=0x7ffe1b92e7a0,
startup_data_len=24) at backend_startup.c:124
#17 0x000055d8ae5a17a6 in postmaster_child_launch
(child_type=B_BACKEND, child_slot=2, startup_data=0x7ffe1b92e7a0,
startup_data_len=24, client_sock=0x7ffe1b92e800) at
launch_backend.c:268
#18 0x000055d8ae5a8290 in BackendStartup (client_sock=0x7ffe1b92e800)
at postmaster.c:3606
#19 0x000055d8ae5a57d2 in ServerLoop () at postmaster.c:1713
#20 0x000055d8ae5a509c in PostmasterMain (argc=3, argv=0x55d8caad5b30)
at postmaster.c:1403
#21 0x000055d8ae430b37 in main (argc=3, argv=0x55d8caad5b30) at main.c:231
(gdb) f 6
#6 0x000055d8ae3afa2e in slot_deform_heap_tuple (slot=0x55d8cabf1a58,
tuple=0x55d8cabf1ab0, offp=0x55d8cabf1ac8, reqnatts=2) at
execTuples.c:1197
1197 pg_assume(attlen > 0 || attlen == -1);
(gdb) p attlen
$1 = -2
Please take a look.
--
Thanks,
Tender Wang
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Fri, 20 Mar 2026, 01:39 Tender Wang, <tndrwang@gmail.com> wrote:
Hi David,
David Rowley <dgrowleyml@gmail.com> 于2026年3月17日周二 05:15写道:
>
> On Mon, 16 Mar 2026 at 22:17, David Rowley <dgrowleyml@gmail.com> wrote:
> >
> > On Mon, 16 Mar 2026 at 20:01, Tender Wang <tndrwang@gmail.com> wrote:
postgres=# update public.region set
r_comment = public.region.r_comment
returning
5 as c0,
pg_catalog.bittypmodout(
cast(public.region.r_regionkey as int4)) as c1;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Succeeded.
(gdb) bt
1197 pg_assume(attlen > 0 || attlen == -1);
(gdb) p attlen
$1 = -2
Thanks for the report. I'll look in detail in the morning when I'm at my computer again. I guess i'll need to add an extra parameter (that will be constant folded away during the inlining) to the deformed function to specify if cstrings can exist in the tuple, which seemingly needs to be true when deforming minimal tuples. I'd rather not lose that optimisation with heap tuples.
David
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Fri, 20 Mar 2026 at 01:56, David Rowley wrote: > > On Fri, 20 Mar 2026, 01:39 Tender Wang, wrote: >> 1197 pg_assume(attlen > 0 || attlen == -1); >> (gdb) p attlen >> $1 = -2 > > > Thanks for the report. I'll look in detail in the morning when I'm at my computer again. I guess i'll need to add an extra parameter (that will be constant folded away during the inlining) to the deformed function to specify if cstrings can exist in the tuple, which seemingly needs to be true when deforming minimal tuples. I'd rather not lose that optimisation with heap tuples. I've pushed a fix for this. A more simple recreator was: with cte as materialized (select relname::cstring as relname from pg_class) select relname from cte; David
Re: More speedups for tuple deformation
От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello David,
16.03.2026 09:01, Tender Wang wrote:
> Hi David,
>
> After c456e391138, I found a crash.
I've also found an assertion failure:
SELECT JSON_ARRAY(VALUES (('', '')));
triggers:
TRAP: failed Assert("attlen > 0 || attlen == -1"), File: "heaptuple.c", Line: 598, PID: 2582495
Could you have a look, please?
Best regards,
Alexander
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Wed, 1 Apr 2026 at 15:00, Alexander Lakhin wrote:
> I've also found an assertion failure:
> SELECT JSON_ARRAY(VALUES (('', '')));
>
> triggers:
> TRAP: failed Assert("attlen > 0 || attlen == -1"), File: "heaptuple.c", Line: 598, PID: 2582495
>
> Could you have a look, please?
Thanks. Looking...
David
Re: More speedups for tuple deformation
От:
Junwang Zhao <zhjwpku@gmail.com>
Дата:
On Wed, Apr 1, 2026 at 11:35 AM David Rowley wrote:
>
> On Wed, 1 Apr 2026 at 15:00, Alexander Lakhin wrote:
> > I've also found an assertion failure:
> > SELECT JSON_ARRAY(VALUES (('', '')));
> >
> > triggers:
> > TRAP: failed Assert("attlen > 0 || attlen == -1"), File: "heaptuple.c", Line: 598, PID: 2582495
> >
> > Could you have a look, please?
>
> Thanks. Looking...
The parser transforms '' (or any cstring) into Const with UNKNOWNOID.
When building the tuple descriptor in ExecTypeFromExprList,
TupleDescInitEntry uses UNKNOWNOID to populate the attribute entry,
thus the failure in nocachegetattr.
Therefore, the assertion should be addressed by removing the pg_assume,
since this case can occur.
Just trying to learn through analysis, might be incorrect. Let's wait for
David's fix.
>
> David
>
>
--
Regards
Junwang Zhao
Re: More speedups for tuple deformation
От:
jian he <jian.universality@gmail.com>
Дата:
On Wed, Apr 1, 2026 at 1:13 PM Junwang Zhao wrote:
>
> The parser transforms '' (or any cstring) into Const with UNKNOWNOID.
> When building the tuple descriptor in ExecTypeFromExprList,
> TupleDescInitEntry uses UNKNOWNOID to populate the attribute entry,
> thus the failure in nocachegetattr.
>
> Therefore, the assertion should be addressed by removing the pg_assume,
> since this case can occur.
>
> Just trying to learn through analysis, might be incorrect. Let's wait for
> David's fix.
>
HI.
You can also trigger it via:
SELECT row_to_json(('', ''));
In transformRowExpr, we can coerce these UNKNOWNOID Const to TEXTOID Const.
But I guess it's harder to guarantee that comment "cstrings don't
exist in heap tuples." in nocachegetattr to be true.
--
jian
https://www.enterprisedb.com/
Re: More speedups for tuple deformation
От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Wed, 1 Apr 2026 at 16:35, David Rowley wrote:
>
> On Wed, 1 Apr 2026 at 15:00, Alexander Lakhin wrote:
> > I've also found an assertion failure:
> > SELECT JSON_ARRAY(VALUES (('', '')));
> >
> > triggers:
> > TRAP: failed Assert("attlen > 0 || attlen == -1"), File: "heaptuple.c", Line: 598, PID: 2582495
> >
> > Could you have a look, please?
>
> Thanks. Looking...
I've pushed a fix for this. Thanks for the report.
David