Skip to content

Commit 90cbff3

Browse files
authored
[BugFix] Avoid O(n²)/O(n³) planning for always-false filters on wide indices (#5953)
* Fix O(n^2)/O(n^3) planning for always-false filters on wide indices When a filter simplifies to always false, RelBuilder replaces its input with an empty Values. Calcite derives collations for it with RelMdCollation.values, which returns n(n+1)/2 field collations for n fields, and every Project above it maps all of them. On wide indices this kept the planner busy for minutes and exhausted the heap. - EmptyValuesFactory creates an empty LogicalValues without deriving collations; OpenSearchRelBuilder and the HEP FilterMergeRule use it. - OpenSearchRelMdCollation reports no collations for an empty Values, registered through OpenSearchRelMetadataProvider on the cluster. Resolves #5952 Signed-off-by: Kai Huang <105710027+ahkcs@users.noreply.github.com> * Add integration test for always-false filter planning on a wide index Signed-off-by: Kai Huang <ahkcs@amazon.com> * Skip collation derivation for empty values in Volcano and field trimming The fix for #5952 only covered empty values created during analysis and the HEP filter merge. When the empty result keeps many output fields, for example an index with thousands of top-level fields, three later steps still built empty values the old way and derived O(n^2) collations: - PruneEmptyRules, through the default RelBuilder values factory; - EnumerableValuesRule, through EnumerableValues.create; - RelFieldTrimmer.trimFields(LogicalValues), through LogicalValues.create. EmptyValuesRules replaces the first two in every planner that OpenSearchPrepareImpl creates, and OpenSearchRelFieldTrimmer rebuilds an empty Values with EmptyValuesFactory. Non-empty values are unchanged. Tests: a unit test that runs flat-wide queries through OpenSearchRelRunners, and an IT index with 4,000 top-level fields. Signed-off-by: Kai Huang <105710027+ahkcs@users.noreply.github.com> --------- Signed-off-by: Kai Huang <105710027+ahkcs@users.noreply.github.com> Signed-off-by: Kai Huang <ahkcs@amazon.com>
1 parent 9204af9 commit 90cbff3

9 files changed

Lines changed: 711 additions & 2 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.calcite.plan.metadata;
7+
8+
import com.google.common.collect.ImmutableList;
9+
import java.util.List;
10+
import org.apache.calcite.plan.Convention;
11+
import org.apache.calcite.plan.RelOptCluster;
12+
import org.apache.calcite.rel.RelCollations;
13+
import org.apache.calcite.rel.RelDistributionTraitDef;
14+
import org.apache.calcite.rel.RelNode;
15+
import org.apache.calcite.rel.core.RelFactories;
16+
import org.apache.calcite.rel.logical.LogicalValues;
17+
import org.apache.calcite.rel.metadata.RelMdDistribution;
18+
import org.apache.calcite.rel.type.RelDataType;
19+
import org.apache.calcite.rex.RexLiteral;
20+
21+
/**
22+
* {@link RelFactories.ValuesFactory} that creates a {@link LogicalValues} with no rows without
23+
* deriving its collation trait.
24+
*
25+
* <p>{@link LogicalValues#create} derives the collation trait with {@code RelMdCollation.values},
26+
* which is O(n^2) in the number of fields for an empty {@code Values}. {@code RelBuilder.empty()}
27+
* goes through this factory, e.g. when a filter simplifies to always false
28+
* (opensearch-project/sql#5952). Non-empty values are created exactly as before.
29+
*/
30+
public final class EmptyValuesFactory implements RelFactories.ValuesFactory {
31+
32+
public static final EmptyValuesFactory INSTANCE = new EmptyValuesFactory();
33+
34+
private EmptyValuesFactory() {}
35+
36+
@Override
37+
public RelNode createValues(
38+
RelOptCluster cluster, RelDataType rowType, List<ImmutableList<RexLiteral>> tuples) {
39+
if (tuples.isEmpty()) {
40+
return new LogicalValues(
41+
cluster,
42+
// Same traits as LogicalValues.create, minus the O(n^2) collation derivation.
43+
cluster
44+
.traitSetOf(Convention.NONE)
45+
.replace(RelCollations.EMPTY)
46+
.replaceIf(
47+
RelDistributionTraitDef.INSTANCE,
48+
() -> RelMdDistribution.values(rowType, ImmutableList.of())),
49+
rowType,
50+
ImmutableList.of());
51+
}
52+
return RelFactories.DEFAULT_VALUES_FACTORY.createValues(cluster, rowType, tuples);
53+
}
54+
}
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.calcite.plan.metadata;
7+
8+
import com.google.common.collect.ImmutableList;
9+
import java.lang.invoke.MethodHandle;
10+
import java.lang.invoke.MethodHandles;
11+
import java.lang.invoke.MethodType;
12+
import java.util.List;
13+
import org.apache.calcite.adapter.enumerable.EnumerableConvention;
14+
import org.apache.calcite.adapter.enumerable.EnumerableRules;
15+
import org.apache.calcite.adapter.enumerable.EnumerableValues;
16+
import org.apache.calcite.adapter.enumerable.EnumerableValuesRule;
17+
import org.apache.calcite.plan.Contexts;
18+
import org.apache.calcite.plan.RelOptCluster;
19+
import org.apache.calcite.plan.RelOptPlanner;
20+
import org.apache.calcite.plan.RelOptRule;
21+
import org.apache.calcite.plan.RelRule;
22+
import org.apache.calcite.plan.RelTraitSet;
23+
import org.apache.calcite.rel.RelCollations;
24+
import org.apache.calcite.rel.RelDistributionTraitDef;
25+
import org.apache.calcite.rel.RelNode;
26+
import org.apache.calcite.rel.core.Values;
27+
import org.apache.calcite.rel.metadata.RelMdDistribution;
28+
import org.apache.calcite.rel.rules.PruneEmptyRules;
29+
import org.apache.calcite.rel.type.RelDataType;
30+
import org.apache.calcite.tools.RelBuilder;
31+
import org.apache.calcite.tools.RelBuilderFactory;
32+
import org.checkerframework.checker.nullness.qual.Nullable;
33+
34+
/**
35+
* Volcano rules that create empty {@code Values} without deriving their collation trait.
36+
*
37+
* <p>Calcite's {@link PruneEmptyRules} build their result with {@code RelBuilder.empty()} through
38+
* the default values factory, and {@link EnumerableValuesRule} converts with {@link
39+
* EnumerableValues#create}. Both derive the collation trait with {@code RelMdCollation.values},
40+
* which is O(n^2) in the number of output fields for an empty {@code Values}
41+
* (opensearch-project/sql#5952). {@link #register} replaces them with equivalents that skip that
42+
* derivation for empty values. Non-empty values are handled exactly as before.
43+
*/
44+
public final class EmptyValuesRules {
45+
46+
private static final RelBuilderFactory EMPTY_VALUES_BUILDER =
47+
RelBuilder.proto(Contexts.of(EmptyValuesFactory.INSTANCE));
48+
49+
private static final List<RelOptRule> PRUNE_EMPTY_RULES =
50+
List.of(
51+
PruneEmptyRules.UNION_INSTANCE,
52+
PruneEmptyRules.MINUS_INSTANCE,
53+
PruneEmptyRules.INTERSECT_INSTANCE,
54+
PruneEmptyRules.EMPTY_TABLE_INSTANCE,
55+
PruneEmptyRules.PROJECT_INSTANCE,
56+
PruneEmptyRules.FILTER_INSTANCE,
57+
PruneEmptyRules.SORT_INSTANCE,
58+
PruneEmptyRules.SORT_FETCH_ZERO_INSTANCE,
59+
PruneEmptyRules.AGGREGATE_INSTANCE,
60+
PruneEmptyRules.WINDOW_INSTANCE,
61+
PruneEmptyRules.JOIN_LEFT_INSTANCE,
62+
PruneEmptyRules.JOIN_RIGHT_INSTANCE,
63+
PruneEmptyRules.CORRELATE_RIGHT_INSTANCE,
64+
PruneEmptyRules.CORRELATE_LEFT_INSTANCE);
65+
66+
static final RelOptRule ENUMERABLE_VALUES_RULE =
67+
EnumerableValuesRule.DEFAULT_CONFIG
68+
.withRuleFactory(EmptyEnumerableValuesRule::new)
69+
.toRule(EmptyEnumerableValuesRule.class);
70+
71+
private EmptyValuesRules() {}
72+
73+
/** Replaces Calcite's empty-pruning and values conversion rules that the planner has. */
74+
public static void register(RelOptPlanner planner) {
75+
for (RelOptRule rule : PRUNE_EMPTY_RULES) {
76+
if (planner.removeRule(rule)) {
77+
planner.addRule(withEmptyValuesBuilder(rule));
78+
}
79+
}
80+
if (planner.removeRule(EnumerableRules.ENUMERABLE_VALUES_RULE)) {
81+
planner.addRule(ENUMERABLE_VALUES_RULE);
82+
}
83+
}
84+
85+
private static RelOptRule withEmptyValuesBuilder(RelOptRule rule) {
86+
return ((RelRule<?>) rule).config.withRelBuilderFactory(EMPTY_VALUES_BUILDER).toRule();
87+
}
88+
89+
/** Converts an empty {@code Values} to {@link EnumerableValues} without deriving collations. */
90+
public static class EmptyEnumerableValuesRule extends EnumerableValuesRule {
91+
// EnumerableValues has only a private constructor besides create(), which derives collations.
92+
private static final @Nullable MethodHandle CONSTRUCTOR = findConstructor();
93+
94+
protected EmptyEnumerableValuesRule(Config config) {
95+
super(config);
96+
}
97+
98+
@Override
99+
public @Nullable RelNode convert(RelNode rel) {
100+
Values values = (Values) rel;
101+
if (!values.getTuples().isEmpty() || CONSTRUCTOR == null) {
102+
return super.convert(rel);
103+
}
104+
// Same traits as EnumerableValues.create, minus the O(n^2) collation derivation.
105+
RelTraitSet traits =
106+
values
107+
.getCluster()
108+
.traitSetOf(EnumerableConvention.INSTANCE)
109+
.replace(RelCollations.EMPTY)
110+
.replaceIf(
111+
RelDistributionTraitDef.INSTANCE,
112+
() -> RelMdDistribution.values(values.getRowType(), values.getTuples()));
113+
try {
114+
return (RelNode)
115+
CONSTRUCTOR.invoke(
116+
values.getCluster(), values.getRowType(), values.getTuples(), traits);
117+
} catch (Throwable e) {
118+
return super.convert(rel);
119+
}
120+
}
121+
122+
private static @Nullable MethodHandle findConstructor() {
123+
try {
124+
return MethodHandles.privateLookupIn(EnumerableValues.class, MethodHandles.lookup())
125+
.findConstructor(
126+
EnumerableValues.class,
127+
MethodType.methodType(
128+
void.class,
129+
RelOptCluster.class,
130+
RelDataType.class,
131+
ImmutableList.class,
132+
RelTraitSet.class));
133+
} catch (ReflectiveOperationException | RuntimeException e) {
134+
return null;
135+
}
136+
}
137+
}
138+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.calcite.plan.metadata;
7+
8+
import com.google.common.collect.ImmutableList;
9+
import org.apache.calcite.rel.RelCollation;
10+
import org.apache.calcite.rel.core.Values;
11+
import org.apache.calcite.rel.metadata.BuiltInMetadata;
12+
import org.apache.calcite.rel.metadata.MetadataDef;
13+
import org.apache.calcite.rel.metadata.MetadataHandler;
14+
import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
15+
import org.apache.calcite.rel.metadata.RelMdCollation;
16+
import org.apache.calcite.rel.metadata.RelMetadataProvider;
17+
import org.apache.calcite.rel.metadata.RelMetadataQuery;
18+
19+
/**
20+
* Collation metadata that overrides {@link RelMdCollation} for {@link Values}.
21+
*
22+
* <p>For a {@code Values} with no rows, {@link RelMdCollation#values} treats every column prefix as
23+
* sorted and returns n collations of length n, n-1, ..., 1, which is O(n^2) in the number of
24+
* fields. Every {@code Project} above it then maps all of them, which is O(n^3). An always-false
25+
* filter on a wide index is replaced by such a {@code Values}, so planning could take minutes and
26+
* exhaust the heap (opensearch-project/sql#5952). An empty input has no meaningful sort order, so
27+
* we report no collations, which is always a valid (conservative) answer.
28+
*/
29+
public class OpenSearchRelMdCollation implements MetadataHandler<BuiltInMetadata.Collation> {
30+
31+
public static final RelMetadataProvider SOURCE =
32+
ReflectiveRelMetadataProvider.reflectiveSource(
33+
new OpenSearchRelMdCollation(), BuiltInMetadata.Collation.Handler.class);
34+
35+
protected OpenSearchRelMdCollation() {}
36+
37+
@Override
38+
public MetadataDef<BuiltInMetadata.Collation> getDef() {
39+
return BuiltInMetadata.Collation.DEF;
40+
}
41+
42+
/** Same as {@link RelMdCollation#collations(Values, RelMetadataQuery)}, except for 0 rows. */
43+
public ImmutableList<RelCollation> collations(Values values, RelMetadataQuery mq) {
44+
if (values.getTuples().isEmpty()) {
45+
return ImmutableList.of();
46+
}
47+
return ImmutableList.copyOf(RelMdCollation.values(mq, values.getRowType(), values.getTuples()));
48+
}
49+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.calcite.plan.metadata;
7+
8+
import com.google.common.collect.ImmutableList;
9+
import org.apache.calcite.rel.metadata.ChainedRelMetadataProvider;
10+
import org.apache.calcite.rel.metadata.DefaultRelMetadataProvider;
11+
import org.apache.calcite.rel.metadata.RelMetadataProvider;
12+
13+
/**
14+
* Metadata provider used by the PPL planner: OpenSearch overrides first, then Calcite's defaults.
15+
*/
16+
public final class OpenSearchRelMetadataProvider {
17+
18+
public static final RelMetadataProvider INSTANCE =
19+
ChainedRelMetadataProvider.of(
20+
ImmutableList.of(OpenSearchRelMdCollation.SOURCE, DefaultRelMetadataProvider.INSTANCE));
21+
22+
private OpenSearchRelMetadataProvider() {}
23+
}

‎core/src/main/java/org/opensearch/sql/calcite/utils/CalciteToolsHelper.java‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
import org.apache.calcite.plan.Contexts;
5858
import org.apache.calcite.plan.Convention;
5959
import org.apache.calcite.plan.RelOptCluster;
60+
import org.apache.calcite.plan.RelOptCostFactory;
6061
import org.apache.calcite.plan.RelOptPlanner;
6162
import org.apache.calcite.plan.RelOptRule;
6263
import org.apache.calcite.plan.RelOptSchema;
@@ -102,6 +103,9 @@
102103
import org.checkerframework.checker.nullness.qual.Nullable;
103104
import org.opensearch.sql.calcite.CalcitePlanContext;
104105
import org.opensearch.sql.calcite.plan.Scannable;
106+
import org.opensearch.sql.calcite.plan.metadata.EmptyValuesFactory;
107+
import org.opensearch.sql.calcite.plan.metadata.EmptyValuesRules;
108+
import org.opensearch.sql.calcite.plan.metadata.OpenSearchRelMetadataProvider;
105109
import org.opensearch.sql.calcite.plan.rule.OpenSearchRules;
106110
import org.opensearch.sql.calcite.plan.rule.PPLSimplifyDedupRule;
107111
import org.opensearch.sql.calcite.profile.PlanProfileBuilder;
@@ -206,7 +210,16 @@ public CalcitePrepare createPrepare() {
206210
/** do nothing, just extend for a public construct for new */
207211
public static class OpenSearchRelBuilder extends RelBuilder {
208212
public OpenSearchRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
209-
super(context, cluster, relOptSchema);
213+
super(withEmptyValuesFactory(context), cluster, relOptSchema);
214+
}
215+
216+
/**
217+
* Put {@link EmptyValuesFactory} ahead of the given context, so {@code empty()} (e.g. for an
218+
* always-false filter) does not derive O(n^2) collations on a wide row type.
219+
*/
220+
private static Context withEmptyValuesFactory(@Nullable Context context) {
221+
Context factory = Contexts.of(EmptyValuesFactory.INSTANCE);
222+
return context == null ? factory : Contexts.chain(factory, context);
210223
}
211224

212225
@Override
@@ -254,6 +267,29 @@ public <R> R perform(
254267
return action.apply(cluster, catalogReader, prepareContext.getRootSchema().plus(), statement);
255268
}
256269

270+
/**
271+
* Replace Calcite's empty-pruning and values conversion rules with ones that do not derive
272+
* O(n^2) collations for empty values. Covers both the analysis planner and the planner that
273+
* {@code RelRunner.prepareStatement} creates.
274+
*/
275+
@Override
276+
protected RelOptPlanner createPlanner(
277+
CalcitePrepare.Context prepareContext,
278+
org.apache.calcite.plan.@Nullable Context externalContext,
279+
@Nullable RelOptCostFactory costFactory) {
280+
RelOptPlanner planner = super.createPlanner(prepareContext, externalContext, costFactory);
281+
EmptyValuesRules.register(planner);
282+
return planner;
283+
}
284+
285+
/** Use {@link OpenSearchRelMetadataProvider} so OpenSearch metadata overrides apply. */
286+
@Override
287+
protected RelOptCluster createCluster(RelOptPlanner planner, RexBuilder rexBuilder) {
288+
RelOptCluster cluster = super.createCluster(planner, rexBuilder);
289+
cluster.setMetadataProvider(OpenSearchRelMetadataProvider.INSTANCE);
290+
return cluster;
291+
}
292+
257293
private void registerCustomizedRules(RelOptPlanner planner) {
258294
OpenSearchRules.OPEN_SEARCH_OPT_RULES.forEach(planner::addRule);
259295
}
@@ -376,6 +412,8 @@ protected SqlToRelConverter getSqlToRelConverter(
376412
protected RelRoot trimUnusedFields(RelRoot root) {
377413
final SqlToRelConverter.Config config =
378414
SqlToRelConverter.config()
415+
// Trimming an empty Values must not derive O(n^2) collations either.
416+
.withRelBuilderFactory(proto(Contexts.empty()))
379417
.withTrimUnusedFields(shouldTrim(root.rel))
380418
.withExpand(THREAD_EXPAND.get())
381419
.withInSubQueryThreshold(requireNonNull(THREAD_INSUBQUERY_THRESHOLD.get()));
@@ -560,7 +598,14 @@ public RelNode visit(TableScan scan) {
560598

561599
/** Try to optimize the plan by using HepPlanner */
562600
private static final List<RelOptRule> hepRuleList =
563-
List.of(FilterMergeRule.Config.DEFAULT.toRule(), PPLSimplifyDedupRule.DEDUP_SIMPLIFY_RULE);
601+
List.of(
602+
// Build with OpenSearchRelBuilder so a merged always-false filter goes through
603+
// EmptyValuesFactory instead of deriving O(n^2) collations.
604+
FilterMergeRule.Config.DEFAULT
605+
.withRelBuilderFactory(proto(Contexts.empty()))
606+
.as(FilterMergeRule.Config.class)
607+
.toRule(),
608+
PPLSimplifyDedupRule.DEDUP_SIMPLIFY_RULE);
564609

565610
private static final HepProgram HEP_PROGRAM =
566611
new HepProgramBuilder().addRuleCollection(hepRuleList).build();

0 commit comments

Comments
 (0)