File size: 38,521 Bytes
5a9e79d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | 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<StreamEdgeUpdateRequestInfo> 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<AdaptiveSkewedJoinOptimizationStrategy>
+ 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<Double>
+ 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<MemorySize>
+ 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<ImmutableStreamEdge> 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<ImmutableStreamEdge> filterEdges(
- List<ImmutableStreamEdge> inEdges, int typeNumber) {
- return inEdges.stream()
- .filter(e -> e.getTypeNumber() == typeNumber)
- .collect(Collectors.toList());
- }
-
private List<StreamEdgeUpdateRequestInfo> generateStreamEdgeUpdateRequestInfos(
List<ImmutableStreamEdge> modifiedEdges, StreamPartitioner<?> outputPartitioner) {
List<StreamEdgeUpdateRequestInfo> 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<ImmutableStreamEdge> filterEdges(
+ List<ImmutableStreamEdge> 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<Integer, Map<Integer, long[]>> 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<ImmutableStreamEdge> 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<BlockingResultInfo> 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<Long> 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<StreamEdgeUpdateRequestInfo> 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<StreamEdgeUpdateRequestInfo> generateCorrelationModificationRequestInfos(
+ List<ImmutableStreamEdge> streamEdges) {
+ List<StreamEdgeUpdateRequestInfo> streamEdgeUpdateRequestInfos = new ArrayList<>();
+ for (ImmutableStreamEdge edge : streamEdges) {
+ streamEdgeUpdateRequestInfos.add(
+ new StreamEdgeUpdateRequestInfo(
+ edge.getEdgeId(), edge.getSourceId(), edge.getTargetId())
+ .withIntraInputKeyCorrelated(false));
+ }
+ return streamEdgeUpdateRequestInfos;
+ }
+
+ private static List<StreamEdgeUpdateRequestInfo>
+ generateForwardPartitionerModificationRequestInfos(
+ List<ImmutableStreamEdge> streamEdges, StreamGraphContext context) {
+ List<StreamEdgeUpdateRequestInfo> 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<ImmutableStreamEdge> edges) {
+ return edges.stream().anyMatch(ImmutableStreamEdge::isExactForwardEdge);
+ }
+
+ private static boolean existForwardForConsecutiveHashOutEdge(List<ImmutableStreamEdge> edges) {
+ return edges.stream().anyMatch(ImmutableStreamEdge::isForwardForConsecutiveHashEdge);
+ }
+}
|