[SQL/PGQ] Native executor for Graph query
Thread notes
1 note#feature#major#enhancement
hackorum-bot#feature#major#enhancement
@global #feature #major #enhancement
Hello everyone,
After my previous email[1]/messages/by-id/CAJyuuthCZ8yQuUAy_1d0DkxtdQ_aZcOX+7bcwagwvAF6BSrHeg@mail.gmail.com I started to work on the custom node for VLE.
I managed to do it, but then I encountered a problem: it was
impossible to mix VLE and non-VLE patterns in a single query.
Therefore, I started working on a native planner / executor for graph
queries, you can find the result attached.
The feature is behind the GUC enable_native_graphtable (set to ON by
default), so switch to OFF to use the rewrite system.
There are some caveats:
- I did not start working on inheritance, partitioning, foreign
tables, and views, so queries on it may be inconsistent.
- Row level security is not something I even started to approach, so
expect lot of errors.
- Queries with lateral syntax are finicky at best, so tread carefully.
I have questions concerning the latter (and sorry if it was already
litigated in the original thread).
In the regression tests (for example graph_table.sql, line 161), we
have the query "SELECT * FROM x1, GRAPH_TABLE (...);".
According to the documentation, we are supposed to take the Cartesian
product of both tables.
x1 is defined with two rows, so we should get two rows (because there
is a single customer with adress = 'US'). What we
currently expect however, is the result of a simple JOIN on graph.cid and x1.a.
The question is then: How should the native executor handle those
cases ? I think rejecting the query outright is sensible,
as in those cases, x1 is not properly defined.
The same question applies to the other test with multiple sources in
SELECT, and in general to the LATERAL behaviour.
For the future (should this patch be accepted), then I (or other) can
work on supporting other path_mode (currently only
WALK is used), other graph traversal algorithms (BFS, Bidirectional,
or for some insane reason A*), and add ways to make
use of the optimizer (push down WHERE / IS conditions, use indexes,
split hop patterns and group afterwards, etc.).
I also attached the graph links I used to write the expected output
for the VLE tests.
Best regards,
Henri GASC
[1]: /messages/by-id/CAJyuuthCZ8yQuUAy_1d0DkxtdQ_aZcOX+7bcwagwvAF6BSrHeg@mail.gmail.com
Classification: Privacy: Basic Personal Data; Export Control: Not
Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business
data
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Hello everyone,
I updated the patch to allow queries with partitioning, inheritance, foreign
tables, and views, to work properly. Queries with lateral syntax will evaluate
WHERE statements outside the graph to produce identical results to the
rewriter pass.
The patch aims to completely replace the rewriter system for graph queries.
I am open to any feedback you may have, and I can split the patches in
smaller ones if this would help you review them better.
Best regards,
Henri GASC
On Sat, Aug 8, 2026 at 11:53 AM Henri GASC <henri.gasc@airbus.com> wrote:
Hello everyone,
After my previous email[1] I started to work on the custom node for VLE.
I managed to do it, but then I encountered a problem: it was
impossible to mix VLE and non-VLE patterns in a single query.
Therefore, I started working on a native planner / executor for graph
queries, you can find the result attached.The feature is behind the GUC enable_native_graphtable (set to ON by
default), so switch to OFF to use the rewrite system.There are some caveats:
- I did not start working on inheritance, partitioning, foreign
tables, and views, so queries on it may be inconsistent.
- Row level security is not something I even started to approach, so
expect lot of errors.
- Queries with lateral syntax are finicky at best, so tread carefully.I have questions concerning the latter (and sorry if it was already
litigated in the original thread).
In the regression tests (for example graph_table.sql, line 161), we
have the query "SELECT * FROM x1, GRAPH_TABLE (...);".
According to the documentation, we are supposed to take the Cartesian
product of both tables.
x1 is defined with two rows, so we should get two rows (because there
is a single customer with adress = 'US'). What we
currently expect however, is the result of a simple JOIN on graph.cid and x1.a.
The question is then: How should the native executor handle those
cases ? I think rejecting the query outright is sensible,
as in those cases, x1 is not properly defined.
The same question applies to the other test with multiple sources in
SELECT, and in general to the LATERAL behaviour.For the future (should this patch be accepted), then I (or other) can
work on supporting other path_mode (currently only
WALK is used), other graph traversal algorithms (BFS, Bidirectional,
or for some insane reason A*), and add ways to make
use of the optimizer (push down WHERE / IS conditions, use indexes,
split hop patterns and group afterwards, etc.).I also attached the graph links I used to write the expected output
for the VLE tests.Best regards,
Henri GASC[1]: /messages/by-id/CAJyuuthCZ8yQuUAy_1d0DkxtdQ_aZcOX+7bcwagwvAF6BSrHeg@mail.gmail.com
Classification: Privacy: Basic Personal Data; Export Control: Not
Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business
data
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Hello everyone,
Here is the updated patch rebased on the current master and with
some issues resolved (prepared statement and mix-up of the order
of variables).
The commitfest is https://commitfest.postgresql.org/patch/7258/
Best regards,
Henri Gasc
On Fri, Sep 4, 2026 at 8:43 AM Henri GASC <henri.gasc@airbus.com> wrote:
Hello everyone,
I updated the patch to allow queries with partitioning, inheritance, foreign
tables, and views, to work properly. Queries with lateral syntax will evaluate
WHERE statements outside the graph to produce identical results to the
rewriter pass.
The patch aims to completely replace the rewriter system for graph queries.I am open to any feedback you may have, and I can split the patches in
smaller ones if this would help you review them better.Best regards,
Henri GASCOn Sat, Aug 8, 2026 at 11:53 AM Henri GASC <henri.gasc@airbus.com> wrote:
Hello everyone,
After my previous email[1] I started to work on the custom node for VLE.
I managed to do it, but then I encountered a problem: it was
impossible to mix VLE and non-VLE patterns in a single query.
Therefore, I started working on a native planner / executor for graph
queries, you can find the result attached.The feature is behind the GUC enable_native_graphtable (set to ON by
default), so switch to OFF to use the rewrite system.There are some caveats:
- I did not start working on inheritance, partitioning, foreign
tables, and views, so queries on it may be inconsistent.
- Row level security is not something I even started to approach, so
expect lot of errors.
- Queries with lateral syntax are finicky at best, so tread carefully.I have questions concerning the latter (and sorry if it was already
litigated in the original thread).
In the regression tests (for example graph_table.sql, line 161), we
have the query "SELECT * FROM x1, GRAPH_TABLE (...);".
According to the documentation, we are supposed to take the Cartesian
product of both tables.
x1 is defined with two rows, so we should get two rows (because there
is a single customer with adress = 'US'). What we
currently expect however, is the result of a simple JOIN on graph.cid and x1.a.
The question is then: How should the native executor handle those
cases ? I think rejecting the query outright is sensible,
as in those cases, x1 is not properly defined.
The same question applies to the other test with multiple sources in
SELECT, and in general to the LATERAL behaviour.For the future (should this patch be accepted), then I (or other) can
work on supporting other path_mode (currently only
WALK is used), other graph traversal algorithms (BFS, Bidirectional,
or for some insane reason A*), and add ways to make
use of the optimizer (push down WHERE / IS conditions, use indexes,
split hop patterns and group afterwards, etc.).I also attached the graph links I used to write the expected output
for the VLE tests.Best regards,
Henri GASC[1]: /messages/by-id/CAJyuuthCZ8yQuUAy_1d0DkxtdQ_aZcOX+7bcwagwvAF6BSrHeg@mail.gmail.com
Classification: Privacy: Basic Personal Data; Export Control: Not
Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business
data
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Hi Henri,
You cited my VLE note as [1] back in July, so I owe you a careful
read. The direction is right: taking execution out of the rewriter is
where Andres pointed. My comment is about where the per-depth state
lives.
I am open to any feedback you may have
Here is one. The patch expresses the composite scan inside the node
rather than in the plan tree: GraphScan leaves lefttree and righttree
NULL and reimplements partition and view scanning inside
nodeGraphScan.c. My impression reading it is that every kind of
scan -- foreign tables and the rest -- ends up having to be
reimplemented in there. The per-depth state is then a stack of raw
TableScanDesc, and for anything but a plain table the cursor is one
per element rather than one per depth, so backtracking does not
propagate into a composite scan.
My suggestion is the following. The note sketched the outer/inner
split and a per-depth stack of PlanStates; what it did not say, and
what I want to add, is that this has to work for an arbitrary inner
subtree:
outer (lefttree) = start vertices, scanned once
inner (righttree) = edge scan for one vertex, parameterized
Push before descending, pop on backtrack, both against the inner
subtree. What is pushed and popped is the PlanState: a depth reached
for the first time gets a new one, initialized as usual, and a depth
being reused is rescanned with the new parameter. Each node type
implements this for its own state, so the inner can be an IndexScan,
an Append over partitions, a SubqueryScan over a view or a ForeignScan
without the graph node knowing which.
The part that needs care is shared state. Some resources live on the
EState rather than on the node -- the parameter workspace, the SubPlan
states, the runtime pruning state -- so initializing or advancing one
depth's subplan has to be coordinated so that it does not disturb
another depth's.
Implementing this on every node type is a lot of work, so it may be
better to start with the few that matter -- Scan, IndexScan, Append --
and have the planner restrict a GraphScan's inner to those. The set
can grow later without the shape changing.
What this buys is that the inner subplan is just a plan. A single
label is a Scan or an IndexScan. Several labels are an Append, and
the children under it need not be alike -- a sequential scan on one
table, an index scan on another, a ForeignScan on a third, whatever
the planner picks for each. Partitioning and inheritance come along
the same way, since they are already Appends.
The same shape composes along the pattern as well. If the outer is
itself a GraphScan, a multi-element pattern is a chain of these nodes,
each taking the vertex it needs from its outer. A VLE element and a
fixed-length element then sit next to each other in that chain without
either having to know about the other.
A star pattern falls out of the same mechanism. Since the inner is
parameterized from the outer tuple, the vertex it is parameterized by
does not have to be the last one on the path; any vertex already bound
will do. So MATCH (a)->(b), (a)->(c) would be a chain again: the
first node binds a and b, and the second takes a, not b, from its
outer and scans the edges leaving it. A branching pattern then needs
nothing beyond choosing which outer column parameterizes each inner.
There is a wider use for it as well. If every PlanState could push
and pop, WITH RECURSIVE could be executed depth first, instead of
computing each level in turn and then sorting on the column that
SEARCH DEPTH FIRST adds.
I have another patch to wrap up, so I cannot give this much time at
the moment, but I hope it is of some use.
Best regards,
Henson
*Classification: * Privacy: Basic Personal Data; Export Control:
Not Technical; National Security: Not National Security; Company
Classification: Airbus Amber; Business or Private Data: Business data
Hello,
Thanks for the message, it was helpful. I was far too focused on the
DFS part and completely forgot your decomposition into outer and
inner tree.
I already wanted to redo my implementation to make the changes
clearer, so that is as good a time as any to correct it. It should also
make the code far simpler.
However, considering b1f106c80[1], I am unsure how to proceed.
I think I will either reimplement only what I need, or build upon the
parent (like I did before).
Best Regards,
Henri GASC
On Mon, Sep 7, 2026 at 3:39 PM Henson Choi <assam258@gmail.com> wrote:
Hi Henri,
You cited my VLE note as [1] back in July, so I owe you a careful
read. The direction is right: taking execution out of the rewriter is
where Andres pointed. My comment is about where the per-depth state
lives.I am open to any feedback you may have
Here is one. The patch expresses the composite scan inside the node
rather than in the plan tree: GraphScan leaves lefttree and righttree
NULL and reimplements partition and view scanning inside
nodeGraphScan.c. My impression reading it is that every kind of
scan -- foreign tables and the rest -- ends up having to be
reimplemented in there. The per-depth state is then a stack of raw
TableScanDesc, and for anything but a plain table the cursor is one
per element rather than one per depth, so backtracking does not
propagate into a composite scan.My suggestion is the following. The note sketched the outer/inner
split and a per-depth stack of PlanStates; what it did not say, and
what I want to add, is that this has to work for an arbitrary inner
subtree:outer (lefttree) = start vertices, scanned once
inner (righttree) = edge scan for one vertex, parameterizedPush before descending, pop on backtrack, both against the inner
subtree. What is pushed and popped is the PlanState: a depth reached
for the first time gets a new one, initialized as usual, and a depth
being reused is rescanned with the new parameter. Each node type
implements this for its own state, so the inner can be an IndexScan,
an Append over partitions, a SubqueryScan over a view or a ForeignScan
without the graph node knowing which.The part that needs care is shared state. Some resources live on the
EState rather than on the node -- the parameter workspace, the SubPlan
states, the runtime pruning state -- so initializing or advancing one
depth's subplan has to be coordinated so that it does not disturb
another depth's.Implementing this on every node type is a lot of work, so it may be
better to start with the few that matter -- Scan, IndexScan, Append --
and have the planner restrict a GraphScan's inner to those. The set
can grow later without the shape changing.What this buys is that the inner subplan is just a plan. A single
label is a Scan or an IndexScan. Several labels are an Append, and
the children under it need not be alike -- a sequential scan on one
table, an index scan on another, a ForeignScan on a third, whatever
the planner picks for each. Partitioning and inheritance come along
the same way, since they are already Appends.The same shape composes along the pattern as well. If the outer is
itself a GraphScan, a multi-element pattern is a chain of these nodes,
each taking the vertex it needs from its outer. A VLE element and a
fixed-length element then sit next to each other in that chain without
either having to know about the other.A star pattern falls out of the same mechanism. Since the inner is
parameterized from the outer tuple, the vertex it is parameterized by
does not have to be the last one on the path; any vertex already bound
will do. So MATCH (a)->(b), (a)->(c) would be a chain again: the
first node binds a and b, and the second takes a, not b, from its
outer and scans the edges leaving it. A branching pattern then needs
nothing beyond choosing which outer column parameterizes each inner.There is a wider use for it as well. If every PlanState could push
and pop, WITH RECURSIVE could be executed depth first, instead of
computing each level in turn and then sorting on the column that
SEARCH DEPTH FIRST adds.I have another patch to wrap up, so I cannot give this much time at
the moment, but I hope it is of some use.Best regards,
Henson
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Hi Henri,
Glad it was useful.
I think I will either reimplement only what I need, or build upon
the parent (like I did before).
I would build upon the parent. The open items behind the revert are
about catalogs and dependencies, not about execution, so the shape
your node sits on should come back much as it was. Reimplementing a
subset means answering the catalog questions that are exactly the ones
still open, and your executor patch would then have to carry them.
Reverting the revert gives you a commit, and that commit is your
development base:
git checkout -b pgq-restore master
git revert --no-commit b1f106c80
git commit -m "Restore SQL/PGQ as a cfbot base; not for review"
Then build your work on top of it, and post both commits in order:
git format-patch -o . master..<your branch>
That gives 0001 for the base and 0002 for your work, and cfbot has
something to apply.
One thing to watch: the base is a large patch touching many files, so
with your own on top the mail may be big enough to be held for
moderation.
Once Ashutosh posts the patch series again, use that as the base
instead and drop 0001.
Best regards,
Henson
*Classification: * Privacy: Basic Personal Data; Export Control:
Not Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business data
Hello hackers,
Here is the updated patch, now in different files. It should hopefully
be clearer to understand and easier to review.
This series only implements the WALK syntax.
Best regards,
Henri GASC
On Tue, Sep 8, 2026 at 1:18 PM Henson Choi <assam258@gmail.com> wrote:
Hi Henri,
Glad it was useful.
I think I will either reimplement only what I need, or build upon
the parent (like I did before).I would build upon the parent. The open items behind the revert are
about catalogs and dependencies, not about execution, so the shape
your node sits on should come back much as it was. Reimplementing a
subset means answering the catalog questions that are exactly the ones
still open, and your executor patch would then have to carry them.Reverting the revert gives you a commit, and that commit is your
development base:git checkout -b pgq-restore master
git revert --no-commit b1f106c80
git commit -m "Restore SQL/PGQ as a cfbot base; not for review"Then build your work on top of it, and post both commits in order:
git format-patch -o . master..<your branch>
That gives 0001 for the base and 0002 for your work, and cfbot has
something to apply.One thing to watch: the base is a large patch touching many files, so
with your own on top the mail may be big enough to be held for
moderation.Once Ashutosh posts the patch series again, use that as the base
instead and drop 0001.Best regards,
Henson
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Attachments:
t253350_70004-Split-graph-queries-into-GraphScan-Append-SeqScan-et.patchapplication/octet-stream; name=0004-Split-graph-queries-into-GraphScan-Append-SeqScan-et.patchDownload+2561-175
0003-Parse-grammar-for-VLE.patchapplication/octet-stream; name=0003-Parse-grammar-for-VLE.patchDownload+379-2
0002-Add-GUC-enable_native-and-max_depth.patchapplication/octet-stream; name=0002-Add-GUC-enable_native-and-max_depth.patchDownload+237-57
0005-Implement-the-executor.patchapplication/octet-stream; name=0005-Implement-the-executor.patchDownload+1349-411
0001-Restore-SQL-PGQ-as-a-cfbot-base-not-for-review.patchapplication/octet-stream; name=0001-Restore-SQL-PGQ-as-a-cfbot-base-not-for-review.patchDownload+15858-77
0008-Remove-dead-code-and-simplify-GraphScan.patchapplication/octet-stream; name=0008-Remove-dead-code-and-simplify-GraphScan.patchDownload+165-236
0007-Add-rows-estimate-to-planner-and-use-IndexScan-if-po.patchapplication/octet-stream; name=0007-Add-rows-estimate-to-planner-and-use-IndexScan-if-po.patchDownload+772-127
0006-Correct-bug-const-with-label-disjunction-and-show-pl.patchapplication/octet-stream; name=0006-Correct-bug-const-with-label-disjunction-and-show-pl.patchDownload+213-37
*Classification: * Privacy: Basic Personal Data; Export Control:
Not Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business data
Hello everyone,
Here is an updated version of the patches that should (hopefully)
pass world tests.
Sorry for sending all the patches again; I'm unsure if cfbot will be
able to pick up the previous version if there is no "v2" for a file (and
all hashes changed).
Henri Gasc
On Tue, Sep 15, 2026 at 10:44 AM Henri GASC <henri.gasc@airbus.com> wrote:
*Classification: * Privacy: Basic Personal Data; Export Control:
Not Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business dataHello hackers,
Here is the updated patch, now in different files. It should hopefully
be clearer to understand and easier to review.
This series only implements the WALK syntax.Best regards,
Henri GASCOn Tue, Sep 8, 2026 at 1:18 PM Henson Choi <assam258@gmail.com> wrote:
Hi Henri,
Glad it was useful.
I think I will either reimplement only what I need, or build upon
the parent (like I did before).I would build upon the parent. The open items behind the revert are
about catalogs and dependencies, not about execution, so the shape
your node sits on should come back much as it was. Reimplementing a
subset means answering the catalog questions that are exactly the ones
still open, and your executor patch would then have to carry them.Reverting the revert gives you a commit, and that commit is your
development base:git checkout -b pgq-restore master
git revert --no-commit b1f106c80
git commit -m "Restore SQL/PGQ as a cfbot base; not for review"Then build your work on top of it, and post both commits in order:
git format-patch -o . master..<your branch>
That gives 0001 for the base and 0002 for your work, and cfbot has
something to apply.One thing to watch: the base is a large patch touching many files, so
with your own on top the mail may be big enough to be held for
moderation.Once Ashutosh posts the patch series again, use that as the base
instead and drop 0001.Best regards,
Henson
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Attachments:
t253350_8v2-0002-Add-GUC-enable_native-and-max_depth.patchapplication/octet-stream; name=v2-0002-Add-GUC-enable_native-and-max_depth.patchDownload+239-57
v2-0001-Restore-SQL-PGQ-as-a-cfbot-base-not-for-review.patchapplication/octet-stream; name=v2-0001-Restore-SQL-PGQ-as-a-cfbot-base-not-for-review.patchDownload+15857-76
v2-0005-Implement-the-executor.patchapplication/octet-stream; name=v2-0005-Implement-the-executor.patchDownload+1349-411
v2-0003-Parse-grammar-for-VLE.patchapplication/octet-stream; name=v2-0003-Parse-grammar-for-VLE.patchDownload+379-2
v2-0008-Remove-dead-code-and-simplify-GraphScan.patchapplication/octet-stream; name=v2-0008-Remove-dead-code-and-simplify-GraphScan.patchDownload+166-237
v2-0007-Add-rows-estimate-to-planner-and-use-IndexScan-if.patchapplication/octet-stream; name=v2-0007-Add-rows-estimate-to-planner-and-use-IndexScan-if.patchDownload+772-127
v2-0004-Split-graph-queries-into-GraphScan-Append-SeqScan.patchapplication/octet-stream; name=v2-0004-Split-graph-queries-into-GraphScan-Append-SeqScan.patchDownload+2562-175
v2-0006-Correct-bug-const-with-label-disjunction-and-show.patchapplication/octet-stream; name=v2-0006-Correct-bug-const-with-label-disjunction-and-show.patchDownload+213-37
Hi Henri,
This series only implements the WALK syntax.
Thanks for splitting this into separate files -- much easier to
follow.
I gave more thought to the spot I flagged in ExecInitGraphScan --
every frame's inner_state is eagerly ExecInitNode'd up to
max_graph_stack_depth (1001 by default), while explain.c only ever
looks at frames[0] when printing the plan. I first thought "just
delay ExecInitNode, keep the array" would be enough, but that only
solves half the problem (the init cost) -- EXPLAIN ANALYZE would
still report only frame 0's share. So here's a bigger structure I'd
like to propose instead.
How I understood the current structure
One GraphScan handles a single quantified hop of the graph pattern,
and inner_plan is the pre-planned, parameterized 1-hop expansion for
it (taking the current vertex as a PARAM_EXEC, so it can use
indexes).
At execution time, GraphScanState keeps a frames[] array (each
element a GraphDepthFrameData), and each element holds both
inner_state (its own ExecInitNode(copyObject(inner_plan)) copy) and
that depth's vertex/edge-property values together. The whole array
is built at once in ExecInitGraphScan, regardless of how deep the
traversal actually goes.
The problem with this seems to be that two things of very different
character -- inner_state, an expensive resource (a PlanState copy
carrying locks and a subplan tree), and the vertex/edge-property
values, which are cheap scalars -- are bundled together into one
GraphDepthFrameData element. So the whole array ends up sized to
the theoretical upper bound (max_graph_stack_depth) rather than the
depth actually reached, and the expensive side (inner_state) gets
built up to that same bound, on the same schedule as the cheap side.
A structure I'd like to propose instead, briefly
Splitting this into two separate concerns:
First, factor "each depth needs its own copy of inner_plan" out into
a generic PlanState-level mechanism. Add an up/down pointer pair to
PlanState, letting a node thread its own PlanState copies into a
chain, independent of lefttree/righttree.
Second, keep the small scalar data -- "the vertex reached at this
depth, and its edge properties" -- separate, since it has nothing to
do with any PlanState. A lean GraphVidData array, owned by
GraphScanState, indexed directly by depth and grown by repalloc
(doubling) only when needed. This array only grows to the deepest
point actually reached, independent of the up/down chain's length.
Writing out how these two would actually move, step by step:
Descending a depth (graph_push):
1. Look at the down pointer of the frame inner currently points to.
2. If down exists -- a copy already exists for this depth.
Use it as-is and move inner there.
3. If down is NULL -- this depth is being reached for the first time.
Make a new copy via graph_init_inner.
Link it onto the end of the chain via up/down.
Move inner there.
4. Either way, prepare this depth's slot in vids[].
If it doesn't exist yet (past vids_capacity), repalloc-double it.
Fill in the vertex key values and the edge properties that led
here.
5. Set need_init to true.
-- a marker for graph_step to call ExecReScan the first time it
steps this frame (this part is unchanged from the current code).
Backtracking (graph_backtrack):
1. Move inner one step toward up.
2. That's it -- the chain itself is never cut.
Whatever was linked in via down stays there.
Resetting for a new seed (graph_reset, graph_fetch_seed):
1. Backtrack repeatedly until inner reaches depth 0 (= inner_head).
2. No node in the chain gets freed.
3. Set need_init back to true on every frame made so far
(vids[0..frames_reached-1]) -- they all need to ExecReScan
against the new seed's vertex values.
4. When the traversal reaches the same depth again, it takes
graph_push's step 2 (down already exists) and reuses it as-is.
The pointer layout, drawn out
What GraphScanState itself holds:
GraphScanState
inner_head ----> depth 0's PlanState copy (always exists, chain head)
inner ----> the innermost depth's PlanState copy right now
vids ----> GraphVidData[0 .. vids_capacity-1] (flat array)
frames_reached = number of depths actually reached so far
E.g. with the traversal currently at depth 2 (frames_reached = 3,
i.e. depths 0/1/2 exist), the inner_head/down chain looks like this:
inner_head inner
| |
v v
PlanState(d0) PlanState(d1) PlanState(d2)
<-up- <-up-
-down-> -down->
up = NULL up = d0 up = d1
down = d1 down = d2 down = NULL
Each arrow is just a pointer -- d0.down == d1, d1.up == d0, and so
on, linked both ways. When graph_push first reaches a new depth, it
links a new node onto the end of this chain and moves inner there.
Backtracking just moves inner one step toward up without cutting the
chain -- so when a later seed descends to the same depth again, it
reuses the existing d1/d2 as-is.
The vids array is entirely separate from this chain, indexed
directly by depth number (kept ASCII-only so the columns don't get
mangled in transit; the explanation is below the table):
vids[0] vids[1] vids[2] vids[3]
(depth 0) (depth 1) (depth 2) (reserved
seed vertex vid, vidnull vid, vidnull via repalloc,
no edge_props edge_props=e1 edge_props=e2 unused yet)
|<--- frames_reached(=3) live entries --->|
vids[0] is the seed vertex (depth 0, no incoming edge), and
vids[1]/vids[2] are the vertex key and the incoming edge's
properties (e1, e2) at each depth. vids[3] is just capacity
vids_capacity already doubled into, not yet used by any depth --
frames_reached(=3) means only vids[0..2] are "live" data.
So the PlanState chain (an expensive resource -- locks, subplan
trees) and the vids array (cheap scalar values) end up as two
separate structures, each shaped for its own access pattern (a chain
vs. a flat array).
Struct changes needed, by struct
PlanState (execnodes.h) -- add:
up (PlanState *)
down (PlanState *)
GraphScanState (execnodes.h) -- drop ndepths/frames
(GraphDepthFrameData *), add instead:
inner_head (PlanState *)
inner (PlanState *)
vids (GraphVidData *)
vids_capacity (int)
frames_reached (int)
eflags (int)
frame_vid_width (int)
GraphDepthFrameData (nodeGraphScan.h) -- retire it, replace with
GraphVidData:
vid_elem, vid_nkeys, vid, vidnull,
edge_props, edge_propsnull, need_init (carried over as-is)
drop the inner_state field
(the PlanState.up/down chain takes its place)
New functions that would target PlanState
ExecShutdownPlanStateChain(PlanState *head)
core-shared (execProcnode.c / executor.h)
graph_init_inner(GraphScanState *node)
internal to nodeGraphScan.c (static)
ExecShutdownGraphScan(GraphScanState *node)
nodeGraphScan.c / nodeGraphScan.h
The struct members, one by one
PlanState.up / PlanState.down
Orthogonal to lefttree/righttree. A generic pair for
when a node type needs to thread several of its own
PlanState copies into a chain for its own reasons.
Most node types would just leave these NULL. Nothing
besides GraphScan would use it right now, but WITH
RECURSIVE (mentioned below) looks like the same shape
of problem, so it could reuse this field directly.
GraphScanState.inner_head
The depth-0 (seed) copy. Made once in ExecInitGraphScan
and never freed until the node ends -- the chain head.
Also where EXPLAIN would show the "Inner" child (this
one spot now covers what used to be
frames[0].inner_state in explain.c).
GraphScanState.inner
The current pointer to the innermost depth's copy for
the path currently on the stack.
NULL when cur_depth < 0 (a new seed is needed).
GraphScanState.vids / vids_capacity / frames_reached
The array of per-depth scalar data, its allocated size,
and how many depths have actually been reached so far.
frames_reached is both the live prefix length of this
array and the current length of the up/down chain. When
a new depth is first reached (graph_push), it would
repalloc-double as needed.
GraphScanState.eflags
Storing the eflags ExecInitGraphScan received.
graph_push needs to pass the same eflags when it
ExecInitNode's a new copy later, during execution, but
doesn't have it as a parameter at that point anymore, so
it needs to be saved as a field.
GraphScanState.frame_vid_width
The widest of the seed key/source key/destination key
widths. Used to size each depth's vid/vidnull arrays.
Currently a local variable in ExecInitGraphScan
(maxwidth), but graph_push would need it again too, so
it'd make sense to move it to a field.
The functions, one by one
graph_init_inner(GraphScanState *node) -> PlanState *
Would copyObject inner_plan and ExecInitNode one copy,
returning it (NULL if inner_plan is NULL).
ExecInitGraphScan would call it once for depth 0,
graph_push once each time a new depth is first reached
-- just pulling together what's currently duplicated in
two places.
ExecShutdownPlanStateChain(PlanState *head)
Would take a whole up/down chain and do two things.
(1) Call ExecShutdownNode on every element, giving each
its own chance at asynchronous shutdown.
(2) Roll every element's instrumentation into head's via
InstrAggNode, except head's own.
One thing to watch for here. ExplainNode only calls
InstrEndLoop (right before printing) to finalize the
cycle of the node it's about to print (head), at the
spot with the "we haven't done ExecutorEnd yet" comment
-- so any frame other than head would never get that
call, and its last cycle would likely still be
unfinalized (running=true) by the time this runs.
Feeding that straight into InstrAggNode would probably
hit its Assert(!add->running). Calling InstrEndLoop on
each element first, before aggregating, should avoid
that.
This function shouldn't be GraphScan-specific -- putting
it in the core (execProcnode.c) would let any node type
that owns a PlanState chain and needs to roll it up at
EXPLAIN time reuse it by just passing its own head.
ExecShutdownGraphScan(GraphScanState *node)
Would be one line:
ExecShutdownPlanStateChain(node->inner_head).
GraphScan would just say "here's where my chain starts"
and hold no traversal/aggregation logic of its own.
This would need a case T_GraphScanState hooked into
execProcnode.c's ExecShutdownNode_walker switch -- the
same hook Gather uses to merge parallel workers' stats
into the leader's (called inside ExecutorRun, before
ExplainPrintPlan).
The rest of the functions
Everything else -- ExecInitGraphScan, ExecEndGraphScan,
ExecReScanGraphScan, graph_push, graph_fetch_seed, graph_step,
graph_build_row, graph_build_edge_array, graph_bind_vertex_params and
friends -- wouldn't be new, just mechanically changed from array
indexing (frames[d]) to walking inner_head/inner and indexing
vids[d].
One thing worth flagging for graph_build_edge_array: indexing vids[]
directly by cur_depth is safe (no risk of reading a leftover depth
from an earlier, deeper traversal), but any new code that walks the
up/down chain itself would need to bound its traversal by cur_depth
(i.e. node->inner) -- since graph_reset only moves inner back and
never cuts the chain, a frame left over from an earlier, deeper
traversal could still be linked on via down.
One more thing worth flagging. up/down would be a field on PlanState
itself, so even though only GraphScan uses it, it gets added to
every node type. That alone makes it a change worth reviewing
carefully.
That said, I'd like to point out what it buys in return. With
up/down as a generic PlanState-level field, the instrumentation
rollup ends up considerably simpler. ExecShutdownGraphScan can be
just one line calling ExecShutdownPlanStateChain(node->inner_head)
precisely because up/down isn't GraphScan's own, but a core mechanism
reusable anywhere. GraphScan itself would need no traversal or
aggregation logic beyond saying "here's where my chain starts" --
if up/down were a GraphScan-only field, that traversal-plus-rollup
logic would have to be written directly inside GraphScan's own code;
pulling it out as a core mechanism would make that whole piece
unnecessary.
Weighed against adding two fields to PlanState, that amount of
simplicity -- plus any other node type running into the same problem
later being able to reuse it as-is -- makes me think this direction
is the right one to take.
Not urgent, just for reference -- the PlanState.up/down +
ExecShutdownPlanStateChain combination above might also be useful
for making WITH RECURSIVE actually execute depth-first. RecursiveUnion
currently works by repeatedly filling a worktable, and SEARCH ... SET
is handled at the parse_cte.c level by accumulating the path into an
array column to sort by afterward (rather than changing the execution
algorithm itself), so a genuinely depth-first execution would need
something that parameterizes the recursive term per depth, creates it
lazily, and backtracks -- which looks like roughly the same shape as
what GraphScan uses here. That's well outside this patch's scope, but
worth keeping in mind if this direction is taken further.
Best regards,
Henson
*Classification: * Privacy: Basic Personal Data; Export Control:
Not Technical; National Security: Not National Security; Company
Classification: Not Applicable; Business or Private Data: Business data
Hello Henson,
While I agree this i a good way to improve the code and allow it to be
reused
in other plan nodes, I do not think now is the time for this, for three
reasons:
- Currently, this would only benefit GraphScanState. While I agree with the
WITH RECURSIVE argument and that the scope is outside this patch,
I think we can update GraphScanState after such a change is implemented.
This can also serve as an argument for such a change, that way we have
two (GraphScanState + WITH RECURSIVE) rather than one (
GraphScanState).
Moreover, waiting to get more eyes on the problem can only be beneficial
(see the last point).
- I would like us to first commit a working version and get feedback from
various real-world use cases before we try to optimize it with such a
change.
There are ways for us to lazy-init the frames when reached rather than all
at once (to reduce memory-foortprint). This would not solve the speed
issue,
but we can simply add the up/down fields to GraphScanState and move the
relevant code later when / if we want them on all PlanState.
- This patch submission seems like the wrong place (too niche) to
discuss a change on a structure this central.
Waiting for more input from more people should provide better
perspective on how such a change can be used in other PlanState-derived
nodes, and in the future.
Best regards,
Henri Gasc
On Thu, Sep 17, 2026 at 6:13 AM Henson Choi <assam258@gmail.com> wrote:
Hi Henri,
This series only implements the WALK syntax.
Thanks for splitting this into separate files -- much easier to
follow.I gave more thought to the spot I flagged in ExecInitGraphScan --
every frame's inner_state is eagerly ExecInitNode'd up to
max_graph_stack_depth (1001 by default), while explain.c only ever
looks at frames[0] when printing the plan. I first thought "just
delay ExecInitNode, keep the array" would be enough, but that only
solves half the problem (the init cost) -- EXPLAIN ANALYZE would
still report only frame 0's share. So here's a bigger structure I'd
like to propose instead.How I understood the current structure
One GraphScan handles a single quantified hop of the graph pattern,
and inner_plan is the pre-planned, parameterized 1-hop expansion for
it (taking the current vertex as a PARAM_EXEC, so it can use
indexes).At execution time, GraphScanState keeps a frames[] array (each
element a GraphDepthFrameData), and each element holds both
inner_state (its own ExecInitNode(copyObject(inner_plan)) copy) and
that depth's vertex/edge-property values together. The whole array
is built at once in ExecInitGraphScan, regardless of how deep the
traversal actually goes.The problem with this seems to be that two things of very different
character -- inner_state, an expensive resource (a PlanState copy
carrying locks and a subplan tree), and the vertex/edge-property
values, which are cheap scalars -- are bundled together into one
GraphDepthFrameData element. So the whole array ends up sized to
the theoretical upper bound (max_graph_stack_depth) rather than the
depth actually reached, and the expensive side (inner_state) gets
built up to that same bound, on the same schedule as the cheap side.A structure I'd like to propose instead, briefly
Splitting this into two separate concerns:
First, factor "each depth needs its own copy of inner_plan" out into
a generic PlanState-level mechanism. Add an up/down pointer pair to
PlanState, letting a node thread its own PlanState copies into a
chain, independent of lefttree/righttree.Second, keep the small scalar data -- "the vertex reached at this
depth, and its edge properties" -- separate, since it has nothing to
do with any PlanState. A lean GraphVidData array, owned by
GraphScanState, indexed directly by depth and grown by repalloc
(doubling) only when needed. This array only grows to the deepest
point actually reached, independent of the up/down chain's length.Writing out how these two would actually move, step by step:
Descending a depth (graph_push):
1. Look at the down pointer of the frame inner currently points to.
2. If down exists -- a copy already exists for this depth.
Use it as-is and move inner there.
3. If down is NULL -- this depth is being reached for the first time.
Make a new copy via graph_init_inner.
Link it onto the end of the chain via up/down.
Move inner there.
4. Either way, prepare this depth's slot in vids[].
If it doesn't exist yet (past vids_capacity), repalloc-double it.
Fill in the vertex key values and the edge properties that led
here.
5. Set need_init to true.
-- a marker for graph_step to call ExecReScan the first time it
steps this frame (this part is unchanged from the current code).Backtracking (graph_backtrack):
1. Move inner one step toward up.
2. That's it -- the chain itself is never cut.
Whatever was linked in via down stays there.Resetting for a new seed (graph_reset, graph_fetch_seed):
1. Backtrack repeatedly until inner reaches depth 0 (= inner_head).
2. No node in the chain gets freed.
3. Set need_init back to true on every frame made so far
(vids[0..frames_reached-1]) -- they all need to ExecReScan
against the new seed's vertex values.
4. When the traversal reaches the same depth again, it takes
graph_push's step 2 (down already exists) and reuses it as-is.The pointer layout, drawn out
What GraphScanState itself holds:
GraphScanState
inner_head ----> depth 0's PlanState copy (always exists, chain head)
inner ----> the innermost depth's PlanState copy right now
vids ----> GraphVidData[0 .. vids_capacity-1] (flat array)
frames_reached = number of depths actually reached so farE.g. with the traversal currently at depth 2 (frames_reached = 3,
i.e. depths 0/1/2 exist), the inner_head/down chain looks like this:inner_head inner
| |
v v
PlanState(d0) PlanState(d1) PlanState(d2)
<-up- <-up-
-down-> -down->
up = NULL up = d0 up = d1
down = d1 down = d2 down = NULLEach arrow is just a pointer -- d0.down == d1, d1.up == d0, and so
on, linked both ways. When graph_push first reaches a new depth, it
links a new node onto the end of this chain and moves inner there.
Backtracking just moves inner one step toward up without cutting the
chain -- so when a later seed descends to the same depth again, it
reuses the existing d1/d2 as-is.The vids array is entirely separate from this chain, indexed
directly by depth number (kept ASCII-only so the columns don't get
mangled in transit; the explanation is below the table):vids[0] vids[1] vids[2] vids[3]
(depth 0) (depth 1) (depth 2) (reserved
seed vertex vid, vidnull vid, vidnull via repalloc,
no edge_props edge_props=e1 edge_props=e2 unused yet)|<--- frames_reached(=3) live entries --->|
vids[0] is the seed vertex (depth 0, no incoming edge), and
vids[1]/vids[2] are the vertex key and the incoming edge's
properties (e1, e2) at each depth. vids[3] is just capacity
vids_capacity already doubled into, not yet used by any depth --
frames_reached(=3) means only vids[0..2] are "live" data.So the PlanState chain (an expensive resource -- locks, subplan
trees) and the vids array (cheap scalar values) end up as two
separate structures, each shaped for its own access pattern (a chain
vs. a flat array).Struct changes needed, by struct
PlanState (execnodes.h) -- add:
up (PlanState *)
down (PlanState *)GraphScanState (execnodes.h) -- drop ndepths/frames
(GraphDepthFrameData *), add instead:inner_head (PlanState *)
inner (PlanState *)
vids (GraphVidData *)
vids_capacity (int)
frames_reached (int)
eflags (int)
frame_vid_width (int)GraphDepthFrameData (nodeGraphScan.h) -- retire it, replace with
GraphVidData:vid_elem, vid_nkeys, vid, vidnull,
edge_props, edge_propsnull, need_init (carried over as-is)drop the inner_state field
(the PlanState.up/down chain takes its place)New functions that would target PlanState
ExecShutdownPlanStateChain(PlanState *head)
core-shared (execProcnode.c / executor.h)graph_init_inner(GraphScanState *node)
internal to nodeGraphScan.c (static)ExecShutdownGraphScan(GraphScanState *node)
nodeGraphScan.c / nodeGraphScan.hThe struct members, one by one
PlanState.up / PlanState.down
Orthogonal to lefttree/righttree. A generic pair for
when a node type needs to thread several of its own
PlanState copies into a chain for its own reasons.Most node types would just leave these NULL. Nothing
besides GraphScan would use it right now, but WITH
RECURSIVE (mentioned below) looks like the same shape
of problem, so it could reuse this field directly.GraphScanState.inner_head
The depth-0 (seed) copy. Made once in ExecInitGraphScan
and never freed until the node ends -- the chain head.Also where EXPLAIN would show the "Inner" child (this
one spot now covers what used to be
frames[0].inner_state in explain.c).GraphScanState.inner
The current pointer to the innermost depth's copy for
the path currently on the stack.NULL when cur_depth < 0 (a new seed is needed).
GraphScanState.vids / vids_capacity / frames_reached
The array of per-depth scalar data, its allocated size,
and how many depths have actually been reached so far.frames_reached is both the live prefix length of this
array and the current length of the up/down chain. When
a new depth is first reached (graph_push), it would
repalloc-double as needed.GraphScanState.eflags
Storing the eflags ExecInitGraphScan received.
graph_push needs to pass the same eflags when it
ExecInitNode's a new copy later, during execution, but
doesn't have it as a parameter at that point anymore, so
it needs to be saved as a field.GraphScanState.frame_vid_width
The widest of the seed key/source key/destination key
widths. Used to size each depth's vid/vidnull arrays.Currently a local variable in ExecInitGraphScan
(maxwidth), but graph_push would need it again too, so
it'd make sense to move it to a field.The functions, one by one
graph_init_inner(GraphScanState *node) -> PlanState *
Would copyObject inner_plan and ExecInitNode one copy,
returning it (NULL if inner_plan is NULL).ExecInitGraphScan would call it once for depth 0,
graph_push once each time a new depth is first reached
-- just pulling together what's currently duplicated in
two places.ExecShutdownPlanStateChain(PlanState *head)
Would take a whole up/down chain and do two things.
(1) Call ExecShutdownNode on every element, giving each
its own chance at asynchronous shutdown.
(2) Roll every element's instrumentation into head's via
InstrAggNode, except head's own.One thing to watch for here. ExplainNode only calls
InstrEndLoop (right before printing) to finalize the
cycle of the node it's about to print (head), at the
spot with the "we haven't done ExecutorEnd yet" comment
-- so any frame other than head would never get that
call, and its last cycle would likely still be
unfinalized (running=true) by the time this runs.
Feeding that straight into InstrAggNode would probably
hit its Assert(!add->running). Calling InstrEndLoop on
each element first, before aggregating, should avoid
that.This function shouldn't be GraphScan-specific -- putting
it in the core (execProcnode.c) would let any node type
that owns a PlanState chain and needs to roll it up at
EXPLAIN time reuse it by just passing its own head.ExecShutdownGraphScan(GraphScanState *node)
Would be one line:
ExecShutdownPlanStateChain(node->inner_head).GraphScan would just say "here's where my chain starts"
and hold no traversal/aggregation logic of its own.This would need a case T_GraphScanState hooked into
execProcnode.c's ExecShutdownNode_walker switch -- the
same hook Gather uses to merge parallel workers' stats
into the leader's (called inside ExecutorRun, before
ExplainPrintPlan).The rest of the functions
Everything else -- ExecInitGraphScan, ExecEndGraphScan,
ExecReScanGraphScan, graph_push, graph_fetch_seed, graph_step,
graph_build_row, graph_build_edge_array, graph_bind_vertex_params and
friends -- wouldn't be new, just mechanically changed from array
indexing (frames[d]) to walking inner_head/inner and indexing
vids[d].One thing worth flagging for graph_build_edge_array: indexing vids[]
directly by cur_depth is safe (no risk of reading a leftover depth
from an earlier, deeper traversal), but any new code that walks the
up/down chain itself would need to bound its traversal by cur_depth
(i.e. node->inner) -- since graph_reset only moves inner back and
never cuts the chain, a frame left over from an earlier, deeper
traversal could still be linked on via down.One more thing worth flagging. up/down would be a field on PlanState
itself, so even though only GraphScan uses it, it gets added to
every node type. That alone makes it a change worth reviewing
carefully.That said, I'd like to point out what it buys in return. With
up/down as a generic PlanState-level field, the instrumentation
rollup ends up considerably simpler. ExecShutdownGraphScan can be
just one line calling ExecShutdownPlanStateChain(node->inner_head)
precisely because up/down isn't GraphScan's own, but a core mechanism
reusable anywhere. GraphScan itself would need no traversal or
aggregation logic beyond saying "here's where my chain starts" --
if up/down were a GraphScan-only field, that traversal-plus-rollup
logic would have to be written directly inside GraphScan's own code;
pulling it out as a core mechanism would make that whole piece
unnecessary.Weighed against adding two fields to PlanState, that amount of
simplicity -- plus any other node type running into the same problem
later being able to reuse it as-is -- makes me think this direction
is the right one to take.Not urgent, just for reference -- the PlanState.up/down +
ExecShutdownPlanStateChain combination above might also be useful
for making WITH RECURSIVE actually execute depth-first. RecursiveUnion
currently works by repeatedly filling a worktable, and SEARCH ... SET
is handled at the parse_cte.c level by accumulating the path into an
array column to sort by afterward (rather than changing the execution
algorithm itself), so a genuinely depth-first execution would need
something that parameterizes the recursive term per depth, creates it
lazily, and backtracks -- which looks like roughly the same shape as
what GraphScan uses here. That's well outside this patch's scope, but
worth keeping in mind if this direction is taken further.Best regards,
Henson
The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other than the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.
Hi Henri,
I do not think now is the time for this, for three reasons
Let me put the proposal in one place first. It is to replace the array
that is sized up front with a doubly-linked list; up/down is what forms
the links; and those links belong on the individual nodes of
inner_plan, not on the GraphScan.
Taking the three in turn: I agree with the third, I agree with the
principle of the second but would like to move one thing ahead of the
commit, and on the first I explained myself badly.
1. On only GraphScanState benefiting
This is where I explained myself badly.
Each depth has its own copy of inner_plan, and the copies are
copyObject() of the same Plan, so their nodes correspond one to one.
up/down holds that correspondence on the nodes themselves: a node's
down is the node in the same position in the next depth's copy.
With the links on every node, two things fall out at once.
The root's chain is the per-depth copies laid out in order. So
GraphScan moves between depths by following down from inner_head and
coming back along up. It does not carry a structure of its own; it
rides the root node's chain.
A non-root node's chain is that node's counterparts, one per depth.
EXPLAIN prints the whole tree under "Inner", so every node in it, the
Append and each scan below it alike, has to merge its instrumentation
with its counterparts. That chain is what they merge along.
So up/down is not a field for GraphScan's sake. There is one link per
node inside inner_plan, and GraphScan borrows one of them, the root's.
The ones carrying the field are every node type that can appear under
a GraphScan.
With the counterparts held by the nodes, the merge is:
static bool
agg_chain_walker(PlanState *ps, void *ctx)
{
if (ps->instrument != NULL)
{
for (PlanState *p = ps->down; p != NULL; p = p->down)
{
if (p->instrument == NULL)
continue;
InstrEndLoop(p->instrument);
InstrAggNode(ps->instrument, p->instrument);
}
}
return planstate_tree_walker(ps, agg_chain_walker, ctx);
}
One pass over the tree, each node folding its own chain, and the
existing walker keeps handling every child shape for free. Without the
links on the nodes, this pairing has to be rebuilt on the merging side
every time, and that logic then lives inside GraphScan -- one node type
carrying a problem that every node in the subtree has.
2. On committing a working version first
Agreed as a principle. But there is one part of what I proposed that I
think has to be settled before a commit.
ExecInitGraphScan() builds every depth up front. With an unbounded
quantifier max_depth is clamped to max_graph_stack_depth + 1, so
ndepths is max_graph_stack_depth + 2 (about a thousand), and each
GraphScan does, at every execution:
- one palloc0 of the frames array, ndepths entries
- four palloc's per frame (vid, vidnull, edge_props, edge_propsnull)
- ExecInitNode(copyObject(inner_plan)) once per frame
The third is the one that matters. inner_plan is a UNION ALL over the
matching edge element tables, so each copy is an Append over the
per-element scans, and a parameterized index scan there does
index_open() and index_beginscan(); for btree that attaches two
BTScanPosData. A two-hop query pays all of it, and a pattern with
three quantified hops pays it three times over. And the cost scales
with max_graph_stack_depth, not with the data.
The way to fix it is your own "lazy-init the frames when reached":
create a depth's copy the first time that depth is reached. Doing
that changes the data structure too. A stack that descends a depth at
a time and backtracks wants something you extend one step at a time
and can step back through -- a doubly-linked list -- rather than an
array sized up front. The links from point 1 are that list, and the
root's chain is this stack.
3. On this thread being the wrong place
Agreed, and I should have said so myself.
Let me be clearer about why I brought up WITH RECURSIVE, though. I am
not proposing to implement it here. The point was only that the same
structure would serve WITH RECURSIVE too -- that it is not specific to
GraphScan. What that structure tidies up in this code is points 1 and
2.
4. The attached patch
wip-graphscan-planstate-updown.txt applies on top of v2-0008. It is
not a submission for this CF entry and I am not asking you to fold it
in. It builds and the graph_table regression test passes.
Best regards,
Henson
Attachments:
wip-graphscan-planstate-updown.txttext/plain; charset=US-ASCII; name=wip-graphscan-planstate-updown.txtDownload+558-163
Hi Henri,
The patch I sent earlier linked the copies at their roots only. Attached
is that fixed: wip-graphscan-planstate-updown-rev-002.txt replaces it and
applies on top of v2-0008 as before.
graph_push() now pairs a new copy with the previous one node by node.
Both trees are ExecInitNode() of copyObject() of the same Plan, so
planstate_tree_walker() visits them in the same order; collecting one in
that order and walking the other pairs them up. A node's down is then
the node in the same position in the next depth's copy, and the root's
chain is, as the special case of that, the per-depth copies in order --
which is what GraphScan follows when it descends and backtracks.
The rollup in ExecShutdownPlanStateChain() is now one pass over the tree
with each node folding its own chain. Shutdown stays on the root's chain
as before, since it is per copy: ExecShutdownNode() recurses into each
copy's tree by itself, so calling it per node would tear each one down
twice.
The expected output changes like this:
-> Append (actual rows=0.90 loops=10)
Buffers: shared hit=51
-> Seq Scan on e1_2 (actual rows=0.50 loops=10)
Buffers: shared hit=10
-> Bitmap Heap Scan on e1_3 (actual rows=0.20 loops=10)
Buffers: shared hit=11
...
Before, the Append read loops=10 over eight nodes that all read loops=3,
and its Buffers read 51 against 16 summed over its children. The
children now sum to 51. It also brought out something that was not
visible at all: the e2_1 scan reported no rows before, when it was in
fact finding two -- they were found below depth 0 and so never reported.
Two things are still open.
First, part of the rollup has to be done per node type. InstrAggNode()
covers PlanState.instrument, but an index scan's Index Searches does not
live there; it comes from IndexScanInstrumentation (iss_Instrument,
ioss_Instrument, biss_Instrument). So that one counter keeps depth 0's
value, and in the output above it reads Index Searches: 3 under
loops=10. It agreed with loops=3 before this change, so this is an
inconsistency the change introduces. show_indexscan_info() in explain.c
already sums the parallel workers' copies of that counter in exactly
that spot, and the chain wants the same treatment in the same place.
IndexScan, IndexOnlyScan and BitmapIndexScan are the three affected, and
any other node type holding its own statistics is in the same position.
This patch does not do it.
Second, ExecShutdownPlanStateChain() adds the same numbers again if it
runs more than once. EXEC_FLAG_BACKWARD is only set for scrollable
cursors, so fetching a NO SCROLL cursor in batches has ExecutePlan() call
ExecShutdownNode() once per batch, and with instrumentation on
InstrAggNode() accumulates each time. Gather guards against re-entry in
ExecShutdownGather(), but simply running the rollup once here would drop
everything after the first batch. Folding a delta -- resetting the
member's accumulated counters once merged -- looks like the right shape,
except that Instrumentation's configuration fields must not be touched,
and I have not settled on how. I would welcome your thoughts.
It builds and the graph_table regression test passes.
Best regards,
Henson