[ 
https://issues.apache.org/jira/browse/CALCITE-7340?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18149951#comment-18149951
 ] 

Mihai Budiu commented on CALCITE-7340:
--------------------------------------

Here is the design, which will also be part of the JavaDoc of a new visitor 
which enforces these invariants:
h2. Correlation variables

A correlation variable is a reference to a row. The evaluation of one sub-plan 
produces the row, and a different sub-plan reads the row through the variable. 
The name of a variable is its correlation id ({{{}CorrelationId{}}}), which a 
plan shows as {{{}$cor0{}}}. We often use the two concepts interchangeably.

The Rel node that connects the two sub-plans is the declaration of the 
variable. For example, a {{Correlate}} evaluates its right input one time for 
each row of its left input. During each evaluation of the right input, the 
variable refers to that row of the left input.

For example, for the tables {{t(k, v)}} and {{{}s(k, w){}}},
{noformat}
SELECT k, (SELECT SUM(w) FROM s WHERE s.k = t.k) FROM t
{noformat}
becomes
{noformat}
LogicalProject(variablesSet=[[$cor0]], K=[$0], EXPR$1=[$SCALAR_QUERY({  -- 
declaration of $cor0
LogicalAggregate(group=[{}], EXPR$0=[SUM($0)])                          -- 
scope of $cor0
  LogicalProject(W=[$1])
    LogicalFilter(condition=[=($0, $cor0.K)])                           -- use 
of $cor0
      LogicalTableScan(table=[[S]])
})])
  LogicalTableScan(table=[[T]])                                         -- 
outside scope of $cor0
{noformat}
and, after the removal of the sub-query,
{noformat}
LogicalProject(K=[$0], EXPR$1=[$2])
  LogicalCorrelate(correlation=[$cor0], joinType=[left], requiredColumns=[{0}]) 
 -- declaration
    LogicalTableScan(table=[[T]])                                               
 -- outside scope
    LogicalAggregate(group=[{}], EXPR$0=[SUM($0)])                              
 -- scope
      LogicalProject(W=[$1])
        LogicalFilter(condition=[=($0, $cor0.K)])                               
 -- use
          LogicalTableScan(table=[[S]])
{noformat}
*Terms*
||Term||Definition||
|Plan|A rooted Rel DAG, including the plans of the sub-queries 
({{{}RexSubQuery{}}}) in the row expressions ({{{}RexNode{}}})|
|Complete plan|A plan that is not a subplan of a larger plan|
|Correlation id|The name of a variable. A declaration and a use refer to a 
variable by its id|
|Correlation Variable Declaration|The Rel node that connects the sub-plan that 
produces the row and the sub-plan that reads the row. 
{{RelNode.getVariablesSet()}} returns the ids of the variables that a node 
declares|
|Correlation Variable Use|A {{RexCorrelVariable}} expression. It refers to the 
variable by its id. A use usually reads one field of the row, as in 
{{{}$cor0.K{}}}. It can also read the full row, as in {{$cor0}}|
|Variable Scope|The sub-plan that can read the row the variable refers to. Uses 
of the variable are only allowed within its scope. The declaration establishes 
the scope|
|Free variable|A variable used in a plan without a declaration in the plan|
|(Alpha) Rename|Give a variable a new id: replace the id in the declaration and 
in all the uses within its scope|

*Rel Nodes that can declare a variable*
||Node||The variable refers to||Scope||
|{{Correlate}}|A row of the left input. The Correlate evaluates its right input 
one time for each row of its left input|The plan of the right input|
|{{{}Project{}}}, {{Filter}}|A row of the input. The node evaluates its row 
expressions one time for each row of its input|The plans of the sub-queries in 
the row expressions of the node|
|{{Join}}|The fields of a row of the left input, followed by the fields of a 
row of the right input. The Join evaluates its condition one time for each such 
pair of rows|The plans of the sub-queries in the condition|

A Project, Filter or Join declares a variable only for the correlated 
sub-queries in its row expressions. For a Join, these are the sub-queries in 
the ON condition, which can read the rows of both inputs.
h2. Invariants

A complete plan obeys the following invariants. A subplan can have free 
variables. {{CorrelateInvariantChecker.isValid}} checks the invariants.

*Invariants of correlation variables*
||Invariant||Rule||
|1. Unique ids|Different variables have different ids. However, a plan can 
contain one sub-plan in more than one position. Thus an id can be declared in 
two positions of a plan only if the declarations are {_}equal{_}. Equality can 
be: object identity (one Rel node that the plan reaches along two paths, i.e., 
the plan is a DAG), and {{RelNode.deepEquals(Object)}} (two Rel node objects 
with equal contents)|
|2. Used only within scope|Each use of a variable is in the scope of the 
declaration of that variable. Thus a complete plan has no free variables, the 
left input of a Correlate does not use the variable of that Correlate, and a 
Project, Filter or Join uses its variable only in sub-queries|
|3. One variable per node|A Rel node declares at most one variable. A Correlate 
always declares exactly one|
|4. Type|The type of a use ({{{}RexCorrelVariable.getType(){}}}) is a record 
type. It can have more fields or fewer fields than the row that the variable 
refers to. However, each field that a use reads must exist in the row, at the 
same position and with the same type. A use that reads the full row must have 
the type of the row. Ideally the type of each use should exactly match the type 
of the row. Plans do not obey the stricter rule today, and the difference is 
possibly a bug|
|5. Required columns|{{Correlate.getRequiredColumns()}} contains the ordinal of 
each field that the uses of the variable of the Correlate read. A use that 
reads the full row reads all the fields|
h2. Rules for code that creates or changes a plan

*Operations on declarations*
||Operation||Rule||
|Make a declaration|Get a new id from {{{}RelOptCluster.createCorrel(){}}}. No 
other variable of the cluster has this id|
|Replace a declaration|The new node can keep the id, because the old node is 
not in the plan after the change|
|Copy a declaration|If the plan keeps the old node and also gets a new node 
that is not equal to the old node, rename the variable of the new node|
|Insert a subplan into a plan|Use capture-avoiding substitution: alpha-rename 
each variable that the subplan declares, if the plan declares or uses the same 
id. The free variables of the subplan keep their ids|
|Remove a declaration|First remove all the uses of the variable, or replace 
them with other expressions|

Any plan returned by a planner must obey these invariants.

Note: currently {{EnumerableBatchNestedLoopJoin}} does not obey invariants 2 
and 3. It is a Join, but it declares many variables, each variable refers to a 
row of the left input, and the right input uses the variables. See CALCITE-7955.

> The rules governing the use of CorrelationId values in plans are not fully 
> specified
> ------------------------------------------------------------------------------------
>
>                 Key: CALCITE-7340
>                 URL: https://issues.apache.org/jira/browse/CALCITE-7340
>             Project: Calcite
>          Issue Type: Bug
>          Components: core
>    Affects Versions: 1.41.0
>            Reporter: Mihai Budiu
>            Assignee: Mihai Budiu
>            Priority: Minor
>
> This issue is really about the Calcite internal representation of Rel nodes.
> There have been several recent discussions about manipulating plans that 
> contain CorrelationId values, and the conclusion seems to be that the rules 
> governing the use of such variables is not clear.
> Ideally these rules should be spelled out in a specification, and there 
> should be a tool to enforce them by validating plans. The JavaDoc for this 
> tool may be the right place to write the specification. I don't expect that 
> the specification will be long or complicated.
> RelBuilder may not be the right place to enforce such rules, because it 
> usually does not have visibility over the entire plan, and some of these 
> rules have to apply globally over entire plans. 
> See CALCITE-5784, CALCITE-7045 and the discussion in github over CALCITE-7336 
> for examples.
>  



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to