Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add query diagnosis warning #1006

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ public final class SystemSessionProperties
public static final String SKIP_REDUNDANT_SORT = "skip_redundant_sort";
public static final String WORK_PROCESSOR_PIPELINES = "work_processor_pipelines";
public static final String ENABLE_DYNAMIC_FILTERING = "enable_dynamic_filtering";
public static final String ENABLE_QUERY_DIAGNOSIS_WARNING = "enable_query_diagnosis_warning";

private final List<PropertyMetadata<?>> sessionProperties;

Expand Down Expand Up @@ -509,6 +510,11 @@ public SystemSessionProperties(
ENABLE_DYNAMIC_FILTERING,
"Enable dynamic filtering",
featuresConfig.isEnableDynamicFiltering(),
false),
booleanProperty(
ENABLE_QUERY_DIAGNOSIS_WARNING,
"Enable query diagnosis warning",
featuresConfig.getQueryDiagnosisWarningEnable(),
false));
}

Expand Down Expand Up @@ -906,4 +912,9 @@ public static boolean isEnableDynamicFiltering(Session session)
{
return session.getSystemProperty(ENABLE_DYNAMIC_FILTERING, Boolean.class);
}

public static boolean isEnableQueryDiagnosisWarning(Session session)
{
return session.getSystemProperty(ENABLE_QUERY_DIAGNOSIS_WARNING, Boolean.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ public class FeaturesConfig
private boolean optimizeTopNRowNumber = true;
private boolean workProcessorPipelines;
private boolean skipRedundantSort = true;
private boolean enableQueryDiagnosisWarning;

private Duration iterativeOptimizerTimeout = new Duration(3, MINUTES); // by default let optimizer wait a long time in case it retrieves some data from ConnectorMetadata
private boolean enableDynamicFiltering;
Expand Down Expand Up @@ -895,6 +896,18 @@ public FeaturesConfig setMaxGroupingSets(int maxGroupingSets)
return this;
}

public boolean getQueryDiagnosisWarningEnable()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public boolean getQueryDiagnosisWarningEnable()
public boolean isEnableQueryDiagnosisWarning()

{
return enableQueryDiagnosisWarning;
}

@Config("analyzer.query-diagnosis-warning-enabled")
public FeaturesConfig setQueryDiagnosisWarningEnable(boolean queryDiagnosisWarning)
{
this.enableQueryDiagnosisWarning = queryDiagnosisWarning;
return this;
}

public boolean isWorkProcessorPipelines()
{
return workProcessorPipelines;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimap;
import io.prestosql.Session;
import io.prestosql.SystemSessionProperties;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.TypeProvider;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.sanity.warnings.DeprecatedFunctionWarning;
import io.prestosql.sql.planner.sanity.warnings.IntegerDivisionWarning;

/**
* It is going to be executed to verify logical planner correctness
Expand Down Expand Up @@ -55,7 +58,10 @@ public PlanSanityChecker(boolean forceSingleNode)
new ValidateAggregationsWithDefaultValues(forceSingleNode),
new ValidateStreamingAggregations(),
new DynamicFiltersChecker())
.build();
.putAll(
Stage.DIAGNOSTIC,
new DeprecatedFunctionWarning(),
new IntegerDivisionWarning()).build();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move .build(); to next line.

}

public void validateFinalPlan(PlanNode planNode, Session session, Metadata metadata, TypeAnalyzer typeAnalyzer, TypeProvider types, WarningCollector warningCollector)
Expand All @@ -66,6 +72,9 @@ public void validateFinalPlan(PlanNode planNode, Session session, Metadata metad
public void validateIntermediatePlan(PlanNode planNode, Session session, Metadata metadata, TypeAnalyzer typeAnalyzer, TypeProvider types, WarningCollector warningCollector)
{
checkers.get(Stage.INTERMEDIATE).forEach(checker -> checker.validate(planNode, session, metadata, typeAnalyzer, types, warningCollector));
if (SystemSessionProperties.isEnableQueryDiagnosisWarning(session)) {
checkers.get(Stage.DIAGNOSTIC).forEach(checker -> checker.validate(planNode, session, metadata, typeAnalyzer, types, warningCollector));
}
}

public interface Checker
Expand All @@ -75,6 +84,6 @@ public interface Checker

private enum Stage
{
INTERMEDIATE, FINAL
INTERMEDIATE, FINAL, DIAGNOSTIC
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner.sanity.warnings;

import com.google.common.collect.ImmutableList;
import io.prestosql.Session;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.spi.PrestoWarning;
import io.prestosql.sql.planner.ExpressionExtractor;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.TypeProvider;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.sanity.PlanSanityChecker;
import io.prestosql.sql.tree.DefaultTraversalVisitor;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.FunctionCall;

import java.util.List;

import static io.prestosql.spi.connector.StandardWarningCode.DREPRCATED_FUNCTION;

public final class DeprecatedFunctionWarning
implements PlanSanityChecker.Checker
{
private List<String> deprecatedFunctions = ImmutableList.of("json_array_get");
Copy link
Member

@ebyhr ebyhr Oct 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can change this to static final variable.

Suggested change
private List<String> deprecatedFunctions = ImmutableList.of("json_array_get");
private static final List<String> DEPRECATED_FUNCTIONS = ImmutableList.of("json_array_get");


@Override
public void validate(PlanNode plan, Session session, Metadata metadata, TypeAnalyzer typeAnalyzer, TypeProvider types, WarningCollector warningCollector)
{
for (Expression expression : ExpressionExtractor.extractExpressions(plan)) {
new DefaultTraversalVisitor<Void, Void>()
{
@Override
protected Void visitFunctionCall(FunctionCall node, Void context)
{
if (node.getName().getParts().stream().anyMatch(deprecatedFunctions::contains)) {
warningCollector.add(new PrestoWarning(DREPRCATED_FUNCTION, "Detected use of deprecated function: json_array_get()"));
Copy link
Member

@ebyhr ebyhr Oct 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we avoid hardcoding the function name here? When we add a deprecated function later, we need to fix this line.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try to detect the annotation "@deprecated" instead of hardcoding.

}
return null;
}
}.process(expression, null);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner.sanity.warnings;

import io.prestosql.Session;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.spi.PrestoWarning;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.planner.ExpressionExtractor;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.TypeProvider;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.sanity.PlanSanityChecker;
import io.prestosql.sql.tree.ArithmeticBinaryExpression;
import io.prestosql.sql.tree.DefaultTraversalVisitor;
import io.prestosql.sql.tree.Expression;

import static io.prestosql.spi.connector.StandardWarningCode.INTEGER_DIVISION;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.sql.tree.ArithmeticBinaryExpression.Operator.DIVIDE;

public final class IntegerDivisionWarning
implements PlanSanityChecker.Checker
{
public IntegerDivisionWarning() {}

@Override
public void validate(PlanNode plan, Session session, Metadata metadata, TypeAnalyzer typeAnalyzer, TypeProvider types, WarningCollector warningCollector)
{
for (Expression expression : ExpressionExtractor.extractExpressions(plan)) {
new DefaultTraversalVisitor<Void, Void>()
{
@Override
protected Void visitArithmeticBinary(ArithmeticBinaryExpression node, Void context)
{
if (node.getOperator().equals(DIVIDE)) {
Type leftType = typeAnalyzer.getType(session, types, node.getLeft());
Type rightType = typeAnalyzer.getType(session, types, node.getRight());
if (leftType.equals(INTEGER) && rightType.equals(INTEGER)) {
warningCollector.add(new PrestoWarning(INTEGER_DIVISION, "Detected integer division. Possible loss of precision."));
}
}
return null;
}
}.process(expression, null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ public void testDefaults()
.setMultimapAggGroupImplementation(MultimapAggGroupImplementation.NEW)
.setDistributedSortEnabled(true)
.setMaxGroupingSets(2048)
.setQueryDiagnosisWarningEnable(false)
.setWorkProcessorPipelines(false)
.setSkipRedundantSort(true)
.setEnableDynamicFiltering(false));
Expand Down Expand Up @@ -172,6 +173,7 @@ public void testExplicitPropertyMappings()
.put("optimizer.optimize-top-n-row-number", "false")
.put("distributed-sort", "false")
.put("analyzer.max-grouping-sets", "2047")
.put("analyzer.query-diagnosis-warning-enabled", "true")
.put("experimental.work-processor-pipelines", "true")
.put("optimizer.skip-redundant-sort", "false")
.put("experimental.enable-dynamic-filtering", "true")
Expand Down Expand Up @@ -235,6 +237,7 @@ public void testExplicitPropertyMappings()
.setMultimapAggGroupImplementation(MultimapAggGroupImplementation.LEGACY)
.setDistributedSortEnabled(false)
.setMaxGroupingSets(2047)
.setQueryDiagnosisWarningEnable(true)
.setDefaultFilterFactorEnabled(true)
.setWorkProcessorPipelines(true)
.setSkipRedundantSort(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public enum StandardWarningCode
{
TOO_MANY_STAGES(0x0000_0001),
REDUNDANT_ORDER_BY(0x0000_0002),
INTEGER_DIVISION(0x0000_0003),
DREPRCATED_FUNCTION(0x0000_0004),

/**/;
private final WarningCode warningCode;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.execution;

import com.google.common.collect.ImmutableMap;
import io.prestosql.Session;
import io.prestosql.execution.warnings.DefaultWarningCollector;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.execution.warnings.WarningCollectorConfig;
import io.prestosql.plugin.tpch.TpchConnectorFactory;
import io.prestosql.spi.PrestoWarning;
import io.prestosql.spi.WarningCode;
import io.prestosql.spi.connector.StandardWarningCode;
import io.prestosql.sql.planner.LogicalPlanner;
import io.prestosql.testing.LocalQueryRunner;
import org.intellij.lang.annotations.Language;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static org.testng.Assert.fail;

public class TestDiagnosisWarning
{
private LocalQueryRunner queryRunner;

@BeforeClass
public void setUp()
{
queryRunner = new LocalQueryRunner(testSessionBuilder()
.setCatalog("local")
.setSchema("tiny")
.build());

queryRunner.createCatalog(
queryRunner.getDefaultSession().getCatalog().get(),
new TpchConnectorFactory(1),
ImmutableMap.of());
}

@AfterClass(alwaysRun = true)
public void tearDown()
{
queryRunner.close();
}

@Test
public void testWarningSession()
{
WarningCode warningCode = StandardWarningCode.INTEGER_DIVISION.toWarningCode();
// sessionProperties = null
assertPlannerWarnings(queryRunner,
"SELECT 1/2",
ImmutableMap.of(),
Optional.empty());

// session enable_query_diagnosis_warning = true
assertPlannerWarnings(queryRunner,
"SELECT 1/2",
Optional.of(warningCode));
}

@Test
public void testIntegerDivisionWarning()
{
WarningCode warningCode = StandardWarningCode.INTEGER_DIVISION.toWarningCode();
assertPlannerWarnings(queryRunner,
"SELECT 1/2",
Optional.of(warningCode));
assertPlannerWarnings(queryRunner,
"SELECT a/2 FROM (VALUES (1)) as t(a)",
Optional.of(warningCode));
assertPlannerWarnings(queryRunner,
"SELECT 1/2.0",
Optional.empty());
}

@Test
public void testDeprecatedFunction()
{
WarningCode warningCode = StandardWarningCode.DREPRCATED_FUNCTION.toWarningCode();
assertPlannerWarnings(queryRunner,
"SELECT 123",
Copy link
Member

@ebyhr ebyhr Oct 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add a normal(=non-deprecated) function to this test.

Optional.empty());
assertPlannerWarnings(queryRunner,
"SELECT json_array_get('[1, 2, 3]', 0)",
Optional.of(warningCode));
assertPlannerWarnings(queryRunner,
"SELECT json_array_get(a, 0) FROM (VALUES ('[1, 2, 3]')) AS t(a)",
Optional.of(warningCode));
}

private static void assertPlannerWarnings(LocalQueryRunner queryRunner, @Language("SQL") String sql, Optional<WarningCode> expectedWarning)
{
assertPlannerWarnings(queryRunner, sql, ImmutableMap.of("enable_query_diagnosis_warning", "true"), expectedWarning);
}

private static void assertPlannerWarnings(LocalQueryRunner queryRunner, @Language("SQL") String sql, Map<String, String> sessionProperties, Optional<WarningCode> expectedWarning)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we change Optional<WarningCode> to List<WarningCode> for multiple warning case?

{
Session.SessionBuilder sessionBuilder = testSessionBuilder()
.setCatalog(queryRunner.getDefaultSession().getCatalog().get())
.setSchema(queryRunner.getDefaultSession().getSchema().get());
sessionProperties.forEach(sessionBuilder::setSystemProperty);
WarningCollector warningCollector = new DefaultWarningCollector(new WarningCollectorConfig());
queryRunner.inTransaction(sessionBuilder.build(), transactionSession -> {
queryRunner.createPlan(transactionSession, sql, LogicalPlanner.Stage.OPTIMIZED_AND_VALIDATED, warningCollector);
return null;
});
Set<WarningCode> warnings = warningCollector.getWarnings().stream()
.map(PrestoWarning::getWarningCode)
.collect(toImmutableSet());
if (expectedWarning.isPresent()) {
if (!warnings.contains(expectedWarning.get())) {
fail("Expected warning: " + expectedWarning);
}
}
else {
if (!warnings.isEmpty()) {
fail("Expect no warning");
}
}
}
}