diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java --- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java +++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java @@ -725,6 +725,33 @@ public class ExecutionConfigOptions { "Set whether to use the SQL/Table operators based on the asynchronous state api. " + "Default value is false."); + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_DELTA_JOIN_CACHE_ENABLED = + key("table.exec.delta-join.cache-enabled") + .booleanType() + .defaultValue(true) + .withDescription( + "Whether to enable the cache of delta join. If enabled, the delta join caches the " + + "records from remote dim table. Default is true."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_DELTA_JOIN_LEFT_CACHE_SIZE = + key("table.exec.delta-join.left.cache-size") + .longType() + .defaultValue(10000L) + .withDescription( + "The cache size used to cache the lookup results of the left table in delta join. " + + "This value must be positive when enabling cache. Default is 10000."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_DELTA_JOIN_RIGHT_CACHE_SIZE = + key("table.exec.delta-join.right.cache-size") + .longType() + .defaultValue(10000L) + .withDescription( + "The cache size used to cache the lookup results of the right table in delta join. " + + "This value must be positive when enabling cache. Default is 10000."); + // ------------------------------------------------------------------------------------------ // Enum option types // ------------------------------------------------------------------------------------------ diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java --- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeltaJoin.java @@ -20,10 +20,12 @@ import org.apache.flink.FlinkVersion; import org.apache.flink.api.dag.Transformation; +import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.configuration.ReadableConfig; import org.apache.flink.streaming.api.functions.async.AsyncFunction; import org.apache.flink.streaming.api.operators.StreamOperatorFactory; import org.apache.flink.streaming.api.transformations.TwoInputTransformation; +import org.apache.flink.table.api.config.ExecutionConfigOptions; import org.apache.flink.table.catalog.DataTypeFactory; import org.apache.flink.table.data.RowData; import org.apache.flink.table.data.conversion.DataStructureConverter; @@ -83,6 +85,7 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecDeltaJoin.DELTA_JOIN_TRANSFORMATION; import static org.apache.flink.table.planner.plan.utils.DeltaJoinUtil.getUnwrappedAsyncLookupFunction; @@ -234,11 +237,17 @@ protected Transformation translateToPlanInternal( RowDataKeySelector leftJoinKeySelector = KeySelectorUtil.getRowDataSelector( classLoader, leftJoinKeys, InternalTypeInfo.of(leftStreamType)); + // currently, delta join only supports consuming INSERT-ONLY stream + RowDataKeySelector leftUpsertKeySelector = + getUpsertKeySelector(new int[0], leftStreamType, classLoader); // right side selector RowDataKeySelector rightJoinKeySelector = KeySelectorUtil.getRowDataSelector( classLoader, rightJoinKeys, InternalTypeInfo.of(rightStreamType)); + // currently, delta join only supports consuming INSERT-ONLY stream + RowDataKeySelector rightUpsertKeySelector = + getUpsertKeySelector(new int[0], rightStreamType, classLoader); StreamOperatorFactory operatorFactory = createAsyncLookupDeltaJoin( @@ -252,7 +261,9 @@ protected Transformation translateToPlanInternal( leftStreamType, rightStreamType, leftJoinKeySelector, + leftUpsertKeySelector, rightJoinKeySelector, + rightUpsertKeySelector, classLoader); final TwoInputTransformation transform = @@ -282,7 +293,9 @@ private StreamOperatorFactory createAsyncLookupDeltaJoin( RowType leftStreamType, RowType rightStreamType, RowDataKeySelector leftJoinKeySelector, + RowDataKeySelector leftUpsertKeySelector, RowDataKeySelector rightJoinKeySelector, + RowDataKeySelector rightUpsertKeySelector, ClassLoader classLoader) { DataTypeFactory dataTypeFactory = @@ -299,6 +312,10 @@ private StreamOperatorFactory createAsyncLookupDeltaJoin( leftStreamType, rightStreamType, leftLookupKeys, + leftJoinKeySelector, + leftUpsertKeySelector, + rightJoinKeySelector, + rightUpsertKeySelector, false); AsyncDeltaJoinRunner rightLookupTableAsyncFunction = @@ -312,15 +329,23 @@ private StreamOperatorFactory createAsyncLookupDeltaJoin( leftStreamType, rightStreamType, rightLookupKeys, + leftJoinKeySelector, + leftUpsertKeySelector, + rightJoinKeySelector, + rightUpsertKeySelector, true); + Tuple2 leftRightCacheSize = getCacheSize(config); + return new StreamingDeltaJoinOperatorFactory( rightLookupTableAsyncFunction, leftLookupTableAsyncFunction, leftJoinKeySelector, rightJoinKeySelector, asyncLookupOptions.asyncTimeout, asyncLookupOptions.asyncBufferCapacity, + leftRightCacheSize.f0, + leftRightCacheSize.f1, leftStreamType, rightStreamType); } @@ -336,6 +361,10 @@ private AsyncDeltaJoinRunner createAsyncDeltaJoinRunner( RowType leftStreamSideType, RowType rightStreamSideType, Map lookupKeys, + RowDataKeySelector leftJoinKeySelector, + RowDataKeySelector leftUpsertKeySelector, + RowDataKeySelector rightJoinKeySelector, + RowDataKeySelector rightUpsertKeySelector, boolean treatRightAsLookupTable) { RelOptTable lookupTable = treatRightAsLookupTable ? rightTempTable : leftTempTable; RowType streamSideType = treatRightAsLookupTable ? leftStreamSideType : rightStreamSideType; @@ -409,8 +438,13 @@ private AsyncDeltaJoinRunner createAsyncDeltaJoinRunner( (DataStructureConverter) lookupSideFetcherConverter, lookupSideGeneratedResultFuture, InternalSerializers.create(lookupTableSourceRowType), + leftJoinKeySelector, + leftUpsertKeySelector, + rightJoinKeySelector, + rightUpsertKeySelector, asyncLookupOptions.asyncBufferCapacity, - treatRightAsLookupTable); + treatRightAsLookupTable, + enableCache(config)); } /** @@ -449,4 +483,33 @@ public RexNode visitInputRef(RexInputRef inputRef) { return condition.accept(converter); } + + private RowDataKeySelector getUpsertKeySelector( + int[] upsertKey, RowType rowType, ClassLoader classLoader) { + final int[] rightUpsertKeys; + if (upsertKey.length > 0) { + rightUpsertKeys = upsertKey; + } else { + rightUpsertKeys = IntStream.range(0, rowType.getFields().size()).toArray(); + } + return KeySelectorUtil.getRowDataSelector( + classLoader, rightUpsertKeys, InternalTypeInfo.of(rowType)); + } + + private boolean enableCache(ReadableConfig config) { + return config.get(ExecutionConfigOptions.TABLE_EXEC_DELTA_JOIN_CACHE_ENABLED); + } + + /** Get the left cache size and right size. */ + private Tuple2 getCacheSize(ReadableConfig config) { + long leftCacheSize = + config.get(ExecutionConfigOptions.TABLE_EXEC_DELTA_JOIN_LEFT_CACHE_SIZE); + long rightCacheSize = + config.get(ExecutionConfigOptions.TABLE_EXEC_DELTA_JOIN_RIGHT_CACHE_SIZE); + if ((leftCacheSize <= 0 || rightCacheSize <= 0) && enableCache(config)) { + throw new IllegalArgumentException( + "Cache size in delta join must be positive when enabling cache."); + } + return Tuple2.of(leftCacheSize, rightCacheSize); + } } diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/StreamingDeltaJoinOperatorFactory.java @@ -36,13 +36,17 @@ public class StreamingDeltaJoinOperatorFactory extends AbstractStreamOperatorFac YieldingOperatorFactory { private final AsyncDeltaJoinRunner rightLookupTableAsyncFunction; - private final RowDataKeySelector rightJoinKeySelector; private final AsyncDeltaJoinRunner leftLookupTableAsyncFunction; + private final RowDataKeySelector leftJoinKeySelector; + private final RowDataKeySelector rightJoinKeySelector; private final long timeout; private final int capacity; + private final long leftSideCacheSize; + private final long rightSideCacheSize; + private final RowType leftStreamType; private final RowType rightStreamType; @@ -53,6 +57,8 @@ public StreamingDeltaJoinOperatorFactory( RowDataKeySelector rightJoinKeySelector, long timeout, int capacity, + long leftSideCacheSize, + long rightSideCacheSize, RowType leftStreamType, RowType rightStreamType) { this.rightLookupTableAsyncFunction = rightLookupTableAsyncFunction; @@ -61,6 +67,8 @@ public StreamingDeltaJoinOperatorFactory( this.rightJoinKeySelector = rightJoinKeySelector; this.timeout = timeout; this.capacity = capacity; + this.leftSideCacheSize = leftSideCacheSize; + this.rightSideCacheSize = rightSideCacheSize; this.leftStreamType = leftStreamType; this.rightStreamType = rightStreamType; } @@ -79,6 +87,8 @@ public > T createStreamOperator( capacity, processingTimeService, mailboxExecutor, + leftSideCacheSize, + rightSideCacheSize, leftStreamType, rightStreamType); deltaJoinOperator.setup( diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/AsyncDeltaJoinRunner.java @@ -31,15 +31,21 @@ import org.apache.flink.table.runtime.collector.TableFunctionResultFuture; import org.apache.flink.table.runtime.generated.GeneratedFunction; import org.apache.flink.table.runtime.generated.GeneratedResultFuture; +import org.apache.flink.table.runtime.keyselector.RowDataKeySelector; import org.apache.flink.table.runtime.typeutils.RowDataSerializer; +import org.apache.flink.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Optional; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -64,6 +70,22 @@ public class AsyncDeltaJoinRunner extends RichAsyncFunction { private final boolean treatRightAsLookupTable; + private final boolean enableCache; + + /** Selector to get join key from left input. */ + private final RowDataKeySelector leftJoinKeySelector; + + /** Selector to get upsert key from left input. */ + private final RowDataKeySelector leftUpsertKeySelector; + + /** Selector to get join key from right input. */ + private final RowDataKeySelector rightJoinKeySelector; + + /** Selector to get upsert key from right input. */ + private final RowDataKeySelector rightUpsertKeySelector; + + private transient DeltaJoinCache cache; + /** * Buffers {@link ResultFuture} to avoid newInstance cost when processing elements every time. * We use {@link BlockingQueue} to make sure the head {@link ResultFuture}s are available. @@ -85,14 +107,28 @@ public AsyncDeltaJoinRunner( DataStructureConverter fetcherConverter, GeneratedResultFuture> generatedResultFuture, RowDataSerializer lookupSideRowSerializer, + RowDataKeySelector leftJoinKeySelector, + RowDataKeySelector leftUpsertKeySelector, + RowDataKeySelector rightJoinKeySelector, + RowDataKeySelector rightUpsertKeySelector, int asyncBufferCapacity, - boolean treatRightAsLookupTable) { + boolean treatRightAsLookupTable, + boolean enableCache) { this.generatedFetcher = generatedFetcher; this.fetcherConverter = fetcherConverter; this.generatedResultFuture = generatedResultFuture; this.lookupSideRowSerializer = lookupSideRowSerializer; + this.leftJoinKeySelector = leftJoinKeySelector; + this.leftUpsertKeySelector = leftUpsertKeySelector; + this.rightJoinKeySelector = rightJoinKeySelector; + this.rightUpsertKeySelector = rightUpsertKeySelector; this.asyncBufferCapacity = asyncBufferCapacity; this.treatRightAsLookupTable = treatRightAsLookupTable; + this.enableCache = enableCache; + } + + public void setCache(DeltaJoinCache cache) { + this.cache = cache; } @Override @@ -121,7 +157,11 @@ public void open(OpenContext openContext) throws Exception { resultFutureBuffer, createFetcherResultFuture(openContext), fetcherConverter, - treatRightAsLookupTable); + treatRightAsLookupTable, + leftUpsertKeySelector, + rightUpsertKeySelector, + enableCache, + cache); // add will throw exception immediately if the queue is full which should never happen resultFutureBuffer.add(rf); allResultFutures.add(rf); @@ -141,8 +181,27 @@ public void open(OpenContext openContext) throws Exception { public void asyncInvoke(RowData input, ResultFuture resultFuture) throws Exception { JoinedRowResultFuture outResultFuture = resultFutureBuffer.take(); + RowData streamJoinKey = null; + if (enableCache) { + if (treatRightAsLookupTable) { + streamJoinKey = leftJoinKeySelector.getKey(input); + cache.requestRightCache(); + } else { + streamJoinKey = rightJoinKeySelector.getKey(input); + cache.requestLeftCache(); + } + } + // the input row is copied when object reuse in StreamDeltaJoinOperator - outResultFuture.reset(input, resultFuture); + outResultFuture.reset(streamJoinKey, input, resultFuture); + + if (enableCache) { + Optional> dataFromCache = tryGetDataFromCache(streamJoinKey); + if (dataFromCache.isPresent()) { + outResultFuture.complete(dataFromCache.get()); + return; + } + } long startTime = System.currentTimeMillis(); // fetcher has copied the input field when object reuse is enabled @@ -177,6 +236,30 @@ public AsyncFunction getFetcher() { return fetcher; } + @VisibleForTesting + public DeltaJoinCache getCache() { + return cache; + } + + private Optional> tryGetDataFromCache(RowData joinKey) { + Preconditions.checkState(enableCache); + + if (treatRightAsLookupTable) { + LinkedHashMap rightRows = cache.getData(joinKey, true); + if (rightRows != null) { + cache.hitRightCache(); + return Optional.of(rightRows.values()); + } + } else { + LinkedHashMap leftRows = cache.getData(joinKey, false); + if (leftRows != null) { + cache.hitLeftCache(); + return Optional.of(leftRows.values()); + } + } + return Optional.empty(); + } + /** * The {@link JoinedRowResultFuture} is used to combine left {@link RowData} and right {@link * RowData} into {@link JoinedRowData}. @@ -191,26 +274,45 @@ public static final class JoinedRowResultFuture implements ResultFuture private final TableFunctionResultFuture joinConditionResultFuture; private final DataStructureConverter resultConverter; + private final boolean enableCache; + private final DeltaJoinCache cache; + private final DelegateResultFuture delegate; private final boolean treatRightAsLookupTable; + private final RowDataKeySelector leftUpsertKeySelector; + private final RowDataKeySelector rightUpsertKeySelector; + + private @Nullable RowData streamJoinKey; private RowData streamRow; private ResultFuture realOutput; private JoinedRowResultFuture( BlockingQueue resultFutureBuffer, TableFunctionResultFuture joinConditionResultFuture, DataStructureConverter resultConverter, - boolean treatRightAsLookupTable) { + boolean treatRightAsLookupTable, + RowDataKeySelector leftUpsertKeySelector, + RowDataKeySelector rightUpsertKeySelector, + boolean enableCache, + DeltaJoinCache cache) { this.resultFutureBuffer = resultFutureBuffer; this.joinConditionResultFuture = joinConditionResultFuture; this.resultConverter = resultConverter; + this.enableCache = enableCache; + this.cache = cache; this.delegate = new DelegateResultFuture(); this.treatRightAsLookupTable = treatRightAsLookupTable; + this.leftUpsertKeySelector = leftUpsertKeySelector; + this.rightUpsertKeySelector = rightUpsertKeySelector; } - public void reset(RowData row, ResultFuture realOutput) { + public void reset( + @Nullable RowData joinKey, RowData row, ResultFuture realOutput) { + Preconditions.checkState( + (enableCache && joinKey != null) || (!enableCache && joinKey == null)); this.realOutput = realOutput; + this.streamJoinKey = joinKey; this.streamRow = row; joinConditionResultFuture.setInput(row); joinConditionResultFuture.setResultFuture(delegate); @@ -219,6 +321,19 @@ public void reset(RowData row, ResultFuture realOutput) { @Override public void complete(Collection result) { + if (result == null) { + result = Collections.emptyList(); + } + + // now we have received the rows from the lookup table, try to set them to the cache + try { + updateCacheIfNecessary(result); + } catch (Throwable t) { + LOG.info("Failed to update the cache", t); + completeExceptionally(t); + return; + } + Collection rowDataCollection = convertToInternalData(result); // call condition collector first, // the filtered result will be routed to the delegateCollector @@ -273,6 +388,61 @@ public void close() throws Exception { joinConditionResultFuture.close(); } + private void updateCacheIfNecessary(Collection lookupRows) throws Exception { + if (!enableCache) { + return; + } + + // 1. build the cache in lookup side if not exists + // 2. update the cache in stream side if exists + if (treatRightAsLookupTable) { + if (cache.getData(streamJoinKey, true) == null) { + cache.buildCache(streamJoinKey, buildMapWithUkAsKeys(lookupRows, true), true); + } + + LinkedHashMap leftCacheData = cache.getData(streamJoinKey, false); + if (leftCacheData != null) { + RowData uk = leftUpsertKeySelector.getKey(streamRow); + cache.upsertCache(streamJoinKey, uk, streamRow, false); + } + } else { + if (cache.getData(streamJoinKey, false) == null) { + cache.buildCache(streamJoinKey, buildMapWithUkAsKeys(lookupRows, false), false); + } + + LinkedHashMap rightCacheData = cache.getData(streamJoinKey, true); + if (rightCacheData != null) { + RowData uk = rightUpsertKeySelector.getKey(streamRow); + cache.upsertCache(streamJoinKey, uk, streamRow, true); + } + } + } + + private LinkedHashMap buildMapWithUkAsKeys( + Collection lookupRows, boolean treatRightAsLookupTable) throws Exception { + LinkedHashMap map = new LinkedHashMap<>(); + for (Object lookupRow : lookupRows) { + RowData rowData = convertToInternalData(lookupRow); + RowData uk; + if (treatRightAsLookupTable) { + uk = rightUpsertKeySelector.getKey(rowData); + map.put(uk, lookupRow); + } else { + uk = leftUpsertKeySelector.getKey(rowData); + map.put(uk, lookupRow); + } + } + return map; + } + + private RowData convertToInternalData(Object data) { + if (resultConverter.isIdentityConversion()) { + return (RowData) data; + } else { + return resultConverter.toInternal(data); + } + } + @SuppressWarnings({"unchecked", "rawtypes"}) private Collection convertToInternalData(Collection data) { if (resultConverter.isIdentityConversion()) { diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/DeltaJoinCache.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/DeltaJoinCache.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/DeltaJoinCache.java @@ -0,0 +1,241 @@ +/* + * 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.operators.join.deltajoin; + +import org.apache.flink.annotation.VisibleForTesting; +import org.apache.flink.metrics.Gauge; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.table.data.RowData; +import org.apache.flink.util.Preconditions; + +import org.apache.flink.shaded.guava33.com.google.common.cache.Cache; +import org.apache.flink.shaded.guava33.com.google.common.cache.CacheBuilder; +import org.apache.flink.shaded.guava33.com.google.common.cache.RemovalListener; +import org.apache.flink.shaded.guava33.com.google.common.cache.RemovalNotification; + +import javax.annotation.Nullable; +import javax.annotation.concurrent.NotThreadSafe; + +import java.util.LinkedHashMap; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Cache for both sides in delta join. + * + *

Note: This cache is not thread-safe although its inner {@link Cache} is thread-safe. + */ +@NotThreadSafe +public class DeltaJoinCache { + + private static final String LEFT_CACHE_METRIC_PREFIX = "deltaJoin.leftCache."; + private static final String RIGHT_CACHE_METRIC_PREFIX = "deltaJoin.rightCache."; + + private static final String METRIC_HIT_RATE = "hitRate"; + private static final String METRIC_REQUEST_COUNT = "requestCount"; + private static final String METRIC_HIT_COUNT = "hitCount"; + private static final String METRIC_KEY_SIZE = "keySize"; + private static final String METRIC_TOTAL_NON_EMPTY_VALUE_SIZE = "totalNonEmptyValues"; + + // use LinkedHashMap to keep order + private final Cache> leftCache; + private final Cache> rightCache; + + // metrics + private final AtomicLong leftTotalSize = new AtomicLong(0L); + private final AtomicLong rightTotalSize = new AtomicLong(0L); + private final AtomicLong leftHitCount = new AtomicLong(0L); + private final AtomicLong leftRequestCount = new AtomicLong(0L); + private final AtomicLong rightHitCount = new AtomicLong(0L); + private final AtomicLong rightRequestCount = new AtomicLong(0L); + + public DeltaJoinCache(long leftCacheMaxSize, long rightCacheMaxSize) { + this.leftCache = + CacheBuilder.newBuilder() + .maximumSize(leftCacheMaxSize) + .removalListener(new DeltaJoinCacheRemovalListener(true)) + .build(); + this.rightCache = + CacheBuilder.newBuilder() + .maximumSize(rightCacheMaxSize) + .removalListener(new DeltaJoinCacheRemovalListener(false)) + .build(); + } + + public void registerMetrics(MetricGroup metricGroup) { + // left cache metric + metricGroup.>gauge( + LEFT_CACHE_METRIC_PREFIX + METRIC_HIT_RATE, + () -> + leftRequestCount.get() == 0 + ? 0.0 + : Long.valueOf(leftHitCount.get()).doubleValue() + / leftRequestCount.get()); + metricGroup.>gauge( + LEFT_CACHE_METRIC_PREFIX + METRIC_REQUEST_COUNT, rightRequestCount::get); + metricGroup.>gauge( + LEFT_CACHE_METRIC_PREFIX + METRIC_HIT_COUNT, leftHitCount::get); + metricGroup.>gauge( + LEFT_CACHE_METRIC_PREFIX + METRIC_KEY_SIZE, leftCache::size); + + metricGroup.>gauge( + LEFT_CACHE_METRIC_PREFIX + METRIC_TOTAL_NON_EMPTY_VALUE_SIZE, leftTotalSize::get); + + // right cache metric + metricGroup.>gauge( + RIGHT_CACHE_METRIC_PREFIX + METRIC_HIT_RATE, + () -> + rightRequestCount.get() == 0 + ? 0.0 + : Long.valueOf(rightHitCount.get()).doubleValue() + / rightRequestCount.get()); + metricGroup.>gauge( + RIGHT_CACHE_METRIC_PREFIX + METRIC_REQUEST_COUNT, rightRequestCount::get); + metricGroup.>gauge( + RIGHT_CACHE_METRIC_PREFIX + METRIC_HIT_COUNT, rightHitCount::get); + metricGroup.>gauge( + RIGHT_CACHE_METRIC_PREFIX + METRIC_KEY_SIZE, rightCache::size); + metricGroup.>gauge( + RIGHT_CACHE_METRIC_PREFIX + METRIC_TOTAL_NON_EMPTY_VALUE_SIZE, rightTotalSize::get); + } + + @Nullable + public LinkedHashMap getData(RowData key, boolean requestRightCache) { + return requestRightCache ? rightCache.getIfPresent(key) : leftCache.getIfPresent(key); + } + + public void buildCache( + RowData key, LinkedHashMap ukDataMap, boolean buildRightCache) { + Preconditions.checkState(getData(key, buildRightCache) == null); + if (buildRightCache) { + rightCache.put(key, ukDataMap); + rightTotalSize.addAndGet(ukDataMap.size()); + } else { + leftCache.put(key, ukDataMap); + leftTotalSize.addAndGet(ukDataMap.size()); + } + } + + public void upsertCache(RowData key, RowData uk, Object data, boolean upsertRightCache) { + if (upsertRightCache) { + upsert(rightCache, key, uk, data, rightTotalSize); + } else { + upsert(leftCache, key, uk, data, leftTotalSize); + } + } + + private void upsert( + Cache> cache, + RowData key, + RowData uk, + Object data, + AtomicLong cacheTotalSize) { + cache.asMap() + .computeIfPresent( + key, + (k, v) -> { + Object oldData = v.put(uk, data); + if (oldData == null) { + cacheTotalSize.incrementAndGet(); + } + return v; + }); + } + + public void requestLeftCache() { + leftRequestCount.incrementAndGet(); + } + + public void requestRightCache() { + rightRequestCount.incrementAndGet(); + } + + public void hitLeftCache() { + leftHitCount.incrementAndGet(); + } + + public void hitRightCache() { + rightHitCount.incrementAndGet(); + } + + private class DeltaJoinCacheRemovalListener + implements RemovalListener> { + + private final boolean isLeftCache; + + public DeltaJoinCacheRemovalListener(boolean isLeftCache) { + this.isLeftCache = isLeftCache; + } + + @Override + public void onRemoval( + RemovalNotification> removalNotification) { + if (removalNotification.getValue() == null) { + return; + } + + if (isLeftCache) { + leftTotalSize.addAndGet(-removalNotification.getValue().size()); + } else { + rightTotalSize.addAndGet(-removalNotification.getValue().size()); + } + } + } + + // ===== visible for test ===== + + @VisibleForTesting + public Cache> getLeftCache() { + return leftCache; + } + + @VisibleForTesting + public Cache> getRightCache() { + return rightCache; + } + + @VisibleForTesting + public AtomicLong getLeftTotalSize() { + return leftTotalSize; + } + + @VisibleForTesting + public AtomicLong getRightTotalSize() { + return rightTotalSize; + } + + @VisibleForTesting + public AtomicLong getLeftHitCount() { + return leftHitCount; + } + + @VisibleForTesting + public AtomicLong getLeftRequestCount() { + return leftRequestCount; + } + + @VisibleForTesting + public AtomicLong getRightHitCount() { + return rightHitCount; + } + + @VisibleForTesting + public AtomicLong getRightRequestCount() { + return rightRequestCount; + } +} diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperator.java @@ -99,7 +99,7 @@ public class StreamingDeltaJoinOperator private static final String METRIC_DELTA_JOIN_OP_TOTAL_IN_FLIGHT_NUM = "deltaJoinOpTotalInFlightNum"; - private static final String METRIC_DELTA_JOIN_ASYNC_IO_TIME = "deltaJoinAsyncIoTime"; + private static final String METRIC_DELTA_JOIN_ASYNC_IO_TIME = "deltaJoinAsyncIOTime"; private final StreamRecord leftEmptyStreamRecord; private final StreamRecord rightEmptyStreamRecord; @@ -116,6 +116,10 @@ public class StreamingDeltaJoinOperator /** Max number of inflight invocation. */ private final int capacity; + private final long leftSideCacheSize; + + private final long rightSideCacheSize; + private transient boolean needDeepCopy; /** {@link TypeSerializer} for left side inputs while making snapshots. */ @@ -138,6 +142,8 @@ public class StreamingDeltaJoinOperator private transient TableAsyncExecutionController asyncExecutionController; + private transient DeltaJoinCache cache; + /** Mailbox executor used to yield while waiting for buffers to empty. */ private final transient MailboxExecutor mailboxExecutor; @@ -172,6 +178,8 @@ public StreamingDeltaJoinOperator( int capacity, ProcessingTimeService processingTimeService, MailboxExecutor mailboxExecutor, + long leftSideCacheSize, + long rightSideCacheSize, RowType leftStreamType, RowType rightStreamType) { // rightLookupTableAsyncFunction is an udx used for left records @@ -184,6 +192,8 @@ public StreamingDeltaJoinOperator( this.processingTimeService = checkNotNull(processingTimeService); this.mailboxExecutor = mailboxExecutor; this.isInputEnded = new boolean[2]; + this.leftSideCacheSize = leftSideCacheSize; + this.rightSideCacheSize = rightSideCacheSize; this.leftEmptyStreamRecord = new StreamRecord<>(new GenericRowData(leftStreamType.getFieldCount())); this.rightEmptyStreamRecord = @@ -224,6 +234,11 @@ public void setup( isLeft(inputIndex) ? leftJoinKeySelector : rightJoinKeySelector; return keySelector.getKey(record.getValue()); }); + + this.cache = new DeltaJoinCache(leftSideCacheSize, rightSideCacheSize); + + leftTriggeredUserFunction.setCache(cache); + rightTriggeredUserFunction.setCache(cache); } @Override @@ -275,6 +290,9 @@ public void open() throws Exception { getRuntimeContext() .getMetricGroup() .gauge(METRIC_DELTA_JOIN_ASYNC_IO_TIME, asyncIOTime::get); + // 3. cache metric + cache.registerMetrics(getRuntimeContext().getMetricGroup()); + // asyncBufferCapacity + 1 as the queue size in order to avoid // blocking on the queue when taking a collector. this.resultHandlerBuffer = new ArrayBlockingQueue<>(capacity + 1);