hashjoins vs. Bloom filters (yet again)
hashjoins vs. Bloom filters (yet again)
Hi,
A random discussion at pgconf.dev made me revisit one of my ancient
patches, attempting to use Bloom filters to hash joins. I did work on
that twice in the past - first in 2015/6 [1], then in 2018 [2]. So let
me briefly revisit that, before I get to the new patch.
old patches
-----------
Those old patches tried to do a fairly small thing during a hash join,
and that's building a Bloom filter on the inner relation (the one that
gets hashed), and then use that filter before probing the hash table.
The benefits come from Bloom filters being (fairly) cheap, and a
negative answer (hash is not in the filter) may allows us to skip a much
more expensive operation.
The old threads patches focused especially at two hash join cases:
(a) A very selective join, i.e. a significant fraction of outer tuples
does not have a match in the hash table.
(b) A selective hash join forced to do batching because the hash table
is too large, and thus forced to spill outer tuples to temporary files.
For (a), the benefit comes from Bloom filters being much cheaper to
probe than a hash table. The exact cost depends on the implementation,
sizes, etc. We're in the ballpark of 50 vs. 500 cycles, maybe. But if
the filter discards 90% of tuples, it can be a big win.
For (b), the filter (for all the batches at once) allows us to discard
some of the outer tuples without writing them to temporary files. Which
is way more expensive than probing a hash table.
The patches got stuck mostly because deciding if it makes sense to
build/use the Bloom filter is somewhat hard. For cases where 100% of the
tuples have a match it's pointless - it's just pure cost, no benefit.
The regressions are relatively small, though (<10%).
For (b) it's much less sensitive to this kind of issues, of course. The
cost of writing outer tuples to temporary files is much higher than
building/probing a Bloom filter.
Clearly, a filter that discards 99% of tuples is great. And a filter
that keeps 99% of tuples is not great. But where exactly are the
thresholds is not quite clear.
There's also a related question of sizing the filter. Bloom filters are
usually sized by specifying the number of distinct values and the
desired false positive rate. And we could try doing that - pick a
standard false positive rate (e.g. the built-in bloom_filter aims for
1-2%), estimate the ndistinct, and get the size of the Bloom filter.
However, chances are the filter is too big. We can't get work_mem, the
join is already using that for the hash table etc. We can maybe use a
fraction of it, and that may not be enough to fit the "perfect" filter.
We could bail out and not use any Bloom filter at all, but that seems a
bit silly. Maybe we can't fit the 2% filter, but 5% of 10% would be OK?
Surely if the join selectivity is 1% (i.e. it discards 99% tuples), then
using a "worse" Bloom filter with 10% false positives would be a win?
It'd still discard ~89% of tuples.
Yet another angle leading to this kind of questions is inaccurate
ndistinct estimates (and we all know those estimates can be quite
unreliable). Let's say we size the filter for 1M distinct values (and it
just about fits into the memory budget), but then during execution we
find there are 2M distinct values. Well, now we may have ~10% false
positive rate. Or maybe we got 5M, and it's 30%. Or 10M / 50%.
At some point the filter stops being worth it, and we should either not
build it, or we should stop probing it. But when is that?
I think we'd need some sort of cost model to make judgments about this.
Anyway, this was just me summarizing the old threads, and what I think
got them stuck. Most of these questions are still open, although I think
we may be able to solve them better than we could ~10 years ago. We have
extended stats, we know about FK constraints during planning, ...
new patch
---------
Now let's talk about the new experimental/PoC patch that came from the
pgconf.dev discussions. It doesn't really solve the issues I just went
through, it's more of an attempt to take it one step further.
One of the things mentioned in the 2018 thread was the possibility to
push the filter much deeper, instead of using it just in the hash join
node itself. It was merely discussed, but there was no code written, or
anything like that. But it's the thing I decided to take a stab at after
getting back from Vancouver.
Consider a starjoin query
SELECT + FROM f JOIN d1 (f.id1 = d1.id)
JOIN d2 (f.id2 = d2.id)
JOIN d2 (f.id3 = d3.id)
WHERE d1.x = 1
AND d2.y = 2
AND d3.z = 3;
which will be planned using a left-deep plan like this one:
HJ
/ \
D3 HJ
/ \
D2 HJ
/ \
D1 F
With hashes on "D" tables, and a scan on "F". With the "old" patches,
each HJ node would use a Bloom filter internally. But there's an
interesting opportunity to "push down" the filters to the scan on "F",
and evaluate them right there, a bit as if the scan had a local qual.
The attached patch implements a PoC of this, and it's pretty effective.
Of course, it depends on the selectivity of the joins (and thus how many
tuples get discarded by the filters). But because it moves all the
"cheap" filter probes *before* probing any of the hash tables, it has a
multiplication effect for the benefits.
Yes, it still has most of the open issues discussed earlier, and those
will need to be addressed. But this "multiplication" may also make it
somewhat less sensitive to the regressions.
In the example above, if each of the 3 joins has 20% selectivity (i.e.
20% tuples go through), then the total selectivity is ~1%. So the "F"
scan produces only 1/100 of tuples. Maybe we got one of the joins wrong,
and it does not eliminate any tuples? That still means the overall
selectivity is only ~4%.
Of course, this only works for larger joins, and maybe the joins are
correlated in some weird way, etc. Also, what does 4% selectivity mean
for the overall query duration?
Attached is a PDF with results from a simple benchmark using joins like
the one above - fact + 1-3 dimensions. The scripts (in the .tgz) set a
couple GUCs to eliminate variations in the plan. The dimension joins are
independent and match a variable fraction of the fact (1% - 100%).
The columns are for three branches - master, and "patched" with the
push-down disabled and enabled, for joins with 1-3 dimensions.
The last two column groups are comparing the "patched" results to
master. With "off" there's no difference (other than random noise), just
as expected. But with the push-down enabled, there are fairly
significant speedups (up to ~3x). Of course, this is just a benchmark,
practical queries may do other stuff, making the gains smaller. OTOH, it
may also be much better, if there are expensive nodes in between.
The PoC patch is not very big or complex. 280KB seems like a lot, but
like 99% of that is changes in test output, because the patch adds some
info about the Bloom filters to EXPLAIN. The actual .c changes are only
~1000 lines, and a half of that is comments.
The most interesting stuff happens in create_hashjoin_plan(), where we
attempt to push-down the filter to a scan in the outer subtree. If that
succeeds, then ExecInitHashJoin initializes the filter so that the scan
can find it, and Hash builds the filter along with the hash table. And
then the scan nodes probe the pushed-down filter in ExecScanExtended().
There's bunch of boilerplate so that setrefs does the right thing with
expressions, etc. But it's a couple lines here and there. I'm actually
surprised how little code this is.
There's one detail I haven't mentioned yet - there's a simple adaptive
behavior, to deal with filters that are not selective enough. Per some
initial tests there's little benefit when the filter keeps >75% tuples,
and for >90% there were measurable regressions (~50%). This was very
consistent for different data types, etc.
So the patch tracks number of matching tuples per 1000 probes, when it
exceeds 90% it switches to sampling. Only 1% of tuples gets probed in
the filter, and if the fraction drops <80%, all the tuples get probed
again. This is very simple, needs more thought. But for the purpose of
the testing it worked quite well. There still is a small regression
(~3%), which I assume is due to building the filter.
Aside from the issues with deciding if to use a filter at all, sizing
it, etc. - which are still valid (even with the adaptive thing), and
need to be solved, there's one more annoying issue specific to this new
push-down stuff.
Earlier, I mentioned the push-down happens in create_hashjoin_plan().
Which means it happens *after* planning and costing. There are reasons
for that, but it has some unfortunate & annoying consequences.
Ideally, we'd know about the filters when constructing the scan nodes,
so we'd have a chance to estimate how many tuples will be eliminated by
probing the filters (which is about the same thing as estimating the
join sizes). But we can't do that, because our planner works bottom-up.
When constructing the scan nodes we know which tables we'll join with,
but we have no idea which of the join algorithms we'll pick.
We'll consider all three join types, and the scan node has no say which
of those will win. But the Bloom filter push-down is specific to hash
joins. So what should the scan node do? Either it can assume it's under
hash join (and set rows/cost as if there's a Bloom filter), or it can
set costs in a join-agnostic way (like now).
The only "correct" way I can think of dealing with this in the bottom-up
world is having two sets of paths - one set for a hash join, one set for
other joins. But that's not just for scans. We'd need that for all
paths, and for different combinations of joins. For the query with 3
joins, we'd end up with 2^3 combinations. That seems not great.
So I tend to see this as an opportunistic optimization. We do the
planning assuming there's no Bloom filter push-down, and then after the
fact we see if there's an opportunity after all. Which means we may not
pick a plan with hash joins, not realizing it might be made faster.
But in my mind that's somewhat acceptable / defensible.
The bigger issue for me is that it may make the EXPLAIN ANALYZE output
way harder to understand. The estimated "rows" are calculated before the
filter push-down happens, while the actual "rows" are with the filter
probing, of course. But it seems pretty easy to get confused by this,
and think it's just an incorrect estimate.
summary
-------
I like the idea of pushing filters down to the scan nodes (or perhaps
even to some other intermediate nodes). But maybe it's too incompatible
with our bottom-up planning, and the issues with costing and/or EXPLAIN
output may be impossible to solve. I wonder what others think.
Now that I revisited the older threads, I think it probably makes sense
with using Bloom filters in the hash join, at least in the two cases
mentioned in the first section. It doesn't have the issues with
bottom-up planning/costing, because it happens in the hash join. And the
issues with that (deciding what fractions are OK, sizing the filter,
...) apply to both that simpler case, and to the push-down.
regards
[1] https://www.postgresql.org/message-id/5670946E.8070705%402ndquadrant.com
[2]
https://www.postgresql.org/message-id/c902844d-837f-5f63-ced3-9f7fd222f175%402ndquadrant.com
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hi,
A random discussion at pgconf.dev made me revisit one of my ancient
patches, attempting to use Bloom filters to hash joins. I did work on
that twice in the past - first in 2015/6 [1], then in 2018 [2]. So let
me briefly revisit that, before I get to the new patch.
old patches
-----------
Those old patches tried to do a fairly small thing during a hash join,
and that's building a Bloom filter on the inner relation (the one that
gets hashed), and then use that filter before probing the hash table.
The benefits come from Bloom filters being (fairly) cheap, and a
negative answer (hash is not in the filter) may allows us to skip a much
more expensive operation.
The old threads patches focused especially at two hash join cases:
(a) A very selective join, i.e. a significant fraction of outer tuples
does not have a match in the hash table.
(b) A selective hash join forced to do batching because the hash table
is too large, and thus forced to spill outer tuples to temporary files.
For (a), the benefit comes from Bloom filters being much cheaper to
probe than a hash table. The exact cost depends on the implementation,
sizes, etc. We're in the ballpark of 50 vs. 500 cycles, maybe. But if
the filter discards 90% of tuples, it can be a big win.
For (b), the filter (for all the batches at once) allows us to discard
some of the outer tuples without writing them to temporary files. Which
is way more expensive than probing a hash table.
The patches got stuck mostly because deciding if it makes sense to
build/use the Bloom filter is somewhat hard. For cases where 100% of the
tuples have a match it's pointless - it's just pure cost, no benefit.
The regressions are relatively small, though (<10%).
For (b) it's much less sensitive to this kind of issues, of course. The
cost of writing outer tuples to temporary files is much higher than
building/probing a Bloom filter.
Clearly, a filter that discards 99% of tuples is great. And a filter
that keeps 99% of tuples is not great. But where exactly are the
thresholds is not quite clear.
There's also a related question of sizing the filter. Bloom filters are
usually sized by specifying the number of distinct values and the
desired false positive rate. And we could try doing that - pick a
standard false positive rate (e.g. the built-in bloom_filter aims for
1-2%), estimate the ndistinct, and get the size of the Bloom filter.
However, chances are the filter is too big. We can't get work_mem, the
join is already using that for the hash table etc. We can maybe use a
fraction of it, and that may not be enough to fit the "perfect" filter.
We could bail out and not use any Bloom filter at all, but that seems a
bit silly. Maybe we can't fit the 2% filter, but 5% of 10% would be OK?
Surely if the join selectivity is 1% (i.e. it discards 99% tuples), then
using a "worse" Bloom filter with 10% false positives would be a win?
It'd still discard ~89% of tuples.
Yet another angle leading to this kind of questions is inaccurate
ndistinct estimates (and we all know those estimates can be quite
unreliable). Let's say we size the filter for 1M distinct values (and it
just about fits into the memory budget), but then during execution we
find there are 2M distinct values. Well, now we may have ~10% false
positive rate. Or maybe we got 5M, and it's 30%. Or 10M / 50%.
At some point the filter stops being worth it, and we should either not
build it, or we should stop probing it. But when is that?
I think we'd need some sort of cost model to make judgments about this.
Anyway, this was just me summarizing the old threads, and what I think
got them stuck. Most of these questions are still open, although I think
we may be able to solve them better than we could ~10 years ago. We have
extended stats, we know about FK constraints during planning, ...
new patch
---------
Now let's talk about the new experimental/PoC patch that came from the
pgconf.dev discussions. It doesn't really solve the issues I just went
through, it's more of an attempt to take it one step further.
One of the things mentioned in the 2018 thread was the possibility to
push the filter much deeper, instead of using it just in the hash join
node itself. It was merely discussed, but there was no code written, or
anything like that. But it's the thing I decided to take a stab at after
getting back from Vancouver.
Consider a starjoin query
SELECT + FROM f JOIN d1 (f.id1 = d1.id) JOIN d2 (f.id2 = d2.id) JOIN d2 (f.id3 = d3.id) WHERE d1.x = 1 AND d2.y = 2 AND d3.z = 3;
which will be planned using a left-deep plan like this one:
HJ / \ D3 HJ / \ D2 HJ / \ D1 F
With hashes on "D" tables, and a scan on "F". With the "old" patches,
each HJ node would use a Bloom filter internally. But there's an
interesting opportunity to "push down" the filters to the scan on "F",
and evaluate them right there, a bit as if the scan had a local qual.
The attached patch implements a PoC of this, and it's pretty effective.
Of course, it depends on the selectivity of the joins (and thus how many
tuples get discarded by the filters). But because it moves all the
"cheap" filter probes *before* probing any of the hash tables, it has a
multiplication effect for the benefits.
Yes, it still has most of the open issues discussed earlier, and those
will need to be addressed. But this "multiplication" may also make it
somewhat less sensitive to the regressions.
In the example above, if each of the 3 joins has 20% selectivity (i.e.
20% tuples go through), then the total selectivity is ~1%. So the "F"
scan produces only 1/100 of tuples. Maybe we got one of the joins wrong,
and it does not eliminate any tuples? That still means the overall
selectivity is only ~4%.
Of course, this only works for larger joins, and maybe the joins are
correlated in some weird way, etc. Also, what does 4% selectivity mean
for the overall query duration?
Attached is a PDF with results from a simple benchmark using joins like
the one above - fact + 1-3 dimensions. The scripts (in the .tgz) set a
couple GUCs to eliminate variations in the plan. The dimension joins are
independent and match a variable fraction of the fact (1% - 100%).
The columns are for three branches - master, and "patched" with the
push-down disabled and enabled, for joins with 1-3 dimensions.
The last two column groups are comparing the "patched" results to
master. With "off" there's no difference (other than random noise), just
as expected. But with the push-down enabled, there are fairly
significant speedups (up to ~3x). Of course, this is just a benchmark,
practical queries may do other stuff, making the gains smaller. OTOH, it
may also be much better, if there are expensive nodes in between.
The PoC patch is not very big or complex. 280KB seems like a lot, but
like 99% of that is changes in test output, because the patch adds some
info about the Bloom filters to EXPLAIN. The actual .c changes are only
~1000 lines, and a half of that is comments.
The most interesting stuff happens in create_hashjoin_plan(), where we
attempt to push-down the filter to a scan in the outer subtree. If that
succeeds, then ExecInitHashJoin initializes the filter so that the scan
can find it, and Hash builds the filter along with the hash table. And
then the scan nodes probe the pushed-down filter in ExecScanExtended().
There's bunch of boilerplate so that setrefs does the right thing with
expressions, etc. But it's a couple lines here and there. I'm actually
surprised how little code this is.
There's one detail I haven't mentioned yet - there's a simple adaptive
behavior, to deal with filters that are not selective enough. Per some
initial tests there's little benefit when the filter keeps >75% tuples,
and for >90% there were measurable regressions (~50%). This was very
consistent for different data types, etc.
So the patch tracks number of matching tuples per 1000 probes, when it
exceeds 90% it switches to sampling. Only 1% of tuples gets probed in
the filter, and if the fraction drops <80%, all the tuples get probed
again. This is very simple, needs more thought. But for the purpose of
the testing it worked quite well. There still is a small regression
(~3%), which I assume is due to building the filter.
Aside from the issues with deciding if to use a filter at all, sizing
it, etc. - which are still valid (even with the adaptive thing), and
need to be solved, there's one more annoying issue specific to this new
push-down stuff.
Earlier, I mentioned the push-down happens in create_hashjoin_plan().
Which means it happens *after* planning and costing. There are reasons
for that, but it has some unfortunate & annoying consequences.
Ideally, we'd know about the filters when constructing the scan nodes,
so we'd have a chance to estimate how many tuples will be eliminated by
probing the filters (which is about the same thing as estimating the
join sizes). But we can't do that, because our planner works bottom-up.
When constructing the scan nodes we know which tables we'll join with,
but we have no idea which of the join algorithms we'll pick.
We'll consider all three join types, and the scan node has no say which
of those will win. But the Bloom filter push-down is specific to hash
joins. So what should the scan node do? Either it can assume it's under
hash join (and set rows/cost as if there's a Bloom filter), or it can
set costs in a join-agnostic way (like now).
The only "correct" way I can think of dealing with this in the bottom-up
world is having two sets of paths - one set for a hash join, one set for
other joins. But that's not just for scans. We'd need that for all
paths, and for different combinations of joins. For the query with 3
joins, we'd end up with 2^3 combinations. That seems not great.
So I tend to see this as an opportunistic optimization. We do the
planning assuming there's no Bloom filter push-down, and then after the
fact we see if there's an opportunity after all. Which means we may not
pick a plan with hash joins, not realizing it might be made faster.
But in my mind that's somewhat acceptable / defensible.
The bigger issue for me is that it may make the EXPLAIN ANALYZE output
way harder to understand. The estimated "rows" are calculated before the
filter push-down happens, while the actual "rows" are with the filter
probing, of course. But it seems pretty easy to get confused by this,
and think it's just an incorrect estimate.
summary
-------
I like the idea of pushing filters down to the scan nodes (or perhaps
even to some other intermediate nodes). But maybe it's too incompatible
with our bottom-up planning, and the issues with costing and/or EXPLAIN
output may be impossible to solve. I wonder what others think.
Now that I revisited the older threads, I think it probably makes sense
with using Bloom filters in the hash join, at least in the two cases
mentioned in the first section. It doesn't have the issues with
bottom-up planning/costing, because it happens in the hash join. And the
issues with that (deciding what fractions are OK, sizing the filter,
...) apply to both that simpler case, and to the push-down.Hi, Tomas
This is terrific and very timely from my POV.
I've been experimenting with a table AM (implemented as a
CustomScan scan provider), and bloom-filter pushdown from a hashjoin is one
of the bigger wins available to it: a fact-table scan joined to a filtered
dimension can use the filter to skip whole row groups and avoid
decompressing columns entirely, rather than just rejecting a tuple after
it's been produced. I'd hacked up a private version of this via a new
table-AM callback (the hashjoin walks the outer subtree, builds a filter
from the build side, and hands it to the AM's scan descriptor). Having now
read your PoC, I think your framework is the better foundation, and I'd
rather build on it than carry a parallel mechanism. But two things stand in
the way of a storage-level consumer using it, and I think both are relatively
small.
1) A CustomScan can't currently be a recipient.
find_bloom_filter_recipient() only recognizes the stock scan tags, and the
probe itself lives in ExecScanExtended(), which a CustomScan never calls
(it dispatches to the provider's ExecCustomScan). The second part is
actually a feature, not a bug: if a CustomScan provider does its own
probing, it can choose the granularity -- per dictionary entry, per row
group, or per row -- instead of being locked into the per-row,
post-materialization probe that the stock nodes get. So all that's needed
on your side is to let the planner attach a filter to a base-relation
CustomScan; the provider takes care of consuming it.
Concretely, that's adding T_CustomScan to the scan-leaf case in
find_bloom_filter_recipient() (CustomScan embeds Scan first, so the
scanrelid test is identical; non-leaf custom nodes have scanrelid == 0 and
fall through to NULL), plus the matching fix_scan_bloom_filters() call in
set_customscan_references(). The provider then calls ExecInitBloomFilters()
in BeginCustomScan and ExecBloomFilters() (or a coarser-grained variant)
inside its scan loop. Everything else -- producer registration, the
es_bloom_producers lookup, the adaptive sampling, EXPLAIN -- is reused
unchanged.
2) The combined-hash filter can't be tested against a single column.
You build one filter keyed on hash32() of all the join keys combined. For a
single-key join that's ideal, and a column store can use it directly: hash
each distinct dictionary value once per row group and skip groups whose
values are all absent. For a multi-column join, though, the combined hash
mixes the keys, so it can only ever be tested per-row (with all key columns
in hand) -- it can't be checked against any one column's dictionary. The
per-row probe is still useful, but the row-group/dictionary skipping, which
is where most of the storage win comes from, isn't available.
The obvious thought is to key a filter per column instead. But I don't
think that should *replace* the combined filter, because per-column filters
are strictly less selective on multi-column joins: they only test whether
each column's value appears *somewhere* in the build side, not whether the
combination does. With build pairs {(1,10),(2,20)}, an outer (1,20) passes
both per-column filters even though it matches no build row, whereas the
combined filter rejects it. So for the row-level probe -- and especially
for plain heap -- the combined filter is the better one, and replacing it
would be a regression.
What I think would actually help is to let the framework *optionally* emit
per-column filters in addition to the combined one, when a recipient
signals it can use them. The combined filter stays the default and does the
precise per-row rejection (unchanged for heap, and usable per-row by a
column store too); the per-column filters are extra, built only on demand,
and let a storage consumer cheaply eliminate whole row groups before the
combined filter does the exact work. The cost is the build CPU and memory
for the extra filters -- but only for consumers that ask, so your design is
untouched when nobody does. For a single-key join the two filters coincide, so
there'd be no reason to build both.
I'd be happy to work on patches for these.
cheers
andrew
-- Andrew Dunstan EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 5/30/26 19:12, Andrew Dunstan wrote:
>
> On 2026-05-29 Fr 8:55 PM, Tomas Vondra wrote:
>> Hi,
>>
>> A random discussion at pgconf.dev made me revisit one of my ancient
>> patches, attempting to use Bloom filters to hash joins. I did work on
>> that twice in the past - first in 2015/6 [1], then in 2018 [2]. So let
>> me briefly revisit that, before I get to the new patch.
>>
>>
>> old patches
>> -----------
>>
>> Those old patches tried to do a fairly small thing during a hash join,
>> and that's building a Bloom filter on the inner relation (the one that
>> gets hashed), and then use that filter before probing the hash table.
>>
>> The benefits come from Bloom filters being (fairly) cheap, and a
>> negative answer (hash is not in the filter) may allows us to skip a much
>> more expensive operation.
>>
>> The old threads patches focused especially at two hash join cases:
>>
>> (a) A very selective join, i.e. a significant fraction of outer tuples
>> does not have a match in the hash table.
>>
>> (b) A selective hash join forced to do batching because the hash table
>> is too large, and thus forced to spill outer tuples to temporary files.
>>
>> For (a), the benefit comes from Bloom filters being much cheaper to
>> probe than a hash table. The exact cost depends on the implementation,
>> sizes, etc. We're in the ballpark of 50 vs. 500 cycles, maybe. But if
>> the filter discards 90% of tuples, it can be a big win.
>>
>> For (b), the filter (for all the batches at once) allows us to discard
>> some of the outer tuples without writing them to temporary files. Which
>> is way more expensive than probing a hash table.
>>
>> The patches got stuck mostly because deciding if it makes sense to
>> build/use the Bloom filter is somewhat hard. For cases where 100% of the
>> tuples have a match it's pointless - it's just pure cost, no benefit.
>> The regressions are relatively small, though (<10%).
>>
>> For (b) it's much less sensitive to this kind of issues, of course. The
>> cost of writing outer tuples to temporary files is much higher than
>> building/probing a Bloom filter.
>>
>> Clearly, a filter that discards 99% of tuples is great. And a filter
>> that keeps 99% of tuples is not great. But where exactly are the
>> thresholds is not quite clear.
>>
>> There's also a related question of sizing the filter. Bloom filters are
>> usually sized by specifying the number of distinct values and the
>> desired false positive rate. And we could try doing that - pick a
>> standard false positive rate (e.g. the built-in bloom_filter aims for
>> 1-2%), estimate the ndistinct, and get the size of the Bloom filter.
>>
>> However, chances are the filter is too big. We can't get work_mem, the
>> join is already using that for the hash table etc. We can maybe use a
>> fraction of it, and that may not be enough to fit the "perfect" filter.
>> We could bail out and not use any Bloom filter at all, but that seems a
>> bit silly. Maybe we can't fit the 2% filter, but 5% of 10% would be OK?
>>
>> Surely if the join selectivity is 1% (i.e. it discards 99% tuples), then
>> using a "worse" Bloom filter with 10% false positives would be a win?
>> It'd still discard ~89% of tuples.
>>
>> Yet another angle leading to this kind of questions is inaccurate
>> ndistinct estimates (and we all know those estimates can be quite
>> unreliable). Let's say we size the filter for 1M distinct values (and it
>> just about fits into the memory budget), but then during execution we
>> find there are 2M distinct values. Well, now we may have ~10% false
>> positive rate. Or maybe we got 5M, and it's 30%. Or 10M / 50%.
>>
>> At some point the filter stops being worth it, and we should either not
>> build it, or we should stop probing it. But when is that?
>>
>> I think we'd need some sort of cost model to make judgments about this.
>>
>> Anyway, this was just me summarizing the old threads, and what I think
>> got them stuck. Most of these questions are still open, although I think
>> we may be able to solve them better than we could ~10 years ago. We have
>> extended stats, we know about FK constraints during planning, ...
>>
>>
>> new patch
>> ---------
>>
>> Now let's talk about the new experimental/PoC patch that came from the
>> pgconf.dev discussions. It doesn't really solve the issues I just went
>> through, it's more of an attempt to take it one step further.
>>
>> One of the things mentioned in the 2018 thread was the possibility to
>> push the filter much deeper, instead of using it just in the hash join
>> node itself. It was merely discussed, but there was no code written, or
>> anything like that. But it's the thing I decided to take a stab at after
>> getting back from Vancouver.
>>
>> Consider a starjoin query
>>
>> SELECT + FROM f JOIN d1 (f.id1 = d1.id)
>> JOIN d2 (f.id2 = d2.id)
>> JOIN d2 (f.id3 = d3.id)
>> WHERE d1.x = 1
>> AND d2.y = 2
>> AND d3.z = 3;
>>
>> which will be planned using a left-deep plan like this one:
>>
>> HJ
>> / \
>> D3 HJ
>> / \
>> D2 HJ
>> / \
>> D1 F
>>
>> With hashes on "D" tables, and a scan on "F". With the "old" patches,
>> each HJ node would use a Bloom filter internally. But there's an
>> interesting opportunity to "push down" the filters to the scan on "F",
>> and evaluate them right there, a bit as if the scan had a local qual.
>>
>> The attached patch implements a PoC of this, and it's pretty effective.
>>
>> Of course, it depends on the selectivity of the joins (and thus how many
>> tuples get discarded by the filters). But because it moves all the
>> "cheap" filter probes *before* probing any of the hash tables, it has a
>> multiplication effect for the benefits.
>>
>> Yes, it still has most of the open issues discussed earlier, and those
>> will need to be addressed. But this "multiplication" may also make it
>> somewhat less sensitive to the regressions.
>>
>> In the example above, if each of the 3 joins has 20% selectivity (i.e.
>> 20% tuples go through), then the total selectivity is ~1%. So the "F"
>> scan produces only 1/100 of tuples. Maybe we got one of the joins wrong,
>> and it does not eliminate any tuples? That still means the overall
>> selectivity is only ~4%.
>>
>> Of course, this only works for larger joins, and maybe the joins are
>> correlated in some weird way, etc. Also, what does 4% selectivity mean
>> for the overall query duration?
>>
>> Attached is a PDF with results from a simple benchmark using joins like
>> the one above - fact + 1-3 dimensions. The scripts (in the .tgz) set a
>> couple GUCs to eliminate variations in the plan. The dimension joins are
>> independent and match a variable fraction of the fact (1% - 100%).
>>
>> The columns are for three branches - master, and "patched" with the
>> push-down disabled and enabled, for joins with 1-3 dimensions.
>>
>> The last two column groups are comparing the "patched" results to
>> master. With "off" there's no difference (other than random noise), just
>> as expected. But with the push-down enabled, there are fairly
>> significant speedups (up to ~3x). Of course, this is just a benchmark,
>> practical queries may do other stuff, making the gains smaller. OTOH, it
>> may also be much better, if there are expensive nodes in between.
>>
>>
>> The PoC patch is not very big or complex. 280KB seems like a lot, but
>> like 99% of that is changes in test output, because the patch adds some
>> info about the Bloom filters to EXPLAIN. The actual .c changes are only
>> ~1000 lines, and a half of that is comments.
>>
>> The most interesting stuff happens in create_hashjoin_plan(), where we
>> attempt to push-down the filter to a scan in the outer subtree. If that
>> succeeds, then ExecInitHashJoin initializes the filter so that the scan
>> can find it, and Hash builds the filter along with the hash table. And
>> then the scan nodes probe the pushed-down filter in ExecScanExtended().
>>
>> There's bunch of boilerplate so that setrefs does the right thing with
>> expressions, etc. But it's a couple lines here and there. I'm actually
>> surprised how little code this is.
>>
>> There's one detail I haven't mentioned yet - there's a simple adaptive
>> behavior, to deal with filters that are not selective enough. Per some
>> initial tests there's little benefit when the filter keeps >75% tuples,
>> and for >90% there were measurable regressions (~50%). This was very
>> consistent for different data types, etc.
>>
>> So the patch tracks number of matching tuples per 1000 probes, when it
>> exceeds 90% it switches to sampling. Only 1% of tuples gets probed in
>> the filter, and if the fraction drops <80%, all the tuples get probed
>> again. This is very simple, needs more thought. But for the purpose of
>> the testing it worked quite well. There still is a small regression
>> (~3%), which I assume is due to building the filter.
>>
>>
>> Aside from the issues with deciding if to use a filter at all, sizing
>> it, etc. - which are still valid (even with the adaptive thing), and
>> need to be solved, there's one more annoying issue specific to this new
>> push-down stuff.
>>
>>
>> Earlier, I mentioned the push-down happens in create_hashjoin_plan().
>> Which means it happens *after* planning and costing. There are reasons
>> for that, but it has some unfortunate & annoying consequences.
>>
>> Ideally, we'd know about the filters when constructing the scan nodes,
>> so we'd have a chance to estimate how many tuples will be eliminated by
>> probing the filters (which is about the same thing as estimating the
>> join sizes). But we can't do that, because our planner works bottom-up.
>> When constructing the scan nodes we know which tables we'll join with,
>> but we have no idea which of the join algorithms we'll pick.
>>
>> We'll consider all three join types, and the scan node has no say which
>> of those will win. But the Bloom filter push-down is specific to hash
>> joins. So what should the scan node do? Either it can assume it's under
>> hash join (and set rows/cost as if there's a Bloom filter), or it can
>> set costs in a join-agnostic way (like now).
>>
>> The only "correct" way I can think of dealing with this in the bottom-up
>> world is having two sets of paths - one set for a hash join, one set for
>> other joins. But that's not just for scans. We'd need that for all
>> paths, and for different combinations of joins. For the query with 3
>> joins, we'd end up with 2^3 combinations. That seems not great.
>>
>>
>> So I tend to see this as an opportunistic optimization. We do the
>> planning assuming there's no Bloom filter push-down, and then after the
>> fact we see if there's an opportunity after all. Which means we may not
>> pick a plan with hash joins, not realizing it might be made faster.
>>
>> But in my mind that's somewhat acceptable / defensible.
>>
>> The bigger issue for me is that it may make the EXPLAIN ANALYZE output
>> way harder to understand. The estimated "rows" are calculated before the
>> filter push-down happens, while the actual "rows" are with the filter
>> probing, of course. But it seems pretty easy to get confused by this,
>> and think it's just an incorrect estimate.
>>
>>
>> summary
>> -------
>>
>> I like the idea of pushing filters down to the scan nodes (or perhaps
>> even to some other intermediate nodes). But maybe it's too incompatible
>> with our bottom-up planning, and the issues with costing and/or EXPLAIN
>> output may be impossible to solve. I wonder what others think.
>>
>>
>> Now that I revisited the older threads, I think it probably makes sense
>> with using Bloom filters in the hash join, at least in the two cases
>> mentioned in the first section. It doesn't have the issues with
>> bottom-up planning/costing, because it happens in the hash join. And the
>> issues with that (deciding what fractions are OK, sizing the filter,
>> ...) apply to both that simpler case, and to the push-down.
>
>
>
> Hi, Tomas
>
> This is terrific and very timely from my POV.
>
> I've been experimenting with a table AM (implemented as a
> CustomScan scan provider), and bloom-filter pushdown from a hashjoin is one
> of the bigger wins available to it: a fact-table scan joined to a filtered
> dimension can use the filter to skip whole row groups and avoid
> decompressing columns entirely, rather than just rejecting a tuple after
> it's been produced. I'd hacked up a private version of this via a new
> table-AM callback (the hashjoin walks the outer subtree, builds a filter
> from the build side, and hands it to the AM's scan descriptor). Having now
> read your PoC, I think your framework is the better foundation, and I'd
> rather build on it than carry a parallel mechanism. But two things stand in
> the way of a storage-level consumer using it, and I think both are
> relatively
> small.
>
OK, good to hear. I was actually thinking about that use case too, i.e.
making it possible for the scan to do something smart with the filter
(like even pushing it even further down, to "storage"). Or maybe the
ForeignScan could push it to the remote side, so that it's actually
filtered there.
I didn't mention that my message, and there are some difficulties:
1) We only build the hash (and bloom) with a delay, after the scan
already produces some tuples. That complicates the pushdown, whiich may
need to happen when starting the scan. Presumably, we'd need to allow
disabling this optimization, optionally.
2) We'd need some sort of "portable" Bloom filter, with serialization
and deserialization, etc.
Both of these seem rather solvable.
> 1) A CustomScan can't currently be a recipient.
>
> find_bloom_filter_recipient() only recognizes the stock scan tags, and the
> probe itself lives in ExecScanExtended(), which a CustomScan never calls
> (it dispatches to the provider's ExecCustomScan). The second part is
> actually a feature, not a bug: if a CustomScan provider does its own
> probing, it can choose the granularity -- per dictionary entry, per row
> group, or per row -- instead of being locked into the per-row,
> post-materialization probe that the stock nodes get. So all that's needed
> on your side is to let the planner attach a filter to a base-relation
> CustomScan; the provider takes care of consuming it.
>
> Concretely, that's adding T_CustomScan to the scan-leaf case in
> find_bloom_filter_recipient() (CustomScan embeds Scan first, so the
> scanrelid test is identical; non-leaf custom nodes have scanrelid == 0 and
> fall through to NULL), plus the matching fix_scan_bloom_filters() call in
> set_customscan_references(). The provider then calls ExecInitBloomFilters()
> in BeginCustomScan and ExecBloomFilters() (or a coarser-grained variant)
> inside its scan loop. Everything else -- producer registration, the
> es_bloom_producers lookup, the adaptive sampling, EXPLAIN -- is reused
> unchanged.
>
Yes, that should work and it's a mostly mechanical change.
Maybe we'd want some sort of opt-in, so that the CustomScan can indicate
it can handle Bloom filters. Like, setting
CUSTOMPATH_SUPPORT_BLOOM_FILTERS to flags.
> 2) The combined-hash filter can't be tested against a single column.
>
> You build one filter keyed on hash32() of all the join keys combined. For a
> single-key join that's ideal, and a column store can use it directly: hash
> each distinct dictionary value once per row group and skip groups whose
> values are all absent. For a multi-column join, though, the combined hash
> mixes the keys, so it can only ever be tested per-row (with all key columns
> in hand) -- it can't be checked against any one column's dictionary. The
> per-row probe is still useful, but the row-group/dictionary skipping, which
> is where most of the storage win comes from, isn't available.
>
> The obvious thought is to key a filter per column instead. But I don't
> think that should *replace* the combined filter, because per-column filters
> are strictly less selective on multi-column joins: they only test whether
> each column's value appears *somewhere* in the build side, not whether the
> combination does. With build pairs {(1,10),(2,20)}, an outer (1,20) passes
> both per-column filters even though it matches no build row, whereas the
> combined filter rejects it. So for the row-level probe -- and especially
> for plain heap -- the combined filter is the better one, and replacing it
> would be a regression.
>
> What I think would actually help is to let the framework *optionally* emit
> per-column filters in addition to the combined one, when a recipient
> signals it can use them. The combined filter stays the default and does the
> precise per-row rejection (unchanged for heap, and usable per-row by a
> column store too); the per-column filters are extra, built only on demand,
> and let a storage consumer cheaply eliminate whole row groups before the
> combined filter does the exact work. The cost is the build CPU and memory
> for the extra filters -- but only for consumers that ask, so your design is
> untouched when nobody does. For a single-key join the two filters
> coincide, so
> there'd be no reason to build both.
>
I think I speculated about this (having per-key filters) in some of the
comments in the patch, although the use case was different. I haven't
thought about TAM, but about different joins where the join keys come
from both sides. Consider a join like
HJ
/ \
A HJ
/ \
B C
where A-(BC) is on (A.x = B.x AND A.y = C.y), so the complete filter
can't be pushed to either side. But we could:
(1) Push the filter on top of the BC join (which in this example is not
really a push-down).
(2) Build filters on (x) and (y) separately, and push-down these.
Or we could do both, really.
I suppose a variation of (2) would work for your use case too, except
we'd push all three filters (x,y), (x) and (y) to the same scan.
I guess this could also be opt-in, enabled by some CUSTOMPATH_ flag.
The question is how efficient can the smaller filters be. The complete
filter can be very selective, while the per-key filters are terrible.
>
> I'd be happy to work on patches for these.
>
Great. It's and interesting experiment / area to explore.
FWIW I think the main difficulty for this PoC is going to be the
planning/costing stuff, and the impact on EXPLAIN.
regards
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 2026-05-30 Sa 2:14 PM, Tomas Vondra wrote:
>
>
> Hi, Tomas
>
> This is terrific and very timely from my POV.
>
> I've been experimenting with a table AM (implemented as a
> CustomScan scan provider), and bloom-filter pushdown from a hashjoin is one
> of the bigger wins available to it: a fact-table scan joined to a filtered
> dimension can use the filter to skip whole row groups and avoid
> decompressing columns entirely, rather than just rejecting a tuple after
> it's been produced. I'd hacked up a private version of this via a new
> table-AM callback (the hashjoin walks the outer subtree, builds a filter
> from the build side, and hands it to the AM's scan descriptor). Having now
> read your PoC, I think your framework is the better foundation, and I'd
> rather build on it than carry a parallel mechanism. But two things stand in
> the way of a storage-level consumer using it, and I think both are
> relatively
> small.
>
> OK, good to hear. I was actually thinking about that use case too, i.e.
> making it possible for the scan to do something smart with the filter
> (like even pushing it even further down, to "storage"). Or maybe the
> ForeignScan could push it to the remote side, so that it's actually
> filtered there.
>
> I didn't mention that my message, and there are some difficulties:
>
> 1) We only build the hash (and bloom) with a delay, after the scan
> already produces some tuples. That complicates the pushdown, whiich may
> need to happen when starting the scan. Presumably, we'd need to allow
> disabling this optimization, optionally.
>
> 2) We'd need some sort of "portable" Bloom filter, with serialization
> and deserialization, etc.
>
> Both of these seem rather solvable.
>
>> 1) A CustomScan can't currently be a recipient.
>>
>> find_bloom_filter_recipient() only recognizes the stock scan tags, and the
>> probe itself lives in ExecScanExtended(), which a CustomScan never calls
>> (it dispatches to the provider's ExecCustomScan). The second part is
>> actually a feature, not a bug: if a CustomScan provider does its own
>> probing, it can choose the granularity -- per dictionary entry, per row
>> group, or per row -- instead of being locked into the per-row,
>> post-materialization probe that the stock nodes get. So all that's needed
>> on your side is to let the planner attach a filter to a base-relation
>> CustomScan; the provider takes care of consuming it.
>>
>> Concretely, that's adding T_CustomScan to the scan-leaf case in
>> find_bloom_filter_recipient() (CustomScan embeds Scan first, so the
>> scanrelid test is identical; non-leaf custom nodes have scanrelid == 0 and
>> fall through to NULL), plus the matching fix_scan_bloom_filters() call in
>> set_customscan_references(). The provider then calls ExecInitBloomFilters()
>> in BeginCustomScan and ExecBloomFilters() (or a coarser-grained variant)
>> inside its scan loop. Everything else -- producer registration, the
>> es_bloom_producers lookup, the adaptive sampling, EXPLAIN -- is reused
>> unchanged.
>>
> Yes, that should work and it's a mostly mechanical change.
>
> Maybe we'd want some sort of opt-in, so that the CustomScan can indicate
> it can handle Bloom filters. Like, setting
> CUSTOMPATH_SUPPORT_BLOOM_FILTERS to flags.
>
>> 2) The combined-hash filter can't be tested against a single column.
>>
>> You build one filter keyed on hash32() of all the join keys combined. For a
>> single-key join that's ideal, and a column store can use it directly: hash
>> each distinct dictionary value once per row group and skip groups whose
>> values are all absent. For a multi-column join, though, the combined hash
>> mixes the keys, so it can only ever be tested per-row (with all key columns
>> in hand) -- it can't be checked against any one column's dictionary. The
>> per-row probe is still useful, but the row-group/dictionary skipping, which
>> is where most of the storage win comes from, isn't available.
>>
>> The obvious thought is to key a filter per column instead. But I don't
>> think that should *replace* the combined filter, because per-column filters
>> are strictly less selective on multi-column joins: they only test whether
>> each column's value appears *somewhere* in the build side, not whether the
>> combination does. With build pairs {(1,10),(2,20)}, an outer (1,20) passes
>> both per-column filters even though it matches no build row, whereas the
>> combined filter rejects it. So for the row-level probe -- and especially
>> for plain heap -- the combined filter is the better one, and replacing it
>> would be a regression.
>>
>> What I think would actually help is to let the framework *optionally* emit
>> per-column filters in addition to the combined one, when a recipient
>> signals it can use them. The combined filter stays the default and does the
>> precise per-row rejection (unchanged for heap, and usable per-row by a
>> column store too); the per-column filters are extra, built only on demand,
>> and let a storage consumer cheaply eliminate whole row groups before the
>> combined filter does the exact work. The cost is the build CPU and memory
>> for the extra filters -- but only for consumers that ask, so your design is
>> untouched when nobody does. For a single-key join the two filters
>> coincide, so
>> there'd be no reason to build both.
>>
> I think I speculated about this (having per-key filters) in some of the
> comments in the patch, although the use case was different. I haven't
> thought about TAM, but about different joins where the join keys come
> from both sides. Consider a join like
>
> HJ
> / \
> A HJ
> / \
> B C
>
> where A-(BC) is on (A.x = B.x AND A.y = C.y), so the complete filter
> can't be pushed to either side. But we could:
>
> (1) Push the filter on top of the BC join (which in this example is not
> really a push-down).
>
> (2) Build filters on (x) and (y) separately, and push-down these.
>
> Or we could do both, really.
>
> I suppose a variation of (2) would work for your use case too, except
> we'd push all three filters (x,y), (x) and (y) to the same scan.
>
> I guess this could also be opt-in, enabled by some CUSTOMPATH_ flag.
>
> The question is how efficient can the smaller filters be. The complete
> filter can be very selective, while the per-key filters are terrible.
>
>> I'd be happy to work on patches for these.
>>
> Great. It's and interesting experiment / area to explore.
Here are 3 patches (developed using Claude) that sit on top of your POC.
Patch 1 enables the pushdown filters for custom scans. As you say it's
fairly mechanical and is enabled by a CUSTOMPATH_SUPPORT_BLOOM_FILTERS
path flag.
Patch 2 provides for building per-key filters in addition to the
multi-key filter if that flag is set. There may be other cases that
would want it, but this would suit my immediate use case.
Patch 3 provides for eager creation of the filter(s) in such cases,
disabling the optimization you mentioned in point 1 above.
>
> FWIW I think the main difficulty for this PoC is going to be the
> planning/costing stuff, and the impact on EXPLAIN.
>
>
I haven't dealt with that or other issues you raise, but I think this is
enough for me to begin testing. I have adapted my TAM to it and verified
that it acts as expected. I will start doing some benchmarks.
cheers
andrew
--
Andrew Dunstan
EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
Postgres is still gaining ground in this area. It’s helpful to see how other databases handle these challenges. On 30/05/2026 02:55, Tomas Vondra wrote: > The patches got stuck mostly because deciding if it makes sense to > build/use the Bloom filter is somewhat hard. For cases where 100% of the > tuples have a match it's pointless - it's just pure cost, no benefit. > The regressions are relatively small, though (<10%). We ran into the same problem when trying to estimate the number of 'generated' NULLs on the nullable side. So, it makes sense to focus on the estimation method for 'unmatched' tuples as a separate task. > However, chances are the filter is too big. We can't get work_mem, the > join is already using that for the hash table etc. We can maybe use a > fraction of it, and that may not be enough to fit the "perfect" filter. > We could bail out and not use any Bloom filter at all, but that seems a > bit silly. Maybe we can't fit the 2% filter, but 5% of 10% would be OK? Looking at DuckDB’s code, using bloom filters during hash table construction solves this issue. From what I can tell, Apache Impala [1] and Spark [2] use the same approach. > Of course, it depends on the selectivity of the joins (and thus how many > tuples get discarded by the filters). But because it moves all the > "cheap" filter probes *before* probing any of the hash tables, it has a > multiplication effect for the benefits. In my experience, the outer side often has a complex subtree and is sometimes capped by a GROUP BY statement, or even a HAVING clause, which can break all estimations. A bloom filter might help if there is an accidental misestimate. > So I tend to see this as an opportunistic optimization. We do the > planning assuming there's no Bloom filter push-down, and then after the > fact we see if there's an opportunity after all. Which means we may not > pick a plan with hash joins, not realizing it might be made faster. This approach should not cause any issues. It is likely a reasonable way to improve performance without expanding the optimisation scope, which would increase planning time. We can always adjust it later if needed. For example, I am designing the post-optimising NestLoop 'lazy join' [3] using the 'gating' concept. > > The bigger issue for me is that it may make the EXPLAIN ANALYZE output > way harder to understand. The estimated "rows" are calculated before the > filter push-down happens, while the actual "rows" are with the filter > probing, of course. But it seems pretty easy to get confused by this, > and think it's just an incorrect estimate. People are often confused when trying to understand the correctness of estimation for parallel plans and, in some cases, MergeJoin plans. Personally, I don't think it's a big issue. Overall, I think there are even more useful ways to apply bloom filters in the planner: 1. Real-time partition pruning 2. FDW pushed-down filters, which are especially helpful for sharded tables. 3. Skipping storage layer blocks. I know of at least one attempt to use the BRIN+FSM approach to avoid reading parts of a large table that definitely don't match the filter. Bloom filters could be used here as well. So, I'm excited about your proposal. Even if you start with a simple case, just make it available for extension modules. [1] https://impala.apache.org/docs/build/html/topics/impala_runtime_filtering.html [2] https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-performance.html [3] https://www.postgresql.org/message-id/3d749085-72b6-46d6-a26a-7c95805c1adb%40gmail.com -- regards, Andrei Lepikhov, pgEdge
Re: hashjoins vs. Bloom filters (yet again)
On 30/05/2026 02:55, Tomas Vondra wrote: > Earlier, I mentioned the push-down happens in create_hashjoin_plan(). > Which means it happens *after* planning and costing. There are reasons > for that, but it has some unfortunate & annoying consequences. > > Ideally, we'd know about the filters when constructing the scan nodes, > so we'd have a chance to estimate how many tuples will be eliminated by > probing the filters (which is about the same thing as estimating the > join sizes). But we can't do that, because our planner works bottom-up. > When constructing the scan nodes we know which tables we'll join with, > but we have no idea which of the join algorithms we'll pick. > > We'll consider all three join types, and the scan node has no say which > of those will win. But the Bloom filter push-down is specific to hash > joins. So what should the scan node do? Either it can assume it's under > hash join (and set rows/cost as if there's a Bloom filter), or it can > set costs in a join-agnostic way (like now). > > The only "correct" way I can think of dealing with this in the bottom-up > world is having two sets of paths - one set for a hash join, one set for > other joins. But that's not just for scans. We'd need that for all > paths, and for different combinations of joins. For the query with 3 > joins, we'd end up with 2^3 combinations. That seems not great. I overlooked this part of your first message, so let me add a quick comment. In principle, the optimiser is not restricted to bottom-up planning. For example, in extension modules, I sometimes use the create_upper_paths_hook to add a 'Top-Down' iteration after 'bottom-up' planning [1]. This helps improve complex query plans, such as adding a Memoize node at the head of a subplan when the number of distinct input parameter values is expected to be low. It can also use the startup_cost-optimal subpaths in MergeJoin if histogram comparisons indicate that only a small portion of the input will be scanned. There are other possible cases involving LIMIT and sort propagation as well. I'm not sure whether this approach makes sense for the specific technique you develop, since it's already quite complex. Also, additional planning iteration is a pure overhead in most of cases except complex analytical queries. However, it might provide an idea for future improvement. [1] https://github.com/danolivo/conf/blob/main/2025-MiddleOut/MiddleOut.pdf -- regards, Andrei Lepikhov, pgEdge
Re: hashjoins vs. Bloom filters (yet again)
On 6/1/26 11:30, Andrei Lepikhov wrote: > Postgres is still gaining ground in this area. It’s helpful to see how other > databases handle these challenges. > > On 30/05/2026 02:55, Tomas Vondra wrote: >> The patches got stuck mostly because deciding if it makes sense to >> build/use the Bloom filter is somewhat hard. For cases where 100% of the >> tuples have a match it's pointless - it's just pure cost, no benefit. >> The regressions are relatively small, though (<10%). > > We ran into the same problem when trying to estimate the number of 'generated' > NULLs on the nullable side. So, it makes sense to focus on the estimation method > for 'unmatched' tuples as a separate task. > Not sure how treating it as a separate task solves that? In any case, the patches I posted a couple minutes ago (for filters in the scope of a single hashjoin, but the problem is the same) deal with this by delaying the build until execution time, when we have better idea how many outer tuples match the hash table. >> However, chances are the filter is too big. We can't get work_mem, the >> join is already using that for the hash table etc. We can maybe use a >> fraction of it, and that may not be enough to fit the "perfect" filter. >> We could bail out and not use any Bloom filter at all, but that seems a >> bit silly. Maybe we can't fit the 2% filter, but 5% of 10% would be OK? > > Looking at DuckDB’s code, using bloom filters during hash table construction > solves this issue. > From what I can tell, Apache Impala [1] and Spark [2] use the same approach. > It's not clear how any of these solve the issue I described (about sizing the filter and the trade offs). The links just say that the feature exist. >> Of course, it depends on the selectivity of the joins (and thus how many >> tuples get discarded by the filters). But because it moves all the >> "cheap" filter probes *before* probing any of the hash tables, it has a >> multiplication effect for the benefits. > > In my experience, the outer side often has a complex subtree and is sometimes > capped by a GROUP BY statement, or even a HAVING clause, which can break all > estimations. A bloom filter might help if there is an accidental misestimate. > Perhaps, but with substantial misestimates all bets are off. Maybe it'd be better to discuss a particular example. >> So I tend to see this as an opportunistic optimization. We do the >> planning assuming there's no Bloom filter push-down, and then after the >> fact we see if there's an opportunity after all. Which means we may not >> pick a plan with hash joins, not realizing it might be made faster. > > This approach should not cause any issues. It is likely a reasonable way to > improve performance without expanding the optimisation scope, which would > increase planning time. We can always adjust it later if needed. > For example, I am designing the post-optimising NestLoop 'lazy join' [3] using > the 'gating' concept. > I agree, except that it also makes EXPLAIN pretty difficult to interpret, because it "breaks" the row counts. >> >> The bigger issue for me is that it may make the EXPLAIN ANALYZE output >> way harder to understand. The estimated "rows" are calculated before the >> filter push-down happens, while the actual "rows" are with the filter >> probing, of course. But it seems pretty easy to get confused by this, >> and think it's just an incorrect estimate. > > People are often confused when trying to understand the correctness of > estimation for parallel plans and, in some cases, MergeJoin plans. Personally, I > don't think it's a big issue. > I disagree. The fact that people may be confused by plans does not mean we can just make plans confusing for everyone. > Overall, I think there are even more useful ways to apply bloom filters in the > planner: > 1. Real-time partition pruning > 2. FDW pushed-down filters, which are especially helpful for sharded tables. > 3. Skipping storage layer blocks. I know of at least one attempt to use the > BRIN+FSM approach to avoid reading parts of a large table that definitely don't > match the filter. Bloom filters could be used here as well. > Could be. I speculated about options (2) and (3) myself elsewhere in this thread. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hi,
A random discussion at pgconf.dev made me revisit one of my ancient
patches, attempting to use Bloom filters to hash joins. I did work on
that twice in the past - first in 2015/6 [1], then in 2018 [2]. So let
me briefly revisit that, before I get to the new patch.
old patches
-----------
Those old patches tried to do a fairly small thing during a hash join,
and that's building a Bloom filter on the inner relation (the one that
gets hashed), and then use that filter before probing the hash table.
The benefits come from Bloom filters being (fairly) cheap, and a
negative answer (hash is not in the filter) may allows us to skip a much
more expensive operation.
The old threads patches focused especially at two hash join cases:
(a) A very selective join, i.e. a significant fraction of outer tuples
does not have a match in the hash table.
(b) A selective hash join forced to do batching because the hash table
is too large, and thus forced to spill outer tuples to temporary files.
For (a), the benefit comes from Bloom filters being much cheaper to
probe than a hash table. The exact cost depends on the implementation,
sizes, etc. We're in the ballpark of 50 vs. 500 cycles, maybe. But if
the filter discards 90% of tuples, it can be a big win.
For (b), the filter (for all the batches at once) allows us to discard
some of the outer tuples without writing them to temporary files. Which
is way more expensive than probing a hash table.
The patches got stuck mostly because deciding if it makes sense to
build/use the Bloom filter is somewhat hard. For cases where 100% of the
tuples have a match it's pointless - it's just pure cost, no benefit.
The regressions are relatively small, though (<10%).
For (b) it's much less sensitive to this kind of issues, of course. The
cost of writing outer tuples to temporary files is much higher than
building/probing a Bloom filter.
Clearly, a filter that discards 99% of tuples is great. And a filter
that keeps 99% of tuples is not great. But where exactly are the
thresholds is not quite clear.
There's also a related question of sizing the filter. Bloom filters are
usually sized by specifying the number of distinct values and the
desired false positive rate. And we could try doing that - pick a
standard false positive rate (e.g. the built-in bloom_filter aims for
1-2%), estimate the ndistinct, and get the size of the Bloom filter.
However, chances are the filter is too big. We can't get work_mem, the
join is already using that for the hash table etc. We can maybe use a
fraction of it, and that may not be enough to fit the "perfect" filter.
We could bail out and not use any Bloom filter at all, but that seems a
bit silly. Maybe we can't fit the 2% filter, but 5% of 10% would be OK?
Surely if the join selectivity is 1% (i.e. it discards 99% tuples), then
using a "worse" Bloom filter with 10% false positives would be a win?
It'd still discard ~89% of tuples.
Yet another angle leading to this kind of questions is inaccurate
ndistinct estimates (and we all know those estimates can be quite
unreliable). Let's say we size the filter for 1M distinct values (and it
just about fits into the memory budget), but then during execution we
find there are 2M distinct values. Well, now we may have ~10% false
positive rate. Or maybe we got 5M, and it's 30%. Or 10M / 50%.
At some point the filter stops being worth it, and we should either not
build it, or we should stop probing it. But when is that?
I think we'd need some sort of cost model to make judgments about this.
Anyway, this was just me summarizing the old threads, and what I think
got them stuck. Most of these questions are still open, although I think
we may be able to solve them better than we could ~10 years ago. We have
extended stats, we know about FK constraints during planning, ...
new patch
---------
Now let's talk about the new experimental/PoC patch that came from the
pgconf.dev discussions. It doesn't really solve the issues I just went
through, it's more of an attempt to take it one step further.
One of the things mentioned in the 2018 thread was the possibility to
push the filter much deeper, instead of using it just in the hash join
node itself. It was merely discussed, but there was no code written, or
anything like that. But it's the thing I decided to take a stab at after
getting back from Vancouver.
Consider a starjoin query
SELECT + FROM f JOIN d1 (f.id1 = d1.id)
JOIN d2 (f.id2 = d2.id)
JOIN d2 (f.id3 = d3.id)
WHERE d1.x = 1
AND d2.y = 2
AND d3.z = 3;
which will be planned using a left-deep plan like this one:
HJ
/ \
D3 HJ
/ \
D2 HJ
/ \
D1 F
With hashes on "D" tables, and a scan on "F". With the "old" patches,
each HJ node would use a Bloom filter internally. But there's an
interesting opportunity to "push down" the filters to the scan on "F",
and evaluate them right there, a bit as if the scan had a local qual.
The attached patch implements a PoC of this, and it's pretty effective.
Of course, it depends on the selectivity of the joins (and thus how many
tuples get discarded by the filters). But because it moves all the
"cheap" filter probes *before* probing any of the hash tables, it has a
multiplication effect for the benefits.
Yes, it still has most of the open issues discussed earlier, and those
will need to be addressed. But this "multiplication" may also make it
somewhat less sensitive to the regressions.
In the example above, if each of the 3 joins has 20% selectivity (i.e.
20% tuples go through), then the total selectivity is ~1%. So the "F"
scan produces only 1/100 of tuples. Maybe we got one of the joins wrong,
and it does not eliminate any tuples? That still means the overall
selectivity is only ~4%.
Of course, this only works for larger joins, and maybe the joins are
correlated in some weird way, etc. Also, what does 4% selectivity mean
for the overall query duration?
Attached is a PDF with results from a simple benchmark using joins like
the one above - fact + 1-3 dimensions. The scripts (in the .tgz) set a
couple GUCs to eliminate variations in the plan. The dimension joins are
independent and match a variable fraction of the fact (1% - 100%).
The columns are for three branches - master, and "patched" with the
push-down disabled and enabled, for joins with 1-3 dimensions.
The last two column groups are comparing the "patched" results to
master. With "off" there's no difference (other than random noise), just
as expected. But with the push-down enabled, there are fairly
significant speedups (up to ~3x). Of course, this is just a benchmark,
practical queries may do other stuff, making the gains smaller. OTOH, it
may also be much better, if there are expensive nodes in between.
The PoC patch is not very big or complex. 280KB seems like a lot, but
like 99% of that is changes in test output, because the patch adds some
info about the Bloom filters to EXPLAIN. The actual .c changes are only
~1000 lines, and a half of that is comments.
The most interesting stuff happens in create_hashjoin_plan(), where we
attempt to push-down the filter to a scan in the outer subtree. If that
succeeds, then ExecInitHashJoin initializes the filter so that the scan
can find it, and Hash builds the filter along with the hash table. And
then the scan nodes probe the pushed-down filter in ExecScanExtended().
There's bunch of boilerplate so that setrefs does the right thing with
expressions, etc. But it's a couple lines here and there. I'm actually
surprised how little code this is.
There's one detail I haven't mentioned yet - there's a simple adaptive
behavior, to deal with filters that are not selective enough. Per some
initial tests there's little benefit when the filter keeps >75% tuples,
and for >90% there were measurable regressions (~50%). This was very
consistent for different data types, etc.
So the patch tracks number of matching tuples per 1000 probes, when it
exceeds 90% it switches to sampling. Only 1% of tuples gets probed in
the filter, and if the fraction drops <80%, all the tuples get probed
again. This is very simple, needs more thought. But for the purpose of
the testing it worked quite well. There still is a small regression
(~3%), which I assume is due to building the filter.
Aside from the issues with deciding if to use a filter at all, sizing
it, etc. - which are still valid (even with the adaptive thing), and
need to be solved, there's one more annoying issue specific to this new
push-down stuff.
Earlier, I mentioned the push-down happens in create_hashjoin_plan().
Which means it happens *after* planning and costing. There are reasons
for that, but it has some unfortunate & annoying consequences.
Ideally, we'd know about the filters when constructing the scan nodes,
so we'd have a chance to estimate how many tuples will be eliminated by
probing the filters (which is about the same thing as estimating the
join sizes). But we can't do that, because our planner works bottom-up.
When constructing the scan nodes we know which tables we'll join with,
but we have no idea which of the join algorithms we'll pick.
We'll consider all three join types, and the scan node has no say which
of those will win. But the Bloom filter push-down is specific to hash
joins. So what should the scan node do? Either it can assume it's under
hash join (and set rows/cost as if there's a Bloom filter), or it can
set costs in a join-agnostic way (like now).
The only "correct" way I can think of dealing with this in the bottom-up
world is having two sets of paths - one set for a hash join, one set for
other joins. But that's not just for scans. We'd need that for all
paths, and for different combinations of joins. For the query with 3
joins, we'd end up with 2^3 combinations. That seems not great.
So I tend to see this as an opportunistic optimization. We do the
planning assuming there's no Bloom filter push-down, and then after the
fact we see if there's an opportunity after all. Which means we may not
pick a plan with hash joins, not realizing it might be made faster.
But in my mind that's somewhat acceptable / defensible.
The bigger issue for me is that it may make the EXPLAIN ANALYZE output
way harder to understand. The estimated "rows" are calculated before the
filter push-down happens, while the actual "rows" are with the filter
probing, of course. But it seems pretty easy to get confused by this,
and think it's just an incorrect estimate.
summary
-------
I like the idea of pushing filters down to the scan nodes (or perhaps
even to some other intermediate nodes). But maybe it's too incompatible
with our bottom-up planning, and the issues with costing and/or EXPLAIN
output may be impossible to solve. I wonder what others think.
Now that I revisited the older threads, I think it probably makes sense
with using Bloom filters in the hash join, at least in the two cases
mentioned in the first section. It doesn't have the issues with
bottom-up planning/costing, because it happens in the hash join. And the
issues with that (deciding what fractions are OK, sizing the filter,
...) apply to both that simpler case, and to the push-down.
Re: hashjoins vs. Bloom filters (yet again)
On 5/29/26 5:55 PM, Tomas Vondra wrote:
> old patches
> -----------
>
> Those old patches tried to do a fairly small thing during a hash join,
> and that's building a Bloom filter on the inner relation (the one that
> gets hashed), and then use that filter before probing the hash table.
>
> The benefits come from Bloom filters being (fairly) cheap, and a
> negative answer (hash is not in the filter) may allows us to skip a much
> more expensive operation.
>
> The old threads patches focused especially at two hash join cases:
>
> (a) A very selective join, i.e. a significant fraction of outer tuples
> does not have a match in the hash table.
>
> (b) A selective hash join forced to do batching because the hash table
> is too large, and thus forced to spill outer tuples to temporary files.
>
> For (a), the benefit comes from Bloom filters being much cheaper to
> probe than a hash table. The exact cost depends on the implementation,
> sizes, etc. We're in the ballpark of 50 vs. 500 cycles, maybe. But if
> the filter discards 90% of tuples, it can be a big win.
>
> For (b), the filter (for all the batches at once) allows us to discard
> some of the outer tuples without writing them to temporary files. Which
> is way more expensive than probing a hash table.
As it happens, I've been exploring the use of a bitmap filter for the
same two cases you mention. This has some relevance to the issues you
mention in your post about sizing, false-positive rate, etc.
Instead of a Bloom filter, I chose to use a bitmap filter, with one bit
per bucket on the build side. As the inner table is built, I set a bit
in the bitmap filter for every occupied bucket. If a bucket is empty,
there are no matching hashes and those hash values can be skipped where
appropriate. The advantages of this bitmap over a Bloom filter are:
- sizing is pre-determined by nbuckets
- small bitmaps (4k for 32k buckets)
- cheaper - nominal cost to set/check bits
A well-chosen Bloom filter will be more discriminating, but the bitmap
has the same no-false-negatives guarantee and costs much less space and
time to build.
I implemented both of your cases:
Drop-before-spill: (Case b)
Build per-batch bitmaps during inner partition pass and drop tuples that
don't have a bit set. Saves I/O on tuples that will never match. This
only works for inner and semi joins.
Single-Batch probe: (Case a)
Only pays off in high-miss-rate joins and a bucket array larger than
L2/L3 cache. This case has a higher penalty for hash table lookup than
the in-cache bitmap check. This case works in multi-batch, but the I/O
cost dominates and there is no gain.
I put runtime guards on both of these; I sampled the drop rate over a
window and disable the filter for the rest of the pass if the rate falls
below a threshold. (~5% for case b; ~25% for case a)
The benchmarks are encouraging:
For case a, I was able to see a best-case improvement of ~15% for
carefully chosen data (dependent on L2/L3 cache size).
For case b, I tested 3 cases with sparse, average and dense probe hits:
sparse probe (~95% miss): +18% to +36%
avg probe (~37% miss): +9% to +13%
dense probe (FK-like, ~0% miss): flat, within noise
(This was on a 8-core x86-64, L1 32KB/core, L2 4MB/core, L3 32MB, 31 GB
RAM. PostgreSQL 19devel, serial hash join,
max_parallel_workers_per_gather = 0, across work_mem = 1-8MB)
Happy to share the patch and full benchmark data if useful.
-Ben Mejia
Re: hashjoins vs. Bloom filters (yet again)
On 6/24/26 00:36, Ben Mejia wrote: > > > On 5/29/26 5:55 PM, Tomas Vondra wrote: > >> old patches >> ----------- >> >> Those old patches tried to do a fairly small thing during a hash join, >> and that's building a Bloom filter on the inner relation (the one that >> gets hashed), and then use that filter before probing the hash table. >> >> The benefits come from Bloom filters being (fairly) cheap, and a >> negative answer (hash is not in the filter) may allows us to skip a much >> more expensive operation. >> >> The old threads patches focused especially at two hash join cases: >> >> (a) A very selective join, i.e. a significant fraction of outer tuples >> does not have a match in the hash table. >> >> (b) A selective hash join forced to do batching because the hash table >> is too large, and thus forced to spill outer tuples to temporary files. >> >> For (a), the benefit comes from Bloom filters being much cheaper to >> probe than a hash table. The exact cost depends on the implementation, >> sizes, etc. We're in the ballpark of 50 vs. 500 cycles, maybe. But if >> the filter discards 90% of tuples, it can be a big win. >> >> For (b), the filter (for all the batches at once) allows us to discard >> some of the outer tuples without writing them to temporary files. Which >> is way more expensive than probing a hash table. > As it happens, I've been exploring the use of a bitmap filter for the > same two cases you mention. This has some relevance to the issues you > mention in your post about sizing, false-positive rate, etc. > > Instead of a Bloom filter, I chose to use a bitmap filter, with one bit > per bucket on the build side. As the inner table is built, I set a bit > in the bitmap filter for every occupied bucket. If a bucket is empty, > there are no matching hashes and those hash values can be skipped where > appropriate. The advantages of this bitmap over a Bloom filter are: > > - sizing is pre-determined by nbuckets > - small bitmaps (4k for 32k buckets) > - cheaper - nominal cost to set/check bits > > A well-chosen Bloom filter will be more discriminating, but the bitmap > has the same no-false-negatives guarantee and costs much less space and > time to build. > Isn't that pretty much the same thing as a Bloom filter with a single hash function? So it has the same false positive properties, i.e. it may be sacrificing some of the accuracy for not having to calculate any more hashes. Could be a win. > I implemented both of your cases: > > Drop-before-spill: (Case b) > Build per-batch bitmaps during inner partition pass and drop tuples that > don't have a bit set. Saves I/O on tuples that will never match. This > only works for inner and semi joins. > OK, makes sense. > > Single-Batch probe: (Case a) > Only pays off in high-miss-rate joins and a bucket array larger than L2/ > L3 cache. This case has a higher penalty for hash table lookup than the > in-cache bitmap check. This case works in multi-batch, but the I/O cost > dominates and there is no gain. > Right, it's hard to beat the hash table in this case. > > I put runtime guards on both of these; I sampled the drop rate over a > window and disable the filter for the rest of the pass if the rate falls > below a threshold. (~5% for case b; ~25% for case a) > This seems similar to the adaptive behavior I implemented in v2. I haven't thought of the idea of using different thresholds for the two cases - I like that. > The benchmarks are encouraging: > > For case a, I was able to see a best-case improvement of ~15% for > carefully chosen data (dependent on L2/L3 cache size). > > For case b, I tested 3 cases with sparse, average and dense probe hits: > > sparse probe (~95% miss): +18% to +36% > avg probe (~37% miss): +9% to +13% > dense probe (FK-like, ~0% miss): flat, within noise > > (This was on a 8-core x86-64, L1 32KB/core, L2 4MB/core, L3 32MB, 31 GB > RAM. PostgreSQL 19devel, serial hash join, > max_parallel_workers_per_gather = 0, across work_mem = 1-8MB) > > Happy to share the patch and full benchmark data if useful. > I'd be happy to collaborate of some of this, if you're interested. Feel free to post your patch here, or in a separate thread. Up to you. Separate threads might be easier for cfbot to track. I've spent some time hacking on v1, i.e. the pushdown - making the planning work properly, etc. That's mostly orthogonal to this, with some overlap. Ideally we'd want to do both I think. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 7/2/26 22:31, Matheus Alcantara wrote: > On Wed Jul 1, 2026 at 10:25 AM -03, Tomas Vondra wrote: >> (d) At planning / execution this works similarly to v1, except that all >> the decisions were already done. The code in createplan.c and executor >> is more for book-keeping and allowing lookup of filters. >> > > I'm wondering if the adaptive probing can mess the execution of the > choose plan. Let's say that a plan was chosen with bloom filters to > pushdown because it would reduce e.g 50% of the rows, what if at > runtime the bloom filter is proved to not be effective and it get > disabled making the scan node to produce 100% of the rows to the node > above that is not expecting? Do we end up with the same issue "expected > x actual rows"? > > I think that if we keep using the unnefective bloom filter the scan node > will still produce more rows than expected, but perhaps this is easier > to understand? > Yes. If we pick a filter expecting it to eliminate 99% of tuples, but then find it does not eliminate any tuples, that'll affect the counts in explain. But that's simply how misestimates work, it's not specific to filter pushdown. It may happen for WHERE clauses etc. The estimate would hit us at some point anyway - it's the selectivity of the join, so even without the pushdown the cardinality would be off above the join. Also, what else could we do? I don't think we can do planning assuming the estimates are off - we have to assume the estimates are OK. We might consider how "safe" a given estimate is, and then maybe not push down filters for "risky" ones, but we don't have any such capability. >> I haven't incorporated the two patches posted by Andrew: >> >> 1) making it work with CustomScans >> >> 2) supporting per-key filters >> >> 3) allow eager creation of filters (disable delayed Hash build) >> >> I agree those seem like a worthwhile improvements, and the patches >> seemed to be OK too, but I was focusing on reworking the planning. Based >> on some off-list discussion, Andrew (or one of his colleagues) should be >> able to adjust those for this v3 patch. >> > > I'm attaching a new v4 patchset incorporating Andrew patches with test > cases. 0001 and 0002 are your v3 untouched, 0003 is some tests added to > exercice the CustomScan path and 0004 is the Andrew changes with a few > changes required from v3 version: > > Unlike the v1 PoC that pushed filters down in create_hashjoin_plan > (where it could simply walk the finished plan tree and accept any scan > node), the filters are now decided during bottom-up path construction, > so a scan only receives a filter if a filter-bearing path was generated > for its base relation. So the main change is teaching path generation > about the custom scan. > Thanks, I'll take a look early next week. My plan is to create a branch carrying all the pieces, and then gradually refine that. One thing I'm a bit concerned about is the CustomScan support. We don't have a single module in the tree, so how would we test the changes? I think it might be necessary to introduce a minimal CustomScan module, so that we can test the new pieces. >> In fact, I'm thinking it might be better to abstract the "filter" and >> stop thinking just about Bloom filters. There probably are other kinds >> of interesting filters, so maybe we should not assume all filters are >> Bloom filters. Those filters probably won't be that different, it's more >> about not putting "Bloom" in naming etc. >> > > I was also thinking about this when reading v1. I was checking other > databases and I realize that Trino [1] and Duckdb (I didn't find any > documentation from Duckdb but you can see this information on explain > analyse output) have "Dynamic Filtering" and IIUC is a similar > optimization that this patch is about. > > I'm wondering if we could name as "Dynamic Filtering" or "Runtime filter > pushdown" or something else instead of Bloom Filters to make it more > generic. > > On explain(analyze) output we can show as as "Runtime filter" and put > the columns (perhaps the values?) used on the filter. > > I think that this can abstract and let the implementation decide if it > will use a bloom filter or not. It's a rough idea, but what do you > think? > Yeah. I don't think the name is that important, it's more about what kind of flexibility is needed. > I'm still thinking about your other points and about the XXX comments. > I'll share more soon. > Thanks! -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On Fri Jul 3, 2026 at 7:10 AM -03, Tomas Vondra wrote: >> I'm wondering if the adaptive probing can mess the execution of the >> choose plan. Let's say that a plan was chosen with bloom filters to >> pushdown because it would reduce e.g 50% of the rows, what if at >> runtime the bloom filter is proved to not be effective and it get >> disabled making the scan node to produce 100% of the rows to the node >> above that is not expecting? Do we end up with the same issue "expected >> x actual rows"? >> >> I think that if we keep using the unnefective bloom filter the scan node >> will still produce more rows than expected, but perhaps this is easier >> to understand? >> > > Yes. If we pick a filter expecting it to eliminate 99% of tuples, but > then find it does not eliminate any tuples, that'll affect the counts in > explain. But that's simply how misestimates work, it's not specific to > filter pushdown. It may happen for WHERE clauses etc. > > The estimate would hit us at some point anyway - it's the selectivity of > the join, so even without the pushdown the cardinality would be off > above the join. > > Also, what else could we do? I don't think we can do planning assuming > the estimates are off - we have to assume the estimates are OK. We might > consider how "safe" a given estimate is, and then maybe not push down > filters for "risky" ones, but we don't have any such capability. > Yeah, I was just worried about this may add more confusing, but after more thinking it does not seems to be the case. I was imagining a scenario where the expected x actual rows is not very accurate and it could be hard to know if it was because outdated stats or because the adaptive probing decided to turn off the filter pushdown but I think that in the end it's all the same problem: The adaptive probing may turn off the filter because it's not very effective but this can happen because of outdated stats that make the planner think that the push down filters would help but it's not. > >>> I haven't incorporated the two patches posted by Andrew: >>> >>> 1) making it work with CustomScans >>> >>> 2) supporting per-key filters >>> >>> 3) allow eager creation of filters (disable delayed Hash build) >>> >>> I agree those seem like a worthwhile improvements, and the patches >>> seemed to be OK too, but I was focusing on reworking the planning. Based >>> on some off-list discussion, Andrew (or one of his colleagues) should be >>> able to adjust those for this v3 patch. >>> >> >> I'm attaching a new v4 patchset incorporating Andrew patches with test >> cases. 0001 and 0002 are your v3 untouched, 0003 is some tests added to >> exercice the CustomScan path and 0004 is the Andrew changes with a few >> changes required from v3 version: >> >> Unlike the v1 PoC that pushed filters down in create_hashjoin_plan >> (where it could simply walk the finished plan tree and accept any scan >> node), the filters are now decided during bottom-up path construction, >> so a scan only receives a filter if a filter-bearing path was generated >> for its base relation. So the main change is teaching path generation >> about the custom scan. >> > > Thanks, I'll take a look early next week. My plan is to create a branch > carrying all the pieces, and then gradually refine that. > Good, thanks. > One thing I'm a bit concerned about is the CustomScan support. We don't > have a single module in the tree, so how would we test the changes? I > think it might be necessary to introduce a minimal CustomScan module, so > that we can test the new pieces. > On 0003 I've created a new test extension that register a CustomScan method. It also expose some sql functions to assert some behaviours of filter pushdown. I think that it's still on early stage but it may help. Let me know what do you think. -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 7/2/26 22:31, Matheus Alcantara wrote:
> On Wed Jul 1, 2026 at 10:25 AM -03, Tomas Vondra wrote:
>> (d) At planning / execution this works similarly to v1, except that all
>> the decisions were already done. The code in createplan.c and executor
>> is more for book-keeping and allowing lookup of filters.
>>
>
> I'm wondering if the adaptive probing can mess the execution of the
> choose plan. Let's say that a plan was chosen with bloom filters to
> pushdown because it would reduce e.g 50% of the rows, what if at
> runtime the bloom filter is proved to not be effective and it get
> disabled making the scan node to produce 100% of the rows to the node
> above that is not expecting? Do we end up with the same issue "expected
> x actual rows"?
>
> I think that if we keep using the unnefective bloom filter the scan node
> will still produce more rows than expected, but perhaps this is easier
> to understand?
>
>> I haven't incorporated the two patches posted by Andrew:
>>
>> 1) making it work with CustomScans
>>
>> 2) supporting per-key filters
>>
>> 3) allow eager creation of filters (disable delayed Hash build)
>>
>> I agree those seem like a worthwhile improvements, and the patches
>> seemed to be OK too, but I was focusing on reworking the planning. Based
>> on some off-list discussion, Andrew (or one of his colleagues) should be
>> able to adjust those for this v3 patch.
>>
>
> I'm attaching a new v4 patchset incorporating Andrew patches with test
> cases. 0001 and 0002 are your v3 untouched, 0003 is some tests added to
> exercice the CustomScan path and 0004 is the Andrew changes with a few
> changes required from v3 version:
>
> Unlike the v1 PoC that pushed filters down in create_hashjoin_plan
> (where it could simply walk the finished plan tree and accept any scan
> node), the filters are now decided during bottom-up path construction,
> so a scan only receives a filter if a filter-bearing path was generated
> for its base relation. So the main change is teaching path generation
> about the custom scan.
>
I took a quick look at the v4 patches adding the earlier patches from
Andrew,, and I think it looks sensible enough for a PoC. Thanks!
I think it'd make sense to split some of these into separate commits, as
it's not necessarily tied to just CustomScan nodes. And even if it is,
it can be a separate easier-to-review change.
I propose we move these two "features" into separate commits:
- "eager" creation of filters
- requesting per-key filters
I think it might be useful for other scans (or even non-scan nodes, if
we choose to allow filter pushdown for these). And it should be a
"generic" thing so that find_bloom_filter_recipient does not need to
check if the recipient is CustomScan. In fact, I think this should be
part of the information about expected filters "propagated" up during
planning.
FWIW It might make sense to show these things in the explain, at least
for development. AFAICS the CustomScan (used by the tests in 0003) does
not actually print the filters, right? And I'm not sure if the per-key
filters will be printed at all. But that's minor / easy to fix.
To move this whole thing forward, we'll need to figure out what to do
about the *big* questions. The four main ones I can think of (based on
memory and skimming the XXX comments in the patches) are:
1) selection of 'interesting' filters
Currently, we pick 'candidate' filters based solely on the selectivity,
but that only works if the scans don't use the filter in some smart way
(i.e. when it's evaluated at the very end). But if the custom scan can
do something very smart with some filters, the selectivity alone may not
be enough. The per-key filters make it even harder, I think.
2) construction of paths with filters (adjusting cost)
Right now the paths are constructed by "cloning" existing scan paths,
which is what create_filtered_scan_path does. But as already mentioned
in some XXX comments, I don't think it can work like this.
First, there's the question of costing. Do we need to adjust the cost in
some path-specific way? Maybe we don't, at least for built-in core
paths? In that case the filters are evaluated on the tuples the path
would produce, so maybe we can just add a bit of CPU cost per tuple, to
account for the evaluation of the filter (and reduce the row estimate).
Ff the filter is selective it'd still win, as expected.
But it's a bit dubious even for built-in core paths, because we'd
operate only on paths that already went through add_path and survived
the selection. Maybe we already eliminated some interesting path?
With "smart" CustomScan it's a bigger problem, though. If the scan is
doing something smart with the filters, it likely needs to adjust the
cost in a much more complex way. But the cloning does not allow that.
But more importantly, we can't copy CustomPath like this, because the
comment in pathnodes.h says:
* Core code must avoid assuming that the CustomPath is only as
* large as the structure declared here; providers are allowed to
* make it the first element in a larger structure. (Since the
* planner never copies Paths, ...
And we'd violate that. (Maybe this is a problem for the in-core scan
paths too?)
Some particular CustomPaths might be OK, but we can't know which ones
are. Maybe we could require scans wih CUSTOMPATH_SUPPORT_BLOOM_FILTERS
to allow such cloning, but it seems pretty fragile.
3) pushdown to multiple consumers (scans of partitioned tables)
Right now, we only allow pushdown to a single consumer. But with
partitioned tables that won't work - each partition scan is a consumer
of the same join (unless it's a partition-wise join, probably). We need
to make that work. It probably can't happen right now, because we don't
push through Append nodes (per find_bloom_filter_recipient), but that
seems like something we should allow.
Does not seem extremely particularly hard to address, though. The
find_bloom_filter_recipient simply needs to collect a list of recipient
nodes, not just the one.
4) parallel hash joins
There's some complexity due to having to put the filter into shmem, but
the v2 patch solved that I think, and we can mostly just copy that. I
don't think we need to solve that now.
I think (3) and (4) are somewhat mechanical. I know, it can easily be
much harder I envision. We won't know until we try.
For (1) and (2), I think we need to make this work more like how we
build paths for pathkeys. Do some sort of initial selection of
interesting filters, without trying to be very smart. So we'd maybe
check the filter discards > 30% of tuples, but without trying to keep
only the "top three" filters.
Then we'd generate the paths for all the possible combinations of
filters, not by cloning but by passing the expected filters to the
create_ function, and constructing a new path. If the scan can do
something smart - cool, it'd calculate the cost. In the worst case it'd
apply the filter at the end, with the generic cost / rows adjustment.
The paths with matching expected filters would still compete (just like
for matching pathkeys), of course.
There's still need to be some limits, though. If the table has 10 joins,
we can't generate paths for each possible combination of filters, that'd
be 2^10 combinations. But there are some inherent limits too, I think.
For example, once we discard ~90% tuples it probably does not make much
sense to keep applying additional filters. If each filter discards ~50%
tuples, that's 3 filters. So even with 10 joins we'd be limited to ~120
paths (which is still a lot, but way lower than 2^10).
We could still have some "heuristics" limits too, e.g. don't keep all
these paths, but prune them very aggressively and pick only the best
ones - just like we do now by only picking 3 most selective filters,
except that we'd do that based on proper costing (and not selectivity).
I plan to experiment with (1) and (2) soon, but it'd be great if you
could experiment with that too, and/or think about alternative ideas.
regards
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On Wed, Jun 3, 2026 at 5:21 AM Oleg Bartunov wrote: > For a plain heap scan this may mostly save hash probes. But with zone/chunk-oriented storage, where chunks have dictionaries, min/max metadata, Bloom summaries, or tenant ranges, the same runtime filter can skip whole chunks. That is the part I find most interesting: turning join-derived knowledge into scan-level pruning, against the normal direction of data flow. > > Bloom is just one carrier for that knowledge. The real feature is a pluggable runtime-filter mechanism that heap, CustomScan, FDW, columnar/table AMs, partitioned storage, or chunk/cold storage can consume at the level they understand. +1. I think it's fine if the optimizer and executor decide to do things strictly with Bloom filters, if that turns out to be a good technique. But if we're talking about pushing things down into table AM we should try to be more general. Or at least, that's my current thinking. -- Robert Haas EDB: http://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On Wed, Jun 3, 2026 at 6:07 AM Tomas Vondra wrote > Right, there's a general concept of a "filter", and Bloom filters are > just one example of that. And maybe we could build other types of > filters more suitable for the scan. But I think it'll still be tied to a > hash join, because what other nodes / joins can build the filter? Even if only hash joins build Bloom filters (or some other kind of filters), those filters can be pushed through other joins. For example, consider: Hash Join Nested Loop -> Seq Scan on a -> Index Scan on b -> Hash -> Seq Scan on c If the hash join to table c builds a Bloom filter, it's perfectly valid to test against that filter before doing the index probe into table b. The hard part is the planning. I feel like doing this at path-to-plan time, after costing decisions have been made, is probably going to be a tough sell. In a plan tree with many joins, pushing down the Bloom filtering (or other filtering) decision to the lowest possible level could drastically change the row count estimates, and thus the costing, for a whole bunch of intermediate nodes, potentially meaning that the best plan is something quite different from what we estimated. On the other hand, if we try to do the "right" thing at planning time -- meaning constructing separate paths for each possible place where we could put the filter -- so that we can do costly properly, that sounds super-expensive, which will be really bad for queries that are supposed to have short execution times, and also not great for cases where the runtime is longer but our estimates are inaccurate, so that the extra planning effort is an expensive way of deciding what to do at random. i haven't hard time to read the paper to which you linked, but I do sort of feel like knowing what the practical experience has been in other systems might be important. Theoretically there are good arguments for and against additional planning effort, but what happens in practice is not clear to me. -- Robert Haas EDB: http://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 7/6/26 21:32, Robert Haas wrote:
> On Wed, Jun 3, 2026 at 6:07 AM Tomas Vondra wrote
>> Right, there's a general concept of a "filter", and Bloom filters are
>> just one example of that. And maybe we could build other types of
>> filters more suitable for the scan. But I think it'll still be tied to a
>> hash join, because what other nodes / joins can build the filter?
>
> Even if only hash joins build Bloom filters (or some other kind of
> filters), those filters can be pushed through other joins. For
> example, consider:
>
> Hash Join
> Nested Loop
> -> Seq Scan on a
> -> Index Scan on b
> -> Hash
> -> Seq Scan on c
>
> If the hash join to table c builds a Bloom filter, it's perfectly
> valid to test against that filter before doing the index probe into
> table b.
>
I don't disagree, but it's that what all the push-down patches in this
thread are already doing? When I said "tied to hash join" I meant the
filter would be built by a hash join, not that all the joins have to be
hash joins. It can certainly by pushed through NL/merge joins.
> The hard part is the planning. I feel like doing this at path-to-plan
> time, after costing decisions have been made, is probably going to be
> a tough sell. In a plan tree with many joins, pushing down the Bloom
> filtering (or other filtering) decision to the lowest possible level
> could drastically change the row count estimates, and thus the
> costing, for a whole bunch of intermediate nodes, potentially meaning
> that the best plan is something quite different from what we
> estimated. On the other hand, if we try to do the "right" thing at
> planning time -- meaning constructing separate paths for each possible
> place where we could put the filter -- so that we can do costly
> properly, that sounds super-expensive, which will be really bad for
> queries that are supposed to have short execution times, and also not
> great for cases where the runtime is longer but our estimates are
> inaccurate, so that the extra planning effort is an expensive way of
> deciding what to do at random.
>
I agree, but I think you're still looking at the v1 patch. The v3 posted
a week ago (and v4 posted by Matheus) are doing this doing the bottom-up
planning, when constructing scan paths.
You're definitely right the extra paths may be rather expensive, and
we'll need to keep that under control. If a query has 10 joins, we can't
realistically consider all 2^10 of filter combinations. The patch does
that by selecting a couple of the most promising filters, but I'm sure
we may need to do more.
With pushdown done at path-to-plan time, this was not an issue, but as
you point out it's after we already selected the plan. So we might have
missed a "better" plan, it was merely an attempt to improve the plan we
already selected. OTOH, that "limited the damage" when our estimates
turned out to be wrong.
But I think there are more options how to limit the cost. For example,
it's unlikely to help when the scan already returns very few tuples. So
maybe we could consider filters only when the row count is above 1000,
or something like that. And maybe we could do something similar based on
cost? But that would ignore savings above the scan (e.g. maybe one of
the later joins is very expensive).
I think a lot of the regressions can be handled by adaptive behavior at
execution time. Like, we can postpone building the filter until after
we've already probed the hash table to know it's worth it. Or disable
the filter when it becomes ineffective. The v3/v4 patches already do
some of this, IIRC.
The CustomScan could ignore a lot of that, of course. For example, v4
has an option to force building the filter eagerly (so that hashjoin
does not wait for the first outer tuple). But that's really a problem of
the CustomScan authors.
Of course, even with the adaptive behavior we're "stuck" with the new
plan (which may differ from the plan we'd have picked otherwise). But
I'm not sure it's really that different. Because really, the impact is
somewhat limited.
What happens is that we pick the K most selective joins, and build
filters for those. And then we plan with that. Those selective joins
would be at the very bottom of the original plan, because we prefer to
do selective joins first.
Let's say a plan has 4 joins.
X
/ \
B2 X
/ \
B1 X
/ \
A2 X
/ \
A1 T
Most likely, A1 and A2 joins are the two most selective, so we get to
build filters for those, and push them to scan on T. Which means the
filtering is applied in the scan, and the joins themselves won't reduce
the cardinality at all!
The B1 and B2 joins become "more selective", and in the new plan
(selected with filter pushdown) will be performed first:
X
/ \
A2 X
/ \
A1 X
/ \
B2 X
/ \
B1 T (filters from A1/A2)
But the A1/A2 filtering still happens *before* B1/B2, thanks to the
filter. So B1/B2 are still planned with the same selectivity and row
counts as before, and so will most likely use the same join algorithm.
So the impact on the query plan is actually much smaller than it might
seem. Which likely limits the risks quite a bit.
Of course, this is just a very simple example. Maybe it's riskier for
more complex joins, not sure.
> i haven't hard time to read the paper to which you linked, but I do
> sort of feel like knowing what the practical experience has been in
> other systems might be important. Theoretically there are good
> arguments for and against additional planning effort, but what happens
> in practice is not clear to me.
>
That's a good idea, but I'm not aware of an open source database
implementing this :-(
regards
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 7/7/26 23:19, Robert Haas wrote: > On Tue, Jul 7, 2026 at 2:39 PM Tomas Vondra wrote: >> I don't disagree, but it's that what all the push-down patches in this >> thread are already doing? When I said "tied to hash join" I meant the >> filter would be built by a hash join, not that all the joins have to be >> hash joins. It can certainly by pushed through NL/merge joins. > > I haven't actually looked at the patches -- I was just responding to > the email. Sounds like I misunderstood. > >> You're definitely right the extra paths may be rather expensive, and >> we'll need to keep that under control. If a query has 10 joins, we can't >> realistically consider all 2^10 of filter combinations. > > Yeah. > >> But I think there are more options how to limit the cost. For example, >> it's unlikely to help when the scan already returns very few tuples. So >> maybe we could consider filters only when the row count is above 1000, >> or something like that. And maybe we could do something similar based on >> cost? But that would ignore savings above the scan (e.g. maybe one of >> the later joins is very expensive). > > I'm not sure which scan you mean when you say "when the scan already > returns very few tuples." Suppose we propose to join A to B. We plan > to use a hash join and use B as the build table and A as the probe > table. So, if I understand correctly, we'd build the bloom filter on B > and use it when scanning A. Do you mean that the filter is unlikely to > help when B is small, or when A is small? When A is small, i.e. the outer side of the join (not the side on which we built the hash / filter). The idea is that if the outer side has 1000 rows, even if we eliminate 90% of them it may not pay for itself (because of the cost of extra paths during planning, building the filters etc.). One of my ideas for keeping the number of paths under control was to stop "adding" filters to a path once the cardinality drops below some threshold. Let's say we start with a scan returning 1M rows, and we add 2 filters eliminating 90% tuples each. Cool, now it's expected to return 10k rows. Should we consider a version with a 3rd filter? Maybe it'll help a little bit, but the benefit is certainly much smaller than for the first two filters. > Neither is obvious to me: if > B is small, the hash table will be small, which might make it cheap to > probe, but it also makes the Bloom filter small, so maybe that's > *really* cheap to probe, plus a small Bloom filter is enough to have a > really low false-positive rate. The size of B (on which the hash table is built) is a very poor signal. What matters is the selectivity of the join, and a tiny table can eliminate 1% or 99% - it does not depend on the size. Yes, a tiny table may be cheap to probe (the Bloom filter will still be cheaper, but it'll be closer). For large hash tables the trade offs is a bit different, especially when the join start spilling. But even then it's more about what fraction of tuples it eliminates. But focusing on the relative cost of probing the hash table vs. probing the Bloom filter is missing the point - it's about *when* you probe it. With the pushdown the probe happens much earlier, before doing a lot of other relatively expensive stuff. As an extreme case, imagine we push the filter into a ForeignScan. The foreign scan could copy the filter to the remote side, and discard all the tuples there, saving all the network costs. (Yes, the patches don't do this - yet, but it's not a huge change.) Yes, maybe we could skip building the filter and just probe the hash table directly. That only works in some cases (e.g. the FDW case would not work), and only when the hash table is "complete" (no spilling). > If A is small, you're not going to > save as much in absolute terms, but you save the same thing > percentage-wise as on a larger table. > > It seems like the most important thing -- which I'm aware you already > mentioned -- is how likely it is that a row in A joins to a row in B. > If the answer is "not very likely," the filter has a good chance of > working out. > Exactly. And then it's also about the cost of what happens in between the probe and the join. >> I think a lot of the regressions can be handled by adaptive behavior at >> execution time. Like, we can postpone building the filter until after >> we've already probed the hash table to know it's worth it. Or disable >> the filter when it becomes ineffective. The v3/v4 patches already do >> some of this, IIRC. > > Yeah, adaptive behavior is great. We need to be careful not to add too > much complexity, on the one hand, or to expect perfection, on the > other. But it's a good way of mitigating downsides. > 100% agreed >> Of course, even with the adaptive behavior we're "stuck" with the new >> plan (which may differ from the plan we'd have picked otherwise). But >> I'm not sure it's really that different. Because really, the impact is >> somewhat limited. > > This doesn't especially worry me: any plan can be wrong. If the > planner goes wrong substantially more frequently with this patch than > without, of course that would be bad. But if it just goes wrong for a > different set of queries, I think that's just life. > OK >> What happens is that we pick the K most selective joins, and build >> filters for those. And then we plan with that. Those selective joins >> would be at the very bottom of the original plan, because we prefer to >> do selective joins first. > > This is a clever idea. > >> Let's say a plan has 4 joins. >> >> X >> / \ >> B2 X >> / \ >> B1 X >> / \ >> A2 X >> / \ >> A1 T >> >> Most likely, A1 and A2 joins are the two most selective, so we get to >> build filters for those, and push them to scan on T. Which means the >> filtering is applied in the scan, and the joins themselves won't reduce >> the cardinality at all! >> >> The B1 and B2 joins become "more selective", and in the new plan >> (selected with filter pushdown) will be performed first: >> >> X >> / \ >> A2 X >> / \ >> A1 X >> / \ >> B2 X >> / \ >> B1 T (filters from A1/A2) >> >> But the A1/A2 filtering still happens *before* B1/B2, thanks to the >> filter. So B1/B2 are still planned with the same selectivity and row >> counts as before, and so will most likely use the same join algorithm. > > They could switch to a nested loop, though, which is a little tricky > to reason about: any individual join could be better as a nested loop, > while the set of joins taken together might be better if you use all > hash joins so that the filters can be combined. > No, I don't think they could switch to nested loops. That's the whole point - the B1/B2 joins are planned with *exactly* the same row estimates as before, because A1/A2 still eliminate the tuples before B1/B2. So if they are nested loops in the new plan, it'd be the same in the old plan too. Of course, it can happen that B1/B2 really are nested loops, and that it's a poor choice because A1/A2 eliminated much smaller fraction of tuples than we thought. But that affects both plans the same way. >> So the impact on the query plan is actually much smaller than it might >> seem. Which likely limits the risks quite a bit. >> >> Of course, this is just a very simple example. Maybe it's riskier for >> more complex joins, not sure. > > I don't see that a more complex tree magnifies the risk; I think it's > just about how sure you can be that you're actually going to filter > something out. Your chances of winning probably actually grow with the > number of joins for which you build the filter, because I guess you > can bitwise-AND all of those filters and just test the result. If even > one of the filters is highly selective, that may gain you enough to > pay for the cost of building all of them. This is not guaranteed, of > course, but the risks and rewards seem asymmetric: a useful filter > seems as though it can win much harder than a useless filter can ever > lose. I could be wrong, but my guess is that we only need to do a > moderately good job avoiding the worst case. > I admit I'm hedging a little bit - it's probably fine even for complex plans, but I haven't done enough tests to make such a clear claim. Maybe you're right more filters make it safer. But more filters mean we need to consider more paths, so it's a trade off. Unless we figure out a good way to pick "interesting" combinations. I'm not sure about combining the filters by bitwise-AND. Maybe it could work and help a little bit, but it'd also require all the filters to have the same size. It's worth testing, but I think the cost of the filter probe does not matter all that much (compared to the savings by eliminating the tuples much earlier). regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On Mon Jul 6, 2026 at 10:34 AM -03, Tomas Vondra wrote: > I took a quick look at the v4 patches adding the earlier patches from > Andrew,, and I think it looks sensible enough for a PoC. Thanks! > > I think it'd make sense to split some of these into separate commits, as > it's not necessarily tied to just CustomScan nodes. And even if it is, > it can be a separate easier-to-review change. > > I propose we move these two "features" into separate commits: > > - "eager" creation of filters > > - requesting per-key filters > Yes, I agree. > I think it might be useful for other scans (or even non-scan nodes, if > we choose to allow filter pushdown for these). And it should be a > "generic" thing so that find_bloom_filter_recipient does not need to > check if the recipient is CustomScan. In fact, I think this should be > part of the information about expected filters "propagated" up during > planning. > Agree. > FWIW It might make sense to show these things in the explain, at least > for development. AFAICS the CustomScan (used by the tests in 0003) does > not actually print the filters, right? And I'm not sure if the per-key > filters will be printed at all. But that's minor / easy to fix. > Yeah, it does not print the filters. Also agree with showing this on explain. > To move this whole thing forward, we'll need to figure out what to do > about the *big* questions. The four main ones I can think of (based on > memory and skimming the XXX comments in the patches) are: > I've been thinking about these CustomScan issues but I'll focus more on it once we resolve the questions 1 and 2. > For (1) and (2), I think we need to make this work more like how we > build paths for pathkeys. Do some sort of initial selection of > interesting filters, without trying to be very smart. So we'd maybe > check the filter discards > 30% of tuples, but without trying to keep > only the "top three" filters. > > Then we'd generate the paths for all the possible combinations of > filters, not by cloning but by passing the expected filters to the > create_ function, and constructing a new path. If the scan can do > something smart - cool, it'd calculate the cost. In the worst case it'd > apply the filter at the end, with the generic cost / rows adjustment. > > The paths with matching expected filters would still compete (just like > for matching pathkeys), of course. > > There's still need to be some limits, though. If the table has 10 joins, > we can't generate paths for each possible combination of filters, that'd > be 2^10 combinations. But there are some inherent limits too, I think. > For example, once we discard ~90% tuples it probably does not make much > sense to keep applying additional filters. If each filter discards ~50% > tuples, that's 3 filters. So even with 10 joins we'd be limited to ~120 > paths (which is still a lot, but way lower than 2^10). > > We could still have some "heuristics" limits too, e.g. don't keep all > these paths, but prune them very aggressively and pick only the best > ones - just like we do now by only picking 3 most selective filters, > except that we'd do that based on proper costing (and not selectivity). > > This make sense to me as a direction. I've been sketching this idea and here is my attempt to implement. This is still a PoC, it still need more polishment but I've wrote some comments and commit message to try to explain the idea. For (1), the candidate selection no longer picks the "top three" most selective filters. It still requires a candidate to discard at least bloom_filter_pushdown_threshold (30% by default) of the rel's tuples, but every candidate clearing that bar is kept, with no count-based trim. For (2), combinations are now generated breadth-first by increasing size instead of enumerating every non-empty subset, and a combination stops growing once its combined selectivity drops below a new bloom_filter_pushdown_combination_floor GUC (0.1 by default). bloom_filter_pushdown_max now caps how many filters can be combined into one path rather than how many candidates survive. So, with ~50% selective filters, growth stops around 3 deep regardless of how many candidates exist, so 10 joins doesn't turn into 2^10 paths. Each combination is passed straight into the real create_*_path constructor for its scan type instead of being produced by cloning an already-costed path. A new apply_expected_filters() helper is the generic "cost/rows adjustment" fallback: it charges one cpu_operator_cost per filter per tuple on top of shrinking the row estimate, so filtering is no longer free. IndexPath is the one exception still handled by cloning, since create_index_path() would just redundantly re-derive indexclauses/pathkeys for no benefit, perhaps I think that we can improve this. For CustomPath, core can't safely clone or construct one at all. So it doesn't touch CustomPath for this anymore — a provider that wants filter-aware CustomPaths builds them itself, using the new exported filter-combination function and either costing them for real or falling back to the same generic adjustment core uses. Paths with differing expected filters still never dominate each other in add_path, so they compete on cost exactly like paths with different pathkeys do, same as in v4. This is implemented in 0005; the other patches are the same as those in v4. I think we can try combining some of these patches. Perhaps 0001 and 0002? Appreciate comments on whether this make sense or not. -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 7/7/26 20:39, Tomas Vondra wrote: > ... > >> i haven't hard time to read the paper to which you linked, but I do >> sort of feel like knowing what the practical experience has been in >> other systems might be important. Theoretically there are good >> arguments for and against additional planning effort, but what happens >> in practice is not clear to me. >> > > That's a good idea, but I'm not aware of an open source database > implementing this :-( > I still think the paper is the best source for what I'm trying to do in this thread (more about that later). But your question regarding what are the other databases doing, and the pros/cons of the approaches, is perfectly reasonable. I said I'm not aware of another open source database implementing this stuff, but that's partially because I did not search for it. So over the past couple days I did that - tried looking for databases (preferably open source ones) implementing some variant of this feature ... And indeed - I found databases implementing features like this. It may be called "runtime filter", "dynamic filter" or "join filter" (and I'm sure there are more names for this). AFAIK none implements the approach described in the paper. Which is not that surprising, as the paper is quite new (although, others might have come up with the approach independently, ofc). But also because some of the databases are not doing "our" bottom-up planning. I did look at these databases: DuckDB, ClickHouse, Spark, Trino, Impala, Hive and a couple others. Most of these are analytical databases, some are MPP/distributed engines, etc. Which is not surprising, the filter pushdown is irrelevant for OLTP workloads, it's analytical feature. A lot of this is based on docs I found / googling stuff / ... I did try to verify as much as humanly possible in acceptable amount of time, including looking at the code doing that. Which was pretty difficult, because most of the code seems pretty unreadable - maybe the C++ is simply incomprehensible to me, or maybe I'd need more time to get familiar with the various code bases. Or maybe we managed to make the Postgres code very readable. Not sure. Anyway, there still might be some mistakes / inaccuracies, sorry about that. Please call them out. I'll discuss the things shared by most of the databases first, and then will talk about the interesting bits where the approaches differ. 1) filter types The main thing shared by most of the databases is the types of filters supported. Most of the databases support these three kinds of filters: * Bloom filters * exact "IN" list of values * min/max range filter There are some differences in how the filter type gets selected, sometimes the filter is "hybrid" and combines e.g. Bloom + min/max. Most of these differences seem minor, and depend on how exactly the database uses the filter. For example, min/max filter allows efficient pruning of zonemaps (which are pretty similar to our BRIN minmax indexes). That kind of stuff. I guess this would be up to the CustomScan to decide what kind of filters it can leverage. My conclusion from this is that we should aim for "generic" filter, not just for Bloom filters. Which just validates the points made earlier in this thread, so that's good. 2) impact on planning The main differences seem to be in how the filters affect planning, i.e. at which point are they selected, and how they affect the plan shape (if at all). While the databases do planning in different ways (some are top-down, other bottom-up), it seems all of them decide filters in some post-processing phase, after the overall plan shape was selected. For example DuckDB has a rule-based optimizer, which applies various optimization transformations on the plan, in a particular sequence. And the filter selection is one such "optimizer" pass, which runs after the join order has already been selected (so the filters probably can't affect that aspect). If you look at slide 137 "Order of Optimization Passes in DuckDB (version 1.5)" in [1], then it lists "join_filter_pushdown" as pass 31 at the very end, including join_order etc. Note: There are two papers [1][2] about "Robust Predicate Transfer" in DuckDB, describing a much more elaborate way to decide filters, but AFAIK both are experimental/research implementations, not something DuckDB already does. The other databases seem to do planning in similar ways, i.e. as post-processing on already selected plan. Obviously, the exact point at which it happens is different. 3) heuristics There seem to be different heuristics when deciding whether to create a filter or not, but I've been unable to compile a good overview. Some of the heuristics is very closely tied to details of the MPP plan (which fragments are "local" and "global", ...). But generally, the heuristics are pretty "expected" - estimate the filter selectivity, and if the filter does not eliminate enough tuples, then don't use the filter. 4) partition pruning One interesting idea is that Apache Spark SQL apparently can use the filter to prune partitions (feature "dynamic partition pruning"). Which seem to be "partitions" in the sense we use. The other sysstems (like Impala) can of course use the filter to prune stuff at the storage level (so something a CustomScan would do). But the partition pruning seems like an interesting option. I haven't really considered using filters for that before. That's all I have at this point. TBH I'm not sure how much useful stuff we learned from this :-( [1] https://blobs.duckdb.org/slides/DiDi.pdf [2] https://duckdb.org/library/robust-predicate-transfer/ [3] https://people.iiis.tsinghua.edu.cn/~huanchen/publications/rpt+-vldb26.pdf -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On Mon Jul 13, 2026 at 5:17 PM -03, Tomas Vondra wrote: > I'll discuss the things shared by most of the databases first, and then > will talk about the interesting bits where the approaches differ. > > > 1) filter types > > The main thing shared by most of the databases is the types of filters > supported. Most of the databases support these three kinds of filters: > > * Bloom filters > * exact "IN" list of values > * min/max range filter > > There are some differences in how the filter type gets selected, > sometimes the filter is "hybrid" and combines e.g. Bloom + min/max. Most > of these differences seem minor, and depend on how exactly the database > uses the filter. > > For example, min/max filter allows efficient pruning of zonemaps (which > are pretty similar to our BRIN minmax indexes). > > That kind of stuff. I guess this would be up to the CustomScan to decide > what kind of filters it can leverage. > > My conclusion from this is that we should aim for "generic" filter, not > just for Bloom filters. Which just validates the points made earlier in > this thread, so that's good. > +1. I think that a generic filter API make totatly sense. > > 2) impact on planning > > The main differences seem to be in how the filters affect planning, i.e. > at which point are they selected, and how they affect the plan shape (if > at all). > > While the databases do planning in different ways (some are top-down, > other bottom-up), it seems all of them decide filters in some > post-processing phase, after the overall plan shape was selected. > > For example DuckDB has a rule-based optimizer, which applies various > optimization transformations on the plan, in a particular sequence. And > the filter selection is one such "optimizer" pass, which runs after the > join order has already been selected (so the filters probably can't > affect that aspect). > > If you look at slide 137 "Order of Optimization Passes in DuckDB > (version 1.5)" in [1], then it lists "join_filter_pushdown" as pass 31 > at the very end, including join_order etc. > > Note: There are two papers [1][2] about "Robust Predicate Transfer" in > DuckDB, describing a much more elaborate way to decide filters, but > AFAIK both are experimental/research implementations, not something > DuckDB already does. > > The other databases seem to do planning in similar ways, i.e. as > post-processing on already selected plan. Obviously, the exact point at > which it happens is different. > > Trino also have rule-based optmizer that apply the pushdown filtering [1]. "Extensible query optimizers in practice" [2] book also briefly mention Catalyst which is an extensinble query optmiser for Spark SQL which also implement filtering pushdown using rules (section 3.4). I am inclined to think that Postgres should do something similar and have a post planning phase to create these filters (which IIUC it is the architecture that the last patches is based on). > 3) heuristics > > There seem to be different heuristics when deciding whether to create a > filter or not, but I've been unable to compile a good overview. Some of > the heuristics is very closely tied to details of the MPP plan (which > fragments are "local" and "global", ...). > > But generally, the heuristics are pretty "expected" - estimate the > filter selectivity, and if the filter does not eliminate enough tuples, > then don't use the filter. > It seems to me that some implementations just assume that pushing down filters is always beneficial, so at post-planning phase it always push down the filters. I did not manage to play with the expected/actual costing on Duckdb to see how the filtering pushdown changes the expected/actual values, but for Trino it decide if it should push down the filters after the costs are evaluated, so when filtering push down is present on query plan we see a difference on expected / actual costing values. It also seems to me that another option is some kind of "rule based" behavior to decide if the filtering push down should exists or not, e.g if the join keys match some criteria just push the filter down and don't care if it's worth or not. Paper "Materialization Strategies in the Vertica Analytic Database: Lessons Learned" [3] present Sideways Information Passing (SIP) (which is filtering push down generally speaking) and it has some rules to decide if the push down should happen or not. > > 4) partition pruning > > One interesting idea is that Apache Spark SQL apparently can use the > filter to prune partitions (feature "dynamic partition pruning"). Which > seem to be "partitions" in the sense we use. The other sysstems (like > Impala) can of course use the filter to prune stuff at the storage level > (so something a CustomScan would do). > > But the partition pruning seems like an interesting option. I haven't > really considered using filters for that before. > IIRC Trino also implement partition pruning with dynamic filtering. I think that is something that we can consider to discuss. Just don't know yet how the current discussed architecture would fit for this. [1] https://github.com/trinodb/trino/blob/master/core/trino-main/src/main/java/io/trino/sql/planner/PlanOptimizers.java#L584 [2] https://www.microsoft.com/en-us/research/wp-content/uploads/2024/12/Extensible-Query-Optimizers-in-Practice.pdf [3] https://15721.courses.cs.cmu.edu/spring2020/papers/13-execution/shrinivas-icde2013.pdf -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 7/14/26 00:09, Tomas Vondra wrote: > ... > > In the first plan, we have very limited pushdown options. We really want > to push filters to the fact_table scan, but let's add a selective WHERE > condition on dim_2. That won't add any filters on fact_table, because > the patch only looks at the join clauses and fact_table joins only with > dim_1 (and that filters nothing). > > We might add a filter from dim_2 to dim_1, although that does not seem > to happen with the v4 patch for some reason (seems like a bug). > FWIW this happens because we only ever construct hashjoins with cheapest_total_path (and the parameterized version), and those don't include paths expecting pushed-down filters. So it's not really a bug, but something we'd probably want to relax, to allow pushing filters to this side of the join too. I haven't done anything about it, but it seems somewhat mechanical. Of course, it would increase the number of paths explored. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 7/14/26 00:51, Matheus Alcantara wrote: > On Mon Jul 13, 2026 at 5:17 PM -03, Tomas Vondra wrote: >> ... >> >> 2) impact on planning >> >> The main differences seem to be in how the filters affect planning, i.e. >> at which point are they selected, and how they affect the plan shape (if >> at all). >> >> While the databases do planning in different ways (some are top-down, >> other bottom-up), it seems all of them decide filters in some >> post-processing phase, after the overall plan shape was selected. >> >> For example DuckDB has a rule-based optimizer, which applies various >> optimization transformations on the plan, in a particular sequence. And >> the filter selection is one such "optimizer" pass, which runs after the >> join order has already been selected (so the filters probably can't >> affect that aspect). >> >> If you look at slide 137 "Order of Optimization Passes in DuckDB >> (version 1.5)" in [1], then it lists "join_filter_pushdown" as pass 31 >> at the very end, including join_order etc. >> >> Note: There are two papers [1][2] about "Robust Predicate Transfer" in >> DuckDB, describing a much more elaborate way to decide filters, but >> AFAIK both are experimental/research implementations, not something >> DuckDB already does. >> >> The other databases seem to do planning in similar ways, i.e. as >> post-processing on already selected plan. Obviously, the exact point at >> which it happens is different. >> >> > > Trino also have rule-based optmizer that apply the pushdown filtering > [1]. > > "Extensible query optimizers in practice" [2] book also briefly mention > Catalyst which is an extensinble query optmiser for Spark SQL which also > implement filtering pushdown using rules (section 3.4). > > I am inclined to think that Postgres should do something similar and > have a post planning phase to create these filters (which IIUC it is the > architecture that the last patches is based on). > Which last patch you mean? The v4 creates the scan paths with filters at the beginning of the planning, which seems exactly the opposite to the post-processing approach. Which means it can change the join order, it can change which join algorithms we selected, etc. The approach in v1 is what I'd call post-processing, as it made the decisions in createplan, after everything else was already decided. It could not change join order or join algorithms, it was entirely opportunistic. >> 3) heuristics >> >> There seem to be different heuristics when deciding whether to create a >> filter or not, but I've been unable to compile a good overview. Some of >> the heuristics is very closely tied to details of the MPP plan (which >> fragments are "local" and "global", ...). >> >> But generally, the heuristics are pretty "expected" - estimate the >> filter selectivity, and if the filter does not eliminate enough tuples, >> then don't use the filter. >> > > It seems to me that some implementations just assume that pushing down > filters is always beneficial, so at post-planning phase it always push > down the filters. I did not manage to play with the expected/actual > costing on Duckdb to see how the filtering pushdown changes the > expected/actual values, but for Trino it decide if it should push down > the filters after the costs are evaluated, so when filtering push down > is present on query plan we see a difference on expected / actual > costing values. > > It also seems to me that another option is some kind of "rule based" > behavior to decide if the filtering push down should exists or not, e.g > if the join keys match some criteria just push the filter down and don't > care if it's worth or not. Paper "Materialization Strategies in the > Vertica Analytic Database: Lessons Learned" [3] present Sideways > Information Passing (SIP) (which is filtering push down generally > speaking) and it has some rules to decide if the push down should happen > or not. > Some engines may do that unconditionally in the post-planning phase. It can't change the plan anyway, so why bother with costing, right? But then they still do some cost/benefit decisions at execution time, either when deciding to build the filters, or to disable filters that turn out to be ineffective. As for the expected vs actual difference, I think this would be a big issue, because it'd make EXPLAIN output utterly confusing. I don't think I could convince myself to commit that into core ... >> >> 4) partition pruning >> >> One interesting idea is that Apache Spark SQL apparently can use the >> filter to prune partitions (feature "dynamic partition pruning"). Which >> seem to be "partitions" in the sense we use. The other sysstems (like >> Impala) can of course use the filter to prune stuff at the storage level >> (so something a CustomScan would do). >> >> But the partition pruning seems like an interesting option. I haven't >> really considered using filters for that before. >> > > IIRC Trino also implement partition pruning with dynamic filtering. I > think that is something that we can consider to discuss. Just don't know > yet how the current discussed architecture would fit for this. > Yeah. I don't think we need to support "partition pruning" right away, more like an interesting future improvement. In a way, it's not all that different from pruning blocks in a CustomScan or something, except it'd be done by a node somewhere higher in the plan. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On Mon Jul 13, 2026 at 8:55 PM -03, Tomas Vondra wrote: > Which last patch you mean? The v4 creates the scan paths with filters at > the beginning of the planning, which seems exactly the opposite to the > post-processing approach. Which means it can change the join order, it > can change which join algorithms we selected, etc. > > The approach in v1 is what I'd call post-processing, as it made the > decisions in createplan, after everything else was already decided. It > could not change join order or join algorithms, it was entirely > opportunistic. > Sorry, that last paragraph was confusing — I didn't reread my reply before sending it. I mixed up the v1 and v4 implementations while writing it. What I actually meant to say is that v4 (and v5, as an evolution of v4, which I sent in my previous reply) seems like the way to go. Of course there's a lot to improve and think about, but the overall idea — creating paths with and without the pushed-down filters, accounting for them when costing the scan path, and letting the cost-based path selection decide which is better — makes sense to me. It consider the fact that pushing down filters is not free and it did not make EXPLAIN consufing with the expected x actual problem. > Some engines may do that unconditionally in the post-planning phase. It > can't change the plan anyway, so why bother with costing, right? But > then they still do some cost/benefit decisions at execution time, either > when deciding to build the filters, or to disable filters that turn out > to be ineffective. > > As for the expected vs actual difference, I think this would be a big > issue, because it'd make EXPLAIN output utterly confusing. I don't think > I could convince myself to commit that into core ... > I definitely agree with this, it can lead to a lot of confusion, e.g., "is the expected-vs-actual difference because of filter pushdown, or because the statistics are out of date?" So I'd also like to avoid that kind of behavior. -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 7/14/26 15:28, Matheus Alcantara wrote: > On Mon Jul 13, 2026 at 8:55 PM -03, Tomas Vondra wrote: >> Which last patch you mean? The v4 creates the scan paths with filters at >> the beginning of the planning, which seems exactly the opposite to the >> post-processing approach. Which means it can change the join order, it >> can change which join algorithms we selected, etc. >> >> The approach in v1 is what I'd call post-processing, as it made the >> decisions in createplan, after everything else was already decided. It >> could not change join order or join algorithms, it was entirely >> opportunistic. >> > > Sorry, that last paragraph was confusing — I didn't reread my reply > before sending it. I mixed up the v1 and v4 implementations while > writing it. > > What I actually meant to say is that v4 (and v5, as an evolution of v4, > which I sent in my previous reply) seems like the way to go. Of course > there's a lot to improve and think about, but the overall idea — > creating paths with and without the pushed-down filters, accounting for > them when costing the scan path, and letting the cost-based path > selection decide which is better — makes sense to me. It consider the > fact that pushing down filters is not free and it did not make EXPLAIN > consufing with the expected x actual problem. > OK, thanks for the clarification. >> Some engines may do that unconditionally in the post-planning phase. It >> can't change the plan anyway, so why bother with costing, right? But >> then they still do some cost/benefit decisions at execution time, either >> when deciding to build the filters, or to disable filters that turn out >> to be ineffective. >> >> As for the expected vs actual difference, I think this would be a big >> issue, because it'd make EXPLAIN output utterly confusing. I don't think >> I could convince myself to commit that into core ... >> > > I definitely agree with this, it can lead to a lot of confusion, e.g., > "is the expected-vs-actual difference because of filter pushdown, or > because the statistics are out of date?" So I'd also like to avoid that > kind of behavior. > Agreed. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 7/13/26 21:26, Matheus Alcantara wrote: > ... > > This make sense to me as a direction. I've been sketching this idea and > here is my attempt to implement. This is still a PoC, it still need more > polishment but I've wrote some comments and commit message to try to > explain the idea. > OK, thanks. I didn't have much time to do a thorough review yet, but let me share at least some general feedback. > For (1), the candidate selection no longer picks the "top three" most > selective filters. It still requires a candidate to discard at least > bloom_filter_pushdown_threshold (30% by default) of the rel's tuples, > but every candidate clearing that bar is kept, with no count-based trim. > > For (2), combinations are now generated breadth-first by increasing size > instead of enumerating every non-empty subset, and a combination stops > growing once its combined selectivity drops below a new > bloom_filter_pushdown_combination_floor GUC (0.1 by default). > bloom_filter_pushdown_max now caps how many filters can be combined into > one path rather than how many candidates survive. So, with ~50% > selective filters, growth stops around 3 deep regardless of how many > candidates exist, so 10 joins doesn't turn into 2^10 paths. > Makes sense. I've been working on allowing building filters on joins, not just on baserels (per my message from a couple days ago), and I think that'll also need relaxing this in some way (there are likely quite a few possible join rels, more than 3). I don't know if these default thresholds are reasonable - e.g. 0.1 seems rather high, if the relation happens to be large it may easily be a couple million rows etc. Maybe it'd be better to base this on number of rows, not as a fraction. But not sure. I wonder if we could base this heuristic on some approximate cost/benefit ratio instead. FWIW I think we could take inspiration from the SIGMOD paper I mentioned a couple times already - the authors do propose a bunch of heuristics to decide which filters to build etc. There's a nice overview in section 3.10 of the paper. Some are a bit debatable, but most seem sensible. > Each combination is passed straight into the real create_*_path > constructor for its scan type instead of being produced by cloning an > already-costed path. A new apply_expected_filters() helper is the > generic "cost/rows adjustment" fallback: it charges one > cpu_operator_cost per filter per tuple on top of shrinking the row > estimate, so filtering is no longer free. IndexPath is the one exception > still handled by cloning, since create_index_path() would just > redundantly re-derive indexclauses/pathkeys for no benefit, perhaps I > think that we can improve this. > Hmm, not sure what to do about indexpaths. Maybe we could have a "filter" variant that takes an existing IndexPath as a source, and reuses the indexclaused/pathkeys (without recalculating it). But then still does whatever other adjustments are necessary. > For CustomPath, core can't safely clone or construct one at all. So > it doesn't touch CustomPath for this anymore — a provider that wants > filter-aware CustomPaths builds them itself, using the new exported > filter-combination function and either costing them for real or > falling back to the same generic adjustment core uses. I think this will need some more though. I don't think we want to run the find_interesting_bloom_filters() from scratch multiple times, it can be fairly expensive. It'd be good to "cache" the filters somewhere, so that the CustomScan can pick the filters from there. Say, we could stash it in the RelOptInfo, right? This will matter much more for filters on joins, because for that we'll have to run a simplified version of the join enumeration, and that's certainly not free. That can also cache stuff more aggressively (e.g. the valid join relids can be calculated just once). > Paths with differing expected filters still never dominate each other in > add_path, so they compete on cost exactly like paths with different > pathkeys do, same as in v4. > Yeah. The good thing is the new paths with filters still compete among each other, so hopefully that eliminates a fair number of them. But I wonder how effective that is, and whether we could introduce some more heuristics to discard more of them. The paper does describe a bunch of heuristics when generating candidate filters for joins, but I think it also describes heuristics when adding filters to a scan. But I don't recall the details. It might also be interesting to try constructing queries that would be affected by this (e.g. a fact with a bunch of dimensions with filters), and measuring the practical impact. Can you give that a try? > This is implemented in 0005; the other patches are the same as those in > v4. I think we can try combining some of these patches. Perhaps 0001 and > 0002? > Yeah, it does not make much sense to keep 0001 around - it's the initial approach doing the pushdown in createplan.c, and IMHO we agree that's not the right approach. I only kept it around to make the 0002 changes obvious, but we can get rid of 0001. One comment - let's include the changes in expected output in each of the patches, so that "make check" passes after each individual patch. I think it makes debugging simple. V4 did it like that, but v5 seems to move some of the output changes to the last part. > Appreciate comments on whether this make sense or not. > I think it does. But as you say, there's plenty of stuff to figure out and polish. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hi, Here is a v6 with an experimental version of building the filters on joins, and a couple more improvements. I did not include your v5 changes in selecting interesting filters - sorry about that. I ran out of time, and I assume you may have a newer version of those changes? Your changes seem largely orthogonal to the changes I did, so it should not be very hard to adjust. v6-0001-PoC-hashjoin-bloom-filter-pushdown.patch ---- In v6 I merged the 0001 and 0002 patches, so this completely abandons the initial v1 approach of filter pushdown at createplan time. It now happens during the bottom-up path construction, as introduced in v3. v6-0002-Check-expected-filters-even-for-partial-paths.patch v6-0003-Skip-paths-with-filters-in-get_cheapest_path_for_.patch ---- 0002 and 0003 fix two gaps, where we failed to consider filters - when planning joins on partial paths, and when evaluating cheapest paths with specific pathkeys. The join planning with partial paths may be a bit surprising, but the thing we missed is that partial paths can join with non-partial ones (when the join is not parallel, and happens in the worker). So we need to be careful about this, and just do the same check as elsewhere. The "cheapest path with pathkeys" is a clear omission. In a couple places we simply ask for "cheapest path with pathkeys" not considering the filters at all, and in that case we better get a path with no filters by default. There probably are cases where we could consider the expected filters, and get cheapest path with some specific filters. I'm speficically thinking about merge joins (which now AFAIK mostly discard the filters), aggregations and so on. But I haven't done anything about this. v6-0004-Make-sure-Gather-nodes-don-t-have-filters.patch ---- This is more or a paranoia/safety, to make sure we're not passing filters through Gather nodes. Which seems like a possible improvement, but it's not supported by this version (and I'm not sure how hard would it be). v6-0005-Add-tests-for-CustomScan-filter-pushdown.patch v6-0006-Allow-a-CustomScan-to-consume-a-pushed-down-hashj.patch ---- These are the original CustomScan patches, no change to thse. v6-0007-Properly-plan-filters-built-on-joins.patch v6-0008-Add-GUCs-for-limiting-join-enumaration.patch v6-0009-Allow-filters-built-for-queries-with-LATERAL-join.patch ---- This is the new stuff, related to building (and estimting) filters on joins. It's split into 3 smaller parts, but it really is one change. I already explained the issue in [1], and how the paper deals with that by running the join planning in two phases. First a simpler phase to identify interesting filter candidates, and then the regular join search. This implements roughly that, with a couple simplifications. The core is in enumerate_bloom_filter_build_relids, which enumerates relids of possible join relations, similarly to what standard_join_search would. It operates only on relids (no RelOptInfo, no path construction, ...). In [1] I speculated about using DPccp to enumerate the joins, and maybe we could do that. But I don't think it'd be any faster, as most of the time is spent in checking join legality, etc. There is a bunch of other limits intended to limit the overhead: 1) The relids are generated only once per query, cached in PlannerInfo. 2) We don't generate relids for joins of more than 3 rels (which limits e.g. how many dimensions can be used to derive a filter). 3) We don't generate more than 100 relids. Of course, (2) and (3) limits are somewhat arbitrary, and I think we can use much higher values in practice. In the comments I speculate we could "prune" the join search space quite a bit by deducing which relations are interesting filter targets (e.g. not tiny ones), and leveraging the join graph structure. I also suspect this is related to the "join hardness" thread, which is exactly about limiting the number of valid join relations in a query. So maybe there's something we could use here. I think one worthwhile task would be inspecting the plan changes due to this patch series. In fact, that's how I ended up with 0002 and 0003 patches, by looking for weird plans changes in tests. There probably are a couple more cases to investigate. A bunch of plans changed because "Join Filter" lists clauses a bit differently, but I think that's correct / expected. The patches have to deduce clauses from ECs, and that may cache a slightly different variant of the clause. It's annoying but harmless. I'll have to put this on the backburner for a couple days, but then I plan to add some more test coverage, with schemas/queries designed specifically to leverage filters. And look for places in the planner that might/should consider filters. regards [1] https://postgr.es/m/68389077-45fa-4b7b-89d3-89fdffde1283@vondra.me -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 7/20/26 20:17, Matheus Alcantara wrote: >> ... >> >> It might also be interesting to try constructing queries that would be >> affected by this (e.g. a fact with a bunch of dimensions with filters), >> and measuring the practical impact. Can you give that a try? >> > > I gave this a try. Attached is star-schema-bloom-repro.sql, which builds > a 10M-row fact table with 6 dimension tables, FKs uniformly distributed > (no correlation between fact rows and dimension values, the worst case > for the search, since nothing prunes candidate combinations early). I > tried to reproduce the same shape as the star-schema scenario in ref > [26] that the paper's related work section mentions, plus a snowflake > variant (ref [8]). > > Each query joins the fact table to N dimensions (N = 2..6), each with a > WHERE filter surviving ~30-40% of rows, individually just over our > bloom_filter_pushdown_threshold (0.3), so none of them get discarded > before the combination search runs, and the combination_floor (0.1) > isn't crossed until several are combined. I think that this stress > exactly the case you're asking about: a fact table whose scan > accumulates several non-trivial candidate filters and has to search > combinations of them. Please let me know if I miss-understood something. > Seems like a reasonable example to test. I'd have started with something completely synthetic, but that doesn't matter. > Settings: defaults (bloom_filter_pushdown_max=3, threshold=0.3, > combination_floor=0.1), max_parallel_workers_per_gather=0. Each query run > with enable_hashjoin_bloom off and on, same session, same data: > > N filtered dims | planning time (bloom on) | planning time (bloom off) > 2 | 1.3 ms | 1.2 ms > 3 | 3.9 ms | 1.8 ms > 4 | 10.1 ms | 4.5 ms > 5 | 21.0 ms | 6.4 ms > 6 | 56.6 ms | 7.9 ms > 6 (snowflake | 29.0 ms | 6.5 ms > > Two things stand out: > > 1. Planning time grows superlinearly once N passes 4, jumping almost 10x > at N=6 relative to the OFF baseline for the same join search. That's > find_bloom_filter_combinations() actually having to walk C(n,2)/C(n,3) > subsets rather than being cut off early. Capping > bloom_filter_pushdown_max=1 (no combining at all, closest thing we have > to your Heuristic-7 idea) brought N=6 planning time down to ~20ms. > Yeah, that's not great. It's probably even worse with the support for filters on joins. Wwe'll need to investigate a bit where does the extra time come from, and do something about it. > 2. Execution time did not improve with the feature on for this dataset, > it's consistently ~7-11% worse (e.g. N=6: 2541ms OFF vs 2810ms ON). I > checked the plans and the join order chosen is identical in both cases, > and only one Bloom filter (on the single most selective join column) > ever gets realized, no matter how many combinations were built or how > many candidates existed. I think that most of this is because the > planning time degradation. > > So I think that we need better heuristics to decide when to create such > filters. As I mention above, I'll work on to implement such heuristics > based on the paper to see if we get better values here. > Possibly. I think it'd be good to know how many new paths we actually got, and see if we can eliminate at least some of them early (I don't recall - does add_path compare costs for paths with the same filters)? regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 7/20/26 23:31, Matheus Alcantara wrote: > On Mon Jul 20, 2026 at 4:17 PM -03, Tomas Vondra wrote: >>> So I think that we need better heuristics to decide when to create such >>> filters. As I mention above, I'll work on to implement such heuristics >>> based on the paper to see if we get better values here. >>> >> >> Possibly. I think it'd be good to know how many new paths we actually >> got, and see if we can eliminate at least some of them early (I don't >> recall - does add_path compare costs for paths with the same filters)? >> > > I instrumented generate_expected_filter_paths() to count, per base rel, > the eligible base paths, the filter combinations, and the pathlist > length before/after the add_path() calls. Running the star-schema > queries for the fact_sales scan: > > N basepaths combinations new paths pathlist before -> after > 2 3 3 9 5 -> 14 > 3 4 7 28 7 -> 35 > 4 5 13 65 9 -> 74 > 5 6 23 138 11 -> 149 > 6 7 36 252 13 -> 265 > Do I understand correctly this is for paths on the fact_sales, and there are no new paths on the other relations (dimensions)? > About your question: yes, add_path() does cost-compare paths that carry > the same filter set - they go through the normal cost/pathkeys/rows > domination like any other pair. What it deliberately does not do is > compare across different filter sets: add_path bails out as soon as > expected_filters differ, on the grounds that a scan feeding filter A and > a scan feeding filter B serve different parent joins and aren't > comparable. I think that's the right call, pruning by cost across filter > sets seems wrong, since a more expensive scan carrying a better filter > can pay off at the join above. > > The consequence, though, is that add_path prunes essentially nothing > here. The surviving count is basepaths * combinations exactly — 0 pruned > in every single query. The fact_sales pathlist goes from N+1 base paths > to (N+1)*combinations - ~20x at N=6 - and every one of those extra scan > paths then has to be considered as a join input at every level, which I > think that is where the superlinear planning time comes from. > Right, that explanation seems plausible. I'm not sure if you tried with the v5 or v6 patches, but I assume the join stuff in v6 would make this somewhat worse due to generating even more candidate filters. Well, maybe not for starjoin schemas, but for snowflake. > So it seems to me that early elimination has to happen before add_path, in the > candidate/combination generation. > Yeah. Some heuristics to prune paths more aggressively. I this is what the "heuristic 4" in the paper is about. That says: If multiple Bloom filters are candidates on the same relation (originating from different join clauses), then we create Bloom filter scan plans with all possible Bloom filter candidates applied as opposed to testing out sub-plans with various subsets of Bloom filter candidates applied. In other words, we apply all valid candidate Bloom filters on a base table simultaneously, as an additional heuristic to limit the search space (Heuristic 4). AFAICS that says they consider all filters at once, no combinations. I'm not sure what they do about joins, maybe they consider only the most selective filters (for larger joins). That'd prefer "more bushy" plans. We'll have to experiment with this a bit, I guess. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hi,
Here's a v8, with a bunch of changes on top of v7 from last week. The
changes are related mostly to generating the build join relids, so
hopefully it's not too disruptive w.r.t. your work on selecting filter
combinations, building paths etc.
The 0001-0012 parts are from v7, the changes are in 0013-0020. I kept
them unsquashed, to make it easier to review/understand etc.
v8-0013-Consider-foreign-keys-when-estimating-filter-sele.patch
v8-0014-Rework-bloom_build_side_join_ratio.patch
-----
The main change is in 0013 and 0014. While reviewing the TPC-H results
from last week, Q9 kept puzzling me (even with all the fixes from v7).
The new plan was ~10x faster (good), but the filter estimates were
considerably off. Which is surprising, because without the filters the
estimates are fairly accurate.
Turns out, the filter estimates were completely ignoring FK constrains.
For most queries that's fine, but Q9 has joins on a multi-column FK, and
in that case ignoring the FK can results in under-estimate. It just
happens to pick the right plan, but that's mostly luck.
0013 attempted to fix that, but I realized bloom_build_side_join_ratio
calculates the join cardinality (which is then used to calculate the
filter selectivity) for given relids "from scratch". It does consider
the FK between the target rel and the build relids, but not for the
joins in the build relids. And doing that "from scratch" is hard,
because we'd need to reverse-engineer a way to build the relids.
I think this means we have to calculate the join sizes while creating
the build relids, just like during the regular planning, and 0014 is a
step in that direction.
I'm not claiming this is perfect, though.
The trouble is the relevant functions (for generating clauses from ECs,
calculating join rel size, ...) take RelOptInfo for the join relations.
But we don't have those, except for the baserels. The intent is to keep
this first phase as cheap as possible, and building "proper" RelOptInfos
somewhat contradicts that.
The v7 built just the relids, and re-implemented a bunch of stuff (e.g.
a lot of find_interesting_bloom_filters was about generating the clauses
from EC, etc. But now we need to track e.g. join cardinality, etc.
v8 introduces a SimpleRelOptInfo, with only the minimal subset of fields
required for the first phase. That does the trick, but it also means we
have to "copy" a bunch of functions accepting RelOptInfo:
- calc_joinrel_size_estimate
- set_joinrel_size_estimates
- generate_join_implied_equalities
- build_joinrel_restrictlist
- subbuild_joinrel_joinlist
- build_joinrel_joinlist
It's rather annoying, because now we have literally a 100% copy, with
the only change being s/RelOptInfo/SimpleRelOptInfo/ in the function
signature. There's still a bunch of functions copies accepting Relids
(like simple_join_is_legal), those should probably accept the new struct
too. But I'm not sure having this "simple" variant is a good idea, the
code duplication is annoying, so I haven't done that.
Maybe it'd be possible to build "fake" RelOptInfo, with just the fields
needed for calculating the join result size initialized. We'd still not
generate the various paths (which seems like the most expensive part).
But it seems pretty fragile. It might easily happen that this RelOptInfo
gets passed to a place expecting some of the other field, etc.
OTOH, building SimpleRelOptInfo first, and then also RelOptInfo (which
gets to recalculate a bunch of fields) is also not free. Even without
the annoying code duplication.
But I'm also not sure what to do about this :-( All I know is that this
makes the filter selectivity estimates. Maybe it'd be possible to build
RelOptInfo in phases, or something.
v8-0015-Sort-filters-pushed-down-to-a-scan-by-selectivity.patch
-----
It seems reasonable to sort the filters pushed down to a scan node so
that the most selective filters are evaluated first. There's probably a
more elaborate costing, considering cost of probing each filter (some
filters may have many more hash functions etc.). I haven't done that.
In fact, the primary motivation for this change was plan stability. A
surprising consequence of pushing down a filter is that all it makes the
order of those joins "irrelevant". The cardinality gets reduced at the
scan level - the joins "provide" the filters, but do not affect the
cardinality.
So if F joins to D1 and D2, with a filter for each dimension, it then
does not matter if D1 joins before D2 or vice versa. This makes the plan
"unstable" because a small change in statistics can flip the order, even
if the filters discard very different fractions of tuples.
This change stabilizes at least the order of filters, but we probably
need to think about stabilizing the plans in some way.
It probably needs to consider things like false positive rate for the
filters, etc.
v8-0017-Show-expected-filter-selectivity-in-EXPLAIN.patch
-----
It seems useful to know what's the expected selectivity of the filter,
so that it can be compared to the fraction of discarded tuples. It's
only shown for VERBOSE and/or ANALYZE runs, not for plain EXPLAIN.
I just realized it the semantics of this new field is somewhat opposite
to the "rejected" fraction, it should probably be unified.
v8-0016-Add-basic-regression-tests-for-filter-pushdown.patch
v8-0018-Add-a-multi-column-FK-join-to-the-simple-test.patch
v8-0019-Test-a-starjoin-with-multi-column-FK-join-clauses.patch
v8-0020-Test-a-snowflake-join-with-multi-column-FK-join-c.patch
-----
The remaining patches add a couple regression tests focused on the
filter pushdown. The patches do affect plans in various regression
suites, of course. But sometimes it's hard to determine if the plan
change for a complex query is desirable/expected.
These new tests add a bunch of starjoin/snowflake joins, where we know
the expected behavior. The tests are too expensive to be committable,
but for development that's not an issue.
regards
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On Tue Jul 28, 2026 at 5:58 PM -03, Tomas Vondra wrote: > Is this with the v8 I posted? There's not the "expected" field for the > filter, so I guess it doesn't have the filter estimate fix from my v8 > patches. And the estimates/actuals seem similar to what I saw before. > > For the record, this is what I see on 10GB data set for this join > > -> Seq Scan on lineitem (cost=0.00..1725034.76 rows=3275719 width=29) > (actual time=0.037..2947.777 rows=3260827.00 loops=1) > Bloom Filter 2: keys=(l_suppkey, l_partkey) expected=5.5% > checked=59986051 rejected=56725225 (94.6%) > Buffers: shared hit=576 read=1124567 > > Which seems pretty spot on. It might also depend on other GUCs affecting > the filters, I'm using > > set bloom_filter_pushdown_max = 10 > set bloom_filter_pushdown_max_build_relids = 10 > set bloom_filter_pushdown_max_build_sets = 10 > > Maybe we're not matching the filters to joins correctly (relids equality > vs. subset). > It didn't have the filter estimate fix from your v8. With your patch the estimation and the plan looks very similar to what you have. I'm attaching v9 which include the following changes (1-6 are from the previous "my" v8): 1. Candidate selection: no count-based cap - find_interesting_bloom_filters() now returns every candidate that clears bloom_filter_pushdown_threshold, instead of trimming to the bloom_filter_pushdown_max most selective. (This is the v5-0005 candidate-selection change that wasn't carried into v6/v7.) 2. Real costing for filter-aware scan paths - paths are built through the real create_*_path constructors, and apply_expected_filters() charges one cpu_operator_cost per filter per tuple, so filtering is no longer modeled as free and a filter is only chosen when it's actually cheaper. (also from v5-0005) 3. Heuristic 4 - apply all candidates at once - replaced the subset enumeration with a single combination that applies all non-overlapping candidates (most-selective first), so we no longer build a path per subset. bloom_filter_pushdown_max is repurposed to cap how many filters are applied simultaneously (per-tuple probe cost), and the combination_floor GUC from v5 is dropped. This collapses the path explosion and keeps planning time acceptable on the TPC-H queries. 4. IndexPath filter variant - create_filtered_scan_path() clones the source IndexPath, reusing its indexclauses/pathkeys, and applies the same probe-cost/row adjustment as the other scan types. I'm not sure if I understood correctly your feedback regarding this topic on [1]. 5. Cache interesting filters on the RelOptInfo - the find_interesting_bloom_filters() result is cached and reused, so it isn't recomputed for core path generation and again by a CustomScan provider. 6. CustomScan providers build their own filter-aware paths via the exported find_bloom_filter_combinations() + apply_expected_filters(), rather than core constructing CustomPaths. (also from v5-0005) New in this patchset(v9-021): while debugging a Q8 regression I found the filters were being built with bloom_create(), which forces a 1MB bitset floor and lets optimal_k() go up to MAX_HASH_FUNCS (10). For a filter that probes a large apply side that's a bad fit. In Q8 the (l_partkey) filter probes all ~60M lineitem rows, and with a 1MB bitset IIUC each probe is ~10 random accesses into a bitset that doesn't fit in L2 cache, a likely cache miss per hash. So the probe stops being the cheap "constant k" the cost model (and the paper) assume, and the filter costs more than it saves even though it rejects >98% of the rows. This is basically the situation that IIUC the paper warns about in section 3.5: keep the filter small enough to stay in cache and use few hash functions. 7. Probe-oriented filter sizing - I added bloom_create_probe(), in nodeHash.c which uses a 1KB floor and caps the hash functions at 4. So the filter is sized to the build side and (hopefully) stays cache resident. So, in this case the Q8 (l_partkey) filter goes from: bits=8388608 hashes=10 memory=1024kB (rejects 98.1%) to bits=131072 hashes=4 memory=16kB (rejects 98.1%) Same rejection rate, ~15x smaller and L2 cache resident. TPC-H scale 10, warm cache, max_parallel_workers_per_gather=0, work_mem=256MB; medians of 3 runs, enable_hashjoin_bloom off vs on: query off (ms) on (ms) delta Q3 107623 107418 -0.2% Q5 20307 18433 -9.2% Q7 21815 19933 -8.6% Q8 18834 18824 ~0% Q9 42602 40292 -5.4% Q10 24180 20850 -13.8% Q18 264641 144729 -45.3% (was a regression) Q21 35614 37960 +6.6% (was ~+41%) The interesting part is that the sizing change did more than fix Q8. Q18 has the same shape (a filter probing all of lineitem), so cheaper probes flipped it from a regression into a large win, and Q21 came down from roughly +41% to +6.6%. Q21 is the only regression left, at +6.6% instead of ~41% on previous version. I'm wondering if some other heuristic discussed on the paper could help, e.g Heuristic 5 (explicitly skipping a filter whose build side is too large to keep the bitset in cache). I didn't look deeper on all the new patches that you worked on v8. I was focusing on implementing these new ideas to see some improvements. I intend to do it next. -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On Fri Jul 31, 2026 at 9:52 AM -03, Tomas Vondra wrote: >> I'm attaching v9 which include the following changes (1-6 are from the >> previous "my" v8): >> > > Cool. I'll add that to my working branch, and will make sure to include > the patches in future versions, so that you don't have to rebase/rework > it again. > > We could also agree on maintaining a shared branch somewhere, and post > new patch versions to -hackers from time to time. That's what we did for > index prefetching, and I think it worked. The one risk is it can move > the discussion off-list too, so we'd need to be careful about that. > Yeah, I think that it's a good idea. Do you mind sharing on github? >> 1. Candidate selection: no count-based cap - >> find_interesting_bloom_filters() now returns every candidate that clears >> bloom_filter_pushdown_threshold, instead of trimming to the >> bloom_filter_pushdown_max most selective. (This is the v5-0005 >> candidate-selection change that wasn't carried into v6/v7.) >> >> 2. Real costing for filter-aware scan paths - paths are built through the >> real create_*_path constructors, and apply_expected_filters() charges one >> cpu_operator_cost per filter per tuple, so filtering is no longer modeled >> as free and a filter is only chosen when it's actually cheaper. (also >> from v5-0005) >> >> 3. Heuristic 4 - apply all candidates at once - replaced the subset >> enumeration with a single combination that applies all non-overlapping >> candidates (most-selective first), so we no longer build a path per >> subset. bloom_filter_pushdown_max is repurposed to cap how many filters >> are applied simultaneously (per-tuple probe cost), and the >> combination_floor GUC from v5 is dropped. This collapses the path >> explosion and keeps planning time acceptable on the TPC-H queries. >> >> 4. IndexPath filter variant - create_filtered_scan_path() clones the >> source IndexPath, reusing its indexclauses/pathkeys, and applies the same >> probe-cost/row adjustment as the other scan types. I'm not sure if I >> understood correctly your feedback regarding this topic on [1]. >> >> 5. Cache interesting filters on the RelOptInfo - the >> find_interesting_bloom_filters() result is cached and reused, so it isn't >> recomputed for core path generation and again by a CustomScan provider. >> >> 6. CustomScan providers build their own filter-aware paths via the >> exported find_bloom_filter_combinations() + apply_expected_filters(), >> rather than core constructing CustomPaths. (also from v5-0005) >> > > OK. I think these changes look reasonable. > Good to know, thanks. >> New in this patchset(v9-021): while debugging a Q8 regression I found >> the filters were being built with bloom_create(), which forces a 1MB >> bitset floor and lets optimal_k() go up to MAX_HASH_FUNCS (10). For a >> filter that probes a large apply side that's a bad fit. In Q8 the >> (l_partkey) filter probes all ~60M lineitem rows, and with a 1MB bitset >> IIUC each probe is ~10 random accesses into a bitset that doesn't fit in >> L2 cache, a likely cache miss per hash. So the probe stops being the >> cheap "constant k" the cost model (and the paper) assume, and the filter >> costs more than it saves even though it rejects >98% of the rows. This >> is basically the situation that IIUC the paper warns about in section >> 3.5: keep the filter small enough to stay in cache and use few hash >> functions. >> > > This is a very interesting observation! I think it's related to my point > about "filter sizing" being one of the open questions. > > I definitely agree we should not require 1MB+ filters - if 1kB is > enough, we should just use that. Because as you say, if it can fit into > L2 / do fewer random probes, that can easily make a huge difference. > Great, so I think that we are on the same the page regarding this topic. This change also surprised me, I wouldn't expect such difference. I'm wondering if this size should be configured using a GUC instead of hard code value. For development it may help to explore other scenarios, but for the user perspective I'm not sure. What do you think? > FWIW I disagree with "heuristic 5" from the paper, which says: > > If the expected size of the Bloom filter is beyond a threshold, > a Bloom filter is not created. > > The reason is that one of the benefits is being able to discard tuples > for batching hash joins, so that we don't have to spill them to disk. In > those cases the filter is likely fairly large (because the hash table is > a multiple of work_mem), but the higher cost seems to be worth it. It's > still way cheaper than the eliminated I/O. > > I think we'll need to come up with some simple cost model, so that we > can do good approximate decisions. > Ok, make sense, I agree. >> TPC-H scale 10, warm cache, max_parallel_workers_per_gather=0, >> work_mem=256MB; medians of 3 runs, enable_hashjoin_bloom off vs on: >> >> query off (ms) on (ms) delta >> >> Q3 107623 107418 -0.2% >> Q5 20307 18433 -9.2% >> Q7 21815 19933 -8.6% >> Q8 18834 18824 ~0% >> Q9 42602 40292 -5.4% >> Q10 24180 20850 -13.8% >> Q18 264641 144729 -45.3% (was a regression) >> Q21 35614 37960 +6.6% (was ~+41%) >> >> The interesting part is that the sizing change did more than fix Q8. Q18 >> has the same shape (a filter probing all of lineitem), so cheaper probes >> flipped it from a regression into a large win, and Q21 came down from >> roughly +41% to +6.6%. >> >> Q21 is the only regression left, at +6.6% instead of ~41% on previous >> version. I'm wondering if some other heuristic discussed on the paper >> could help, e.g Heuristic 5 (explicitly skipping a filter whose build >> side is too large to keep the bitset in cache). >> > > That's great. I wouldn't have expected the impact to be so significant. > > There's a couple things that puzzle me: > > 1) The timings I see on TPC-H 10GB are much lower. I mean, for me Q3 > takes ~5s on master, while for you it seems to take ~100s. Similarly for > the other queries. What kind of hardware / build are you using? > Yeah, my machine seems much slower compared with your. I'm using a MacBook Pro M3 with debug symbols and asserts enabled. I tried to not make the machine busy while running the tests to not effect the execution time but it seems it didn't help to much. > 2) The queries using filter pushdown seem to be different too. In my > runs on the last patch version (without your latest changes), I see > these queries using a filter: > > 2 3 4 5 7 8 9 10 11 12 14 16 20 > > I don't know if your table shows results for all queries with a filter > in the plan, or if you selected just some interesting ones. But even > then, I've not seen 18 or 21 to pick a plan with a filter. > > I suspect this may be due to schema differences (e.g. indexes, ...). I just pick the most interesting ones. I didn't execute all TPC-H queries due to long time running. My schema have a bunch of indexes, so I think that this enable more queries to use the filters. > I've pushed my ugly WIP scripts here, so that we can compare: > > https://github.com/tvondra/pg-tpch-bloom > > It's ugly and may not be easy to use. What matters is the create-X > scripts, which create the objects / load data, etc. The run.sh script > then runs the actual test (but it's something I often tweak, depending > on what I need at the moment). > > FWIW I'm not saying we should be running the tests on the same schema. > There's a lot of value in testing a wider range of cases. But it might > be good to know where do the differences come from. I'll try to play with your scripts and also try to create my scripts to share my state (I'm running my tpch database for a while and I may already manually change something that I don't remember that may cause such differences). > FWIW I've been looking at some "random" plan changes in the TPC-H runs > I've been doing this week, and it seems there's a couple queries where a > simple ANALYZE can "flip" the plan to a substantially different one. > > I believe this happens mostly because of the LIKE conditions in a couple > queries, where the estimate depends on which values end up in the MCV. > The estimate can easily change 2x, which is enough to change the shape > of the plan. Of course, plan changes like this are expected and the cost > is not hugely different (so the timing is expected to be similar too). > > But it's significant enough to invalidate the evaluation of the pushed > down filters if there's analyze in between. I've seen this to happen on > Q2, Q7, Q9, Q15, but it also depends on the scale etc. (with more flips > on larger data sets) > Interesting finding. > I think we need to be careful about comparing timings only with the same > stats, i.e. without an ANALYZE in between. I wonder if we could use the > export/import of stats introduced in PG18 to stabilize this. Increasing > the statistics target to 10000 seems to (mostly) solve this. > Yeah, I think that it may help, or at least a script that prepare the schema to compare the timings (with same indexes, statistics target, etc) properly. >> I didn't look deeper on all the new patches that you worked on v8. I was >> focusing on implementing these new ideas to see some improvements. I >> intend to do it next. >> > > Understood, makes sense. Let's take some time to review each others > patches, and then we can agree which open questions to work on next. > Sounds a good plan. -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: hashjoins vs. Bloom filters (yet again)
On 7/30/26 21:00, Matheus Alcantara wrote: > On Tue Jul 28, 2026 at 5:58 PM -03, Tomas Vondra wrote: > ... > > TPC-H scale 10, warm cache, max_parallel_workers_per_gather=0, > work_mem=256MB; medians of 3 runs, enable_hashjoin_bloom off vs on: > > query off (ms) on (ms) delta > > Q3 107623 107418 -0.2% > Q5 20307 18433 -9.2% > Q7 21815 19933 -8.6% > Q8 18834 18824 ~0% > Q9 42602 40292 -5.4% > Q10 24180 20850 -13.8% > Q18 264641 144729 -45.3% (was a regression) > Q21 35614 37960 +6.6% (was ~+41%) > > The interesting part is that the sizing change did more than fix Q8. Q18 > has the same shape (a filter probing all of lineitem), so cheaper probes > flipped it from a regression into a large win, and Q21 came down from > roughly +41% to +6.6%. > > Q21 is the only regression left, at +6.6% instead of ~41% on previous > version. I'm wondering if some other heuristic discussed on the paper > could help, e.g Heuristic 5 (explicitly skipping a filter whose build > side is too large to keep the bitset in cache). > I've been running some benchmarks on my v8 patches (from 28/7) and the most recent v9 (from 30/7), and I see a fairly consistent improvements in the 1-5% range (v9 over v8). This is on top of the (substantial) improvement compared to master, and it has to come just from using s smaller/cheaper filter. So that's nice. I did not see any massive improvements in the ~50% range, but I also did not see Q18 using a plans with filters, so it probably depends on the schema/indexes, etc. It may also depend on scale, etc. Attached is a spreadsheet with results from scales 10GB, 50GB and 100GB, and different statistics target (based on the observation that some queries flip between plans, which makes it difficult to compare results). The results are with target 10000, where the plans are stable, particularly on 50/100GB. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 8/19/26 17:05, Bruce Momjian wrote: > On Mon, Jul 13, 2026 at 10:17:28PM +0200, Tomas Vondra wrote: >> On 7/7/26 20:39, Tomas Vondra wrote: >> >> ... >> >> 1) filter types >> >> The main thing shared by most of the databases is the types of filters >> supported. Most of the databases support these three kinds of filters: >> >> * Bloom filters >> * exact "IN" list of values >> * min/max range filter >> >> There are some differences in how the filter type gets selected, >> sometimes the filter is "hybrid" and combines e.g. Bloom + min/max. Most >> of these differences seem minor, and depend on how exactly the database >> uses the filter. > > One topic that came up in the Pittsburgh AI Workshop was the idea of > combining indexes. For example, right now, all indexes point to heap, > and we usually go from index to heap. We can combine indexes using > bitmap scans of heap tids. Would there be any value of improving our > ability to combine indexes beyond bitmap scans? > Are you describing something like this [1]? That is, ability to build a bitmap (from bitmap index scan), and pass it into an index scan, so that it can benefit from the selective bitmap filter and ordering of the regular index scan? I think that's an interesting idea / scan variant, skipping a possibly expensive Sort. But I don't quite see how is that related to the topic of this thread? It transfers predicate within a single scan (from one index to the other), while the hashjoin bloom pushdown "transfers" predicates between different plan nodes, possibly very distant. regards [1] https://www.postgresql.org/message-id/flat/CAHueFRVqNuKQ0%2BLQPZVwMgJ%2BLpuTbZ21%2BztwFbgPhBf9maFGYA%40mail.gmail.com -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 8/21/26 20:52, Matheus Alcantara wrote:
> On Fri Aug 21, 2026 at 12:20 PM -03, Tomas Vondra wrote:
>> I don't see how we could get into such situation, really.
>>
>> If we get to calling find_bloom_filter_recipient() when building a hash
>> join, it means we constructed the hashjoin path with a filter on the
>> hash, and an outer input that expects the filter. And at this point we
>> can't change our mind - *have* to find a recipient, otherwise it'd
>> invalidate the estimates calculated expecting the filter.
>>
>> I'm not claiming it can't happen with the current code, but that if it
>> happens it's a bug. Those are not "legitimate" (correct) plans.
>>
>
> Yeah, make sense, I agree with this. I think that I overthink here.
>
>>>> Agreed. I was wondering about such cases too. I think the question is:
>>>>
>>>> Is it correct to match the filter for a "larger" build relids, or
>>>> do the relids have to match exactly?
>>>>
>>>> I think we have to require an exact match, for to keep the estimates
>>>> correct. AFAIK this would resolve the example you described, and also
>>>> cases where the selectivity is reduced by the extra joins.
>>>>
>>>
>>> Done, compute_join_expected_filters now requires
>>> bms_equal(f->build_relids, other_relids) instead of bms_is_subset and it
>>> resolves the divergence.
>>>
>>> But I've notice one trade-off: in a snowflake, when a dimension is
>>> pre-joined with its sub-dimensions before it joins the fact, the hash
>>> join's build side is {d1,d11,d12}, not {d1}. Under subset the {d1}
>>> candidate (keys=(id1)) was realized there opportunistically (with a
>>> selectivity computed over {d1} alone, exactly the divergence we're
>>> fixing). Under exact match {d1} no longer matches, so the fact loses
>>> that filter. The correctly-scoped {d1,d11,d12} candidate (still
>>> keys=(id1), but selectivity over the whole build side) is in fact
>>> generated, but the dedup in find_interesting_bloom_filters drops it: it
>>> keeps a larger build side only if it's strictly more selective than a
>>> smaller one it contains, and with d11/d12 unrestricted the two are
>>> equally selective. The prefer the smaller build side rule on
>>> find_interesting_bloom_filters is correct under subset (a small build
>>> side matches any superset inner) but is exactly wrong under exact match
>>> (the small build side may never be realizable). So exact match fixes the
>>> estimate but drops fact-table filtering in snowflakes. The star case is
>>> unaffected. I updated hashjoin_bloom_snowflake.out accordingly but I
>>> think that keeping the fact filter with a correct estimate would mean
>>> reworking that dedup to keep equally-selective supersets. What do you
>>> think?
>>>
>>
>> Hmmm, but isn't that actually correct / desirable (depending on where we
>> put the WHERE restriction)? Which of the snowflake queries are you
>> referring to?
>>
>> If we have
>>
>> ... WHERE d1.r < 0.5;
>>
>> then it seems correct to build the filter just on {d1}, join with it,
>> and then maybe join with d11/d12 later. While with
>>
>> ... WHERE d11.r < 0.5;
>>
>> we'd build the filter on {d1,d11}, join with that, and then joining with
>> d12 sometime later.
>>
>> Or have you observed a query where this causes a regression? (It's never
>> gonna be perfect, it's a heuristic. But would be interesting feedback.)
>>
>
> I didn't observed any regression although I didn't execute any
> performance tests with v10 but what I measured is the filter usage drop:
> v10 pushes 6 fewer filter instances than v9 across the snowflake test.
>
> The query that I was mentioning is the WHERE d1.r < 0.5 in
> hashjoin_bloom_snowflake. To try to explain better I'll put my reasoning
> of this problem into two passes:
>
> Pass 1, candidate generation (per relation that could receive a filter
> on find_interesting_bloom_filters(), here the fact f). We enumerate the
> build sides that could filter the fact. Only d1 restricts it (f.id1 =
> d1.id, and d1 has r < 0.5), so the candidates are {d1}, {d1,d11},
> {d1,d11,d12}, all keyed on id1, and all equally selective, since d11/d12
> don't restrict anything. The de-dup logic then collapses
> equally-selective candidates to the smallest build side. So the fact's
> candidate list ends up as just [{d1}]; {d1,d11,d12} is dropped here.
>
> Pass 2, realization (compute_join_expected_filters()). We try to attach
> each surviving candidate to an actual hash join, and in v10 that match
> is exact, the candidate's build_relids must equal the join's inner
> (build) side.
>
> In this plan the fact's only hash join has inner = {d1,d11,d12}, because
> the planner fully pre-joins the d1 subtree before touching the fact:
>
> Hash Join
> Hash Cond: (f.id2 = d2.id)
> -> Hash Join
> Hash Cond: (f.id1 = d1.id)
> -> Seq Scan on bloom_snowflake_fact f <- no filter
> -> Hash
> -> Hash Join
> Hash Cond: (d12.id = d1.id12)
> -> Seq Scan on bloom_snowflake_dim_1_2 d12
> -> Hash
> -> Hash Join
> Hash Cond: (d11.id = d1.id11)
> -> Seq Scan on bloom_snowflake_dim_1_1 d11
> Bloom Filter 1: keys=(id)
> -> Hash
> Bloom Filter 1
> -> Seq Scan on bloom_snowflake_dim_1 d1
> Filter: (r < '0.5'::double precision)
>
> So at realization pass the one candidate we kept, {d1}, matches no inner
> ({d1} != {d1,d11,d12}), and the candidate that would have matched,
> {d1,d11,d12}, was already discarded by the de-dup in pass 1.
>
I think this is a bit weird. I think the join of "f" to "d1" is expected
to discard ~50% of the tuples, right?
The way I imagine the join planning to work is that it builds different
join orders, including e.g. a left-deep:
HJ
/ \
D12 HJ
/ \
D11 HJ
/ \
D1 F
and the bushy plan (which is the plan you showed)
HJ
/ \
HJ F
/ \
D12 HJ
/ \
D11 D1
I was assuming the left deep would win (thanks to the filter), but now I
realize that may not be true, for two reasons.
First, pushing down a filter usually means the tuples get discarded
early, but the actual join gets postponed after other joins. But that
can't happen here - we can't join D1 last, because D11 and D12 are
joined "through" D1. Which likely eliminates a lot of the benefit.
Second, it may even make the join more expensive, because it increases
the number of probes. In the bushy plan (the second one), each of the
D11 and D12 hash tables gets probed once for each D1 row. But with the
left-deep plan, those hashes get probed once per F row. And F >> D1.
> v9 filtered the fact because its realization used subset matching: {d1}
> is a subset from {d1,d11,d12}, so {d1} attached to the pre-joined inner.
> Exact matching (the item-2 change) closes the over-crediting that subset
> matching allowed, but it also removes that escape hatch, and the de-dup,
> which picks the smallest equally-selective build side without knowing
> which build sides will actually show up as join inners, happens to
> discard the only realizable candidate.
>
> That all being said, based on your reply I'm not sure if this is a real
> issue or just an expected behavior based on v10 changes. I'm missing
> something here?
>
I think you may very well be right, and we may need to rethink the
heuristic. We may need to prefer larger build sides, say by accepting
larger relids if it does not make the filter worse (instead of requiring
an improvement). Or something like that, not sure.
I'd consider the above plan to be a regression compared to v9.
regards
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hello Denis!
Thanks for the interesting and insightful feedback! Sorry for not
responding earlier, too much other stuff to deal with :-(
On 8/14/26 15:01, Denis Rodionov wrote:
>
> On 8/12/26 22:18, Tomas Vondra wrote:
>> Agreed. I was wondering about such cases too. I think the question is:
>>
>> Is it correct to match the filter for a "larger" build relids, or
>> do the relids have to match exactly?
>>
>> I think we have to require an exact match, for to keep the estimates
>> correct. AFAIK this would resolve the example you described, and also
>> cases where the selectivity is reduced by the extra joins.
> Hi,
>
> I took another look at the Bloom filter selectivity estimate in v9, in
> particular in light of the discussion above about requiring an exact
> match between f->build_relids and the realized build side.
>
> Requiring an exact match should ensure that the estimate and the
> physical filter refer to the same build relation set. However, I think
> there is a separate issue with how the selectivity for that relation set
> is estimated: using ordinary join cardinality divided by the owner
> cardinality can become too pessimistic in the presence of join fanout.
>
> The paper discussed in this thread already models Bloom filtering as an
> approximate semi-join [1]. My concern is that the ordinary-join-
> cardinality approximation used in v9 can diverge substantially from that
> semantics in the presence of fanout.
>
Just to confirm, by "join fanout" you mean a join multiplying
cardinality of (some) rows?
> As I understand the current code, bloom_build_side_join_ratio()
> estimates the surviving fraction roughly as
>
> rows({owner} JOIN build_relids) / rows(owner),
> clamped to [0, 1].
>
> The problem is that an ordinary join counts every matching pair, while a
> Bloom filter only cares whether at least one matching build key exists.
> Ignoring false positives, the quantity we need therefore seems to be the
> semi-join selectivity
>
> s = |owner SEMI JOIN build| / |owner|
> or equivalently
> s = P(a probe tuple has at least one matching build key).
>
> For example, suppose the probe side has 200000 rows and 10000 distinct
> keys, with every key occurring 20 times. The build side contains only
> 2000 of those keys, with every build key occurring 10 times.
> Only 20% of probe tuples have a matching build key, so s = 0.20.
> However, the ordinary join produces 2000 * 20 * 10 = 400000 rows, and
> the current ratio becomes 400000 / 200000 = 2, which is clamped to 1.0.
>
> So the estimate says that essentially all probe tuples survive, while an
> ideal Bloom filter with no false positives would reject about 80%.
> Increasing the number of duplicate build rows increases the ordinary
> join cardinality further, but does not change the set of keys
> represented by the Bloom filter.
>
> This suggests that ExpectedFilter.selectivity should be based on semi-
> join survival rather than inner-join cardinality.
>
Right.
It essentially calculates cardinalities of the two joins, and estimates
the selectivity as the ratio
|owner join build| / |build|
While working on this I came to the conclusion this would be a
good-enough estimate, even with the join fanout, even if it was too
pessimistic in some cases.
Maybe it's not ... How bad can it be?
Let's say we're joining T1 and T2, each with 1000 rows. Let's say T1 has
1000 distinct keys (1 to 1000), while T2 only has 10 distinct keys (1 to
10), each with 100 rows.
Then |T1 join T2| = 1000, and our current estimate says the Bloom filter
selectivity is 100%, because
|T1 join T2| / |T2| = 1.0
but you're saying we should estimate 1%, because only 1% of the T1 rows
finds a match in T2. Seems like a good point, surely we can calculate
that estimate? I mean, we're already calculating it when estimating the
join cardinality.
I don't really mind if the filter costing is pessimistic in some cases,
but the thing that worries me is that this likely also "breaks" the
estimates for the filtered paths. IIRC we use the selectivity to set
those, so can't those get quite off? That'd be very annoying, as one of
the reasons to do this bottom-up planning was to show correct estimates
in EXPLAIN.
> The second component is the Bloom false-positive probability.
>
> Let m be the number of bits in the Bloom filter, k the number of Bloom
> hash probes, and n the number of distinct build keys inserted into the
> filter.
>
> Under the usual uniform-hashing approximation, a single bit-setting
> operation misses a particular bit with probability
> 1 - 1/m.
>
> After k * n such operations, the probability that this bit is still zero is
>
> (1 - 1/m)^(k*n),
>
> which for sufficiently large m is approximately
>
> exp(-k*n/m).
>
> The probability that the bit is set is therefore approximately
>
> 1 - exp(-k*n/m),
>
> and the usual Bloom false-positive estimate is
>
> p ~= (1 - exp(-k*n/m))^k.
>
> Now let s be the semi-join survival probability.
>
> A fraction s of probe tuples has a real build-side match and therefore
> always passes the Bloom filter. The remaining fraction 1 - s has no real
> match, but a fraction p of those tuples still passes because of false
> positives.
>
> The expected Bloom survival is therefore
> bloom_sel = s + (1 - s) * p,
> and the expected rejected fraction is
> r = 1 - bloom_sel = (1 - s) * (1 - p).
> For example, if s = 0.20 and p = 0.10,
> bloom_sel = 0.20 + 0.80 * 0.10 = 0.28,
> and
> r = 0.80 * 0.90 = 0.72.
>
> So about 72% of probe tuples are expected to be rejected.
>
I don't follow. Can you clarify how this affects the patch?
I think we know we'll have to consider the false positive rate when
costing the filters, estimating cardinalities for the filtered paths,
etc. IIRC there was a discussion about considering that when sizing the
filter (e.g. that it might be better to accept smaller filters with
worse false positive ratio, etc.).
I don't think anyone worked on that yet, so it's still on TODO.
> PostgreSQL's JOIN_SEMI selectivity machinery seems to model the quantity
> needed for the first component. I experimented with constructing a dummy
> SpecialJoinInfo using JOIN_SEMI for the hash clauses, applying
> get_foreign_key_join_selectivity() to FK clauses and
> clauselist_selectivity(..., JOIN_SEMI, ...) to the remaining clauses.
>
> The harder case is a joined build side, for example
> owner SEMI JOIN (R1 JOIN R2).
>
> In this case we need to estimate which build keys survive the complete
> build subtree. For example, if R1 initially contains keys {1, 2, 3, 4,
> 5}, but R1 JOIN R2 leaves only rows with keys {1, 2}, then the Bloom
> filter built by the upper Hash Join represents only {1, 2}.
>
You mean literally estimating which keys survive? Can that even be done?
It's not clear to me why we'd need to go beyond what the current join
planning/estimation does. Why can't we estimate this simply as
owner SEMI JOIN (R1 JOIN R2)
as you wrote earlier? Maybe there's an obvious flaw I don't see.
> So the desired quantity is
> s = P(an owner key matches at least one key produced by the complete
> build subtree).
>
> That is, the relevant estimate is owner SEMI JOIN (R1 JOIN R2), not
> owner SEMI JOIN R1.
>
> This is also how the paper describes the problem: different build-side
> relation sets correspond to different Bloom-filter cardinality
> estimates, because joins on the build side may remove distinct build
> keys before the Bloom filter is constructed.
>
Right. But we already have a code to estimate such joins (in the core,
not in the patch), no? Can't we just "delegate" the estimate to that?
> The false-positive estimate has a related dependency. Ideally, n should
> be the number of distinct values (NDV) of the build hash key after the
> complete build subtree has been evaluated, because repeated occurrences
> of the same key do not add new information to the Bloom filter.
>
True. We cheated a bit by just treating each row as a unique key. Which
may make the filter larger.
> If the Bloom layout is fixed, using the build row count as an upper
> bound for the number of distinct inserted keys overestimates filter
> occupancy whenever duplicates are present. With an adaptive sizing
> policy the effect also depends on how m and k are chosen, so estimating
> the surviving build-key NDV would still be preferable.
>
No argument here. I think my argument was that this is good enough for
v1, and that it's better to have an oversized filter than a filter with
unexpectedly bad false positive rate. And our ndistinct estimates are
pretty bad (and joins make it worse), so this seemed reasonable.
There already are "adaptive Bloom filter" variants designed to handle
this kind of issue, but that seemed overly complex.
> v9 already keeps the required build relation set in ExpectedFilter, so
> this seems compatible with the existing architecture. The main question
> is how to obtain the semi-join estimate for the complete joined build
> side without duplicating more of the normal join-planning machinery.
>
> So I wanted to ask two questions.
>
> Does it make sense for ExpectedFilter.selectivity to represent the
> expected Bloom survival s + (1 - s) * p, with s based on semi-join
> selectivity rather than ordinary join cardinality?
>
I'm returning to this patch after a month, but I think it makes sense. I
suppose it wouldn't be hard to demonstrate the issue with the current
row count estimate (on filtered paths) in EXPLAIN. And with the semijoin
it would be more accurate.
I wonder how reliable those estimates are ... but worth a try.
> And for joined build sides, would it make sense to estimate the semi-
> join against the complete build relation set and use the surviving
> build-key NDV for the Bloom false-positive estimate, or would there be a
> better way to reuse the normal joinrel/selectivity machinery?
>
I don't know. My experience with our ndistinct estimates is not great, I
mean, it's not difficult to get values that are quite off. I can't
really imagine propagating those through joins would not make it much
worse. But maybe I'm too pessimistic.
regards
--
Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 8/24/26 10:39, Denis Rodionov wrote: > ... > > Attached is a proof-of-concept patch (on top of v9-0001..v9-0021) that > implements the semijoin + false-positive model from my review, to make > the discussion concrete. It's not meant as a finished patch; it's more > of "here's what the formula looks like as code, and here's what testing > it turned up". > Ah, I see you've already implemented a PoC of the filter estimation. I didn't notice that before responding to the earlier message. I'll take a closer look at this in the next couple days. Thanks! -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 9/2/26 20:12, Andrei Lepikhov wrote: > On 22/08/2026 00:26, Tomas Vondra wrote: > > As I see it, the bottom-up, cost-based approach quickly becomes > complicated, and two of the underlying problems look fundamental. > > 1. Estimating the number of unmatched rows. This is the key input to the > filter's cost model, and I don't see a way to implement it. We do have > eqjoinsel_semi(), but it compares MCV lists and then assumes uniformity over > n_distinct for everything else — and the unmatched rows live mostly in that > tail. So it is not that the estimate is imprecise; for the part of the > population that decides the answer, there is no distribution model at all, only > a count of distinct values. Histogram-based join estimation, of the kind GPORCA > does by aligning buckets, does not exist here. That is one more piece of basic > technology we would need first. > Systems that ship this feature don't really solve it either — they work around > it. The CIDR 2026 paper [1] on bitmap filters in SQL Server describes an > optimiser that decides on the filter from ordinary join selectivity, then defers > the bitmap's shape and memory budget to run time. That is adaptation, not > estimation. > Well, maybe we need some more infrastructure, to allow calculating sufficiently good filter estimates. But it's not clear to me why we couldn't rely on the existing JOIN_SEMI estimates, as suggested by Denis Rodionov. I didn't have time to look at his patch/results yet, though. FWIW I don't think the estimates can ever be perfect, especially for complex joins (and that transfers to the filter estimates). > 2. Path propagation. Filtered paths seem to need planning as parameterised ones. > That may well be doable. However, the use case is narrow compared with the > growth of the search space it brings for complex queries, and the effect is not > local: once filters are in the optimiser, the best join order itself changes [2]. > True, which is why the patch (and the paper) aims to only create very limited number of filtered paths, and only when there's a plausible chance of that helping. I can imagine it'd be gated by some GUC in the end, and people having to opt in, but I'd prefer that to not be needed. I don't see the join order changes as an issue. That's expected, and also how the optimization can bring the most significant benefits. The adaptation approach simply can't get those. > Hence, unblocking the bottom-up route means solving both of these in advance, > and I don't see either one coming any closer. > Most patches look difficult at the beginning. > Meanwhile, as the v2 patch [3] shows, the opportunistic approach can plausibly > satisfy 'do better or the same'. Its open questions — how to represent the cost > in EXPLAIN, how to decide adaptively whether to enable the filter, the overhead > in parallel plans — are real, but none of them blocks the design the way the two > above do. > > What it buys: simple code and zero overhead at planning time. Also, I don't read > these as competing designs. The opportunistic path can go in now and collect the > field experience the bottom-up one is currently missing. > > I ran a v2-modified instance under a real-life ORM load. Besides the positive > changes in execution time, it turned up something I did not expect: the filter > makes visible those cases where one more index, on one side of the join clause > expression, would switch a heavy HashJoin into a fast parameterised NestLoop. > > I'm not against the bottom-up approach outright. Tomas already notes in [3] that > an FK join needs no filter at all, since every outer tuple finds a match — and > that is a plan-time decision we can make exactly. So I would call it a starting > point for an incremental cost model rather than evidence that the general > problem is tractable. > > Does anyone see a way to estimate unmatched rows that I have missed? > I'm not against doing v2 (with a local filter for "all" hash joins), and yes - it should be simpler. But IMHO it targets quite different use cases than the "pushdown" patch. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 29/09/2026 19:57, Tomas Vondra wrote: > On 9/2/26 20:12, Andrei Lepikhov wrote: >> 1. Estimating the number of unmatched rows. This is the key input to the >> filter's cost model, and I don't see a way to implement it. We do have >> eqjoinsel_semi(), but it compares MCV lists and then assumes uniformity over >> n_distinct for everything else — and the unmatched rows live mostly in that >> tail. So it is not that the estimate is imprecise; for the part of the >> population that decides the answer, there is no distribution model at all, only >> a count of distinct values. Histogram-based join estimation, of the kind GPORCA >> does by aligning buckets, does not exist here. That is one more piece of basic >> technology we would need first. >> Systems that ship this feature don't really solve it either — they work around >> it. The CIDR 2026 paper [1] on bitmap filters in SQL Server describes an >> optimiser that decides on the filter from ordinary join selectivity, then defers >> the bitmap's shape and memory budget to run time. That is adaptation, not >> estimation. >> > > Well, maybe we need some more infrastructure, to allow calculating > sufficiently good filter estimates. But it's not clear to me why we > couldn't rely on the existing JOIN_SEMI estimates, as suggested by Denis > Rodionov. I didn't have time to look at his patch/results yet, though. > > FWIW I don't think the estimates can ever be perfect, especially for > complex joins (and that transfers to the filter estimates). Hmm, my point isn't perfection — it's scope and blind spots. Let me summarise what we can actually derive today. These three items are everything eqjoinsel_semi() has to work with: 1. Strip the matched MCVs and the NULL fraction, then look at what the ndistinct counts leave over. No difference there — no prediction of unmatched rows at all. 2. FK->PK joins. Here we do have an estimate, derived from the constraint and the estimated input sizes. 3. (Potentially) matching histogram boundaries. Postgres does this in mergejoinscansel() and nowhere else. That is a reasonable set, but it says nothing about two tables of similar size with similar statistics — which is the common case. And in practice, especially in ERP systems, users preprocess values like this: CASE WHEN day = 'sunday' THEN salary*2 ELSE salary END examine_variable() finds no statistics for that expression, so we fall back to DEFAULT_NUM_DISTINCT and the default selectivities. Anything we then compute for unmatched rows inherits that guess. This is exactly why the opportunistic approach works better here: it doesn't need the number at all. > >> 2. Path propagation. Filtered paths seem to need planning as parameterised ones. >> That may well be doable. However, the use case is narrow compared with the >> growth of the search space it brings for complex queries, and the effect is not >> local: once filters are in the optimiser, the best join order itself changes [2]. >> > > True, which is why the patch (and the paper) aims to only create very > limited number of filtered paths, and only when there's a plausible > chance of that helping. I can imagine it'd be gated by some GUC in the > end, and people having to opt in, but I'd prefer that to not be needed. > > I don't see the join order changes as an issue. That's expected, and > also how the optimization can bring the most significant benefits. The > adaptation approach simply can't get those. That might not be a big issue. My point is what we are stacking: in a bushy join tree, the number of unmatched rows is one uncertainty on top of another — the join clause selectivity. Whatever level of conservatism we eventually pick, it will either admit too many overly aggressive plans (and fails more frequently as a result) or cut the number of Bloom filters down to almost nothing. >> Meanwhile, as the v2 patch [3] shows, the opportunistic approach can plausibly >> satisfy 'do better or the same'. Its open questions — how to represent the cost >> in EXPLAIN, how to decide adaptively whether to enable the filter, the overhead >> in parallel plans — are real, but none of them blocks the design the way the two >> above do. >> >> What it buys: simple code and zero overhead at planning time. Also, I don't read >> these as competing designs. The opportunistic path can go in now and collect the >> field experience the bottom-up one is currently missing. >> >> I ran a v2-modified instance under a real-life ORM load. Besides the positive >> changes in execution time, it turned up something I did not expect: the filter >> makes visible those cases where one more index, on one side of the join clause >> expression, would switch a heavy HashJoin into a fast parameterised NestLoop. >> >> I'm not against the bottom-up approach outright. Tomas already notes in [3] that >> an FK join needs no filter at all, since every outer tuple finds a match — and >> that is a plan-time decision we can make exactly. So I would call it a starting >> point for an incremental cost model rather than evidence that the general >> problem is tractable. >> >> Does anyone see a way to estimate unmatched rows that I have missed? >> > > I'm not against doing v2 (with a local filter for "all" hash joins), and > yes - it should be simpler. But IMHO it targets quite different use > cases than the "pushdown" patch. Good. It also looks like a reasonably safe route. Other systems did not drop planning either — they deferred to runtime exactly those decisions they could not estimate. So we can borrow both their experience and their runtime fallback heuristics instead of inventing our own. I have also tested the v2 patch (plus some extra code for partial paths) on a couple of ERP workloads. The overhead is small even when the filter does not pay off — and in any case, we can add a GUC to turn it off. So maybe we should pursue both? The opportunistic approach solves the problems we have today and has a chance to land in core much sooner. The path-based one extends the scope of the optimiser and improves planning in general, but it has to wait for the infrastructure. -- regards, Andrei Lepikhov, pgEdge
Re: hashjoins vs. Bloom filters (yet again)
On 10/5/26 14:04, Andrei Lepikhov wrote: > On 29/09/2026 19:57, Tomas Vondra wrote: >> On 9/2/26 20:12, Andrei Lepikhov wrote: >>> 1. Estimating the number of unmatched rows. This is the key input to the >>> filter's cost model, and I don't see a way to implement it. We do have >>> eqjoinsel_semi(), but it compares MCV lists and then assumes uniformity over >>> n_distinct for everything else — and the unmatched rows live mostly in that >>> tail. So it is not that the estimate is imprecise; for the part of the >>> population that decides the answer, there is no distribution model at all, only >>> a count of distinct values. Histogram-based join estimation, of the kind GPORCA >>> does by aligning buckets, does not exist here. That is one more piece of basic >>> technology we would need first. >>> Systems that ship this feature don't really solve it either — they work around >>> it. The CIDR 2026 paper [1] on bitmap filters in SQL Server describes an >>> optimiser that decides on the filter from ordinary join selectivity, then defers >>> the bitmap's shape and memory budget to run time. That is adaptation, not >>> estimation. >>> >> >> Well, maybe we need some more infrastructure, to allow calculating >> sufficiently good filter estimates. But it's not clear to me why we >> couldn't rely on the existing JOIN_SEMI estimates, as suggested by Denis >> Rodionov. I didn't have time to look at his patch/results yet, though. >> >> FWIW I don't think the estimates can ever be perfect, especially for >> complex joins (and that transfers to the filter estimates). > > Hmm, my point isn't perfection — it's scope and blind spots. > > Let me summarise what we can actually derive today. These three items are > everything eqjoinsel_semi() has to work with: > > 1. Strip the matched MCVs and the NULL fraction, then look at what the ndistinct > counts leave over. No difference there — no prediction of unmatched rows at all. > 2. FK->PK joins. Here we do have an estimate, derived from the constraint and > the estimated input sizes. > 3. (Potentially) matching histogram boundaries. Postgres does this in > mergejoinscansel() and nowhere else. > > That is a reasonable set, but it says nothing about two tables of similar size > with similar statistics — which is the common case. And in practice, especially > in ERP systems, users preprocess values like this: > > CASE WHEN day = 'sunday' THEN salary*2 ELSE salary END > > examine_variable() finds no statistics for that expression, so we fall back to > DEFAULT_NUM_DISTINCT and the default selectivities. Anything we then compute for > unmatched rows inherits that guess. This is exactly why the opportunistic > approach works better here: it doesn't need the number at all. > I'm probably missing something, but I don't understand point you're trying to make. Sure, pushdown is more complex than applying filters inside the single hashjoin (which is what v2 does), no argument there. I fail to see how the "opportunistic approach works better". In fact, the pushdown makes the plan more resilient to poor estimates (which is what you're pointing out), and picking poor join orders. Because while it does change join order, it does not change the order in which we apply the "join filtering". That's one of the key benefits. We may be unable to get accurate estimate of the Bloom filter, because the stats we have are not sufficient. And maybe we'll not do the pushdown in some cases because or estimate is too conservative. I don't think that's a huge issue, as long as we don't cause (big) regressions relative to "no pushdown" plans. In fact, I wonder if the "join result size" is similarly important to the filter selectivity, when picking "candidate filters." >> >>> 2. Path propagation. Filtered paths seem to need planning as parameterised ones. >>> That may well be doable. However, the use case is narrow compared with the >>> growth of the search space it brings for complex queries, and the effect is not >>> local: once filters are in the optimiser, the best join order itself changes [2]. >>> >> >> True, which is why the patch (and the paper) aims to only create very >> limited number of filtered paths, and only when there's a plausible >> chance of that helping. I can imagine it'd be gated by some GUC in the >> end, and people having to opt in, but I'd prefer that to not be needed. >> >> I don't see the join order changes as an issue. That's expected, and >> also how the optimization can bring the most significant benefits. The >> adaptation approach simply can't get those. > > That might not be a big issue. My point is what we are stacking: in a bushy join > tree, the number of unmatched rows is one uncertainty on top of another — the > join clause selectivity. Whatever level of conservatism we eventually pick, it > will either admit too many overly aggressive plans (and fails more frequently as > a result) or cut the number of Bloom filters down to almost nothing. > But we're already calculating that estimate when building the plans, even without the filter pushdown. We don't change that at all. And as I wrote above - increased resiliency to poor estimates (and thus poor join orders) is one of the benefits of filter pushdown. >>> Meanwhile, as the v2 patch [3] shows, the opportunistic approach can plausibly >>> satisfy 'do better or the same'. Its open questions — how to represent the cost >>> in EXPLAIN, how to decide adaptively whether to enable the filter, the overhead >>> in parallel plans — are real, but none of them blocks the design the way the two >>> above do. >>> >>> What it buys: simple code and zero overhead at planning time. Also, I don't read >>> these as competing designs. The opportunistic path can go in now and collect the >>> field experience the bottom-up one is currently missing. >>> >>> I ran a v2-modified instance under a real-life ORM load. Besides the positive >>> changes in execution time, it turned up something I did not expect: the filter >>> makes visible those cases where one more index, on one side of the join clause >>> expression, would switch a heavy HashJoin into a fast parameterised NestLoop. >>> >>> I'm not against the bottom-up approach outright. Tomas already notes in [3] that >>> an FK join needs no filter at all, since every outer tuple finds a match — and >>> that is a plan-time decision we can make exactly. So I would call it a starting >>> point for an incremental cost model rather than evidence that the general >>> problem is tractable. >>> >>> Does anyone see a way to estimate unmatched rows that I have missed? >>> >> >> I'm not against doing v2 (with a local filter for "all" hash joins), and >> yes - it should be simpler. But IMHO it targets quite different use >> cases than the "pushdown" patch. > > Good. > > It also looks like a reasonably safe route. Other systems did not drop planning > either — they deferred to runtime exactly those decisions they could not > estimate. So we can borrow both their experience and their runtime fallback > heuristics instead of inventing our own. > > I have also tested the v2 patch (plus some extra code for partial paths) on a > couple of ERP workloads. The overhead is small even when the filter does not pay > off — and in any case, we can add a GUC to turn it off. > > So maybe we should pursue both? The opportunistic approach solves the problems > we have today and has a chance to land in core much sooner. The path-based one > extends the scope of the optimiser and improves planning in general, but it has > to wait for the infrastructure. > Perhaps. I think it makes sense to do v2 (i.e. Bloom filters inside a single hashjoin node) first, and use it to introduce infrastructure that is also useful for the pushdown patches. Like sizing filters, the adaptive behavior, etc. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 05/10/2026 18:24, Tomas Vondra wrote: > On 10/5/26 14:04, Andrei Lepikhov wrote: >> On 29/09/2026 19:57, Tomas Vondra wrote: > Sure, pushdown is more complex than applying filters inside the single > hashjoin (which is what v2 does), no argument there. Fair enough - complexity isn't my argument, let's keep it out of scope. My argument is narrower: the path-based pushdown design needs a number that today's statistics can't produce, and I don't see what fills that gap. > I fail to see how > the "opportunistic approach works better". Maybe I wasn't precise enough. By 'better' I meant broader and more stable, not faster. Broader: the opportunistic approach can be applied to every HashJoin in the plan, and it can push filter clauses down as deep as needed if there are no strong evidence that filter can't provide any meaningful impact. It also works in the cases where we have no usable statistics at all - which, in ERP-style schemas, is most of them. Stable: it doesn't change the join order. You're right that this cuts both ways - changing the join order is where the biggest wins are, and I'm not disputing that. My point is that it's a trade: path-based approach gains the best-case plans, and you also gain a new way to lose them. > > In fact, the pushdown makes the plan more resilient to poor estimates > (which is what you're pointing out), and picking poor join orders. > Because while it does change join order, it does not change the order in > which we apply the "join filtering". That's one of the key benefits. I may be using 'resilient' differently from you. So, let's specify. A pushed-down filter can only lower the row estimates below it - it never raises them, right? That pushes some segments of plan tree towards the aggressive side: NestLoop , Memoize, HashAgg with a smaller hash table. When the filter really is that selective, this is exactly what we want. When it isn't, we have picked a plan that fails badly rather than one that is merely slow. That asymmetry is my whole concern. Overestimation costs us a sort or a bigger hash table. Underestimation gives us a stack of nested loops that runs for a week. And Postgres multiplies selectivities, so a per-filter bias compounds it. The opportunistic version can only make that plan faster, or leave it alone. > > We may be unable to get accurate estimate of the Bloom filter, because > the stats we have are not sufficient. And maybe we'll not do the > pushdown in some cases because or estimate is too conservative. I don't > think that's a huge issue, as long as we don't cause (big) regressions > relative to "no pushdown" plans. My point here is that if we add path-based Bloom implementation alone, we have a methodological blind spot. Two things make me sceptical of anything built on ndistinct here. First, the case I keep running into is two relations of similar size with similar ndistinct - the MCV lists don't overlap usefully, and the unmatched rows live in the tail that we model with a single number. Second, ndistinct doesn't shrink as we go up the tree the way rows do: as far as I can see, eqjoinsel() works from get_variable_numdistinct() and then clamps, so a column keeps its base-table distinct count until the row estimate drops below it. That is a long-standing source of trouble on its own, and a filter estimate built on top would inherit it. >> That might not be a big issue. My point is what we are stacking: in a bushy join >> tree, the number of unmatched rows is one uncertainty on top of another — the >> join clause selectivity. Whatever level of conservatism we eventually pick, it >> will either admit too many overly aggressive plans (and fails more frequently as >> a result) or cut the number of Bloom filters down to almost nothing. >> > > But we're already calculating that estimate when building the plans, > even without the filter pushdown. We don't change that at all. And as I > wrote above - increased resiliency to poor estimates (and thus poor join > orders) is one of the benefits of filter pushdown. Today a bad join selectivity gives us a bad row count; with the filter in the cost model it also gives us a different join order and different node types. This is more about blast radius of the feature. >> So maybe we should pursue both? The opportunistic approach solves the problems >> we have today and has a chance to land in core much sooner. The path-based one >> extends the scope of the optimiser and improves planning in general, but it has >> to wait for the infrastructure. >> > Perhaps. I think it makes sense to do v2 (i.e. Bloom filters inside a > single hashjoin node) first, and use it to introduce infrastructure that > is also useful for the pushdown patches. Like sizing filters, the > adaptive behavior, etc. Agreed. I'd put the division of labour like this: - The opportunistic filter is the default: build it unless we can prove it is pointless. For example, a FK join where every outer row finds a match. So it works as a safety net. - The path-based version is then free to do the thing only it can do: reach plans we would not otherwise consider. And because the safety net is already there, it doesn't have to fire often to be worth having. When the selectivity behind a filter rests on a guess it can simply decline to push. -- regards, Andrei Lepikhov, pgEdge
Re: hashjoins vs. Bloom filters (yet again)
On 10/6/26 13:26, Andrei Lepikhov wrote: > On 05/10/2026 18:24, Tomas Vondra wrote: >> On 10/5/26 14:04, Andrei Lepikhov wrote: >>> On 29/09/2026 19:57, Tomas Vondra wrote: >> Sure, pushdown is more complex than applying filters inside the single >> hashjoin (which is what v2 does), no argument there. > > Fair enough - complexity isn't my argument, let's keep it out of scope. My > argument is narrower: the path-based pushdown design needs a number that today's > statistics can't produce, and I don't see what fills that gap. > >> I fail to see how >> the "opportunistic approach works better". > > Maybe I wasn't precise enough. By 'better' I meant broader and more stable, not > faster. > > Broader: the opportunistic approach can be applied to every HashJoin in the > plan, and it can push filter clauses down as deep as needed if there are no > strong evidence that filter can't provide any meaningful impact. It also works > in the cases where we have no usable statistics at all - which, in ERP-style > schemas, is most of them. > AFAIK it faces the same challenge with estimating filter selectivity, even if the Bloom filter is used only in the hashjoin that built it. v2 did no pushdown, if I remember correctly. I can't imagine committing a version that would do a pushdown at execution time, for reasons that I explained before (breaking EXPLAIN). > Stable: it doesn't change the join order. You're right that this cuts both ways > - changing the join order is where the biggest wins are, and I'm not disputing > that. My point is that it's a trade: path-based approach gains the best-case > plans, and you also gain a new way to lose them. > The pushdown changes the join order, but does not change the order in which the filtering happens. >> >> In fact, the pushdown makes the plan more resilient to poor estimates >> (which is what you're pointing out), and picking poor join orders. >> Because while it does change join order, it does not change the order in >> which we apply the "join filtering". That's one of the key benefits. > > I may be using 'resilient' differently from you. So, let's specify. > > A pushed-down filter can only lower the row estimates below it - it never raises > them, right? That pushes some segments of plan tree towards the aggressive side: > NestLoop , Memoize, HashAgg with a smaller hash table. > When the filter really is that selective, this is exactly what we want. When it > isn't, we have picked a plan that fails badly rather than one that is merely slow. > > That asymmetry is my whole concern. Overestimation costs us a sort or a bigger > hash table. Underestimation gives us a stack of nested loops that runs for a > week. And Postgres multiplies selectivities, so a per-filter bias compounds it. > > The opportunistic version can only make that plan faster, or leave it alone. > I don't think it works like that. The important details is that while the apparent join order changes, the order in which the join filtering happens remains pretty much the same. Consider a trivial example - a left-deep plan F-D1-D2-D3-D4-D5, joining a fact table to dimensions, starting with the most selective dimension joins. Now let's build Bloom filters for dimensions D1 and D2, which also changes the join order to F-D3-D4-D5-D1-D2. But the D1/D2 filtering still happens *before* D3 gets joined, and that join expects the same cardinality from that input. There's no reason why this would "push" the plan tree towards a "more aggressive" side. Maybe this example is too simple. It'd be helpful if you could share an example demonstrating the issue. >> >> We may be unable to get accurate estimate of the Bloom filter, because >> the stats we have are not sufficient. And maybe we'll not do the >> pushdown in some cases because or estimate is too conservative. I don't >> think that's a huge issue, as long as we don't cause (big) regressions >> relative to "no pushdown" plans. > > My point here is that if we add path-based Bloom implementation alone, we have a > methodological blind spot. > > Two things make me sceptical of anything built on ndistinct here. First, the > case I keep running into is two relations of similar size with similar ndistinct > - the MCV lists don't overlap usefully, and the unmatched rows live in the tail > that we model with a single number. Second, ndistinct doesn't shrink as we go up > the tree the way rows do: as far as I can see, eqjoinsel() works from > get_variable_numdistinct() and then clamps, so a column keeps its base-table > distinct count until the row estimate drops below it. That is a long-standing > source of trouble on its own, and a filter estimate built on top would inherit it. > Sure, no argument about ndistinct being very crude statistic, often producing wildly inaccurate estimates. But AFAIK the filter pushdown does not make us more exposed, because it merely relies on the join cardinality estimates. >>> That might not be a big issue. My point is what we are stacking: in a bushy join >>> tree, the number of unmatched rows is one uncertainty on top of another — the >>> join clause selectivity. Whatever level of conservatism we eventually pick, it >>> will either admit too many overly aggressive plans (and fails more frequently as >>> a result) or cut the number of Bloom filters down to almost nothing. >>> >> >> But we're already calculating that estimate when building the plans, >> even without the filter pushdown. We don't change that at all. And as I >> wrote above - increased resiliency to poor estimates (and thus poor join >> orders) is one of the benefits of filter pushdown. > > Today a bad join selectivity gives us a bad row count; with the filter in the > cost model it also gives us a different join order and different node types. > This is more about blast radius of the feature. > I don't think so. It gives us a different apparent join order, but the data is still filtered in the same order as before. >>> So maybe we should pursue both? The opportunistic approach solves the problems >>> we have today and has a chance to land in core much sooner. The path-based one >>> extends the scope of the optimiser and improves planning in general, but it has >>> to wait for the infrastructure. >>> >> Perhaps. I think it makes sense to do v2 (i.e. Bloom filters inside a >> single hashjoin node) first, and use it to introduce infrastructure that >> is also useful for the pushdown patches. Like sizing filters, the >> adaptive behavior, etc. > > Agreed. I'd put the division of labour like this: > > - The opportunistic filter is the default: build it unless we can prove it is > pointless. For example, a FK join where every outer row finds a match. So it > works as a safety net. > Agreed. > - The path-based version is then free to do the thing only it can do: reach > plans we would not otherwise consider. And because the safety net is already > there, it doesn't have to fire often to be worth having. When the selectivity > behind a filter rests on a guess it can simply decline to push. > Not sure how could it "know" which plans would be unreachable, or what kind of safety net you mean. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
On 06/10/2026 16:07, Tomas Vondra wrote: > > On 10/6/26 13:26, Andrei Lepikhov wrote: >> On 05/10/2026 18:24, Tomas Vondra wrote: >> Broader: the opportunistic approach can be applied to every HashJoin in the >> plan, and it can push filter clauses down as deep as needed if there are no >> strong evidence that filter can't provide any meaningful impact. It also works >> in the cases where we have no usable statistics at all - which, in ERP-style >> schemas, is most of them. >> > > AFAIK it faces the same challenge with estimating filter selectivity, > even if the Bloom filter is used only in the hashjoin that built it. In my view, the opportunistic approach would use estimates only to reject provably pointless cases, and would build the filter whenever the case is uncertain. That's the asymmetry I keep pointing at: the path-based version needs a number — how selective the filter is — and feeds it into the cost model, so a wrong estimate gives us a different plan. The opportunistic version needs only a one-sided test: can we prove this filter is useless? A wrong answer there costs us some hashing, not a join order. It also lets us handle COALESCE(), CASE and other constructs that collapse statistics to default selectivities — the cases where the path-based version has nothing to work with at all. > > v2 did no pushdown, if I remember correctly. I can't imagine committing > a version that would do a pushdown at execution time, for reasons that I > explained before (breaking EXPLAIN). On the EXPLAIN point: agreed, a filter that appears at execution time only is not committable. What I have in mind stays visible in the plan — the decision is made at plan time, the filter just doesn't have to be load-bearing for the cost model. BTW, it seems to me that there is also some precedent for showing execution-time decisions in EXPLAIN: runtime partition pruning reports "Subplans Removed". I'd expect a filter to be presentable the same way. >> A pushed-down filter can only lower the row estimates below it - it never raises >> them, right? That pushes some segments of plan tree towards the aggressive side: >> NestLoop , Memoize, HashAgg with a smaller hash table. >> When the filter really is that selective, this is exactly what we want. When it >> isn't, we have picked a plan that fails badly rather than one that is merely slow. >> >> That asymmetry is my whole concern. Overestimation costs us a sort or a bigger >> hash table. Underestimation gives us a stack of nested loops that runs for a >> week. And Postgres multiplies selectivities, so a per-filter bias compounds it. > > I don't think it works like that. The important details is that while > the apparent join order changes, the order in which the join filtering > happens remains pretty much the same. > > Consider a trivial example - a left-deep plan F-D1-D2-D3-D4-D5, joining > a fact table to dimensions, starting with the most selective dimension > joins. Now let's build Bloom filters for dimensions D1 and D2, which > also changes the join order to F-D3-D4-D5-D1-D2. But the D1/D2 filtering > still happens *before* D3 gets joined, and that join expects the same > cardinality from that input. There's no reason why this would "push" the > plan tree towards a "more aggressive" side. > > Maybe this example is too simple. It'd be helpful if you could share an > example demonstrating the issue. In the current v10 the INNER JOIN example works well. But even here I see one source of uncertainty: the Bloom filter promises more than it can deliver. Please look at the attached example. The estimates there are quite accurate, and we still get a 3x regression in execution time. Yes, we can find a fix for each root cause of this bad plan, but the uncertainty remains: I can imagine a case with many NULLs in the input that pass the filter and cause a regression as well. Also, don't forget that the typical case isn't a multi-way join like this one, but a more complex query with limited freedom to reorder joins — outer joins, lateral references, and so on. This is not an argument for dropping this work, just a demonstration that the scope should start narrow and be extended step by step as new estimation machinery arrives. -- regards, Andrei Lepikhov, pgEdge
Re: hashjoins vs. Bloom filters (yet again)
On 10/8/26 15:35, Andrei Lepikhov wrote: > On 06/10/2026 16:07, Tomas Vondra wrote: >> >> On 10/6/26 13:26, Andrei Lepikhov wrote: >>> On 05/10/2026 18:24, Tomas Vondra wrote: >>> Broader: the opportunistic approach can be applied to every HashJoin in the >>> plan, and it can push filter clauses down as deep as needed if there are no >>> strong evidence that filter can't provide any meaningful impact. It also works >>> in the cases where we have no usable statistics at all - which, in ERP-style >>> schemas, is most of them. >>> >> >> AFAIK it faces the same challenge with estimating filter selectivity, >> even if the Bloom filter is used only in the hashjoin that built it. > > In my view, the opportunistic approach would use estimates only to reject > provably pointless cases, and would build the filter whenever the case is > uncertain. That's the asymmetry I keep pointing at: the path-based version needs > a number — how selective the filter is — and feeds it into the cost model, so a > wrong estimate gives us a different plan. > > The opportunistic version needs only a one-sided test: can we prove this filter > is useless? A wrong answer there costs us some hashing, not a join order. It > also lets us handle COALESCE(), CASE and other constructs that collapse > statistics to default selectivities — the cases where the path-based version has > nothing to work with at all. > To some extent, yes. I don't think the plans are that different, for the reasons I explained earlier (regarding the join order changing, but not the filter order, and us already relying on these estimates anyway). But you're right it introduces certain amount or new risk, particularly when the filters seem more selective. Which can happen for a couple reasons, both for a single join (but then we already have the problem in regular plans, I think) and when combining filters from multiple joins (and they are e.g. correlated in some way). It'd be interesting to see actual examples where this causes (serious) problems compared to "old" plans. >> >> v2 did no pushdown, if I remember correctly. I can't imagine committing >> a version that would do a pushdown at execution time, for reasons that I >> explained before (breaking EXPLAIN). > > On the EXPLAIN point: agreed, a filter that appears at execution time only is > not committable. What I have in mind stays visible in the plan — the decision is > made at plan time, the filter just doesn't have to be load-bearing for the cost > model. Showing the filter in the explain is not enough. If you push it down, you also have to go through all the intermediate nodes and adjust the rowcount and cost estimates to make the explain "correct". > > BTW, it seems to me that there is also some precedent for showing execution-time > decisions in EXPLAIN: runtime partition pruning reports "Subplans Removed". I'd > expect a filter to be presentable the same way. AFAIK that doesn't "break" the rowcount estimate, no? >>> A pushed-down filter can only lower the row estimates below it - it never raises >>> them, right? That pushes some segments of plan tree towards the aggressive side: >>> NestLoop , Memoize, HashAgg with a smaller hash table. >>> When the filter really is that selective, this is exactly what we want. When it >>> isn't, we have picked a plan that fails badly rather than one that is merely slow. >>> >>> That asymmetry is my whole concern. Overestimation costs us a sort or a bigger >>> hash table. Underestimation gives us a stack of nested loops that runs for a >>> week. And Postgres multiplies selectivities, so a per-filter bias compounds it. >> >> I don't think it works like that. The important details is that while >> the apparent join order changes, the order in which the join filtering >> happens remains pretty much the same. >> >> Consider a trivial example - a left-deep plan F-D1-D2-D3-D4-D5, joining >> a fact table to dimensions, starting with the most selective dimension >> joins. Now let's build Bloom filters for dimensions D1 and D2, which >> also changes the join order to F-D3-D4-D5-D1-D2. But the D1/D2 filtering >> still happens *before* D3 gets joined, and that join expects the same >> cardinality from that input. There's no reason why this would "push" the >> plan tree towards a "more aggressive" side. >> >> Maybe this example is too simple. It'd be helpful if you could share an >> example demonstrating the issue. > > In the current v10 the INNER JOIN example works well. But even here I see one > source of uncertainty: the Bloom filter promises more than it can deliver. > Please look at the attached example. The estimates there are quite accurate, and > we still get a 3x regression in execution time. > > Yes, we can find a fix for each root cause of this bad plan, but the uncertainty > remains: I can imagine a case with many NULLs in the input that pass the filter > and cause a regression as well. Also, don't forget that the typical case isn't a > multi-way join like this one, but a more complex query with limited freedom to > reorder joins — outer joins, lateral references, and so on. > > This is not an argument for dropping this work, just a demonstration that the > scope should start narrow and be extended step by step as new estimation > machinery arrives. > This is a simple example of the current patch not considering the false positive rate of the filter. The bloom_create logic sizes the filter to have 1-2% false positives (because that's enough for amcheck), but for a table with 10M rows that's ~200k rows. Which almost exactly matches the slow plan: -> Seq Scan on f (cost=0.00..156747.74 rows=2014 width=8) (actual rows=230415.00 loops=1) If you increase BLOOM_PROBE_MIN_BITSET_BYTES to 32kB, that fixes that and the plan becomes about 30% faster than the regular one. FWIW I'm not suggesting this is the right fix in general, it's just a proof that it's about false positive rate. The correct solution is to consider FPR when sizing the filters and estimating the selectivity for the paths. That's already on the TODO somewhere. But you're right this is not a fix for all possible issues. The filter (or a combination of filters) may be less selective for other reasons. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hi, Here's a significantly improved version of the v2 patch, using Bloom filters in a single hashjoin node (no pushdown). I'm still 100% convinced the goal should be filter pushdown - that's where the real gains are - saving CPU time (cheaper Bloom probes), disk I/O (by discarding tuples early with nbatch>1) and join order robustness (join order less vulnerable/sensitive to misestimates). I've been thinking about how to move this patch series forward, in that direction, in an incremental way. No matter how we get to do a pushdown (whether the bottom-up or opportunistic approach, discussed elsewhere in this thread), it'll still need to figure out all the questions as the local filters. Say, sizing the filter, populating the filter (in serial and parallel cases), reporting stuff in explain, and so on. So it seems reasonable to introduce that first, even if the gains are much smaller, and then build the pushdown stuff on that, somehow. v2.1 ---- I spent the last couple weeks working on this, rebasing and cleaning up the v2 patch, fixing all kinds of bugs in the PoC patch. The attached v2.1 is much cleaner, maybe ~90% to committable (but as we all know, the remaining 10% may take another 90% of the development time). There's still a couple of FIXMEs and XXX with open questions, but I'm not aware of any "actual" bugs. I planned to also rework the pushdown patches on top of it, but I have not managed to do that yet - the cleanup took me longer, and I have to take a break from the patch for a bit. I'm not sure when/if I'll have time for that again. So I'm posting at least the reworked v2.1, for others to take a look. The overall structure of the patch was basically right (easy to see by comparing v2 and v2.1 branches). It's probably not worth going over all the bugs I found in the v2 patch in detail, but it's what you'd expect from a PoC patch: - parallel queries probing filter too late, not before spilling them to disk (efficiency) - insufficient locking in parallel query (correctness) - confusion when the GUC changes during query execution (weird, but can happen) - incorrect instrumentation in plans calling shutdown (spi, cursors) - various improvements in the EXPLAIN (may need more work) - incorrect accounting for probe hits/misses for joins with duplicates in the inner relation (which meant incorrect build decisions) - various other smaller issues Where appropriate, I tried to briefly explain the issue in comments before the fixed code - by explaining why it needs to be this way, without being too verbose. If some changes are unclear, let me know and I'll try to remember what the issue was, and why it's fixed this way. I'm still a bit unsure about is the handling of instrumentation in ExecShutdownHash. It took me ages to get it working correctly (I think), so that it does not lose/discard instrumentation with SPI/cursors, etc. The adaptive heuristics (building/enabling/disabling filters) relies on that, so some queries were silently not using good filters etc. filter sizing ------------- The other "big" question is how to size the filter. There are two main challenges, I think. 1) in some cases the filter is not really faster than the hash table One thing I realized after looking at perf results is that even a very selective filter (discarding 90%+ rows) may not be any faster than checking the hash table. I believe this simply happens for hash tables with very few buckets, because then the buckets are pretty much the same as a Bloom filter. Let's say we have a hash table with 128K buckets - each bucket is a HashJoinTuple pointer, so this means 1MB of data (the whole hash table may be much larger, but that does not matter). We size the buckets for load factor 1.0 (NTUP_PER_BUCKET=1), so in most cases it's enough to check if the bucket is NULL to reject the tuple. The Bloom filter won't really save anything in this case, it may even be more expensive. I think the solution will be to consider the size of the buckets array, and not build the filter if the array is small. But what is small? It probably depends on some L2/L3 cache size, but we'll need to pick some sort of threshold. 1MB, maybe? We could also make it relative to the filter size - if the filter is more than 1/8 of the buckets, it may not help very much. Probably requires some microbenchmarks, to find what values might work. Maybe if we had a way to read the L2/L3 sizes from the system, that'd help us too. FWIW this only applies to nbatch=1 case, of course. In batched joins the savings come mainly from discarding tuples early, before spilling them to disk. May need some thresholds too, but certainly much higher. 2) we don't really know the number of elements We can build the filter in two places. While building the hash table, and during probing. And in both cases we don't really know the number of filter elements, which affects the sizing. While building the hash table it's obvious - we only have an estimate of the row count, but it may be inaccurate. If we decide to build the filter half-way through the hash table build (when going from nbatch=1 to nbatch=2), we at least know the number of tuples seen so far, but at this point we also know the estimate was wrong. The code size the filter for 2x the tuples, but that's wishful thinking. I wonder if we might do something smarter, like writing the hash values into a file, and then buildign the filter from that. Yes, it will cost something, but the hashvalues are tiny - much smaller than the tuples. We could probably also deduplicate them cheaply. So maybe it's worth a properly sized filter. Worth a try / experiment, I guess? Another detail is that sizing the filter for tuples is not quite right. We really care about number of distinct keys, and if the inner relation has duplicates, it may be a much smaller value. Maybe it'd be worth building a HLL counter, or something? we'd only need to do any of this in the nbatch>1 case, ofc. With a single batch we have all the values in the hashtable, which means we know the exect row count, and we could maybe calculate distincts too. benchmarks ---------- I'm attaching scripts + results from a simple benchmark on v2.1, joining a "fact" table to one or more dimensions, varying the selectivity of the join (by placing condition on the dimension, i.e. the inner relation). The PDFs summarize the results from two machines, a recent ryzen 5 and an old xeon. There are some differences, but the overall message is mostly the same. In both cases the most selective filter (keeping only 10% rows) wins only for work_mem=1MB, because it's batched. It's not very visible The single-batch runs got only mildly faster (by ~10%), and only with many buckets (not very visible in the PDFs, check the raw CSV results). I think this illustrates my earlier point about sizing the filter in relation to the buckets array. regards -- Tomas Vondra
Re: hashjoins vs. Bloom filters (yet again)
Hi,
Thanks for reworking the patches!
I reviewed v2.1 - the serial and parallel paths - and did differential
testing: 9 join shapes x {single-batch, batched} x {serial, parallel},
comparing result multisets with the filter forced on vs. off, including
the parallel shared-filter merge and a NULL-heavy anti-join. All tests
matched, with the bloom filter active. I didn't find any correctness
issue.
On Tue Oct 27, 2026 at 1:48 PM -03, Tomas Vondra wrote:
> filter sizing
> -------------
>
> The other "big" question is how to size the filter. There are two main
> challenges, I think.
>
> 1) in some cases the filter is not really faster than the hash table
>
> One thing I realized after looking at perf results is that even a very
> selective filter (discarding 90%+ rows) may not be any faster than
> checking the hash table. I believe this simply happens for hash tables
> with very few buckets, because then the buckets are pretty much the same
> as a Bloom filter.
>
> Let's say we have a hash table with 128K buckets - each bucket is a
> HashJoinTuple pointer, so this means 1MB of data (the whole hash table
> may be much larger, but that does not matter). We size the buckets for
> load factor 1.0 (NTUP_PER_BUCKET=1), so in most cases it's enough to
> check if the bucket is NULL to reject the tuple. The Bloom filter won't
> really save anything in this case, it may even be more expensive.
>
> I think the solution will be to consider the size of the buckets array,
> and not build the filter if the array is small. But what is small? It
> probably depends on some L2/L3 cache size, but we'll need to pick some
> sort of threshold. 1MB, maybe? We could also make it relative to the
> filter size - if the filter is more than 1/8 of the buckets, it may not
> help very much. Probably requires some microbenchmarks, to find what
> values might work. Maybe if we had a way to read the L2/L3 sizes from
> the system, that'd help us too.
>
I played with this idea and it seems that we need a small change: I've
added a new GUC, hashjoin_bloom_min_hashtable_size (in bytes), checked in
the single-batch adaptive build so we skip the filter when the bucket
array is below it:
@@ -1230,6 +1230,20 @@ ExecHashBloomAdaptiveBuild(HashJoinTable hashtable)
Assert(hashtable->bloomEnabled);
Assert(hashtable->bloomFilter == NULL);
+ /*
+ * The hash table of a single-batch join stays in memory, and if its bucket
+ * array is small enough to live in the CPU caches, a lookup is cheap enough
+ * that probing a Bloom filter first does not pay for itself - not even when
+ * the join is selective enough to reject most of the outer tuples. Skip the
+ * filter while the bucket array is below the configured size. Setting the
+ * size to 0 disables the check. (A batched join sizes and builds its filter
+ * up front and never reaches this path, so this does not affect it.)
+ */
+ if (hashjoin_bloom_min_hashtable_size > 0 &&
+ (Size) hashtable->nbuckets * sizeof(HashJoinTuple) <
+ (Size) hashjoin_bloom_min_hashtable_size)
+ return;
+
hashjoin_bloom_min_hashtable_size is the smallest bucket-array size
(nbuckets * sizeof(HashJoinTuple)) for which we bother building a
filter; below it the array is cache-resident enough that a lookup is as
cheap as a filter probe. It only touches the nbatch=1 path, as you noted
the batched case is different.
I kept the default at 0, i.e. the check is off and behavior is
unchanged, and I think that's the right default for now: the useful
threshold is machine-dependent (see below), so I'd rather not bake a
number in that's wrong elsewhere. The GUC lets us measure. A better
long-term answer is probably the one you suggested, detect the value
from the L2/L3 cache size at startup, so this wouldn't be a constant or
something people have to hand-tune.
The benchmark: fact of 3M rows joined to a dimension of N distinct keys,
fact keys spread over 10*N so ~90% of probes are rejected (your "very
selective filter" case), single batch, no parallelism.
inner bucket array plain hash join v2.1 today v2.1 + gate=8MB
100k 1 MB 572 ms 708 ms 562 ms
500k 4 MB 793 ms 877 ms 776 ms
1M 8 MB 1034 ms 1016 ms 1016 ms
2M 16 MB 1623 ms 1370 ms 1376 ms
4M 32 MB 2088 ms 2060 ms 2029 ms
(best-of-3 wall time, lower is faster)
So on my machine the filter is a loss up to a ~8MB bucket array (the L2
is 16MB here), even at 90% selectivity, and I think that it's not the
adaptive-disable that saves us, the disable logic keys on selectivity,
and here the filter is selective, it's just that rejecting a lookup that
was going to hit L2 isn't worth the probe. That's why I think this needs
an explicit size gate and not another probe-window heuristic. A gate of
8MB fixes the regressions and keeps the wins. EXPLAIN confirms it fires
exactly at the threshold, the filter disappears below 8MB and is built
at 8MB and above.
A 1MB threshold would be too low here, the filter is still a loss at a
4MB bucket array, so the gate needs to sit higher, nearer the cache
size. Since that's machine-dependent, it'd be really useful to have the
same sweep on your machine, if the crossover tracks L2/L3 there too,
we'd have enough to pick a sane default (or justify reading the cache
size from the system).
> 2) we don't really know the number of elements
>
> We can build the filter in two places. While building the hash table,
> and during probing. And in both cases we don't really know the number of
> filter elements, which affects the sizing.
>
> While building the hash table it's obvious - we only have an estimate of
> the row count, but it may be inaccurate. If we decide to build the
> filter half-way through the hash table build (when going from nbatch=1
> to nbatch=2), we at least know the number of tuples seen so far, but at
> this point we also know the estimate was wrong. The code size the filter
> for 2x the tuples, but that's wishful thinking.
>
> I wonder if we might do something smarter, like writing the hash values
> into a file, and then buildign the filter from that. Yes, it will cost
> something, but the hashvalues are tiny - much smaller than the tuples.
> We could probably also deduplicate them cheaply. So maybe it's worth a
> properly sized filter. Worth a try / experiment, I guess?
>
> Another detail is that sizing the filter for tuples is not quite right.
> We really care about number of distinct keys, and if the inner relation
> has duplicates, it may be a much smaller value. Maybe it'd be worth
> building a HLL counter, or something?
>
> we'd only need to do any of this in the nbatch>1 case, ofc. With a
> single batch we have all the values in the hashtable, which means we
> know the exect row count, and we could maybe calculate distincts too.
>
I also poked at the underestimate and the tuples-vs-distinct cases a
bit. They looked milder than I expected. A large underestimate still
ended up with a reasonably sized filter, and I couldn't easily get the
"sized for tuples, not distinct keys" waste to bite, because the planner
tends to put the low-ndistinct, duplicate-heavy relation on the probe
side rather than hashing it. So the hashvalue spill-file / HLL idea
still seems worth trying, but as an improvement, not a regression fix, I
think.
--
Matheus Alcantara
EDB: https://www.enterprisedb.com