PoC: adding CustomJoin, separate from CustomScan

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

PoC: adding CustomJoin, separate from CustomScan

От:
Tomas Vondra <tomas@vondra.me>
Дата:
Вложения:
Hi,

I've been experimenting with executor nodes inspired by papers on
executor robustness (think "Algorithms that don't explode if an estimate
is off."). And I decided to use the CustomScan API, because it seemed
like an ideal solution for my experiments - convenient, isolated, easy
to try on other releases, ...

I'm going to discuss a couple issues with using CustomScan for joins,
and propose some improvements to the CustomScan API to address those.
I'd welcome feedback on the proposed changes / ideas of alternative
approaches, etc. Of course, I may be wrong / missing something about the
CustomScan design, feel free to point that out.

For the "scan" algorithm (SmoothScan [1]), this mostly worked fine. I
ended up copying some (a lot) of the code matching clauses to an index
from indexscan planning, and that's a bit ugly. But the CustomScan API
does not promise to address that, so it did not surprise me, and I
accept that and I can deal with that (at least for now). Other than
that, the CustomScan worked fine for my experimental "scan" method.

But when implementing a custom join (generalized join [2]), it was a
quite different story. The CustomScan claims to support joins, you just
need to use the set_join_pathlist hook, and set a couple fields in the
plan/executor nodes differently. Like, leave scanrelid=0 etc.

And that kinda works for the planning phase, but at execution it turned
out to be much trickier. The main hurdle I ran into is how do you
construct the result tuple?

In regular joins, you can do that by setting
ecxt_innertuple/ecxt_outertuple, and calling ExecProject(). Or something
along those lines. But for CustomScan joins, that's not possible - the
targetlist is modified so that all the Vars have INDEX_VAR, as pointed
out by a comment in primnodes.h:

> In ForeignScan and CustomScan plan nodes, INDEX_VAR is abused to
> signify references to columns of a custom scan tuple type.

Which makes sense, because while the CustomScan can have nested plans,
it does not have a concept of an explicit inner/outer plan.

It seemed to me I'd have to essentially build the tuples "on my own",
which seems quite tricky and inconvenient. And also a bit against the
idea of CustomScan shielding extensions from this kind of "core" stuff.

I may be entirely wrong, of course. Perhaps I'm missing something, and
there's a simple way to do this? I tried to look at existing extensions
implementing joins through CustomScan, but there are not that many, and
I haven't found any good solution.

I also tried reading through the ~2014 threads related to CustomScan,
and how it got modified to allow joins. But I don't see this discussed
there either. It seems to me the CustomScan received the minimum amount
of "tweaks" to allow joins, but it's not very practical.

I realize ForeignScan supports joins in a very similar way (i.e. you
leave scanrelid=0, etc.). But I think there's a difference - the foreign
join code is not really supposed to build the tuples, it gets the
"formed" tuples from somewhere else, more or less. For example
postgres_fdw deparses a query, sends it somewhere, that other node does
the actual join, builds the tuple from inner/outer, and sends it back.
The postgres_fdw code does not need to worry about mapping the target
list to inner/outer etc. This does not work for CustomScan I think
(unless it's doing the same sort of query offloading).

I did ask for suggestions on Discord what's the right way to do this
with CustomScan and joins, and the response was that this may not have
been thought through very carefully, and some improvements may be
necessary to make it more convenient.

So I decided to give this a try. The way I see it, most of the issues
stem from grafting joins onto an interface that's designed for scans.
The whole sequence of custom nodes:

  CustomPath -> CustomScan -> CustomScanState

is based on scans. CustomPath "inherits" from Path, CustomScan from
"Scan", CustomScanState from "ScanState". It's not clear to me how to
make this work with "JoinPath", "JoinPlan" and "JoinState" in a
reasonable way.

I suppose some of the "join" data can be stashed in the private fields,
of the structs, but then the various planner/executor parts need to know
about that in some way. How else would setrefs do the right thing with
translating the targetlist into inner/outer references? (Maybe it could
be done in PlanCustomPath, but it seems too early?)


The "proper" way seems to be to have separate nodes for joins:

  CustomJoinPath -> CustomJoin -> CustomJoinState

The attached PoC patch does that (except for the CustomJoinPath, it can
do with CustomPath for now). It's more or less a copy-paste adjusting
all the places modifying all the places with "case CustomScan" to also
deal with "CustomJoin" - either in the same way, or sometimes in a way
that works for joins. It's fairly mechanical.

With this patch, my custom join can simply do

    econtext->ecxt_outertuple = outer;
    econtext->ecxt_innertuple = inner;

    return ExecProject(node->js.ps.ps_ProjInfo);

and it works.

One thing that surprised me a bit is that there's no testing extension
implementing a simple custom scan/join. So it's hard to show this :-(


I'm sure there's places that need more work (some of which are marked
with FIXME, and I probably missed some). But it surprised me how small
the patch is - most of it is the mechanical adjustments of switches. It
would get a bit larger, e.g. due to sgml docs (which the PoC patch does
not update).

The patch also renames a couple structs to have "Scan" in them, e.g.
CustomExecMethods are now CustomScanExecMethods. This is necessary
because the methods get the "plan state" of the particular type (i.e.
CustomScanState vs. CustomJoinState), etc. I guess we could do with some
"shared" state, but it seems like a recipe for confusion, and I'm not
sure it'd remove that much "code" anyway.

So that's what I have for now.

Note: I mentioned some extensions implementing SmoothScan/G-join. I plan
to publish those once I polish that a bit more. It's more a research
rather than something ready to use right now.


regards


[1] https://scholar.harvard.edu/files/stratos/files/smooth_vldbj.pdf

[2]
https://dl.gi.de/server/api/core/bitstreams/ce8e3fab-0bac-45fc-a6d4-66edaa52d574/content

-- 
Tomas Vondra

Re: PoC: adding CustomJoin, separate from CustomScan

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Jul 24, 2025 at 9:04 AM Tomas Vondra  wrote:
> With this patch, my custom join can simply do
>
>     econtext->ecxt_outertuple = outer;
>     econtext->ecxt_innertuple = inner;
>
>     return ExecProject(node->js.ps.ps_ProjInfo);
>
> and it works.

This doesn't seem like the right approach to me because, AFAICS, it's
only going to work if you're replacing a single join. But I think it
would be very desirable for a CustomScan to be able to replace
multiple joins with a single scan node and handle all the details
internally. I'm fairly certain that was part of the original design
intent here.

And I think that must already work for foreign joins, because I
believe postgres_fdw is perfectly capable of pushing a multi-way join
down to a remote node -- and if it's doing that, it's somehow solving
the problem you encountered here. So maybe we can study how that works
and figure out how to apply it to this case.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: PoC: adding CustomJoin, separate from CustomScan

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 7/24/25 15:57, Robert Haas wrote:
> On Thu, Jul 24, 2025 at 9:04 AM Tomas Vondra  wrote:
>> With this patch, my custom join can simply do
>>
>>     econtext->ecxt_outertuple = outer;
>>     econtext->ecxt_innertuple = inner;
>>
>>     return ExecProject(node->js.ps.ps_ProjInfo);
>>
>> and it works.
> 
> This doesn't seem like the right approach to me because, AFAICS, it's
> only going to work if you're replacing a single join. But I think it
> would be very desirable for a CustomScan to be able to replace
> multiple joins with a single scan node and handle all the details
> internally. I'm fairly certain that was part of the original design
> intent here.
> 

I'm not sure I understand this multiway-join argument. Yes, CustomJoin
can only handle regular joins of two relations. But I haven't suggested
to forbid using CustomScan to do arbitrary multiway-joins, though. You
can still do that, but it means you'll probably have to do much more
manual work. It doesn't seem great to force "regular" joins to do all
that manual work, though.

I was thinking about this a bit more, and I think the CustomScan join
essentially has to construct it's own info how to build the tuple, most
likely in PlanCustomPath, because once setrefs.c does it's thing it's
way too late for that I think. And the only way to store that is
custom_private, so no fancy custom structs. I'll give it a try.

Seems much more convenient to allow doing what regulars joins do, and
only force the extension to do the manual stuff if it wants to do
something like multiway-joins ...


> And I think that must already work for foreign joins, because I
> believe postgres_fdw is perfectly capable of pushing a multi-way join
> down to a remote node -- and if it's doing that, it's somehow solving
> the problem you encountered here. So maybe we can study how that works
> and figure out how to apply it to this case.
> 

AFAICS postgres_fdw completely sidesteps this issue, because it deparses
the join into a SQL statement in postgresGetForeignPlan(), and it's the
remote server responsible for building the tuple. The postgres_fdw has
nothing to do to make that happen. It just gets the tuple, puts it into
the ecxt_scantuple slot, and that's it. It doesn't need to worry about
inner/outer tuple, etc.

That's not what the CustomScan can rely on, I think. At least my use
case can't do that - I have to build the tuple, somehow.


regards

-- 
Tomas Vondra



Re: PoC: adding CustomJoin, separate from CustomScan

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Jul 24, 2025 at 12:48 PM Tomas Vondra  wrote:
> I was thinking about this a bit more, and I think the CustomScan join
> essentially has to construct it's own info how to build the tuple, most
> likely in PlanCustomPath, because once setrefs.c does it's thing it's
> way too late for that I think. And the only way to store that is
> custom_private, so no fancy custom structs. I'll give it a try.

Yeah, I think that's probably right.

> Seems much more convenient to allow doing what regulars joins do, and
> only force the extension to do the manual stuff if it wants to do
> something like multiway-joins ...

I think that the motivating use case for the existing support was
wanting to offload work to something that looks altogether unlike the
normal PostgreSQL executor, rather than (as you want to do) implement
a new type of join within the PostgreSQL executor. The latter might
merit different infrastructure, although I cringe a little bit at the
idea of having two ways of implementing custom joins when the total
number of projects using this infrastructure is probably less than
five.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: PoC: adding CustomJoin, separate from CustomScan

От:
Paul A Jungwirth <pj@illuminatedcomputing.com>
Дата:
On Thu, Jul 24, 2025 at 12:09 PM Robert Haas  wrote:
> I think that the motivating use case for the existing support was
> wanting to offload work to something that looks altogether unlike the
> normal PostgreSQL executor, rather than (as you want to do) implement
> a new type of join within the PostgreSQL executor. The latter might
> merit different infrastructure, although I cringe a little bit at the
> idea of having two ways of implementing custom joins when the total
> number of projects using this infrastructure is probably less than
> five.

I'm interested in using this. It sounds like it would let me implement
temporal outer/semi/anti joins very nicely. I didn't realize I could
do that with CustomScan as well---I'll investigate that---but
CustomJoin does sound like a better fit.

I'm not sure how to let users *ask* for a temporal join though. . . .
How do other CustomScans "get there"? Perhaps I could use a noop
function you include in the ON section that is declarative
pseudo-syntax, e.g. naming the tsrange columns, and a planner hook
that looks for that. I'm also not completely sure that temporal joins
have the same algebraic properties (associative, commutative, etc) as
non-temporal, or when mixed with non-temporal. Perhaps I can find a
research paper about that. Can the planner freely re-order
CustomScans? Anyway, I just wanted to say that there might be six
projects. :-)

Yours,

-- 
Paul              ~{:-)
pj@illuminatedcomputing.com


Re: PoC: adding CustomJoin, separate from CustomScan

От:
Tomas Vondra <tomas@vondra.me>
Дата:


On 7/25/25 17:34, Paul A Jungwirth wrote:
> On Thu, Jul 24, 2025 at 12:09 PM Robert Haas  wrote:
>> I think that the motivating use case for the existing support was
>> wanting to offload work to something that looks altogether unlike the
>> normal PostgreSQL executor, rather than (as you want to do) implement
>> a new type of join within the PostgreSQL executor. The latter might
>> merit different infrastructure, although I cringe a little bit at the
>> idea of having two ways of implementing custom joins when the total
>> number of projects using this infrastructure is probably less than
>> five.
> 
> I'm interested in using this. It sounds like it would let me implement
> temporal outer/semi/anti joins very nicely. I didn't realize I could
> do that with CustomScan as well---I'll investigate that---but
> CustomJoin does sound like a better fit.
> 

I managed to make it work with the CustomScan by manually building the
tuple based on information extracted from target lists while creating
the plan (so prior to setrefs and all that).

I didn't have time to experiment with that more, so I don't know what
limitations that implies. E.g. I'm not sure if this makes evaluating
expressions (like join clauses) harder, or something like that.

The CustomJoin sure was easier / more convenient to use, though.

> I'm not sure how to let users *ask* for a temporal join though. . . .
> How do other CustomScans "get there"? Perhaps I could use a noop
> function you include in the ON section that is declarative
> pseudo-syntax, e.g. naming the tsrange columns, and a planner hook
> that looks for that. I'm also not completely sure that temporal joins
> have the same algebraic properties (associative, commutative, etc) as
> non-temporal, or when mixed with non-temporal. Perhaps I can find a
> research paper about that. Can the planner freely re-order
> CustomScans? Anyway, I just wanted to say that there might be six
> projects. :-)
> 

I don't think CustomScans help with parser/grammar at all. It's just a
planner/executor node, it has no way to interact with parser. Maybe some
sort of "custom operator" would work, not sure. Not sure what exactly
you need in the planner.

For planning, CustomScan joins are simply part of the regular join
search. We generate all the various paths for a joinrel, and then give
the set_join_pathlist_hook hook a chance to add some more. AFAIK it
doesn't affect the join order search, or anything like that. At least
not directly.


regards

-- 
Tomas Vondra



Re: PoC: adding CustomJoin, separate from CustomScan

От:
Paul A Jungwirth <pj@illuminatedcomputing.com>
Дата:
On Fri, Jul 25, 2025 at 9:23 AM Tomas Vondra  wrote:
> I don't think CustomScans help with parser/grammar at all. It's just a
> planner/executor node, it has no way to interact with parser. Maybe some
> sort of "custom operator" would work, not sure. Not sure what exactly
> you need in the planner.

I agree, although if other people are using CustomScans I wonder what
the user does to prompt their appearance, since the grammar is not
extendable.

If my SupportRequestInlineSRF patch got in, you could have functions
that replace themselves with CustomScans/CustomJoins. That would be
cool, both for temporal joins and for another thing I've wanted to
build for years: a pandas-like dataframe library, or at least a way to
pass "predicates" to an array without reifying them at every step. I
have a couple extensions, aggs_for_arrays and aggs_for_vecs, that
would combine really nicely with that.

> For planning, CustomScan joins are simply part of the regular join
> search. We generate all the various paths for a joinrel, and then give
> the set_join_pathlist_hook hook a chance to add some more. AFAIK it
> doesn't affect the join order search, or anything like that. At least
> not directly.

I finally found some research on the algebraic properties of temporal
operators. Snodgrass and some others edited a collection of academic
papers in 1993 and published it as *Temporal Databases: Theory,
Design, and Implementation*. On page 175 they have:

**Theorem 12** The following equivalences hold for the valid-time algebra.
Q ∪̂ R ≡ R ∪̂ Q
Q ⨯̂ R ≡ R ⨯̂ Q
σ̂F1(σ̂F2(Q)) ≡ σ̂F2(σ̂F1(Q))
Q ∪̂ (R ∪̂ S) ≡ (Q ∪̂ R) ∪̂ S
Q ⨯̂ (R ⨯̂ S) ≡ (Q ⨯̂ R) ⨯̂ S
Q ⨯̂ (R ∪̂ S) ≡ (Q ⨯̂ R) ∪̂ (Q ⨯̂ S)
σ̂F(Q ∪̂ R) ≡ σ̂F(Q) ∪̂ σ̂F(R)
σ̂F(Q −̂ R) ≡ σ̂F(Q) −̂ σ̂F(R)
π̂X(Q ∪̂ R) ≡ π̂X(Q) ∪̂ π̂X(R)

**Theorem 13** The distributive property of Cartesian product over
difference, or Q ⨯̂ (R −̂ S) ≡ (Q ⨯̂ R) −̂ (Q ⨯̂ S), does not hold for
the valid-time algebra.

If that gets garbled in transmission, it might be more legible here:
https://illuminatedcomputing.com/posts/2017/12/temporal-databases-bibliography/

I haven't read the whole chapter yet, but at first glance it seems
applicable to how people do valid-time tables today.

It's interesting that most identities are still valid for temporal
tables, but not all. I don't know what the Postgres planner takes
advantage of, but maybe it is *better* to use CustomScan, to prevent
invalid transformations. But then you are giving up some optimization
potential.

Yours,

-- 
Paul              ~{:-)
pj@illuminatedcomputing.com


FAQ