Skip to content

Commit 31d9038

Browse files
authored
Avoid dropping aggregate groupings in local plans (#129370) (#130053)
The local plan optimizer should not change the layout, as it has already been agreed upon. However, CombineProjections can violate this when some grouping elements refer to the same attribute. This occurs when ReplaceFieldWithConstantOrNull replaces missing fields with the same reference for a given data type. Closes #128054 Closes #129811 (cherry picked from commit 2bc6284)
1 parent f50af93 commit 31d9038

File tree

6 files changed

+168
-60
lines changed

6 files changed

+168
-60
lines changed

docs/changelog/129370.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
pr: 129370
2+
summary: Avoid dropping aggregate groupings in local plans
3+
area: ES|QL
4+
type: bug
5+
issues:
6+
- 129811
7+
- 128054

x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/EsqlActionIT.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1476,6 +1476,39 @@ public void testQueryOnEmptyDataIndex() {
14761476
}
14771477
}
14781478

1479+
public void testGroupingStatsOnMissingFields() {
1480+
assertAcked(client().admin().indices().prepareCreate("missing_field_index").setMapping("data", "type=long"));
1481+
long oneValue = between(1, 1000);
1482+
indexDoc("missing_field_index", "1", "data", oneValue);
1483+
refresh("missing_field_index");
1484+
QueryPragmas pragmas = randomPragmas();
1485+
pragmas = new QueryPragmas(
1486+
Settings.builder().put(pragmas.getSettings()).put(QueryPragmas.MAX_CONCURRENT_SHARDS_PER_NODE.getKey(), 1).build()
1487+
);
1488+
EsqlQueryRequest request = new EsqlQueryRequest();
1489+
request.query("FROM missing_field_index,test | STATS s = sum(data) BY color, tag | SORT color");
1490+
request.pragmas(pragmas);
1491+
try (var r = run(request)) {
1492+
var rows = getValuesList(r);
1493+
assertThat(rows, hasSize(4));
1494+
for (List<Object> row : rows) {
1495+
assertThat(row, hasSize(3));
1496+
}
1497+
assertThat(rows.get(0).get(0), equalTo(20L));
1498+
assertThat(rows.get(0).get(1), equalTo("blue"));
1499+
assertNull(rows.get(0).get(2));
1500+
assertThat(rows.get(1).get(0), equalTo(10L));
1501+
assertThat(rows.get(1).get(1), equalTo("green"));
1502+
assertNull(rows.get(1).get(2));
1503+
assertThat(rows.get(2).get(0), equalTo(30L));
1504+
assertThat(rows.get(2).get(1), equalTo("red"));
1505+
assertNull(rows.get(2).get(2));
1506+
assertThat(rows.get(3).get(0), equalTo(oneValue));
1507+
assertNull(rows.get(3).get(1));
1508+
assertNull(rows.get(3).get(2));
1509+
}
1510+
}
1511+
14791512
private void assertEmptyIndexQueries(String from) {
14801513
try (EsqlQueryResponse resp = run(from + "METADATA _source | KEEP _source | LIMIT 1")) {
14811514
assertFalse(resp.values().hasNext());
@@ -1610,6 +1643,8 @@ private void createAndPopulateIndex(String indexName, Settings additionalSetting
16101643
"time",
16111644
"type=long",
16121645
"color",
1646+
"type=keyword",
1647+
"tag",
16131648
"type=keyword"
16141649
)
16151650
);

x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/LocalLogicalPlanOptimizer.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
* This class is part of the planner. Data node level logical optimizations. At this point we have access to
3030
* {@link org.elasticsearch.xpack.esql.stats.SearchStats} which provides access to metadata about the index.
3131
*
32-
* <p>NB: This class also reapplies all the rules from {@link LogicalPlanOptimizer#operators()} and {@link LogicalPlanOptimizer#cleanup()}
32+
* <p>NB: This class also reapplies all the rules from {@link LogicalPlanOptimizer#operators(boolean)}
33+
* and {@link LogicalPlanOptimizer#cleanup()}
3334
*/
3435
public class LocalLogicalPlanOptimizer extends ParameterizedRuleExecutor<LogicalPlan, LocalLogicalOptimizerContext> {
3536

@@ -51,7 +52,7 @@ protected List<Batch<LogicalPlan>> batches() {
5152
var rules = new ArrayList<Batch<LogicalPlan>>();
5253
rules.add(local);
5354
// TODO: if the local rules haven't touched the tree, the rest of the rules can be skipped
54-
rules.addAll(asList(operators(), cleanup()));
55+
rules.addAll(asList(operators(true), cleanup()));
5556
return replaceRules(rules);
5657
}
5758

x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/LogicalPlanOptimizer.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,15 @@
7979
* <li>The {@link LogicalPlanOptimizer#substitutions()} phase rewrites things to expand out shorthand in the syntax. For example,
8080
* a nested expression embedded in a stats gets replaced with an eval followed by a stats, followed by another eval. This phase
8181
* also applies surrogates, such as replacing an average with a sum divided by a count.</li>
82-
* <li>{@link LogicalPlanOptimizer#operators()} (NB: The word "operator" is extremely overloaded and referrers to many different
82+
* <li>{@link LogicalPlanOptimizer#operators(boolean)} (NB: The word "operator" is extremely overloaded and referrers to many different
8383
* things.) transform the tree in various different ways. This includes folding (i.e. computing constant expressions at parse
8484
* time), combining expressions, dropping redundant clauses, and some normalization such as putting literals on the right whenever
8585
* possible. These rules are run in a loop until none of the rules make any changes to the plan (there is also a safety shut off
8686
* after many iterations, although hitting that is considered a bug)</li>
8787
* <li>{@link LogicalPlanOptimizer#cleanup()} Which can replace sorts+limit with a TopN</li>
8888
* </ul>
8989
*
90-
* <p>Note that the {@link LogicalPlanOptimizer#operators()} and {@link LogicalPlanOptimizer#cleanup()} steps are reapplied at the
90+
* <p>Note that the {@link LogicalPlanOptimizer#operators(boolean)} and {@link LogicalPlanOptimizer#cleanup()} steps are reapplied at the
9191
* {@link LocalLogicalPlanOptimizer} layer.</p>
9292
*/
9393
public class LogicalPlanOptimizer extends ParameterizedRuleExecutor<LogicalPlan, LogicalOptimizerContext> {
@@ -118,7 +118,7 @@ protected static List<Batch<LogicalPlan>> rules() {
118118
var skip = new Batch<>("Skip Compute", new SkipQueryOnLimitZero());
119119
var label = new Batch<>("Set as Optimized", Limiter.ONCE, new SetAsOptimized());
120120

121-
return asList(substitutions(), operators(), skip, cleanup(), label);
121+
return asList(substitutions(), operators(false), skip, cleanup(), label);
122122
}
123123

124124
protected static Batch<LogicalPlan> substitutions() {
@@ -153,10 +153,10 @@ protected static Batch<LogicalPlan> substitutions() {
153153
);
154154
}
155155

156-
protected static Batch<LogicalPlan> operators() {
156+
protected static Batch<LogicalPlan> operators(boolean local) {
157157
return new Batch<>(
158158
"Operator Optimization",
159-
new CombineProjections(),
159+
new CombineProjections(local),
160160
new CombineEvals(),
161161
new PruneEmptyPlans(),
162162
new PropagateEmptyRelation(),

x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/CombineProjections.java

Lines changed: 87 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,24 @@
1818
import org.elasticsearch.xpack.esql.core.expression.ReferenceAttribute;
1919
import org.elasticsearch.xpack.esql.expression.function.grouping.Categorize;
2020
import org.elasticsearch.xpack.esql.plan.logical.Aggregate;
21+
import org.elasticsearch.xpack.esql.plan.logical.Eval;
2122
import org.elasticsearch.xpack.esql.plan.logical.LogicalPlan;
2223
import org.elasticsearch.xpack.esql.plan.logical.Project;
2324
import org.elasticsearch.xpack.esql.plan.logical.UnaryPlan;
2425

2526
import java.util.ArrayList;
27+
import java.util.HashSet;
2628
import java.util.LinkedHashSet;
2729
import java.util.List;
30+
import java.util.Set;
2831

2932
public final class CombineProjections extends OptimizerRules.OptimizerRule<UnaryPlan> {
33+
// don't drop groupings from a local plan, as the layout has already been agreed upon
34+
private final boolean local;
3035

31-
public CombineProjections() {
36+
public CombineProjections(boolean local) {
3237
super(OptimizerRules.TransformDirection.UP);
38+
this.local = local;
3339
}
3440

3541
@Override
@@ -60,29 +66,89 @@ protected LogicalPlan rule(UnaryPlan plan) {
6066
return plan;
6167
}
6268

63-
// Agg with underlying Project (group by on sub-queries)
64-
if (plan instanceof Aggregate a) {
65-
if (child instanceof Project p) {
66-
var groupings = a.groupings();
67-
List<NamedExpression> groupingAttrs = new ArrayList<>(a.groupings().size());
68-
for (Expression grouping : groupings) {
69-
if (grouping instanceof Attribute attribute) {
70-
groupingAttrs.add(attribute);
71-
} else if (grouping instanceof Alias as && as.child() instanceof Categorize) {
72-
groupingAttrs.add(as);
69+
if (plan instanceof Aggregate a && child instanceof Project p) {
70+
var groupings = a.groupings();
71+
72+
// sanity checks
73+
for (Expression grouping : groupings) {
74+
if ((grouping instanceof Attribute || grouping instanceof Alias as && as.child() instanceof Categorize) == false) {
75+
// After applying ReplaceAggregateNestedExpressionWithEval,
76+
// evaluatable groupings can only contain attributes.
77+
throw new EsqlIllegalArgumentException("Expected an attribute or grouping function, got {}", grouping);
78+
}
79+
}
80+
assert groupings.size() <= 1
81+
|| groupings.stream().anyMatch(group -> group.anyMatch(expr -> expr instanceof Categorize)) == false
82+
: "CombineProjections only tested with a single CATEGORIZE with no additional groups";
83+
84+
// Collect the alias map for resolving the source (f1 = 1, f2 = f1, etc..)
85+
AttributeMap.Builder<Attribute> aliasesBuilder = AttributeMap.builder();
86+
for (NamedExpression ne : p.projections()) {
87+
// Record the aliases.
88+
// Projections are just aliases for attributes, so casting is safe.
89+
aliasesBuilder.put(ne.toAttribute(), (Attribute) Alias.unwrap(ne));
90+
}
91+
var aliases = aliasesBuilder.build();
92+
93+
// Propagate any renames from the lower projection into the upper groupings.
94+
List<Expression> resolvedGroupings = new ArrayList<>();
95+
for (Expression grouping : groupings) {
96+
Expression transformed = grouping.transformUp(Attribute.class, as -> aliases.resolve(as, as));
97+
resolvedGroupings.add(transformed);
98+
}
99+
100+
// This can lead to duplicates in the groupings: e.g.
101+
// | EVAL x = y | STATS ... BY x, y
102+
if (local) {
103+
// On the data node, the groupings must be preserved because they affect the physical output (see
104+
// AbstractPhysicalOperationProviders#intermediateAttributes).
105+
// In case that propagating the lower projection leads to duplicates in the resolved groupings, we'll leave an Eval in place
106+
// of the original projection to create new attributes for the duplicate groups.
107+
Set<Expression> seenResolvedGroupings = new HashSet<>(resolvedGroupings.size());
108+
List<Expression> newGroupings = new ArrayList<>();
109+
List<Alias> aliasesAgainstDuplication = new ArrayList<>();
110+
111+
for (int i = 0; i < groupings.size(); i++) {
112+
Expression resolvedGrouping = resolvedGroupings.get(i);
113+
if (seenResolvedGroupings.add(resolvedGrouping)) {
114+
newGroupings.add(resolvedGrouping);
73115
} else {
74-
// After applying ReplaceAggregateNestedExpressionWithEval,
75-
// groupings (except Categorize) can only contain attributes.
76-
throw new EsqlIllegalArgumentException("Expected an Attribute, got {}", grouping);
116+
// resolving the renames leads to a duplicate here - we need to alias the underlying attribute this refers to.
117+
// should really only be 1 attribute, anyway, but going via .references() includes the case of a
118+
// GroupingFunction.NonEvaluatableGroupingFunction.
119+
Attribute coreAttribute = resolvedGrouping.references().iterator().next();
120+
121+
Alias renameAgainstDuplication = new Alias(
122+
coreAttribute.source(),
123+
TemporaryNameUtils.locallyUniqueTemporaryName(coreAttribute.name(), "temp_name"),
124+
coreAttribute
125+
);
126+
aliasesAgainstDuplication.add(renameAgainstDuplication);
127+
128+
// propagate the new alias into the new grouping
129+
AttributeMap.Builder<Attribute> resolverBuilder = AttributeMap.builder();
130+
resolverBuilder.put(coreAttribute, renameAgainstDuplication.toAttribute());
131+
AttributeMap<Attribute> resolver = resolverBuilder.build();
132+
133+
newGroupings.add(resolvedGrouping.transformUp(Attribute.class, attr -> resolver.resolve(attr, attr)));
77134
}
78135
}
79-
plan = new Aggregate(
80-
a.source(),
81-
p.child(),
82-
a.aggregateType(),
83-
combineUpperGroupingsAndLowerProjections(groupingAttrs, p.projections()),
84-
combineProjections(a.aggregates(), p.projections())
85-
);
136+
137+
LogicalPlan newChild = aliasesAgainstDuplication.isEmpty()
138+
? p.child()
139+
: new Eval(p.source(), p.child(), aliasesAgainstDuplication);
140+
plan = a.with(newChild, newGroupings, combineProjections(a.aggregates(), p.projections()));
141+
} else {
142+
// On the coordinator, we can just discard the duplicates.
143+
// All substitutions happen before; groupings must be attributes at this point except for non-evaluatable groupings which
144+
// will be an alias like `c = CATEGORIZE(attribute)`.
145+
// Due to such aliases, we can't use an AttributeSet to deduplicate. But we can use a regular set to deduplicate based on
146+
// regular equality (i.e. based on names) instead of name ids.
147+
// TODO: The deduplication based on simple equality will be insufficient in case of multiple non-evaluatable groupings, e.g.
148+
// for `| EVAL x = y | STATS ... BY CATEGORIZE(x), CATEGORIZE(y)`. That will require semantic equality instead. Also
149+
// applies in the local case below.
150+
List<Expression> newGroupings = new ArrayList<>(new LinkedHashSet<>(resolvedGroupings));
151+
plan = a.with(p.child(), newGroupings, combineProjections(a.aggregates(), p.projections()));
86152
}
87153
}
88154

@@ -145,38 +211,6 @@ private static List<NamedExpression> combineProjections(List<? extends NamedExpr
145211
return replaced;
146212
}
147213

148-
private static List<Expression> combineUpperGroupingsAndLowerProjections(
149-
List<? extends NamedExpression> upperGroupings,
150-
List<? extends NamedExpression> lowerProjections
151-
) {
152-
assert upperGroupings.size() <= 1
153-
|| upperGroupings.stream().anyMatch(group -> group.anyMatch(expr -> expr instanceof Categorize)) == false
154-
: "CombineProjections only tested with a single CATEGORIZE with no additional groups";
155-
// Collect the alias map for resolving the source (f1 = 1, f2 = f1, etc..)
156-
AttributeMap.Builder<Attribute> aliasesBuilder = AttributeMap.builder();
157-
for (NamedExpression ne : lowerProjections) {
158-
// Record the aliases.
159-
// Projections are just aliases for attributes, so casting is safe.
160-
aliasesBuilder.put(ne.toAttribute(), (Attribute) Alias.unwrap(ne));
161-
}
162-
var aliases = aliasesBuilder.build();
163-
164-
// Propagate any renames from the lower projection into the upper groupings.
165-
// This can lead to duplicates: e.g.
166-
// | EVAL x = y | STATS ... BY x, y
167-
// All substitutions happen before; groupings must be attributes at this point except for CATEGORIZE which will be an alias like
168-
// `c = CATEGORIZE(attribute)`.
169-
// Therefore, it is correct to deduplicate based on simple equality (based on names) instead of name ids (Set vs. AttributeSet).
170-
// TODO: The deduplication based on simple equality will be insufficient in case of multiple CATEGORIZEs, e.g. for
171-
// `| EVAL x = y | STATS ... BY CATEGORIZE(x), CATEGORIZE(y)`. That will require semantic equality instead.
172-
LinkedHashSet<NamedExpression> resolvedGroupings = new LinkedHashSet<>();
173-
for (NamedExpression ne : upperGroupings) {
174-
NamedExpression transformed = (NamedExpression) ne.transformUp(Attribute.class, a -> aliases.resolve(a, a));
175-
resolvedGroupings.add(transformed);
176-
}
177-
return new ArrayList<>(resolvedGroupings);
178-
}
179-
180214
/**
181215
* Replace grouping alias previously contained in the aggregations that might have been projected away.
182216
*/

x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/LocalLogicalPlanOptimizerTests.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
import static org.elasticsearch.xpack.esql.EsqlTestUtils.withDefaultLimitWarning;
8181
import static org.elasticsearch.xpack.esql.core.tree.Source.EMPTY;
8282
import static org.hamcrest.Matchers.contains;
83+
import static org.hamcrest.Matchers.equalTo;
8384
import static org.hamcrest.Matchers.hasSize;
8485
import static org.hamcrest.Matchers.is;
8586
import static org.hamcrest.Matchers.not;
@@ -645,6 +646,36 @@ public void testUnionTypesInferNonNullAggConstraint() {
645646
assertEquals("integer_long_field", unionTypeField.fieldName().string());
646647
}
647648

649+
/**
650+
* \_Aggregate[[first_name{r}#7, $$first_name$temp_name$17{r}#18],[SUM(salary{f}#11,true[BOOLEAN]) AS SUM(salary)#5, first_nam
651+
* e{r}#7, first_name{r}#7 AS last_name#10]]
652+
* \_Eval[[null[KEYWORD] AS first_name#7, null[KEYWORD] AS $$first_name$temp_name$17#18]]
653+
* \_EsRelation[test][_meta_field{f}#12, emp_no{f}#6, first_name{f}#7, ge..]
654+
*/
655+
public void testGroupingByMissingFields() {
656+
var plan = plan("FROM test | STATS SUM(salary) BY first_name, last_name");
657+
var testStats = statsForMissingField("first_name", "last_name");
658+
var localPlan = localPlan(plan, testStats);
659+
Limit limit = as(localPlan, Limit.class);
660+
Aggregate aggregate = as(limit.child(), Aggregate.class);
661+
assertThat(aggregate.groupings(), hasSize(2));
662+
ReferenceAttribute grouping1 = as(aggregate.groupings().get(0), ReferenceAttribute.class);
663+
ReferenceAttribute grouping2 = as(aggregate.groupings().get(1), ReferenceAttribute.class);
664+
Eval eval = as(aggregate.child(), Eval.class);
665+
assertThat(eval.fields(), hasSize(2));
666+
Alias eval1 = eval.fields().get(0);
667+
Literal literal1 = as(eval1.child(), Literal.class);
668+
assertNull(literal1.value());
669+
assertThat(literal1.dataType(), is(DataType.KEYWORD));
670+
Alias eval2 = eval.fields().get(1);
671+
Literal literal2 = as(eval2.child(), Literal.class);
672+
assertNull(literal2.value());
673+
assertThat(literal2.dataType(), is(DataType.KEYWORD));
674+
assertThat(grouping1.id(), equalTo(eval1.id()));
675+
assertThat(grouping2.id(), equalTo(eval2.id()));
676+
as(eval.child(), EsRelation.class);
677+
}
678+
648679
private IsNotNull isNotNull(Expression field) {
649680
return new IsNotNull(EMPTY, field);
650681
}

0 commit comments

Comments
 (0)