diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/DefaultStreamGraphContext.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/DefaultStreamGraphContext.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/DefaultStreamGraphContext.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/DefaultStreamGraphContext.java @@ -155,6 +155,10 @@ public boolean modifyStreamEdge(List requestInfos) if (requestInfo.getTypeNumber() != 0) { targetEdge.setTypeNumber(requestInfo.getTypeNumber()); } + if (requestInfo.getIntraInputKeyCorrelated() != null) { + modifyIntraInputKeyCorrelation( + targetEdge, requestInfo.getIntraInputKeyCorrelated()); + } } // Notify the listener that the StreamGraph has been updated. @@ -205,6 +209,12 @@ public IntermediateDataSetID getConsumedIntermediateDataSetId(String edgeId) { return consumerEdgeIdToIntermediateDataSetMap.get(edgeId).getId(); } + @Override + public StreamPartitioner getOutputPartitioner( + String edgeId, Integer sourceId, Integer targetId) { + return checkNotNull(getStreamEdge(sourceId, targetId, edgeId)).getPartitioner(); + } + private boolean validateStreamEdgeUpdateRequest(StreamEdgeUpdateRequestInfo requestInfo) { Integer sourceNodeId = requestInfo.getSourceId(); Integer targetNodeId = requestInfo.getTargetId(); @@ -310,6 +320,14 @@ private void modifyOutputPartitioner( targetEdge.getPartitioner()); } + private void modifyIntraInputKeyCorrelation( + StreamEdge targetEdge, boolean existIntraInputKeyCorrelation) { + if (targetEdge.isIntraInputKeyCorrelated() == existIntraInputKeyCorrelation) { + return; + } + targetEdge.setIntraInputKeyCorrelated(existIntraInputKeyCorrelation); + } + private void tryConvertForwardPartitionerAndMergeForwardGroup(StreamEdge targetEdge) { checkState(targetEdge.getPartitioner() instanceof ForwardPartitioner); Integer sourceNodeId = targetEdge.getSourceId(); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphContext.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphContext.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphContext.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphContext.java @@ -25,6 +25,7 @@ import org.apache.flink.streaming.api.graph.util.StreamEdgeUpdateRequestInfo; import org.apache.flink.streaming.api.graph.util.StreamNodeUpdateRequestInfo; import org.apache.flink.streaming.api.operators.StreamOperatorFactory; +import org.apache.flink.streaming.runtime.partitioner.StreamPartitioner; import javax.annotation.Nullable; @@ -96,4 +97,15 @@ interface StreamGraphUpdateListener { /** This method is called whenever the StreamGraph is updated. */ void onStreamGraphUpdated(); } + + /** + * Gets the output partitioner of the specified edge. + * + * @param edgeId id of the edge + * @param sourceId source node id of the edge + * @param targetId target node id of the edge + * @return the output partitioner + */ + @Nullable + StreamPartitioner getOutputPartitioner(String edgeId, Integer sourceId, Integer targetId); } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/ImmutableStreamEdge.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/ImmutableStreamEdge.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/ImmutableStreamEdge.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/ImmutableStreamEdge.java @@ -20,6 +20,9 @@ import org.apache.flink.annotation.Internal; import org.apache.flink.streaming.api.graph.StreamEdge; +import org.apache.flink.streaming.runtime.partitioner.BroadcastPartitioner; +import org.apache.flink.streaming.runtime.partitioner.ForwardForConsecutiveHashPartitioner; +import org.apache.flink.streaming.runtime.partitioner.ForwardPartitioner; /** Helper class that provides read-only StreamEdge. */ @Internal @@ -45,4 +48,16 @@ public int getSourceId() { public String getEdgeId() { return streamEdge.getEdgeId(); } + + public boolean isForwardForConsecutiveHashEdge() { + return streamEdge.getPartitioner() instanceof ForwardForConsecutiveHashPartitioner; + } + + public boolean isExactForwardEdge() { + return streamEdge.getPartitioner().getClass().equals(ForwardPartitioner.class); + } + + public boolean isBroadcastEdge() { + return streamEdge.getPartitioner() instanceof BroadcastPartitioner; + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/StreamEdgeUpdateRequestInfo.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/StreamEdgeUpdateRequestInfo.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/StreamEdgeUpdateRequestInfo.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/StreamEdgeUpdateRequestInfo.java @@ -21,6 +21,8 @@ import org.apache.flink.annotation.Internal; import org.apache.flink.streaming.runtime.partitioner.StreamPartitioner; +import javax.annotation.Nullable; + /** Helper class carries the data required to updates a stream edge. */ @Internal public class StreamEdgeUpdateRequestInfo { @@ -35,6 +37,9 @@ public class StreamEdgeUpdateRequestInfo { // typeNumber. private int typeNumber; + // Null means no modifications will be applied to it + @Nullable private Boolean intraInputKeyCorrelated; + public StreamEdgeUpdateRequestInfo(String edgeId, Integer sourceId, Integer targetId) { this.edgeId = edgeId; this.sourceId = sourceId; @@ -52,6 +57,12 @@ public StreamEdgeUpdateRequestInfo withTypeNumber(int typeNumber) { return this; } + public StreamEdgeUpdateRequestInfo withIntraInputKeyCorrelated( + boolean intraInputKeyCorrelated) { + this.intraInputKeyCorrelated = intraInputKeyCorrelated; + return this; + } + public String getEdgeId() { return edgeId; } @@ -71,4 +82,9 @@ public StreamPartitioner getOutputPartitioner() { public int getTypeNumber() { return typeNumber; } + + @Nullable + public Boolean getIntraInputKeyCorrelated() { + return intraInputKeyCorrelated; + } } diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java --- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java +++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java @@ -177,6 +177,49 @@ public class OptimizerConfigOptions { + "hash join optimization is only performed at runtime, and NONE " + "means the optimization is only carried out at compile time."); + @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH) + public static final ConfigOption + TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_STRATEGY = + key("table.optimizer.skewed-join-optimization.strategy") + .enumType(AdaptiveSkewedJoinOptimizationStrategy.class) + .defaultValue(AdaptiveSkewedJoinOptimizationStrategy.AUTO) + .withDescription( + "Flink will handle skew in shuffled joins (sort-merge and hash) " + + "at runtime by splitting data according to the skewed join " + + "key. The value of this configuration determines how Flink performs " + + "this optimization. AUTO means Flink will automatically apply this " + + "optimization, FORCED means Flink will enforce this optimization even " + + "if it introduces extra hash shuffle, and NONE means this optimization " + + "will not be executed."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH) + public static final ConfigOption + TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_SKEWED_FACTOR = + key("table.optimizer.skewed-join-optimization.skewed-factor") + .doubleType() + .defaultValue(4.0) + .withDescription( + "When a join operator instance encounters input data that exceeds N times the median " + + "size of other concurrent join operator instances, it is considered skewed " + + "(where N represents this skewed-factor). In such cases, Flink may automatically " + + "split the skewed data into multiple parts to ensure a more balanced data " + + "distribution, unless the data volume is below the skewed threshold(defined " + + "using table.optimizer.skewed-join-optimization.skewed-threshold)."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH) + public static final ConfigOption + TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_SKEWED_THRESHOLD = + key("table.optimizer.skewed-join-optimization.skewed-threshold") + .memoryType() + .defaultValue(MemorySize.ofMebiBytes(256)) + .withDescription( + "When a join operator instance encounters input data that exceeds N times the median " + + "size of other concurrent join operator instances, it is considered skewed " + + "(where N represents the table.optimizer.skewed-join-optimization.skewed-factor). " + + "In such cases, Flink may automatically split the skewed data into multiple " + + "parts to ensure a more balanced data distribution, unless the data volume " + + "is below this skewed threshold."); + /** * The data volume of build side needs to be under this value. If the data volume of build side * is too large, the building overhead will be too large, which may lead to a negative impact on @@ -352,4 +395,34 @@ public InlineElement getDescription() { return description; } } + + /** Strategies used for {@link #TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_STRATEGY}. */ + @PublicEvolving + public enum AdaptiveSkewedJoinOptimizationStrategy implements DescribedEnum { + AUTO("auto", text(" Flink will automatically perform this optimization.")), + FORCED( + "forced", + text( + "Flink will perform this optimization even if it introduces extra hash shuffling.")), + NONE("none", text("Skewed join optimization will not be performed.")); + + private final String value; + + private final InlineElement description; + + AdaptiveSkewedJoinOptimizationStrategy(String value, InlineElement description) { + this.value = value; + this.description = description; + } + + @Override + public String toString() { + return value; + } + + @Override + public InlineElement getDescription() { + return description; + } + } } diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java --- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/AdaptiveJoinProcessor.java @@ -142,6 +142,11 @@ private boolean isAdaptiveJoinEnabled(ProcessorContext context) { != OptimizerConfigOptions.AdaptiveBroadcastJoinStrategy.NONE && !TableConfigUtils.isOperatorDisabled( tableConfig, OperatorType.BroadcastHashJoin); + isAdaptiveJoinEnabled |= + tableConfig.get( + OptimizerConfigOptions + .TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_STRATEGY) + != OptimizerConfigOptions.AdaptiveSkewedJoinOptimizationStrategy.NONE; JobManagerOptions.SchedulerType schedulerType = context.getPlanner() .getExecEnv() diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala --- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/delegation/BatchPlanner.scala @@ -20,7 +20,7 @@ package org.apache.flink.table.planner.delegation import org.apache.flink.api.common.RuntimeExecutionMode import org.apache.flink.api.dag.Transformation import org.apache.flink.configuration.ExecutionOptions -import org.apache.flink.runtime.scheduler.adaptivebatch.StreamGraphOptimizationStrategy +import org.apache.flink.runtime.scheduler.adaptivebatch.{BatchExecutionOptionsInternal, StreamGraphOptimizationStrategy} import org.apache.flink.table.api._ import org.apache.flink.table.api.config.OptimizerConfigOptions import org.apache.flink.table.catalog.{CatalogManager, FunctionCatalog} @@ -35,7 +35,7 @@ import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodePlanDumper import org.apache.flink.table.planner.plan.optimize.{BatchCommonSubGraphBasedOptimizer, Optimizer} import org.apache.flink.table.planner.plan.utils.FlinkRelOptUtil import org.apache.flink.table.planner.utils.DummyStreamExecutionEnvironment -import org.apache.flink.table.runtime.strategy.{AdaptiveBroadcastJoinOptimizationStrategy, PostProcessAdaptiveJoinStrategy} +import org.apache.flink.table.runtime.strategy.{AdaptiveBroadcastJoinOptimizationStrategy, AdaptiveSkewedJoinOptimizationStrategy, PostProcessAdaptiveJoinStrategy} import org.apache.calcite.plan.{ConventionTraitDef, RelTrait, RelTraitDef} import org.apache.calcite.rel.RelCollationTraitDef @@ -106,11 +106,27 @@ class BatchPlanner( super.afterTranslation() val configuration = getTableConfig val optimizationStrategies = new util.ArrayList[String]() - if ( - configuration.get(OptimizerConfigOptions.TABLE_OPTIMIZER_ADAPTIVE_BROADCAST_JOIN_STRATEGY) - != OptimizerConfigOptions.AdaptiveBroadcastJoinStrategy.NONE - ) { + val isAdaptiveBroadcastJoinEnabled = configuration.get( + OptimizerConfigOptions.TABLE_OPTIMIZER_ADAPTIVE_BROADCAST_JOIN_STRATEGY) != OptimizerConfigOptions.AdaptiveBroadcastJoinStrategy.NONE + val isAdaptiveSkewedJoinEnabled = configuration.get( + OptimizerConfigOptions.TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_STRATEGY) != OptimizerConfigOptions.AdaptiveSkewedJoinOptimizationStrategy.NONE + if (isAdaptiveBroadcastJoinEnabled) { optimizationStrategies.add(classOf[AdaptiveBroadcastJoinOptimizationStrategy].getName) + } + if (isAdaptiveSkewedJoinEnabled) { + optimizationStrategies.add(classOf[AdaptiveSkewedJoinOptimizationStrategy].getName) + configuration.set( + BatchExecutionOptionsInternal.ADAPTIVE_SKEWED_OPTIMIZATION_SKEWED_FACTOR, + configuration.get( + OptimizerConfigOptions.TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_SKEWED_FACTOR) + ) + configuration.set( + BatchExecutionOptionsInternal.ADAPTIVE_SKEWED_OPTIMIZATION_SKEWED_THRESHOLD, + configuration.get( + OptimizerConfigOptions.TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_SKEWED_THRESHOLD) + ) + } + if (isAdaptiveBroadcastJoinEnabled || isAdaptiveSkewedJoinEnabled) { optimizationStrategies.add(classOf[PostProcessAdaptiveJoinStrategy].getName) } configuration.set( diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveBroadcastJoinOptimizationStrategy.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveBroadcastJoinOptimizationStrategy.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveBroadcastJoinOptimizationStrategy.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveBroadcastJoinOptimizationStrategy.java @@ -40,8 +40,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import static org.apache.flink.table.runtime.strategy.AdaptiveJoinOptimizationUtils.filterEdges; +import static org.apache.flink.table.runtime.strategy.AdaptiveJoinOptimizationUtils.isBroadcastJoin; +import static org.apache.flink.table.runtime.strategy.AdaptiveJoinOptimizationUtils.isBroadcastJoinDisabled; import static org.apache.flink.util.Preconditions.checkState; /** The stream graph optimization strategy of adaptive broadcast join. */ @@ -77,6 +79,10 @@ protected void tryOptimizeAdaptiveJoin( ImmutableStreamNode adaptiveJoinNode, List upstreamStreamEdges, AdaptiveJoin adaptiveJoin) { + if (!canPerformOptimization( + adaptiveJoinNode, context.getStreamGraph().getConfiguration())) { + return; + } for (ImmutableStreamEdge upstreamEdge : upstreamStreamEdges) { IntermediateDataSetID relatedDataSetId = context.getConsumedIntermediateDataSetId(upstreamEdge.getEdgeId()); @@ -165,6 +171,11 @@ protected void tryOptimizeAdaptiveJoin( } } + private boolean canPerformOptimization( + ImmutableStreamNode adaptiveJoinNode, ReadableConfig config) { + return !isBroadcastJoinDisabled(config) && !isBroadcastJoin(adaptiveJoinNode); + } + private void aggregatedInputBytesByTypeNumber( ImmutableStreamNode adaptiveJoinNode, int typeNumber, long producedBytes) { Integer streamNodeId = adaptiveJoinNode.getId(); @@ -174,13 +185,6 @@ private void aggregatedInputBytesByTypeNumber( .merge(typeNumber, producedBytes, Long::sum); } - private List filterEdges( - List inEdges, int typeNumber) { - return inEdges.stream() - .filter(e -> e.getTypeNumber() == typeNumber) - .collect(Collectors.toList()); - } - private List generateStreamEdgeUpdateRequestInfos( List modifiedEdges, StreamPartitioner outputPartitioner) { List streamEdgeUpdateRequestInfos = new ArrayList<>(); diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveJoinOptimizationUtils.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveJoinOptimizationUtils.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveJoinOptimizationUtils.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.flink.table.runtime.strategy; + +import org.apache.flink.configuration.ReadableConfig; +import org.apache.flink.streaming.api.graph.util.ImmutableStreamEdge; +import org.apache.flink.streaming.api.graph.util.ImmutableStreamNode; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.apache.flink.table.api.config.ExecutionConfigOptions.TABLE_EXEC_DISABLED_OPERATORS; + +/** Utils for adaptive join optimization strategies. */ +public class AdaptiveJoinOptimizationUtils { + + public static List filterEdges( + List inEdges, int typeNumber) { + return inEdges.stream() + .filter(e -> e.getTypeNumber() == typeNumber) + .collect(Collectors.toList()); + } + + public static boolean isBroadcastJoin(ImmutableStreamNode adaptiveJoinNode) { + return adaptiveJoinNode.getInEdges().stream() + .anyMatch(ImmutableStreamEdge::isBroadcastEdge); + } + + public static boolean isBroadcastJoinDisabled(ReadableConfig config) { + String value = config.get(TABLE_EXEC_DISABLED_OPERATORS); + if (value == null) { + return false; + } + String[] operators = value.split(","); + for (String operator : operators) { + operator = operator.trim(); + if (operator.isEmpty()) { + continue; + } + if (operator.equals("HashJoin") || operator.equals("BroadcastHashJoin")) { + return true; + } + } + return false; + } +} diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveSkewedJoinOptimizationStrategy.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveSkewedJoinOptimizationStrategy.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/AdaptiveSkewedJoinOptimizationStrategy.java @@ -0,0 +1,311 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.flink.table.runtime.strategy; + +import org.apache.flink.configuration.ReadableConfig; +import org.apache.flink.runtime.jobgraph.IntermediateDataSetID; +import org.apache.flink.runtime.scheduler.adaptivebatch.AllToAllBlockingResultInfo; +import org.apache.flink.runtime.scheduler.adaptivebatch.BlockingResultInfo; +import org.apache.flink.runtime.scheduler.adaptivebatch.OperatorsFinished; +import org.apache.flink.streaming.api.graph.StreamGraphContext; +import org.apache.flink.streaming.api.graph.util.ImmutableStreamEdge; +import org.apache.flink.streaming.api.graph.util.ImmutableStreamNode; +import org.apache.flink.streaming.api.graph.util.StreamEdgeUpdateRequestInfo; +import org.apache.flink.streaming.runtime.partitioner.ForwardForConsecutiveHashPartitioner; +import org.apache.flink.streaming.runtime.partitioner.StreamPartitioner; +import org.apache.flink.table.api.config.OptimizerConfigOptions; +import org.apache.flink.table.runtime.operators.join.FlinkJoinType; +import org.apache.flink.table.runtime.operators.join.adaptive.AdaptiveJoin; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.apache.flink.runtime.scheduler.adaptivebatch.util.VertexParallelismAndInputInfosDeciderUtils.computeSkewThreshold; +import static org.apache.flink.runtime.scheduler.adaptivebatch.util.VertexParallelismAndInputInfosDeciderUtils.median; +import static org.apache.flink.table.runtime.strategy.AdaptiveJoinOptimizationUtils.filterEdges; +import static org.apache.flink.table.runtime.strategy.AdaptiveJoinOptimizationUtils.isBroadcastJoin; +import static org.apache.flink.util.Preconditions.checkNotNull; +import static org.apache.flink.util.Preconditions.checkState; + +/** The stream graph optimization strategy of adaptive skewed join. */ +public class AdaptiveSkewedJoinOptimizationStrategy + extends BaseAdaptiveJoinOperatorOptimizationStrategy { + private static final Logger LOG = + LoggerFactory.getLogger(AdaptiveSkewedJoinOptimizationStrategy.class); + + private static final int LEFT_INPUT_TYPE_NUMBER = 1; + private static final int RIGHT_INPUT_TYPE_NUMBER = 2; + + private Map> aggregatedProducedBytesByTypeNumberAndNodeId; + + private OptimizerConfigOptions.AdaptiveSkewedJoinOptimizationStrategy + adaptiveSkewedJoinOptimizationStrategy; + private long skewedThresholdInBytes; + private double skewedFactor; + + @Override + public void initialize(StreamGraphContext context) { + ReadableConfig config = context.getStreamGraph().getConfiguration(); + aggregatedProducedBytesByTypeNumberAndNodeId = new HashMap<>(); + adaptiveSkewedJoinOptimizationStrategy = + config.get( + OptimizerConfigOptions + .TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_STRATEGY); + skewedFactor = + config.get( + OptimizerConfigOptions + .TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_SKEWED_FACTOR); + skewedThresholdInBytes = + config.get( + OptimizerConfigOptions + .TABLE_OPTIMIZER_ADAPTIVE_SKEWED_JOIN_OPTIMIZATION_SKEWED_THRESHOLD) + .getBytes(); + } + + @Override + public boolean onOperatorsFinished( + OperatorsFinished operatorsFinished, StreamGraphContext context) throws Exception { + visitDownstreamAdaptiveJoinNode(operatorsFinished, context); + + return true; + } + + @Override + void tryOptimizeAdaptiveJoin( + OperatorsFinished operatorsFinished, + StreamGraphContext context, + ImmutableStreamNode adaptiveJoinNode, + List upstreamStreamEdges, + AdaptiveJoin adaptiveJoin) { + if (!canPerformOptimization(adaptiveJoinNode)) { + return; + } + for (ImmutableStreamEdge edge : upstreamStreamEdges) { + BlockingResultInfo resultInfo = getBlockingResultInfo(operatorsFinished, context, edge); + checkState(resultInfo instanceof AllToAllBlockingResultInfo); + aggregatedProducedBytesByTypeNumber( + adaptiveJoinNode, + edge.getTypeNumber(), + ((AllToAllBlockingResultInfo) resultInfo).getAggregatedSubpartitionBytes()); + } + if (context.areAllUpstreamNodesFinished(adaptiveJoinNode)) { + applyAdaptiveSkewedJoinOptimization( + context, adaptiveJoinNode, adaptiveJoin.getJoinType()); + freeNodeStatistic(adaptiveJoinNode.getId()); + } + } + + private boolean canPerformOptimization(ImmutableStreamNode adaptiveJoinNode) { + // For broadcast joins, especially those generated by + // AdaptiveBroadcastJoinOptimizationStrategy, skip perform optimization to + // avoid unexpected problems. + if (isBroadcastJoin(adaptiveJoinNode)) { + return false; + } + if (adaptiveSkewedJoinOptimizationStrategy + == OptimizerConfigOptions.AdaptiveSkewedJoinOptimizationStrategy.AUTO) { + return !existExactForwardOutEdge(adaptiveJoinNode.getOutEdges()) + && !existForwardForConsecutiveHashOutEdge(adaptiveJoinNode.getOutEdges()); + } else if (adaptiveSkewedJoinOptimizationStrategy + == OptimizerConfigOptions.AdaptiveSkewedJoinOptimizationStrategy.FORCED) { + return !existExactForwardOutEdge(adaptiveJoinNode.getOutEdges()); + } else { + return false; + } + } + + private static BlockingResultInfo getBlockingResultInfo( + OperatorsFinished operatorsFinished, + StreamGraphContext context, + ImmutableStreamEdge edge) { + List resultInfos = + operatorsFinished.getResultInfoMap().get(edge.getSourceId()); + IntermediateDataSetID intermediateDataSetId = + context.getConsumedIntermediateDataSetId(edge.getEdgeId()); + for (BlockingResultInfo result : resultInfos) { + if (result.getResultId().equals(intermediateDataSetId)) { + return result; + } + } + throw new IllegalStateException( + "No matching BlockingResultInfo found for edge ID: " + edge.getEdgeId()); + } + + private void aggregatedProducedBytesByTypeNumber( + ImmutableStreamNode adaptiveJoinNode, int typeNumber, List subpartitionBytes) { + Integer streamNodeId = adaptiveJoinNode.getId(); + long[] aggregatedSubpartitionBytes = + aggregatedProducedBytesByTypeNumberAndNodeId + .computeIfAbsent(streamNodeId, k -> new HashMap<>()) + .computeIfAbsent( + typeNumber, (ignore) -> new long[subpartitionBytes.size()]); + checkState(subpartitionBytes.size() == aggregatedSubpartitionBytes.length); + for (int i = 0; i < subpartitionBytes.size(); i++) { + aggregatedSubpartitionBytes[i] += subpartitionBytes.get(i); + } + } + + private void applyAdaptiveSkewedJoinOptimization( + StreamGraphContext context, + ImmutableStreamNode adaptiveJoinNode, + FlinkJoinType joinType) { + long[] leftInputSize = + aggregatedProducedBytesByTypeNumberAndNodeId + .get(adaptiveJoinNode.getId()) + .get(LEFT_INPUT_TYPE_NUMBER); + checkState( + leftInputSize != null, + "Left input bytes of adaptive join [%s] is unknown, which is unexpected.", + adaptiveJoinNode.getId()); + long[] rightInputSize = + aggregatedProducedBytesByTypeNumberAndNodeId + .get(adaptiveJoinNode.getId()) + .get(RIGHT_INPUT_TYPE_NUMBER); + checkState( + rightInputSize != null, + "Right input bytes of adaptive join [%s] is unknown, which is unexpected.", + adaptiveJoinNode.getId()); + + long leftSkewedThreshold = + computeSkewThreshold(median(leftInputSize), skewedFactor, skewedThresholdInBytes); + long rightSkewedThreshold = + computeSkewThreshold(median(rightInputSize), skewedFactor, skewedThresholdInBytes); + + boolean isLeftOptimizable = false; + boolean isRightOptimizable = false; + switch (joinType) { + case RIGHT: + isRightOptimizable = true; + break; + case INNER: + isLeftOptimizable = true; + isRightOptimizable = true; + break; + case LEFT: + case SEMI: + case ANTI: + isLeftOptimizable = true; + break; + case FULL: + default: + throw new IllegalStateException( + String.format("Unexpected join type %s.", joinType)); + } + + isLeftOptimizable = + isLeftOptimizable + & existBytesLargerThanThreshold(leftInputSize, leftSkewedThreshold); + isRightOptimizable = + isRightOptimizable + & existBytesLargerThanThreshold(rightInputSize, rightSkewedThreshold); + + if (isLeftOptimizable) { + boolean isModificationSucceed = + tryModifyInputAndOutputEdges(context, adaptiveJoinNode, LEFT_INPUT_TYPE_NUMBER); + LOG.info( + "Apply skewed join optimization {} for left input of node {}.", + isModificationSucceed ? "succeeded" : "failed", + adaptiveJoinNode.getId()); + } + if (isRightOptimizable) { + boolean isModificationSucceed = + tryModifyInputAndOutputEdges( + context, adaptiveJoinNode, RIGHT_INPUT_TYPE_NUMBER); + LOG.info( + "Apply skewed join optimization {} for right input of node {}.", + isModificationSucceed ? "succeeded" : "failed", + adaptiveJoinNode.getId()); + } + } + + private static boolean tryModifyInputAndOutputEdges( + StreamGraphContext context, ImmutableStreamNode adaptiveJoinNode, int typeNumber) { + List modifiedRequests = new ArrayList<>(); + // Modify the IntraInputKeyCorrelation of all input edges with the specified typeNumber to + // false. + modifiedRequests.addAll( + generateCorrelationModificationRequestInfos( + filterEdges(adaptiveJoinNode.getInEdges(), typeNumber))); + // Modify ForwardForConsecutiveHashPartitioner of the output edges to HashPartitioner + modifiedRequests.addAll( + generateForwardPartitionerModificationRequestInfos( + adaptiveJoinNode.getOutEdges(), context)); + return context.modifyStreamEdge(modifiedRequests); + } + + private static List generateCorrelationModificationRequestInfos( + List streamEdges) { + List streamEdgeUpdateRequestInfos = new ArrayList<>(); + for (ImmutableStreamEdge edge : streamEdges) { + streamEdgeUpdateRequestInfos.add( + new StreamEdgeUpdateRequestInfo( + edge.getEdgeId(), edge.getSourceId(), edge.getTargetId()) + .withIntraInputKeyCorrelated(false)); + } + return streamEdgeUpdateRequestInfos; + } + + private static List + generateForwardPartitionerModificationRequestInfos( + List streamEdges, StreamGraphContext context) { + List streamEdgeUpdateRequestInfos = new ArrayList<>(); + for (ImmutableStreamEdge edge : streamEdges) { + if (edge.isForwardForConsecutiveHashEdge()) { + StreamPartitioner partitioner = + checkNotNull( + context.getOutputPartitioner( + edge.getEdgeId(), edge.getSourceId(), edge.getTargetId())); + StreamPartitioner newPartitioner = + ((ForwardForConsecutiveHashPartitioner) partitioner) + .getHashPartitioner(); + streamEdgeUpdateRequestInfos.add( + new StreamEdgeUpdateRequestInfo( + edge.getEdgeId(), edge.getSourceId(), edge.getTargetId()) + .withOutputPartitioner(newPartitioner)); + } + } + return streamEdgeUpdateRequestInfos; + } + + private void freeNodeStatistic(Integer nodeId) { + aggregatedProducedBytesByTypeNumberAndNodeId.remove(nodeId); + } + + private static boolean existBytesLargerThanThreshold(long[] inputBytes, long threshold) { + for (long byteSize : inputBytes) { + if (byteSize > threshold) { + return true; + } + } + return false; + } + + private static boolean existExactForwardOutEdge(List edges) { + return edges.stream().anyMatch(ImmutableStreamEdge::isExactForwardEdge); + } + + private static boolean existForwardForConsecutiveHashOutEdge(List edges) { + return edges.stream().anyMatch(ImmutableStreamEdge::isForwardForConsecutiveHashEdge); + } +}