Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
Hey, this is my first patch for Postgres, so please let me know if I got something about the contribution policies wrong. Our main workload does a lot of index-only scans, and in perf profiles of it a good part of the time showed up under ExecScan(). Digging into the code I noticed that IndexScan, IndexOnlyScan and BitmapHeapScan all still go through the generic out-of-line ExecScan(). So each tuple pays for an indirect call to the access method and for the runtime EPQ / qual / projection checks. SeqScan got rid of that with fb9f95502 (and 83a53572a6f made sure SeqNext actually gets inlined). The attached patch does the same for index-only scans. There are now ExecIndexOnlyScan, ...WithQuals, ...WithProject, ...WithQualProject and ...EPQ, the variant is picked in ExecInitIndexOnlyScan(), and IndexOnlyNext() is pg_always_inline. The EPQ variant just calls ExecScan() like ExecSeqScanEPQ does. One thing that cost me bit more time: the runtime key setup (which may call ExecReScan()) has to happen before the pg_assume() calls. If it comes after, gcc can't know that pstate->qual is still non-NULL after the call, keeps the !qual && !projInfo branch of ExecScanExtended() and you end up with a second inlined copy of IndexOnlyNext() in each variant. I added a comment for that. Test setup: table with id int primary key and two more int columns, 5M rows, vacuumed so it's all-visible. enable_seqscan and enable_bitmapscan off, jit off, no parallel. gcc 12, -O2, i7-13700H. instructions latency SELECT count(*) FROM t WHERE id BETWEEN 1 AND 1000000 -5.2% -5 to -11% same, plus AND id % 3 = 0 -4.8% -3 to -5% SELECT id + 1 FROM t WHERE id BETWEEN 1 AND 1000000 OFFSET 2000000 -6.3% -4 to -10% Instructions are from callgrind (single user mode), so those are kinda deterministic. Latency is median pgbench latency over 5 interleaved rounds, server pinned to one P-core. It's a range because I ran everything a second time with -falign-functions=64 and the wall clock results moved by several percent just from the the layout change. So I wouldn't put too much weight on the exact latency numbers, but it was faster in all cases. tbh the code gets bigger: the per-tuple function is 576-858 bytes depending on the variant, and the IOS functions together go from ~0.6kB to ~3.5kB. Tests: regress and isolation pass with cassert, and CI on my github fork is green on all platforms. There is no existing test that runs an index-only scan under EPQ though. I checked that path manually with a correlated subquery in an UPDATE that has to wait for a concurrent update. I can turn that into an isolation test if people think it's worth it. any thoughts? Best, Matthias
Re: Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Wed, Oct 14, 2026 at 3:37 AM Matthias Dötsch wrote: > > Hey, > > this is my first patch for Postgres, so please let me know if I got > something about the contribution policies wrong. > > Our main workload does a lot of index-only scans, and in perf profiles of it > a good part of the time showed up under ExecScan(). Digging into the > code I noticed that IndexScan, IndexOnlyScan and BitmapHeapScan all > still go through the generic out-of-line ExecScan(). So each tuple pays > for an indirect call to the access method and for the runtime EPQ / > qual / projection checks. SeqScan got rid of that with fb9f95502 (and > 83a53572a6f made sure SeqNext actually gets inlined). > > The attached patch does the same for index-only scans. There are now > ExecIndexOnlyScan, ...WithQuals, ...WithProject, ...WithQualProject and > ...EPQ, the variant is picked in ExecInitIndexOnlyScan(), and > IndexOnlyNext() is pg_always_inline. The EPQ variant just calls > ExecScan() like ExecSeqScanEPQ does. > > One thing that cost me bit more time: the runtime key setup (which may call > ExecReScan()) has to happen before the pg_assume() calls. If it comes > after, gcc can't know that pstate->qual is still non-NULL after the > call, keeps the !qual && !projInfo branch of ExecScanExtended() and you > end up with a second inlined copy of IndexOnlyNext() in each variant. > I added a comment for that. > > Test setup: table with id int primary key and two more int columns, 5M > rows, vacuumed so it's all-visible. enable_seqscan and enable_bitmapscan > off, jit off, no parallel. gcc 12, -O2, i7-13700H. > > instructions latency > SELECT count(*) FROM t > WHERE id BETWEEN 1 AND 1000000 -5.2% -5 to -11% > same, plus AND id % 3 = 0 -4.8% -3 to -5% > SELECT id + 1 FROM t > WHERE id BETWEEN 1 AND 1000000 OFFSET 2000000 -6.3% -4 to -10% > > Instructions are from callgrind (single user mode), so those are kinda > deterministic. Latency is median pgbench latency over 5 interleaved > rounds, server pinned to one P-core. It's a range because I ran > everything a second time with -falign-functions=64 and the wall clock > results moved by several percent just from the the layout change. So I > wouldn't put too much weight on the exact latency numbers, but it was > faster in all cases. > > tbh the code gets bigger: the per-tuple function is 576-858 bytes depending > on the variant, and the IOS functions together go from ~0.6kB to > ~3.5kB. > > Tests: regress and isolation pass with cassert, and CI on my github > fork is green on all platforms. There is no existing test that runs an > index-only scan under EPQ though. I checked that path manually with a > correlated subquery in an UPDATE that has to wait for a concurrent > update. I can turn that into an isolation test if people think it's > worth it. > > > any thoughts? > > Best, > Matthias Hi Matthias, This looks like a natural extension of the ExecSeqScan specialization work, and the reduction in instruction count is encouraging. However, I wonder whether we should evaluate the broader tradeoffs before introducing more hand-specialized executor variants. While the optimization makes sense in isolation, I'm less certain about its long-term benefits relative to the additional code complexity and maintenance cost. In particular, it would be interesting to see how much of the improvement survives with LTO/PGO enabled. Both can help with inlining and code layout, potentially reducing the benefit of manual specialization. It would also be useful to measure the incremental gain with JIT expression compilation enabled, even though PostgreSQL's current JIT does not cover the scan loop itself. I'm also concerned about the cumulative code-size cost. The increase from roughly 0.6 KB to 3.5 KB may be acceptable for IndexOnlyScan alone, but applying the same approach to IndexScan, BitmapHeapScan, and other nodes could have broader implications for instruction-cache locality and maintainability. Finally, with ongoing work on batched execution and index access, I think it would be worth understanding whether these optimizations remain complementary or primarily target the same per-tuple overhead. In particular, if batching amortizes executor dispatch and function-call costs, how much additional benefit would specialization provide? I'm not suggesting that we should avoid this optimization. The existing ExecSeqScan work provides a reasonable precedent, and the results so far are promising. I'd just like to see a clearer picture of the incremental performance benefit and the longer-term maintenance implications before extending this pattern further. Thanks, Haibo
Re: Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-10-14 11:12:57 -0700, Haibo Yan wrote: > However, I wonder whether we should evaluate the broader tradeoffs > before introducing more hand-specialized executor variants. While > the optimization makes sense in isolation, I'm less certain about > its long-term benefits relative to the additional code complexity > and maintenance cost. > > In particular, it would be interesting to see how much of the > improvement survives with LTO/PGO enabled. Both can help with > inlining and code layout, potentially reducing the benefit of > manual specialization. I really don't see how it could obsolete the improvement in the patch (it could help at the same time obviously, but the patch should improve LTO and non-LTO). The compiler has no way of knowing that estate->es_epq_active, indexstate->ss.ps.qual, indexstate->ss.ps.ps_ProjInfo don't change during query execution, that's something only we know. It's possible that that some LTO implementations would end up inlining ExecSeqScan() and then convert the indirect function call to IndexOnlyNext() into a [potentially guarded] direct function call. But that's only a relatively small portion of the benefit of the specializations! There's is *some* support for speculative assumptions with PGO informed LTO, but to my knowledge that's for stuff like speculative devirtualization. I don't think it'd apply to anything like what we're dealing with here. But even if it did, it'd not help with specializations, as the problem is having to check all those branches in every IndexOnlyNext(), which in turn require a bunch of loads. > It would also be useful to measure the > incremental gain with JIT expression compilation enabled, even > though PostgreSQL's current JIT does not cover the scan loop itself. > I'm also concerned about the cumulative code-size cost. The > increase from roughly 0.6 KB to 3.5 KB may be acceptable for > IndexOnlyScan alone, but applying the same approach to IndexScan, > BitmapHeapScan, and other nodes could have broader implications > for instruction-cache locality and maintainability. Of course we shouldn't go overboard, but I'd expect this to *increase* icache locality in a broad range of use cases. Postgres' binary is way too big and our execution paths way too "wide" for relatively small increases in code size to harm meaningfully, when the same changes make the amount of code executed smaller in almost all cases. E.g. the EPQ handling code is never required in hot execution paths, and keeping that on separate cachelines will *increase* the actual icache effectiveness. > Finally, with ongoing work on batched execution and index access, > I think it would be worth understanding whether these optimizations > remain complementary or primarily target the same per-tuple > overhead. In particular, if batching amortizes executor dispatch > and function-call costs, how much additional benefit would > specialization provide? I think batching in ExecIndexOnlyScan() is unlikely to be very generally applicable anytime soon, because it's so often used in contexts like nested loops, where - unless you have a much more complicated join implementation - you will only want to fetch a single tuple on the inner side. I also think we're not that close to actually getting the batched execution stuff. And more importantly, even with the batched execution, and a lot of additional improvements, you'd *still* want specialization for having a qual, EPQ, projection, because checking them inside the loop over the tuples in the batch makes no sense. The only thing that'd actually be amortized is the indirect function call to *Next(). Greetings, Andres Freund
Re: Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
On Wed, Oct 14, 2026 at 12:14 PM Andres Freund wrote: > > Hi, > > On 2026-10-14 11:12:57 -0700, Haibo Yan wrote: > > However, I wonder whether we should evaluate the broader tradeoffs > > before introducing more hand-specialized executor variants. While > > the optimization makes sense in isolation, I'm less certain about > > its long-term benefits relative to the additional code complexity > > and maintenance cost. > > > > In particular, it would be interesting to see how much of the > > improvement survives with LTO/PGO enabled. Both can help with > > inlining and code layout, potentially reducing the benefit of > > manual specialization. > > I really don't see how it could obsolete the improvement in the patch (it > could help at the same time obviously, but the patch should improve LTO and > non-LTO). The compiler has no way of knowing that estate->es_epq_active, > indexstate->ss.ps.qual, indexstate->ss.ps.ps_ProjInfo don't change during > query execution, that's something only we know. > > It's possible that that some LTO implementations would end up inlining > ExecSeqScan() and then convert the indirect function call to IndexOnlyNext() > into a [potentially guarded] direct function call. But that's only a > relatively small portion of the benefit of the specializations! > > There's is *some* support for speculative assumptions with PGO informed LTO, > but to my knowledge that's for stuff like speculative devirtualization. I > don't think it'd apply to anything like what we're dealing with here. But even > if it did, it'd not help with specializations, as the problem is having to > check all those branches in every IndexOnlyNext(), which in turn require a > bunch of loads. > > > > It would also be useful to measure the > > incremental gain with JIT expression compilation enabled, even > > though PostgreSQL's current JIT does not cover the scan loop itself. > > > I'm also concerned about the cumulative code-size cost. The > > increase from roughly 0.6 KB to 3.5 KB may be acceptable for > > IndexOnlyScan alone, but applying the same approach to IndexScan, > > BitmapHeapScan, and other nodes could have broader implications > > for instruction-cache locality and maintainability. > > Of course we shouldn't go overboard, but I'd expect this to *increase* icache > locality in a broad range of use cases. Postgres' binary is way too big and > our execution paths way too "wide" for relatively small increases in code size > to harm meaningfully, when the same changes make the amount of code executed > smaller in almost all cases. E.g. the EPQ handling code is never required in > hot execution paths, and keeping that on separate cachelines will *increase* > the actual icache effectiveness. > > > > Finally, with ongoing work on batched execution and index access, > > I think it would be worth understanding whether these optimizations > > remain complementary or primarily target the same per-tuple > > overhead. In particular, if batching amortizes executor dispatch > > and function-call costs, how much additional benefit would > > specialization provide? > > I think batching in ExecIndexOnlyScan() is unlikely to be very generally > applicable anytime soon, because it's so often used in contexts like nested > loops, where - unless you have a much more complicated join implementation - > you will only want to fetch a single tuple on the inner side. > > I also think we're not that close to actually getting the batched execution > stuff. > > And more importantly, even with the batched execution, and a lot of additional > improvements, you'd *still* want specialization for having a qual, EPQ, > projection, because checking them inside the loop over the tuples in the batch > makes no sense. The only thing that'd actually be amortized is the indirect > function call to *Next(). > > > Greetings, > > Andres Freund Hi Andres, Matthias, Thanks, Andres, for the detailed explanation. After looking into this more carefully, I agree with your points. In particular, I was conflating compiler inlining with specialization based on executor-state invariants. LTO/PGO cannot generally establish those invariants, and batching would not eliminate the need to avoid per-tuple qual, projection, and EPQ checks. Your explanation of why specialization can improve instruction-cache locality also makes sense. I was still curious about the code-layout and frontend effects, particularly under mixed workloads, so I ran some additional tests rather than continuing to speculate. On Linux x86-64 (i9-10900K, GCC 13.3), I compared unpatched master against v2 with both default and 64-byte function alignment. The main findings were: Specialization consistently reduced retired instructions. For the qual-only case, the reduction was about 5.5% at both alignments. With default alignment, the qual-only case improved latency by roughly 5-6%. With 64-byte alignment, however, the improvement disappeared. This interaction reproduced in two independently balanced measurement series. PMU measurements showed increased frontend-bound activity and DSB-to-MITE transition penalties in the aligned qual-only case. However, there was no convincing increase in L1I misses or instruction-fetch stalls. This suggests that code placement and instruction delivery matter, but does not demonstrate I-cache pollution. An earlier mixed-workload run showed a small slowdown, but it did not reproduce reliably in subsequent balanced experiments. I therefore don't consider it evidence of a general regression. Interestingly, even a SeqScan-only control showed changes in frontend delivery metrics, despite not executing any of the new IndexOnlyScan variants. This suggests that relocation of existing executor code can matter independently of the additional variants. I also reviewed the correctness aspects on both macOS ARM64 and Linux x86-64, focusing on EPQ, runtime keys, rescans, and the pg_assume() invariants. I found no correctness regression. One useful gap emerged from that investigation: the existing tests do not appear to exercise a correlated IndexOnlyScan within EPQ. I've attached a small test-only isolation patch covering this path. It uses a concurrent UPDATE and three rows to verify refreshed runtime keys, NULL handling, qual rejection, and projection within the same EPQ state. Instrumentation confirmed that v2 enters ExecIndexOnlyScanEPQ(). The test passes on both unpatched master and v2, including 140 repeated runs across -O2 and -O0 builds. I also verified that it detects five deliberately injected faults involving EPQ dispatch, runtime keys, quals, and projection. The test does not depend on the specialization patch itself, so it could be considered independently. Overall, the results have addressed most of my earlier concerns. The code-layout sensitivity is interesting, but I haven't found evidence of a reproducible mixed-workload regression or a correctness problem that would argue against this optimization. I'd appreciate your thoughts on whether the attached EPQ isolation test would be useful to include. Thanks, Haibo
Re: Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
Hi Andres, Haibo, thanks for the explanations and for testing this. On Wed, 14 Oct 2026 19:01:43 -0700, Haibo Yan wrote: > With default alignment, the qual-only case improved latency by > roughly 5-6%. With 64-byte alignment, however, the improvement > disappeared. I see the same here, only the direction differs per query. Same queries as before, master vs patch, default alignment and -falign-functions=64 (i7-13700H, gcc 12): instructions wall-clock wall-clock default align 64 no qual, no projection -5.2% -10.9% -5.1% with qual -4.8% -5.2% -2.8% with projection -6.3% -4.4% -10.4% So with 64-byte alignment the qual case shrinks like in your run, and the projection case gets bigger. Your SeqScan control probably explains it, the patch moves everything behind it in the binary. I'd rather go by the instruction counts, those are stable and match between our two machines. > In particular, it would be interesting to see how much of the > improvement survives with LTO/PGO enabled. I tried -Db_lto=true (gcc 12, -flto=auto): master+LTO patch+LTO diff no qual, no projection 637,092,111 603,092,078 -5.3% with qual 659,425,866 626,759,171 -5.0% with projection 645,088,506 603,088,469 -6.5% LTO alone gives about 2.7% on master for me, and the patch still saves the same ~5% on top. nm on the LTO master binary still shows ExecScan() and IndexOnlyNext() as seperate functions, so I guess LTO didn't inline anything there, which would match what Andres said. JIT: LLVM 15, jit=on, jit_above_cost=0, jit_optimize_above_cost=0. To get the compile cost out of the callgrind numbers I ran the same queries with 1 row and subtracted that. The patch then saves 34.0M / 32.7M / 42.0M instructions, the same as without JIT to within a hundred instructions, which makes sense since it doesn't touch the JIT compiled parts at all. Net of the compile that's -5.6% / -5.3% / -6.7%. Wall-clock with JIT: -9.2%, -8.1%, -5.8%. Andres mentioned nested loops, so I also tried that out: 1M outer rows, inner index only scan on the pkey of the 5M row table, one match each. Instructions -0.4% without and -0.6% with a filter on the inner side, wall-clock within noise (~1.3 s per query, rounds vary by about 5%). Makes sense I think, the lookup is ~9400 instructions and almost all of it is rescan and btree, ExecScan() is only 30-50 of them. > I'd appreciate your thoughts on whether the attached EPQ isolation > test would be useful to include. Yes, I think so. It passes here on master and with the patch, and CI on my github fork is green with it. With a temporary elog() in ExecIndexOnlyScanEPQ() I could see that it really goes through that function. I attached it as 0001 of v3 with you as author, tell me if this is the usual flow here. Is there anything else you'd want to see tested or benchmarked before this could move on? Other workloads, other compilers, more EPQ cases? Happy to run more, I'm just not sure which cases matter most. Regards, Matthias
Re: Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Thu, Oct 15, 2026 at 12:29 AM Matthias Dötsch wrote: > > Hi Andres, Haibo, > > thanks for the explanations and for testing this. > > On Wed, 14 Oct 2026 19:01:43 -0700, Haibo Yan wrote: > > With default alignment, the qual-only case improved latency by > > roughly 5-6%. With 64-byte alignment, however, the improvement > > disappeared. > > I see the same here, only the direction differs per query. Same queries > as before, master vs patch, default alignment and -falign-functions=64 > (i7-13700H, gcc 12): > > instructions wall-clock wall-clock > default align 64 > no qual, no projection -5.2% -10.9% -5.1% > with qual -4.8% -5.2% -2.8% > with projection -6.3% -4.4% -10.4% > > So with 64-byte alignment the qual case shrinks like in your run, and > the projection case gets bigger. Your SeqScan control probably explains > it, the patch moves everything behind it in the binary. I'd rather go > by the instruction counts, those are stable and match between our two > machines. > > > In particular, it would be interesting to see how much of the > > improvement survives with LTO/PGO enabled. > > I tried -Db_lto=true (gcc 12, -flto=auto): > > master+LTO patch+LTO diff > no qual, no projection 637,092,111 603,092,078 -5.3% > with qual 659,425,866 626,759,171 -5.0% > with projection 645,088,506 603,088,469 -6.5% > > LTO alone gives about 2.7% on master for me, and the patch still saves > the same ~5% on top. nm on the LTO master binary still shows ExecScan() > and IndexOnlyNext() as seperate functions, so I guess LTO didn't inline > anything there, which would match what Andres said. > > JIT: LLVM 15, jit=on, jit_above_cost=0, jit_optimize_above_cost=0. To > get the compile cost out of the callgrind numbers I ran the same > queries with 1 row and subtracted that. The patch then saves 34.0M / > 32.7M / 42.0M instructions, the same as without JIT to within a hundred > instructions, which makes sense since it doesn't touch the JIT compiled > parts at all. Net of the compile that's -5.6% / -5.3% / -6.7%. > Wall-clock with JIT: -9.2%, -8.1%, -5.8%. > > Andres mentioned nested loops, so I also tried that out: 1M outer rows, > inner index only scan on the pkey of the 5M row table, one match each. > Instructions -0.4% without and -0.6% with a filter on the inner side, > wall-clock within noise (~1.3 s per query, rounds vary by about 5%). > Makes sense I think, the lookup is ~9400 instructions and almost all of > it is rescan and btree, ExecScan() is only 30-50 of them. > > > I'd appreciate your thoughts on whether the attached EPQ isolation > > test would be useful to include. > > Yes, I think so. It passes here on master and with the patch, and CI on > my github fork is green with it. With a temporary elog() in > ExecIndexOnlyScanEPQ() I could see that it really goes through that > function. I attached it as 0001 of v3 with you as author, tell me if > this is the usual flow here. > > Is there anything else you'd want to see tested or benchmarked before > this could move on? Other workloads, other compilers, more EPQ cases? > Happy to run more, I'm just not sure which cases matter most. > > Regards, > Matthias Hi Matthias, Thanks for the additional benchmarks and for including the EPQ isolation test in v3. The LTO and JIT results are useful. They confirm Andres' point that specialization provides benefits that compiler optimization and the current JIT implementation cannot eliminate. The nested-loop results also make sense. When most of the work is spent on rescans and B-tree lookups, reducing the ExecScan() overhead can only have a limited impact. Regarding the authorship of the test patch, I'm not entirely familiar with the usual community conventions. Since you're maintaining the complete patch series, I'm happy for you to use your own name for 0001. I don't need separate author credit for this test. As for further testing, I think we've covered the main areas I was concerned about. The correctness checks, EPQ coverage, and performance results look sufficient to me at this point. The CI results are also encouraging. I haven't found anything that would justify holding up v3 for additional benchmarking. I'd be inclined to let the normal review process continue and see if other reviewers identify anything that needs further investigation. Thanks again for following up on all these points. Regards, Haibo
Re: Perf: Specialize ExecIndexOnlyScan() like ExecSeqScan()
От:
David Geier <geidav.pg@gmail.com>
Дата:
Hi Matthias! > this is my first patch for Postgres, so please let me know if I got > something about the contribution policies wrong. Welcome and thanks for your contribution! > Our main workload does a lot of index-only scans, and in perf profiles > of it > a good part of the time showed up under ExecScan(). Digging into the > code I noticed that IndexScan, IndexOnlyScan and BitmapHeapScan all > still go through the generic out-of-line ExecScan(). So each tuple pays > for an indirect call to the access method and for the runtime EPQ / > qual / projection checks. SeqScan got rid of that with fb9f95502 (and > 83a53572a6f made sure SeqNext actually gets inlined). > > The attached patch does the same for index-only scans. There are now > ExecIndexOnlyScan, ...WithQuals, ...WithProject, ...WithQualProject and > ...EPQ, the variant is picked in ExecInitIndexOnlyScan(), and > IndexOnlyNext() is pg_always_inline. The EPQ variant just calls > ExecScan() like ExecSeqScanEPQ does. +1 on doing that change for Index (Only) Scan. It would propose to do it as well for Bitmap Index Scan. Then we cover the three most important table access plan nodes. Beyond that, ExecScan() is used by many more nodes (Tid Scan, CTE Scan, etc.). I'm wondering how similar the code would be to make all - or at least most - of them work and if we cannot write some shared abstraction that saves us from repeating all the boiler plate. -- David Geier