This is an automated email from the ASF dual-hosted git repository.
huaxingao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git
The following commit(s) were added to refs/heads/main by this push:
new a56ec9e444 Flink: Backport add periodic and timed reload of the lookup
join full cache (#19059)
a56ec9e444 is described below
commit a56ec9e444082e32b3ab0755c3dba95421aeea72
Author: GuoYu <[email protected]>
AuthorDate: Sat Nov 21 06:08:13 2026 +0800
Flink: Backport add periodic and timed reload of the lookup join full cache
(#19059)
---
.../iceberg/flink/FlinkDynamicTableFactory.java | 6 +
.../iceberg/flink/source/IcebergTableSource.java | 14 +-
.../lookup/FullCacheReloadTriggerFactory.java | 77 ++++++++++
.../lookup/IcebergFullCachingLookupFunction.java | 146 +++++++++++++++---
.../flink/source/lookup/IcebergLookupReader.java | 6 +-
.../flink/source/TestIcebergLookupJoinSql.java | 125 ++++++++++++++++
.../lookup/TestFullCacheReloadTriggerFactory.java | 128 ++++++++++++++++
.../flink/source/lookup/TestIcebergLookup.java | 165 +++++++++++++++++++--
.../iceberg/flink/FlinkDynamicTableFactory.java | 6 +
.../iceberg/flink/source/IcebergTableSource.java | 14 +-
.../lookup/FullCacheReloadTriggerFactory.java | 77 ++++++++++
.../lookup/IcebergFullCachingLookupFunction.java | 146 +++++++++++++++---
.../flink/source/lookup/IcebergLookupReader.java | 6 +-
.../flink/source/TestIcebergLookupJoinSql.java | 125 ++++++++++++++++
.../lookup/TestFullCacheReloadTriggerFactory.java | 128 ++++++++++++++++
.../flink/source/lookup/TestIcebergLookup.java | 165 +++++++++++++++++++--
16 files changed, 1256 insertions(+), 78 deletions(-)
diff --git
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
index 0c7244dc23..1f9d58a44a 100644
---
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
+++
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
@@ -34,6 +34,7 @@ import
org.apache.flink.table.catalog.exceptions.DatabaseAlreadyExistException;
import org.apache.flink.table.catalog.exceptions.TableAlreadyExistException;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.lookup.LookupOptions;
import org.apache.flink.table.factories.DynamicTableSinkFactory;
import org.apache.flink.table.factories.DynamicTableSourceFactory;
import org.apache.iceberg.catalog.TableIdentifier;
@@ -134,6 +135,11 @@ public class FlinkDynamicTableFactory
options.add(FlinkCreateTableOptions.USE_DYNAMIC_ICEBERG_SINK);
options.add(FlinkCreateTableOptions.DYNAMIC_RECORD_GENERATOR_IMPL);
options.add(IcebergLookupOptions.FULL_CACHE_EAGER_LOAD);
+ options.add(LookupOptions.FULL_CACHE_RELOAD_STRATEGY);
+ options.add(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL);
+ options.add(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_SCHEDULE_MODE);
+ options.add(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME);
+ options.add(LookupOptions.FULL_CACHE_TIMED_RELOAD_INTERVAL_IN_DAYS);
return options;
}
diff --git
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
index 7cd93f53e0..b33196d425 100644
---
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
+++
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.flink.annotation.Internal;
+import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
@@ -42,6 +43,7 @@ import
org.apache.flink.table.connector.source.abilities.SupportsProjectionPushD
import
org.apache.flink.table.connector.source.abilities.SupportsSourceWatermark;
import org.apache.flink.table.connector.source.lookup.LookupFunctionProvider;
import org.apache.flink.table.connector.source.lookup.LookupOptions;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.factories.FactoryUtil;
@@ -54,6 +56,7 @@ import org.apache.iceberg.flink.FlinkFilters;
import org.apache.iceberg.flink.FlinkReadOptions;
import org.apache.iceberg.flink.TableLoader;
import org.apache.iceberg.flink.source.assigner.SplitAssignerType;
+import org.apache.iceberg.flink.source.lookup.FullCacheReloadTriggerFactory;
import org.apache.iceberg.flink.source.lookup.IcebergFullCachingLookupFunction;
import org.apache.iceberg.flink.source.lookup.IcebergLookupOptions;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
@@ -289,9 +292,18 @@ public class IcebergTableSource
.defaultValue(FlinkReadOptions.CASE_SENSITIVE_OPTION.defaultValue())
.parse();
+ CacheReloadTrigger reloadTrigger =
+
FullCacheReloadTriggerFactory.create(Configuration.fromMap(properties));
+
LookupFunction lookupFn =
new IcebergFullCachingLookupFunction(
- loader, projectedRowType, lookupKeyIndexes, filters,
caseSensitive, eagerLoad);
+ loader,
+ projectedRowType,
+ lookupKeyIndexes,
+ filters,
+ caseSensitive,
+ eagerLoad,
+ reloadTrigger);
return LookupFunctionProvider.of(lookupFn);
}
}
diff --git
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/FullCacheReloadTriggerFactory.java
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/FullCacheReloadTriggerFactory.java
new file mode 100644
index 0000000000..a8ea334bc5
--- /dev/null
+++
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/FullCacheReloadTriggerFactory.java
@@ -0,0 +1,77 @@
+/*
+ * 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.iceberg.flink.source.lookup;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.table.connector.source.lookup.LookupOptions;
+import
org.apache.flink.table.connector.source.lookup.LookupOptions.LookupCacheType;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.PeriodicCacheReloadTrigger;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.TimedCacheReloadTrigger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+public class FullCacheReloadTriggerFactory {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(FullCacheReloadTriggerFactory.class);
+
+ private static final List<ConfigOption<?>> RELOAD_OPTIONS =
+ List.of(
+ LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
+ LookupOptions.FULL_CACHE_PERIODIC_RELOAD_SCHEDULE_MODE,
+ LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME,
+ LookupOptions.FULL_CACHE_TIMED_RELOAD_INTERVAL_IN_DAYS);
+
+ public static @Nullable CacheReloadTrigger create(Configuration lookupConf) {
+ if (!lookupConf.contains(LookupOptions.FULL_CACHE_RELOAD_STRATEGY)) {
+ warnIgnoredOptions(lookupConf);
+ return null;
+ }
+
+ Configuration triggerConf = new Configuration(lookupConf);
+ triggerConf.set(LookupOptions.CACHE_TYPE, LookupCacheType.FULL);
+
+ return switch (lookupConf.get(LookupOptions.FULL_CACHE_RELOAD_STRATEGY)) {
+ case PERIODIC -> PeriodicCacheReloadTrigger.fromConfig(triggerConf);
+ case TIMED -> TimedCacheReloadTrigger.fromConfig(triggerConf);
+ };
+ }
+
+ private static void warnIgnoredOptions(Configuration lookupConf) {
+ List<String> ignored =
+ RELOAD_OPTIONS.stream()
+ .filter(lookupConf::contains)
+ .map(ConfigOption::key)
+ .collect(Collectors.toList());
+ if (!ignored.isEmpty()) {
+ LOG.warn(
+ "Full cache will not be reloaded: {} is not set, so {} will be
ignored",
+ LookupOptions.FULL_CACHE_RELOAD_STRATEGY.key(),
+ ignored);
+ }
+ }
+
+ private FullCacheReloadTriggerFactory() {}
+}
diff --git
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
index d7e78913e3..337fb0b151 100644
---
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
+++
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
@@ -23,9 +23,12 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import javax.annotation.Nullable;
import org.apache.flink.annotation.Internal;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.MetricGroup;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
@@ -51,8 +54,10 @@ import org.slf4j.LoggerFactory;
* table, after projection and pushed-down filters are applied.
*
* <p>The cache is loaded from the current snapshot either when the function
is opened or on the
- * first lookup, depending on {@link
IcebergLookupOptions#FULL_CACHE_EAGER_LOAD}. It is never
- * refreshed, so later changes to the table are not visible.
+ * first lookup, depending on {@link
IcebergLookupOptions#FULL_CACHE_EAGER_LOAD}. When a {@link
+ * CacheReloadTrigger} is configured, the cache is reloaded on the trigger's
schedule: a reload that
+ * finds no new snapshot keeps the loaded cache, and a reload that fails fails
the next lookup
+ * instead of serving the previously loaded cache.
*/
@Internal
public class IcebergFullCachingLookupFunction extends LookupFunction {
@@ -68,15 +73,22 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
private final List<Expression> pushedFilters;
private final boolean caseSensitive;
private final boolean eagerLoad;
+ private final @Nullable CacheReloadTrigger reloadTrigger;
private transient Table table;
private transient IcebergLookupReader reader;
private transient RowDataSerializer rowSerializer;
- private transient RowDataSerializer keySerializer;
+ // lookup() and reloads run on different threads, and toBinaryRow reuses its
output row
+ private transient RowDataSerializer lookupKeySerializer;
+ private transient RowDataSerializer loadKeySerializer;
private transient RowData.FieldGetter[] keyGetters;
- private transient InMemoryLookupCache cache;
+ private transient volatile InMemoryLookupCache cache;
+ private transient volatile Throwable reloadFailure;
+ private transient volatile boolean closed;
private transient Counter missCounter;
+ private transient Counter loadCounter;
+ private transient Counter loadFailuresCounter;
private transient volatile long currentSnapshotId;
private transient volatile long cachedRecords;
private transient volatile long latestLoadTimeMs;
@@ -87,13 +99,15 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
int[] lookupKeyIndexes,
List<Expression> pushedFilters,
boolean caseSensitive,
- boolean eagerLoad) {
+ boolean eagerLoad,
+ @Nullable CacheReloadTrigger reloadTrigger) {
this.tableLoader = tableLoader;
this.projectedRowType = projectedRowType;
this.lookupKeyIndexes = lookupKeyIndexes;
this.pushedFilters = pushedFilters;
this.caseSensitive = caseSensitive;
this.eagerLoad = eagerLoad;
+ this.reloadTrigger = reloadTrigger;
}
@Override
@@ -106,9 +120,12 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
MetricGroup metricGroup = context.getMetricGroup().addGroup(METRIC_GROUP);
this.missCounter = metricGroup.counter("missCount");
- this.currentSnapshotId = IcebergLookupReader.CURRENT_SNAPSHOT;
+ this.loadCounter = metricGroup.counter("loadCount");
+ this.loadFailuresCounter = metricGroup.counter("numLoadFailures");
+ this.currentSnapshotId = IcebergLookupReader.NO_SNAPSHOT_ID;
this.cachedRecords = 0L;
this.latestLoadTimeMs = UNINITIALIZED;
+ this.reloadFailure = null;
metricGroup.gauge("snapshotId", () -> currentSnapshotId);
metricGroup.gauge("numCachedRecords", () -> cachedRecords);
metricGroup.gauge("latestLoadTime", () -> latestLoadTimeMs);
@@ -129,6 +146,10 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
if (eagerLoad) {
loadCache();
}
+
+ if (reloadTrigger != null) {
+ reloadTrigger.open(new ReloadContext(this));
+ }
}
/**
@@ -137,11 +158,15 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
*/
@Override
public Collection<RowData> lookup(RowData keyRow) throws IOException {
- if (cache == null) {
+ checkReloadFailure();
+
+ InMemoryLookupCache currentCache = cache;
+ if (currentCache == null) {
loadCache();
+ currentCache = cache;
}
- List<RowData> hit = cache.get(keySerializer.toBinaryRow(keyRow));
+ List<RowData> hit =
currentCache.get(lookupKeySerializer.toBinaryRow(keyRow));
if (hit == null) {
missCounter.inc();
return Collections.emptyList();
@@ -152,22 +177,63 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
@Override
public void close() throws Exception {
+ this.closed = true;
+
try {
- tableLoader.close();
+ if (reloadTrigger != null) {
+ reloadTrigger.close();
+ }
} finally {
- if (cache != null) {
- cache.close();
+ try {
+ tableLoader.close();
+ } finally {
+ if (cache != null) {
+ cache.close();
+ }
+
+ super.close();
}
+ }
+ }
- super.close();
+ private CompletableFuture<Void> triggerReload() {
+ if (cache == null || closed || reloadFailure != null) {
+ return CompletableFuture.completedFuture(null);
+ }
+
+ try {
+ loadCache();
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable failure) {
+ if (closed) {
+ return CompletableFuture.completedFuture(null);
+ }
+
+ loadFailuresCounter.inc();
+ this.reloadFailure = failure;
+ LOG.error(
+ "IcebergFullCachingLookupFunction reload failed, the job will fail
on the next lookup "
+ + "instead of serving the previously loaded cache",
+ failure);
+ return CompletableFuture.failedFuture(failure);
}
}
- private void loadCache() throws IOException {
+ private synchronized void loadCache() throws IOException {
+ if (closed) {
+ return;
+ }
+
table.refresh();
Snapshot snapshot = table.currentSnapshot();
- long snapshotId =
- snapshot == null ? IcebergLookupReader.CURRENT_SNAPSHOT :
snapshot.snapshotId();
+ long snapshotId = snapshot == null ? IcebergLookupReader.NO_SNAPSHOT_ID :
snapshot.snapshotId();
+
+ if (cache != null && snapshotId == currentSnapshotId) {
+ LOG.info(
+ "IcebergFullCachingLookupFunction skipping reload, snapshot {} is
already cached",
+ snapshot == null ? "none" : snapshotId);
+ return;
+ }
LOG.info(
"IcebergFullCachingLookupFunction loading started, snapshot={},
committedAt={}, projected fields={}, pushedFilters={}",
@@ -181,22 +247,32 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
long start = System.currentTimeMillis();
try (CloseableIterable<RowData> rows = reader.read(snapshotId)) {
for (RowData row : rows) {
+ if (closed) {
+ return;
+ }
+
loaded.add(extractKey(row), rowSerializer.toBinaryRow(row).copy());
rowCnt++;
}
- } finally {
- this.latestLoadTimeMs = System.currentTimeMillis() - start;
+ }
+
+ long loadTimeMs = System.currentTimeMillis() - start;
+
+ if (closed) {
+ return;
}
this.cache = loaded;
this.currentSnapshotId = snapshotId;
this.cachedRecords = rowCnt;
+ this.latestLoadTimeMs = loadTimeMs;
+ loadCounter.inc();
LOG.info(
"IcebergFullCachingLookupFunction loading finished, snapshot={},
rows={}, cost={} ms",
snapshot == null ? "none" : snapshotId,
rowCnt,
- latestLoadTimeMs);
+ loadTimeMs);
}
private BinaryRowData extractKey(RowData row) {
@@ -205,7 +281,7 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
key.setField(i, keyGetters[i].getFieldOrNull(row));
}
- return keySerializer.toBinaryRow(key).copy();
+ return loadKeySerializer.toBinaryRow(key).copy();
}
private void createAccessors() {
@@ -218,6 +294,36 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
}
this.rowSerializer = new RowDataSerializer(projectedRowType);
- this.keySerializer = new RowDataSerializer(keyTypes);
+ this.lookupKeySerializer = new RowDataSerializer(keyTypes);
+ this.loadKeySerializer = new RowDataSerializer(keyTypes);
+ }
+
+ private void checkReloadFailure() throws IOException {
+ Throwable failure = reloadFailure;
+ if (failure != null) {
+ throw new IOException(
+ "Lookup cache reload failed, failing the job instead of serving the
previously loaded cache",
+ failure);
+ }
+ }
+
+ private record ReloadContext(IcebergFullCachingLookupFunction function)
+ implements CacheReloadTrigger.Context {
+
+ @Override
+ public long currentProcessingTime() {
+ return System.currentTimeMillis();
+ }
+
+ @Override
+ public long currentWatermark() {
+ throw new UnsupportedOperationException(
+ "Watermarks are currently unsupported in cache reload triggers.");
+ }
+
+ @Override
+ public CompletableFuture<Void> triggerReload() {
+ return function.triggerReload();
+ }
}
}
diff --git
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
index d669178557..165b7e1327 100644
---
a/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
+++
b/flink/v1.20/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
@@ -43,7 +43,7 @@ import org.apache.iceberg.util.SnapshotUtil;
@Internal
class IcebergLookupReader {
- static final long CURRENT_SNAPSHOT = -1L;
+ static final long NO_SNAPSHOT_ID = -1L;
private final Table table;
private final Schema projectedSchema;
@@ -76,7 +76,7 @@ class IcebergLookupReader {
CloseableIterable<RowData> read(long snapshotId) {
Schema tableSchema =
- snapshotId == CURRENT_SNAPSHOT ? table.schema() :
SnapshotUtil.schemaFor(table, snapshotId);
+ snapshotId == NO_SNAPSHOT_ID ? table.schema() :
SnapshotUtil.schemaFor(table, snapshotId);
RowDataFileScanTaskReader fileReader =
new RowDataFileScanTaskReader(
@@ -84,7 +84,7 @@ class IcebergLookupReader {
TableScan scan =
table.newScan().caseSensitive(caseSensitive).project(projectedSchema).filter(filter);
- if (snapshotId != CURRENT_SNAPSHOT) {
+ if (snapshotId != NO_SNAPSHOT_ID) {
scan = scan.useSnapshot(snapshotId);
}
diff --git
a/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
b/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
index 40c13af6d4..de0be59917 100644
---
a/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
+++
b/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
@@ -26,6 +26,7 @@ import java.io.IOException;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.types.Row;
+import org.apache.flink.util.CloseableIterator;
import org.apache.iceberg.DataFile;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Schema;
@@ -43,6 +44,8 @@ import org.junit.jupiter.api.Test;
/** Tests SQL lookup join with Iceberg table source. */
class TestIcebergLookupJoinSql extends TestSqlBase {
+ private static final long RELOAD_TIMEOUT_MS = 10_000L;
+
private static final Schema DIM_SCHEMA =
new Schema(
required(1, "user_id", Types.LongType.get()),
@@ -171,6 +174,91 @@ class TestIcebergLookupJoinSql extends TestSqlBase {
Row.of(3L, 3L, "carol", "guangzhou"));
}
+ @Test
+ void lookupJoinReloadsFullCacheFromNewSnapshot() throws Exception {
+ Table dimTable =
+ CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER,
DIM_SCHEMA);
+ GenericAppenderHelper helper =
+ new GenericAppenderHelper(dimTable, FileFormat.PARQUET,
temporaryFolder);
+ helper.appendToTable(
+ helper.writeFile(
+ Lists.newArrayList(
+ dimRecord(1L, "alice", "beijing"),
+ dimRecord(2L, "bob", "shanghai"),
+ dimRecord(3L, "carol", "guangzhou"))));
+
+ TableEnvironment streamEnv = getStreamingTableEnv();
+ // The probe emits randomized keys until the test stops it, so the reload
has time to pick up
+ // the snapshot appended below.
+ createRepeatingOrdersTable(streamEnv, "orders_reload_new_snapshot", 10);
+
+ String joinSql =
+ lookupJoinSql(
+ "o.user_id, u.name",
+ "orders_reload_new_snapshot",
+ "OPTIONS('lookup.full-cache.reload-strategy'='PERIODIC', "
+ + "'lookup.full-cache.periodic-reload.interval'='500 ms', "
+ +
"'lookup.full-cache.periodic-reload.schedule-mode'='FIXED_RATE')",
+ null);
+
+ try (CloseableIterator<Row> iter =
streamEnv.executeSql(joinSql).collect()) {
+ // The first row proves that the lookup function is open and the cache
is loaded from the
+ // snapshot that does not contain the row appended next.
+ assertThat(iter.next()).isNotNull();
+
+ helper.appendToTable(
+ helper.writeFile(Lists.newArrayList(dimRecord(10L, "henry",
"shenzhen"))));
+
+ long deadline = System.currentTimeMillis() + RELOAD_TIMEOUT_MS;
+ boolean reloaded = false;
+ while (!reloaded && System.currentTimeMillis() < deadline) {
+ reloaded = "henry".equals(iter.next().getField(1));
+ }
+
+ assertThat(reloaded).as("A reload must replace the cache with the latest
snapshot").isTrue();
+ }
+ }
+
+ @Test
+ void lookupJoinWithTimedReloadOptionsInTableDdl() throws Exception {
+ createDefaultDimTable();
+
+ TableEnvironment streamEnv = getStreamingTableEnv();
+ createOrdersTable(streamEnv, "orders_timed_reload", 3);
+
+ SqlHelpers.sql(
+ streamEnv,
+ "CREATE TABLE default_catalog.default_database.dim_users_timed_reload
(\n"
+ + " user_id BIGINT,\n"
+ + " name STRING,\n"
+ + " city STRING\n"
+ + ") WITH (\n"
+ + " 'connector' = 'iceberg',\n"
+ + " 'catalog-name' = 'iceberg_catalog',\n"
+ + " 'catalog-type' = 'hadoop',\n"
+ + " 'warehouse' = '%s',\n"
+ + " 'catalog-database' = '%s',\n"
+ + " 'catalog-table' = '%s',\n"
+ + " 'lookup.cache' = 'FULL',\n"
+ + " 'lookup.full-cache.reload-strategy' = 'TIMED',\n"
+ + " 'lookup.full-cache.timed-reload.iso-time' = '02:30'\n"
+ + ")",
+ CATALOG_EXTENSION.warehouse(),
+ TestFixtures.DATABASE,
+ TestFixtures.TABLE);
+
+ String joinSql =
+ "SELECT o.order_id, u.name\n"
+ + "FROM orders_timed_reload AS o\n"
+ + "LEFT JOIN
default_catalog.default_database.dim_users_timed_reload\n"
+ + " FOR SYSTEM_TIME AS OF o.proc_time AS u\n"
+ + " ON o.user_id = u.user_id";
+
+ assertThat(SqlHelpers.sql(streamEnv, joinSql))
+ .as("The timed reload options must be accepted as table options")
+ .containsExactlyInAnyOrder(Row.of(1L, "alice"), Row.of(2L, "bob"),
Row.of(3L, "carol"));
+ }
+
@Test
void lookupJoinAcceptsFullCacheType() throws Exception {
createDimTable(dimRecord(1L, "alice", "beijing"));
@@ -207,6 +295,25 @@ class TestIcebergLookupJoinSql extends TestSqlBase {
.hasStackTraceContaining("only supports lookup.cache=FULL");
}
+ @Test
+ void lookupJoinRejectsPeriodicReloadWithoutInterval() throws Exception {
+ createDimTable(dimRecord(1L, "alice", "beijing"));
+
+ TableEnvironment streamEnv = getStreamingTableEnv();
+ createOrdersTable(streamEnv, "orders_reload_without_interval", 1);
+
+ String joinSql =
+ lookupJoinSql(
+ "o.order_id, u.name",
+ "orders_reload_without_interval",
+ "OPTIONS('lookup.cache'='FULL',
'lookup.full-cache.reload-strategy'='PERIODIC')",
+ null);
+
+ assertThatThrownBy(() -> SqlHelpers.sql(streamEnv, joinSql))
+ .as("The reload configured in the SQL options is validated while
planning the join")
+ .hasStackTraceContaining("lookup.full-cache.periodic-reload.interval");
+ }
+
@Test
void lookupJoinLoadsCacheEagerlyByDefault() throws Exception {
String dataFileLocation = createEmptyProbeAndUnreadableDimTable();
@@ -288,6 +395,24 @@ class TestIcebergLookupJoinSql extends TestSqlBase {
helper.appendToTable(dataFile);
}
+ private static void createRepeatingOrdersTable(
+ TableEnvironment tableEnvironment, String tableName, int numberOfKeys) {
+ SqlHelpers.sql(
+ tableEnvironment,
+ "CREATE TEMPORARY TABLE %s (\n"
+ + " user_id BIGINT,\n"
+ + " proc_time AS PROCTIME()\n"
+ + ") WITH (\n"
+ + " 'connector' = 'datagen',\n"
+ + " 'fields.user_id.kind' = 'random',\n"
+ + " 'fields.user_id.min' = '1',\n"
+ + " 'fields.user_id.max' = '%d',\n"
+ + " 'rows-per-second' = '50'\n"
+ + ")",
+ tableName,
+ numberOfKeys);
+ }
+
private static void createOrdersTable(
TableEnvironment tableEnvironment, String tableName, int numberOfRows) {
SqlHelpers.sql(
diff --git
a/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestFullCacheReloadTriggerFactory.java
b/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestFullCacheReloadTriggerFactory.java
new file mode 100644
index 0000000000..639ef59e41
--- /dev/null
+++
b/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestFullCacheReloadTriggerFactory.java
@@ -0,0 +1,128 @@
+/*
+ * 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.iceberg.flink.source.lookup;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.time.Duration;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.table.connector.source.lookup.LookupOptions;
+import
org.apache.flink.table.connector.source.lookup.LookupOptions.ReloadStrategy;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.PeriodicCacheReloadTrigger;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.TimedCacheReloadTrigger;
+import org.junit.jupiter.api.Test;
+
+class TestFullCacheReloadTriggerFactory {
+
+ @Test
+ void reloadIsDisabledWhenNoReloadOptionIsConfigured() {
+ assertThat(FullCacheReloadTriggerFactory.create(new
Configuration())).isNull();
+ }
+
+ @Test
+ void reloadRequiresTheStrategyOption() {
+ Configuration intervalOnly = new Configuration();
+ intervalOnly.set(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
Duration.ofMinutes(5));
+ assertThat(FullCacheReloadTriggerFactory.create(intervalOnly))
+ .as("An interval without a strategy must not enable reload")
+ .isNull();
+
+ Configuration isoTimeOnly = new Configuration();
+ isoTimeOnly.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME, "10:15");
+ assertThat(FullCacheReloadTriggerFactory.create(isoTimeOnly))
+ .as("A time of day without a strategy must not enable reload")
+ .isNull();
+
+ Configuration intervalInDaysOnly = new Configuration();
+
intervalInDaysOnly.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_INTERVAL_IN_DAYS,
2);
+ assertThat(FullCacheReloadTriggerFactory.create(intervalInDaysOnly))
+ .as("An interval in days without a strategy must not enable reload")
+ .isNull();
+
+ Configuration scheduleModeOnly = new Configuration();
+ scheduleModeOnly.set(
+ LookupOptions.FULL_CACHE_PERIODIC_RELOAD_SCHEDULE_MODE,
+ PeriodicCacheReloadTrigger.ScheduleMode.FIXED_RATE);
+ assertThat(FullCacheReloadTriggerFactory.create(scheduleModeOnly))
+ .as("A schedule mode without a strategy must not enable reload")
+ .isNull();
+ }
+
+ @Test
+ void periodicReloadIsEnabledByStrategyAndInterval() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.PERIODIC);
+ lookupConf.set(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
Duration.ofMinutes(5));
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(PeriodicCacheReloadTrigger.class);
+ }
+
+ @Test
+ void timedReloadIsEnabledByStrategyAndLocalIsoTime() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+ lookupConf.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME, "10:15");
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(TimedCacheReloadTrigger.class);
+ }
+
+ @Test
+ void timedReloadIsEnabledByStrategyAndOffsetIsoTime() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+ lookupConf.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME,
"10:15+07:00");
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(TimedCacheReloadTrigger.class);
+ }
+
+ @Test
+ void strategySelectsTheTriggerOverTheOptionsOfTheOtherStrategy() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+ lookupConf.set(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
Duration.ofMinutes(5));
+ lookupConf.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME, "10:15");
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(TimedCacheReloadTrigger.class);
+ }
+
+ @Test
+ void periodicReloadRequiresInterval() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.PERIODIC);
+
+ assertThatThrownBy(() -> FullCacheReloadTriggerFactory.create(lookupConf))
+ .as("The periodic strategy needs an interval")
+
.hasMessageContaining(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL.key());
+ }
+
+ @Test
+ void timedReloadRequiresIsoTime() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+
+ assertThatThrownBy(() -> FullCacheReloadTriggerFactory.create(lookupConf))
+ .as("The timed strategy needs the time of day to reload at")
+
.hasMessageContaining(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME.key());
+ }
+}
diff --git
a/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
b/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
index d13d89d17a..3e5e1e48df 100644
---
a/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
+++
b/flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
@@ -20,16 +20,22 @@ package org.apache.iceberg.flink.source.lookup;
import static org.apache.iceberg.types.Types.NestedField.optional;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import javax.annotation.Nullable;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.functions.FunctionContext;
import org.apache.flink.table.types.logical.RowType;
+import org.apache.iceberg.DataFile;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Table;
@@ -85,7 +91,7 @@ class TestIcebergLookup {
lookupReader(table, ImmutableList.of(Expressions.equal("category",
"B")), false);
List<List<Object>> rows = Lists.newArrayList();
- try (CloseableIterable<RowData> rowData =
reader.read(IcebergLookupReader.CURRENT_SNAPSHOT)) {
+ try (CloseableIterable<RowData> rowData =
reader.read(IcebergLookupReader.NO_SNAPSHOT_ID)) {
for (RowData row : rowData) {
rows.add(
ImmutableList.of(
@@ -102,12 +108,12 @@ class TestIcebergLookup {
List<Expression> filters = ImmutableList.of(Expressions.equal("CATEGORY",
"B"));
IcebergLookupReader caseSensitiveReader = lookupReader(table, filters,
true);
- assertThatThrownBy(() -> readIds(caseSensitiveReader,
IcebergLookupReader.CURRENT_SNAPSHOT))
+ assertThatThrownBy(() -> readIds(caseSensitiveReader,
IcebergLookupReader.NO_SNAPSHOT_ID))
.as("Case sensitive lookup should reject a filter that doesn't match
the column case")
.isInstanceOf(ValidationException.class)
.hasMessageContaining("CATEGORY");
- assertThat(readIds(lookupReader(table, filters, false),
IcebergLookupReader.CURRENT_SNAPSHOT))
+ assertThat(readIds(lookupReader(table, filters, false),
IcebergLookupReader.NO_SNAPSHOT_ID))
.containsExactly(2L);
}
@@ -123,7 +129,7 @@ class TestIcebergLookup {
assertThat(readIds(reader, pinnedSnapshot))
.as("Pinned snapshot should not contain the appended row")
.containsExactlyInAnyOrder(1L, 2L, 3L);
- assertThat(readIds(reader, IcebergLookupReader.CURRENT_SNAPSHOT))
+ assertThat(readIds(reader, IcebergLookupReader.NO_SNAPSHOT_ID))
.as("Current snapshot should contain the appended row")
.containsExactlyInAnyOrder(1L, 2L, 3L, 6L);
}
@@ -132,7 +138,7 @@ class TestIcebergLookup {
void lookupFunctionReturnsRowsFromCache() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L)))
@@ -152,7 +158,7 @@ class TestIcebergLookup {
void lookupFunctionWithMultiColumnKey() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_AND_CATEGORY_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_AND_CATEGORY_KEY_INDEXES, false,
null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L, "A")))
@@ -172,7 +178,7 @@ class TestIcebergLookup {
void lookupFunctionLoadsCacheLazily() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, null);
lookupFunction.open(new FunctionContext(null));
// Nothing is loaded yet, so the first lookup sees the row appended after
opening.
@@ -187,7 +193,7 @@ class TestIcebergLookup {
void lookupFunctionLoadsCacheEagerly() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, true);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, null);
lookupFunction.open(new FunctionContext(null));
appendRecords(table, ImmutableList.of(record(6L, "frank", "D")));
@@ -202,7 +208,7 @@ class TestIcebergLookup {
void lookupFunctionHandlesEmptyTable() throws Exception {
CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER,
SCHEMA);
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, true);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L))).isEmpty();
@@ -216,7 +222,7 @@ class TestIcebergLookup {
ImmutableList.of(
record(1L, "alice", "A"), record(1L, "alice-2", "A"), record(2L,
"bob", "B")));
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L)))
@@ -238,7 +244,8 @@ class TestIcebergLookup {
ID_KEY_INDEXES,
ImmutableList.of(Expressions.equal("category", "B")),
true,
- false);
+ false,
+ null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L))).isEmpty();
@@ -247,15 +254,117 @@ class TestIcebergLookup {
.satisfies(row -> assertRow(row, 2L, "bob", "B"));
}
+ @Test
+ void lookupFunctionReloadsCacheFromTrigger() throws Exception {
+ Table table =
CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER, SCHEMA);
+ DataFile initialFile = appendRecords(table, ImmutableList.of(record(1L,
"alice", "A")));
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+
+ assertThat(lookupFunction.lookup(keyRow(6L))).isEmpty();
+
+ appendRecords(table, ImmutableList.of(record(6L, "frank", "D")));
+ replaceFile(table, initialFile, ImmutableList.of(record(1L, "alicia",
"C")));
+
+ reloadTrigger.triggerReload().join();
+
+ assertThat(lookupFunction.lookup(keyRow(6L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 6L, "frank", "D"));
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .as("A reload must replace the rows cached for an overwritten key")
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alicia", "C"));
+ }
+
+ @Test
+ void lookupFunctionWithTriggerLoadsCacheLazily() throws Exception {
+ Table table = createTableWithRecords();
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ reloadTrigger.triggerReload().join();
+
+ appendRecords(table, ImmutableList.of(record(6L, "frank", "D")));
+
+ assertThat(lookupFunction.lookup(keyRow(6L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 6L, "frank", "D"));
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+
+ appendRecords(table, ImmutableList.of(record(7L, "grace", "E")));
+ reloadTrigger.triggerReload().join();
+ assertThat(lookupFunction.lookup(keyRow(7L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 7L, "grace", "E"));
+ }
+
+ @Test
+ void lookupFunctionSkipsReloadWhenSnapshotIsUnchanged() throws Exception {
+ Table table =
CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER, SCHEMA);
+ DataFile dataFile = appendRecords(table, ImmutableList.of(record(1L,
"alice", "A")));
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ table.io().deleteFile(dataFile.location());
+
+ assertThatCode(() -> reloadTrigger.triggerReload().join())
+ .as("A reload without a new snapshot must not read the table")
+ .doesNotThrowAnyException();
+
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .as("A reload without a new snapshot must keep serving the loaded
cache")
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+ }
+
+ @Test
+ void lookupFunctionFailsLookupsWhenReloadFails() throws Exception {
+ Table table = createTableWithRecords();
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+
+ DataFile dataFile = appendRecords(table, ImmutableList.of(record(6L,
"frank", "D")));
+ table.io().deleteFile(dataFile.location());
+
+ assertThatThrownBy(() -> reloadTrigger.triggerReload().join())
+ .isInstanceOf(CompletionException.class)
+ .hasMessageContaining(dataFile.location());
+
+ assertThatThrownBy(() -> lookupFunction.lookup(keyRow(1L)))
+ .as("A failed reload must fail the lookup instead of serving the
previous cache")
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("Lookup cache reload failed");
+ }
+
private IcebergFullCachingLookupFunction newLookupFunction(
- int[] lookupKeyIndexes, boolean eagerLoad) {
+ int[] lookupKeyIndexes, boolean eagerLoad, @Nullable CacheReloadTrigger
reloadTrigger) {
return new IcebergFullCachingLookupFunction(
CATALOG_EXTENSION.tableLoader().clone(),
ROW_TYPE,
lookupKeyIndexes,
ImmutableList.of(),
false,
- eagerLoad);
+ eagerLoad,
+ reloadTrigger);
}
private static IcebergLookupReader lookupReader(
@@ -285,8 +394,18 @@ class TestIcebergLookup {
return table;
}
- private void appendRecords(Table table, List<Record> records) throws
Exception {
- new GenericAppenderHelper(table, FileFormat.PARQUET,
temporaryFolder).appendToTable(records);
+ private DataFile appendRecords(Table table, List<Record> records) throws
Exception {
+ GenericAppenderHelper helper =
+ new GenericAppenderHelper(table, FileFormat.PARQUET, temporaryFolder);
+ DataFile dataFile = helper.writeFile(records);
+ helper.appendToTable(dataFile);
+ return dataFile;
+ }
+
+ private void replaceFile(Table table, DataFile oldFile, List<Record>
records) throws Exception {
+ GenericAppenderHelper helper =
+ new GenericAppenderHelper(table, FileFormat.PARQUET, temporaryFolder);
+
table.newOverwrite().deleteFile(oldFile).addFile(helper.writeFile(records)).commit();
}
private static GenericRecord record(Long id, String data, String category) {
@@ -315,4 +434,20 @@ class TestIcebergLookup {
assertThat(row.getString(1)).hasToString(data);
assertThat(row.getString(2)).hasToString(category);
}
+
+ private static class ManualCacheReloadTrigger implements CacheReloadTrigger {
+ private Context context;
+
+ @Override
+ public void open(Context reloadContext) {
+ this.context = reloadContext;
+ }
+
+ @Override
+ public void close() {}
+
+ CompletableFuture<Void> triggerReload() {
+ return context.triggerReload();
+ }
+ }
}
diff --git
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
index 0c7244dc23..1f9d58a44a 100644
---
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
+++
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/FlinkDynamicTableFactory.java
@@ -34,6 +34,7 @@ import
org.apache.flink.table.catalog.exceptions.DatabaseAlreadyExistException;
import org.apache.flink.table.catalog.exceptions.TableAlreadyExistException;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.lookup.LookupOptions;
import org.apache.flink.table.factories.DynamicTableSinkFactory;
import org.apache.flink.table.factories.DynamicTableSourceFactory;
import org.apache.iceberg.catalog.TableIdentifier;
@@ -134,6 +135,11 @@ public class FlinkDynamicTableFactory
options.add(FlinkCreateTableOptions.USE_DYNAMIC_ICEBERG_SINK);
options.add(FlinkCreateTableOptions.DYNAMIC_RECORD_GENERATOR_IMPL);
options.add(IcebergLookupOptions.FULL_CACHE_EAGER_LOAD);
+ options.add(LookupOptions.FULL_CACHE_RELOAD_STRATEGY);
+ options.add(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL);
+ options.add(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_SCHEDULE_MODE);
+ options.add(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME);
+ options.add(LookupOptions.FULL_CACHE_TIMED_RELOAD_INTERVAL_IN_DAYS);
return options;
}
diff --git
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
index 759b316667..50418934a4 100644
---
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
+++
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/IcebergTableSource.java
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.flink.annotation.Internal;
+import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
@@ -41,6 +42,7 @@ import
org.apache.flink.table.connector.source.abilities.SupportsProjectionPushD
import
org.apache.flink.table.connector.source.abilities.SupportsSourceWatermark;
import org.apache.flink.table.connector.source.lookup.LookupFunctionProvider;
import org.apache.flink.table.connector.source.lookup.LookupOptions;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.factories.FactoryUtil;
@@ -55,6 +57,7 @@ import org.apache.iceberg.flink.FlinkFilters;
import org.apache.iceberg.flink.FlinkReadOptions;
import org.apache.iceberg.flink.TableLoader;
import org.apache.iceberg.flink.source.assigner.SplitAssignerType;
+import org.apache.iceberg.flink.source.lookup.FullCacheReloadTriggerFactory;
import org.apache.iceberg.flink.source.lookup.IcebergFullCachingLookupFunction;
import org.apache.iceberg.flink.source.lookup.IcebergLookupOptions;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
@@ -290,9 +293,18 @@ public class IcebergTableSource
.defaultValue(FlinkReadOptions.CASE_SENSITIVE_OPTION.defaultValue())
.parse();
+ CacheReloadTrigger reloadTrigger =
+
FullCacheReloadTriggerFactory.create(Configuration.fromMap(properties));
+
LookupFunction lookupFn =
new IcebergFullCachingLookupFunction(
- loader, projectedRowType, lookupKeyIndexes, filters,
caseSensitive, eagerLoad);
+ loader,
+ projectedRowType,
+ lookupKeyIndexes,
+ filters,
+ caseSensitive,
+ eagerLoad,
+ reloadTrigger);
return LookupFunctionProvider.of(lookupFn);
}
}
diff --git
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/FullCacheReloadTriggerFactory.java
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/FullCacheReloadTriggerFactory.java
new file mode 100644
index 0000000000..a8ea334bc5
--- /dev/null
+++
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/FullCacheReloadTriggerFactory.java
@@ -0,0 +1,77 @@
+/*
+ * 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.iceberg.flink.source.lookup;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.table.connector.source.lookup.LookupOptions;
+import
org.apache.flink.table.connector.source.lookup.LookupOptions.LookupCacheType;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.PeriodicCacheReloadTrigger;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.TimedCacheReloadTrigger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+public class FullCacheReloadTriggerFactory {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(FullCacheReloadTriggerFactory.class);
+
+ private static final List<ConfigOption<?>> RELOAD_OPTIONS =
+ List.of(
+ LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
+ LookupOptions.FULL_CACHE_PERIODIC_RELOAD_SCHEDULE_MODE,
+ LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME,
+ LookupOptions.FULL_CACHE_TIMED_RELOAD_INTERVAL_IN_DAYS);
+
+ public static @Nullable CacheReloadTrigger create(Configuration lookupConf) {
+ if (!lookupConf.contains(LookupOptions.FULL_CACHE_RELOAD_STRATEGY)) {
+ warnIgnoredOptions(lookupConf);
+ return null;
+ }
+
+ Configuration triggerConf = new Configuration(lookupConf);
+ triggerConf.set(LookupOptions.CACHE_TYPE, LookupCacheType.FULL);
+
+ return switch (lookupConf.get(LookupOptions.FULL_CACHE_RELOAD_STRATEGY)) {
+ case PERIODIC -> PeriodicCacheReloadTrigger.fromConfig(triggerConf);
+ case TIMED -> TimedCacheReloadTrigger.fromConfig(triggerConf);
+ };
+ }
+
+ private static void warnIgnoredOptions(Configuration lookupConf) {
+ List<String> ignored =
+ RELOAD_OPTIONS.stream()
+ .filter(lookupConf::contains)
+ .map(ConfigOption::key)
+ .collect(Collectors.toList());
+ if (!ignored.isEmpty()) {
+ LOG.warn(
+ "Full cache will not be reloaded: {} is not set, so {} will be
ignored",
+ LookupOptions.FULL_CACHE_RELOAD_STRATEGY.key(),
+ ignored);
+ }
+ }
+
+ private FullCacheReloadTriggerFactory() {}
+}
diff --git
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
index d7e78913e3..337fb0b151 100644
---
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
+++
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java
@@ -23,9 +23,12 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import javax.annotation.Nullable;
import org.apache.flink.annotation.Internal;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.MetricGroup;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
@@ -51,8 +54,10 @@ import org.slf4j.LoggerFactory;
* table, after projection and pushed-down filters are applied.
*
* <p>The cache is loaded from the current snapshot either when the function
is opened or on the
- * first lookup, depending on {@link
IcebergLookupOptions#FULL_CACHE_EAGER_LOAD}. It is never
- * refreshed, so later changes to the table are not visible.
+ * first lookup, depending on {@link
IcebergLookupOptions#FULL_CACHE_EAGER_LOAD}. When a {@link
+ * CacheReloadTrigger} is configured, the cache is reloaded on the trigger's
schedule: a reload that
+ * finds no new snapshot keeps the loaded cache, and a reload that fails fails
the next lookup
+ * instead of serving the previously loaded cache.
*/
@Internal
public class IcebergFullCachingLookupFunction extends LookupFunction {
@@ -68,15 +73,22 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
private final List<Expression> pushedFilters;
private final boolean caseSensitive;
private final boolean eagerLoad;
+ private final @Nullable CacheReloadTrigger reloadTrigger;
private transient Table table;
private transient IcebergLookupReader reader;
private transient RowDataSerializer rowSerializer;
- private transient RowDataSerializer keySerializer;
+ // lookup() and reloads run on different threads, and toBinaryRow reuses its
output row
+ private transient RowDataSerializer lookupKeySerializer;
+ private transient RowDataSerializer loadKeySerializer;
private transient RowData.FieldGetter[] keyGetters;
- private transient InMemoryLookupCache cache;
+ private transient volatile InMemoryLookupCache cache;
+ private transient volatile Throwable reloadFailure;
+ private transient volatile boolean closed;
private transient Counter missCounter;
+ private transient Counter loadCounter;
+ private transient Counter loadFailuresCounter;
private transient volatile long currentSnapshotId;
private transient volatile long cachedRecords;
private transient volatile long latestLoadTimeMs;
@@ -87,13 +99,15 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
int[] lookupKeyIndexes,
List<Expression> pushedFilters,
boolean caseSensitive,
- boolean eagerLoad) {
+ boolean eagerLoad,
+ @Nullable CacheReloadTrigger reloadTrigger) {
this.tableLoader = tableLoader;
this.projectedRowType = projectedRowType;
this.lookupKeyIndexes = lookupKeyIndexes;
this.pushedFilters = pushedFilters;
this.caseSensitive = caseSensitive;
this.eagerLoad = eagerLoad;
+ this.reloadTrigger = reloadTrigger;
}
@Override
@@ -106,9 +120,12 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
MetricGroup metricGroup = context.getMetricGroup().addGroup(METRIC_GROUP);
this.missCounter = metricGroup.counter("missCount");
- this.currentSnapshotId = IcebergLookupReader.CURRENT_SNAPSHOT;
+ this.loadCounter = metricGroup.counter("loadCount");
+ this.loadFailuresCounter = metricGroup.counter("numLoadFailures");
+ this.currentSnapshotId = IcebergLookupReader.NO_SNAPSHOT_ID;
this.cachedRecords = 0L;
this.latestLoadTimeMs = UNINITIALIZED;
+ this.reloadFailure = null;
metricGroup.gauge("snapshotId", () -> currentSnapshotId);
metricGroup.gauge("numCachedRecords", () -> cachedRecords);
metricGroup.gauge("latestLoadTime", () -> latestLoadTimeMs);
@@ -129,6 +146,10 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
if (eagerLoad) {
loadCache();
}
+
+ if (reloadTrigger != null) {
+ reloadTrigger.open(new ReloadContext(this));
+ }
}
/**
@@ -137,11 +158,15 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
*/
@Override
public Collection<RowData> lookup(RowData keyRow) throws IOException {
- if (cache == null) {
+ checkReloadFailure();
+
+ InMemoryLookupCache currentCache = cache;
+ if (currentCache == null) {
loadCache();
+ currentCache = cache;
}
- List<RowData> hit = cache.get(keySerializer.toBinaryRow(keyRow));
+ List<RowData> hit =
currentCache.get(lookupKeySerializer.toBinaryRow(keyRow));
if (hit == null) {
missCounter.inc();
return Collections.emptyList();
@@ -152,22 +177,63 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
@Override
public void close() throws Exception {
+ this.closed = true;
+
try {
- tableLoader.close();
+ if (reloadTrigger != null) {
+ reloadTrigger.close();
+ }
} finally {
- if (cache != null) {
- cache.close();
+ try {
+ tableLoader.close();
+ } finally {
+ if (cache != null) {
+ cache.close();
+ }
+
+ super.close();
}
+ }
+ }
- super.close();
+ private CompletableFuture<Void> triggerReload() {
+ if (cache == null || closed || reloadFailure != null) {
+ return CompletableFuture.completedFuture(null);
+ }
+
+ try {
+ loadCache();
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable failure) {
+ if (closed) {
+ return CompletableFuture.completedFuture(null);
+ }
+
+ loadFailuresCounter.inc();
+ this.reloadFailure = failure;
+ LOG.error(
+ "IcebergFullCachingLookupFunction reload failed, the job will fail
on the next lookup "
+ + "instead of serving the previously loaded cache",
+ failure);
+ return CompletableFuture.failedFuture(failure);
}
}
- private void loadCache() throws IOException {
+ private synchronized void loadCache() throws IOException {
+ if (closed) {
+ return;
+ }
+
table.refresh();
Snapshot snapshot = table.currentSnapshot();
- long snapshotId =
- snapshot == null ? IcebergLookupReader.CURRENT_SNAPSHOT :
snapshot.snapshotId();
+ long snapshotId = snapshot == null ? IcebergLookupReader.NO_SNAPSHOT_ID :
snapshot.snapshotId();
+
+ if (cache != null && snapshotId == currentSnapshotId) {
+ LOG.info(
+ "IcebergFullCachingLookupFunction skipping reload, snapshot {} is
already cached",
+ snapshot == null ? "none" : snapshotId);
+ return;
+ }
LOG.info(
"IcebergFullCachingLookupFunction loading started, snapshot={},
committedAt={}, projected fields={}, pushedFilters={}",
@@ -181,22 +247,32 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
long start = System.currentTimeMillis();
try (CloseableIterable<RowData> rows = reader.read(snapshotId)) {
for (RowData row : rows) {
+ if (closed) {
+ return;
+ }
+
loaded.add(extractKey(row), rowSerializer.toBinaryRow(row).copy());
rowCnt++;
}
- } finally {
- this.latestLoadTimeMs = System.currentTimeMillis() - start;
+ }
+
+ long loadTimeMs = System.currentTimeMillis() - start;
+
+ if (closed) {
+ return;
}
this.cache = loaded;
this.currentSnapshotId = snapshotId;
this.cachedRecords = rowCnt;
+ this.latestLoadTimeMs = loadTimeMs;
+ loadCounter.inc();
LOG.info(
"IcebergFullCachingLookupFunction loading finished, snapshot={},
rows={}, cost={} ms",
snapshot == null ? "none" : snapshotId,
rowCnt,
- latestLoadTimeMs);
+ loadTimeMs);
}
private BinaryRowData extractKey(RowData row) {
@@ -205,7 +281,7 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
key.setField(i, keyGetters[i].getFieldOrNull(row));
}
- return keySerializer.toBinaryRow(key).copy();
+ return loadKeySerializer.toBinaryRow(key).copy();
}
private void createAccessors() {
@@ -218,6 +294,36 @@ public class IcebergFullCachingLookupFunction extends
LookupFunction {
}
this.rowSerializer = new RowDataSerializer(projectedRowType);
- this.keySerializer = new RowDataSerializer(keyTypes);
+ this.lookupKeySerializer = new RowDataSerializer(keyTypes);
+ this.loadKeySerializer = new RowDataSerializer(keyTypes);
+ }
+
+ private void checkReloadFailure() throws IOException {
+ Throwable failure = reloadFailure;
+ if (failure != null) {
+ throw new IOException(
+ "Lookup cache reload failed, failing the job instead of serving the
previously loaded cache",
+ failure);
+ }
+ }
+
+ private record ReloadContext(IcebergFullCachingLookupFunction function)
+ implements CacheReloadTrigger.Context {
+
+ @Override
+ public long currentProcessingTime() {
+ return System.currentTimeMillis();
+ }
+
+ @Override
+ public long currentWatermark() {
+ throw new UnsupportedOperationException(
+ "Watermarks are currently unsupported in cache reload triggers.");
+ }
+
+ @Override
+ public CompletableFuture<Void> triggerReload() {
+ return function.triggerReload();
+ }
}
}
diff --git
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
index d669178557..165b7e1327 100644
---
a/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
+++
b/flink/v2.2/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergLookupReader.java
@@ -43,7 +43,7 @@ import org.apache.iceberg.util.SnapshotUtil;
@Internal
class IcebergLookupReader {
- static final long CURRENT_SNAPSHOT = -1L;
+ static final long NO_SNAPSHOT_ID = -1L;
private final Table table;
private final Schema projectedSchema;
@@ -76,7 +76,7 @@ class IcebergLookupReader {
CloseableIterable<RowData> read(long snapshotId) {
Schema tableSchema =
- snapshotId == CURRENT_SNAPSHOT ? table.schema() :
SnapshotUtil.schemaFor(table, snapshotId);
+ snapshotId == NO_SNAPSHOT_ID ? table.schema() :
SnapshotUtil.schemaFor(table, snapshotId);
RowDataFileScanTaskReader fileReader =
new RowDataFileScanTaskReader(
@@ -84,7 +84,7 @@ class IcebergLookupReader {
TableScan scan =
table.newScan().caseSensitive(caseSensitive).project(projectedSchema).filter(filter);
- if (snapshotId != CURRENT_SNAPSHOT) {
+ if (snapshotId != NO_SNAPSHOT_ID) {
scan = scan.useSnapshot(snapshotId);
}
diff --git
a/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
b/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
index 40c13af6d4..de0be59917 100644
---
a/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
+++
b/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/TestIcebergLookupJoinSql.java
@@ -26,6 +26,7 @@ import java.io.IOException;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.types.Row;
+import org.apache.flink.util.CloseableIterator;
import org.apache.iceberg.DataFile;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Schema;
@@ -43,6 +44,8 @@ import org.junit.jupiter.api.Test;
/** Tests SQL lookup join with Iceberg table source. */
class TestIcebergLookupJoinSql extends TestSqlBase {
+ private static final long RELOAD_TIMEOUT_MS = 10_000L;
+
private static final Schema DIM_SCHEMA =
new Schema(
required(1, "user_id", Types.LongType.get()),
@@ -171,6 +174,91 @@ class TestIcebergLookupJoinSql extends TestSqlBase {
Row.of(3L, 3L, "carol", "guangzhou"));
}
+ @Test
+ void lookupJoinReloadsFullCacheFromNewSnapshot() throws Exception {
+ Table dimTable =
+ CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER,
DIM_SCHEMA);
+ GenericAppenderHelper helper =
+ new GenericAppenderHelper(dimTable, FileFormat.PARQUET,
temporaryFolder);
+ helper.appendToTable(
+ helper.writeFile(
+ Lists.newArrayList(
+ dimRecord(1L, "alice", "beijing"),
+ dimRecord(2L, "bob", "shanghai"),
+ dimRecord(3L, "carol", "guangzhou"))));
+
+ TableEnvironment streamEnv = getStreamingTableEnv();
+ // The probe emits randomized keys until the test stops it, so the reload
has time to pick up
+ // the snapshot appended below.
+ createRepeatingOrdersTable(streamEnv, "orders_reload_new_snapshot", 10);
+
+ String joinSql =
+ lookupJoinSql(
+ "o.user_id, u.name",
+ "orders_reload_new_snapshot",
+ "OPTIONS('lookup.full-cache.reload-strategy'='PERIODIC', "
+ + "'lookup.full-cache.periodic-reload.interval'='500 ms', "
+ +
"'lookup.full-cache.periodic-reload.schedule-mode'='FIXED_RATE')",
+ null);
+
+ try (CloseableIterator<Row> iter =
streamEnv.executeSql(joinSql).collect()) {
+ // The first row proves that the lookup function is open and the cache
is loaded from the
+ // snapshot that does not contain the row appended next.
+ assertThat(iter.next()).isNotNull();
+
+ helper.appendToTable(
+ helper.writeFile(Lists.newArrayList(dimRecord(10L, "henry",
"shenzhen"))));
+
+ long deadline = System.currentTimeMillis() + RELOAD_TIMEOUT_MS;
+ boolean reloaded = false;
+ while (!reloaded && System.currentTimeMillis() < deadline) {
+ reloaded = "henry".equals(iter.next().getField(1));
+ }
+
+ assertThat(reloaded).as("A reload must replace the cache with the latest
snapshot").isTrue();
+ }
+ }
+
+ @Test
+ void lookupJoinWithTimedReloadOptionsInTableDdl() throws Exception {
+ createDefaultDimTable();
+
+ TableEnvironment streamEnv = getStreamingTableEnv();
+ createOrdersTable(streamEnv, "orders_timed_reload", 3);
+
+ SqlHelpers.sql(
+ streamEnv,
+ "CREATE TABLE default_catalog.default_database.dim_users_timed_reload
(\n"
+ + " user_id BIGINT,\n"
+ + " name STRING,\n"
+ + " city STRING\n"
+ + ") WITH (\n"
+ + " 'connector' = 'iceberg',\n"
+ + " 'catalog-name' = 'iceberg_catalog',\n"
+ + " 'catalog-type' = 'hadoop',\n"
+ + " 'warehouse' = '%s',\n"
+ + " 'catalog-database' = '%s',\n"
+ + " 'catalog-table' = '%s',\n"
+ + " 'lookup.cache' = 'FULL',\n"
+ + " 'lookup.full-cache.reload-strategy' = 'TIMED',\n"
+ + " 'lookup.full-cache.timed-reload.iso-time' = '02:30'\n"
+ + ")",
+ CATALOG_EXTENSION.warehouse(),
+ TestFixtures.DATABASE,
+ TestFixtures.TABLE);
+
+ String joinSql =
+ "SELECT o.order_id, u.name\n"
+ + "FROM orders_timed_reload AS o\n"
+ + "LEFT JOIN
default_catalog.default_database.dim_users_timed_reload\n"
+ + " FOR SYSTEM_TIME AS OF o.proc_time AS u\n"
+ + " ON o.user_id = u.user_id";
+
+ assertThat(SqlHelpers.sql(streamEnv, joinSql))
+ .as("The timed reload options must be accepted as table options")
+ .containsExactlyInAnyOrder(Row.of(1L, "alice"), Row.of(2L, "bob"),
Row.of(3L, "carol"));
+ }
+
@Test
void lookupJoinAcceptsFullCacheType() throws Exception {
createDimTable(dimRecord(1L, "alice", "beijing"));
@@ -207,6 +295,25 @@ class TestIcebergLookupJoinSql extends TestSqlBase {
.hasStackTraceContaining("only supports lookup.cache=FULL");
}
+ @Test
+ void lookupJoinRejectsPeriodicReloadWithoutInterval() throws Exception {
+ createDimTable(dimRecord(1L, "alice", "beijing"));
+
+ TableEnvironment streamEnv = getStreamingTableEnv();
+ createOrdersTable(streamEnv, "orders_reload_without_interval", 1);
+
+ String joinSql =
+ lookupJoinSql(
+ "o.order_id, u.name",
+ "orders_reload_without_interval",
+ "OPTIONS('lookup.cache'='FULL',
'lookup.full-cache.reload-strategy'='PERIODIC')",
+ null);
+
+ assertThatThrownBy(() -> SqlHelpers.sql(streamEnv, joinSql))
+ .as("The reload configured in the SQL options is validated while
planning the join")
+ .hasStackTraceContaining("lookup.full-cache.periodic-reload.interval");
+ }
+
@Test
void lookupJoinLoadsCacheEagerlyByDefault() throws Exception {
String dataFileLocation = createEmptyProbeAndUnreadableDimTable();
@@ -288,6 +395,24 @@ class TestIcebergLookupJoinSql extends TestSqlBase {
helper.appendToTable(dataFile);
}
+ private static void createRepeatingOrdersTable(
+ TableEnvironment tableEnvironment, String tableName, int numberOfKeys) {
+ SqlHelpers.sql(
+ tableEnvironment,
+ "CREATE TEMPORARY TABLE %s (\n"
+ + " user_id BIGINT,\n"
+ + " proc_time AS PROCTIME()\n"
+ + ") WITH (\n"
+ + " 'connector' = 'datagen',\n"
+ + " 'fields.user_id.kind' = 'random',\n"
+ + " 'fields.user_id.min' = '1',\n"
+ + " 'fields.user_id.max' = '%d',\n"
+ + " 'rows-per-second' = '50'\n"
+ + ")",
+ tableName,
+ numberOfKeys);
+ }
+
private static void createOrdersTable(
TableEnvironment tableEnvironment, String tableName, int numberOfRows) {
SqlHelpers.sql(
diff --git
a/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestFullCacheReloadTriggerFactory.java
b/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestFullCacheReloadTriggerFactory.java
new file mode 100644
index 0000000000..639ef59e41
--- /dev/null
+++
b/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestFullCacheReloadTriggerFactory.java
@@ -0,0 +1,128 @@
+/*
+ * 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.iceberg.flink.source.lookup;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.time.Duration;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.table.connector.source.lookup.LookupOptions;
+import
org.apache.flink.table.connector.source.lookup.LookupOptions.ReloadStrategy;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.PeriodicCacheReloadTrigger;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.TimedCacheReloadTrigger;
+import org.junit.jupiter.api.Test;
+
+class TestFullCacheReloadTriggerFactory {
+
+ @Test
+ void reloadIsDisabledWhenNoReloadOptionIsConfigured() {
+ assertThat(FullCacheReloadTriggerFactory.create(new
Configuration())).isNull();
+ }
+
+ @Test
+ void reloadRequiresTheStrategyOption() {
+ Configuration intervalOnly = new Configuration();
+ intervalOnly.set(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
Duration.ofMinutes(5));
+ assertThat(FullCacheReloadTriggerFactory.create(intervalOnly))
+ .as("An interval without a strategy must not enable reload")
+ .isNull();
+
+ Configuration isoTimeOnly = new Configuration();
+ isoTimeOnly.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME, "10:15");
+ assertThat(FullCacheReloadTriggerFactory.create(isoTimeOnly))
+ .as("A time of day without a strategy must not enable reload")
+ .isNull();
+
+ Configuration intervalInDaysOnly = new Configuration();
+
intervalInDaysOnly.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_INTERVAL_IN_DAYS,
2);
+ assertThat(FullCacheReloadTriggerFactory.create(intervalInDaysOnly))
+ .as("An interval in days without a strategy must not enable reload")
+ .isNull();
+
+ Configuration scheduleModeOnly = new Configuration();
+ scheduleModeOnly.set(
+ LookupOptions.FULL_CACHE_PERIODIC_RELOAD_SCHEDULE_MODE,
+ PeriodicCacheReloadTrigger.ScheduleMode.FIXED_RATE);
+ assertThat(FullCacheReloadTriggerFactory.create(scheduleModeOnly))
+ .as("A schedule mode without a strategy must not enable reload")
+ .isNull();
+ }
+
+ @Test
+ void periodicReloadIsEnabledByStrategyAndInterval() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.PERIODIC);
+ lookupConf.set(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
Duration.ofMinutes(5));
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(PeriodicCacheReloadTrigger.class);
+ }
+
+ @Test
+ void timedReloadIsEnabledByStrategyAndLocalIsoTime() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+ lookupConf.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME, "10:15");
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(TimedCacheReloadTrigger.class);
+ }
+
+ @Test
+ void timedReloadIsEnabledByStrategyAndOffsetIsoTime() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+ lookupConf.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME,
"10:15+07:00");
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(TimedCacheReloadTrigger.class);
+ }
+
+ @Test
+ void strategySelectsTheTriggerOverTheOptionsOfTheOtherStrategy() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+ lookupConf.set(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL,
Duration.ofMinutes(5));
+ lookupConf.set(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME, "10:15");
+
+ assertThat(FullCacheReloadTriggerFactory.create(lookupConf))
+ .isInstanceOf(TimedCacheReloadTrigger.class);
+ }
+
+ @Test
+ void periodicReloadRequiresInterval() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.PERIODIC);
+
+ assertThatThrownBy(() -> FullCacheReloadTriggerFactory.create(lookupConf))
+ .as("The periodic strategy needs an interval")
+
.hasMessageContaining(LookupOptions.FULL_CACHE_PERIODIC_RELOAD_INTERVAL.key());
+ }
+
+ @Test
+ void timedReloadRequiresIsoTime() {
+ Configuration lookupConf = new Configuration();
+ lookupConf.set(LookupOptions.FULL_CACHE_RELOAD_STRATEGY,
ReloadStrategy.TIMED);
+
+ assertThatThrownBy(() -> FullCacheReloadTriggerFactory.create(lookupConf))
+ .as("The timed strategy needs the time of day to reload at")
+
.hasMessageContaining(LookupOptions.FULL_CACHE_TIMED_RELOAD_ISO_TIME.key());
+ }
+}
diff --git
a/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
b/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
index d13d89d17a..3e5e1e48df 100644
---
a/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
+++
b/flink/v2.2/flink/src/test/java/org/apache/iceberg/flink/source/lookup/TestIcebergLookup.java
@@ -20,16 +20,22 @@ package org.apache.iceberg.flink.source.lookup;
import static org.apache.iceberg.types.Types.NestedField.optional;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import javax.annotation.Nullable;
+import
org.apache.flink.table.connector.source.lookup.cache.trigger.CacheReloadTrigger;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.functions.FunctionContext;
import org.apache.flink.table.types.logical.RowType;
+import org.apache.iceberg.DataFile;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Table;
@@ -85,7 +91,7 @@ class TestIcebergLookup {
lookupReader(table, ImmutableList.of(Expressions.equal("category",
"B")), false);
List<List<Object>> rows = Lists.newArrayList();
- try (CloseableIterable<RowData> rowData =
reader.read(IcebergLookupReader.CURRENT_SNAPSHOT)) {
+ try (CloseableIterable<RowData> rowData =
reader.read(IcebergLookupReader.NO_SNAPSHOT_ID)) {
for (RowData row : rowData) {
rows.add(
ImmutableList.of(
@@ -102,12 +108,12 @@ class TestIcebergLookup {
List<Expression> filters = ImmutableList.of(Expressions.equal("CATEGORY",
"B"));
IcebergLookupReader caseSensitiveReader = lookupReader(table, filters,
true);
- assertThatThrownBy(() -> readIds(caseSensitiveReader,
IcebergLookupReader.CURRENT_SNAPSHOT))
+ assertThatThrownBy(() -> readIds(caseSensitiveReader,
IcebergLookupReader.NO_SNAPSHOT_ID))
.as("Case sensitive lookup should reject a filter that doesn't match
the column case")
.isInstanceOf(ValidationException.class)
.hasMessageContaining("CATEGORY");
- assertThat(readIds(lookupReader(table, filters, false),
IcebergLookupReader.CURRENT_SNAPSHOT))
+ assertThat(readIds(lookupReader(table, filters, false),
IcebergLookupReader.NO_SNAPSHOT_ID))
.containsExactly(2L);
}
@@ -123,7 +129,7 @@ class TestIcebergLookup {
assertThat(readIds(reader, pinnedSnapshot))
.as("Pinned snapshot should not contain the appended row")
.containsExactlyInAnyOrder(1L, 2L, 3L);
- assertThat(readIds(reader, IcebergLookupReader.CURRENT_SNAPSHOT))
+ assertThat(readIds(reader, IcebergLookupReader.NO_SNAPSHOT_ID))
.as("Current snapshot should contain the appended row")
.containsExactlyInAnyOrder(1L, 2L, 3L, 6L);
}
@@ -132,7 +138,7 @@ class TestIcebergLookup {
void lookupFunctionReturnsRowsFromCache() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L)))
@@ -152,7 +158,7 @@ class TestIcebergLookup {
void lookupFunctionWithMultiColumnKey() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_AND_CATEGORY_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_AND_CATEGORY_KEY_INDEXES, false,
null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L, "A")))
@@ -172,7 +178,7 @@ class TestIcebergLookup {
void lookupFunctionLoadsCacheLazily() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, null);
lookupFunction.open(new FunctionContext(null));
// Nothing is loaded yet, so the first lookup sees the row appended after
opening.
@@ -187,7 +193,7 @@ class TestIcebergLookup {
void lookupFunctionLoadsCacheEagerly() throws Exception {
Table table = createTableWithRecords();
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, true);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, null);
lookupFunction.open(new FunctionContext(null));
appendRecords(table, ImmutableList.of(record(6L, "frank", "D")));
@@ -202,7 +208,7 @@ class TestIcebergLookup {
void lookupFunctionHandlesEmptyTable() throws Exception {
CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER,
SCHEMA);
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, true);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L))).isEmpty();
@@ -216,7 +222,7 @@ class TestIcebergLookup {
ImmutableList.of(
record(1L, "alice", "A"), record(1L, "alice-2", "A"), record(2L,
"bob", "B")));
- lookupFunction = newLookupFunction(ID_KEY_INDEXES, false);
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L)))
@@ -238,7 +244,8 @@ class TestIcebergLookup {
ID_KEY_INDEXES,
ImmutableList.of(Expressions.equal("category", "B")),
true,
- false);
+ false,
+ null);
lookupFunction.open(new FunctionContext(null));
assertThat(lookupFunction.lookup(keyRow(1L))).isEmpty();
@@ -247,15 +254,117 @@ class TestIcebergLookup {
.satisfies(row -> assertRow(row, 2L, "bob", "B"));
}
+ @Test
+ void lookupFunctionReloadsCacheFromTrigger() throws Exception {
+ Table table =
CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER, SCHEMA);
+ DataFile initialFile = appendRecords(table, ImmutableList.of(record(1L,
"alice", "A")));
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+
+ assertThat(lookupFunction.lookup(keyRow(6L))).isEmpty();
+
+ appendRecords(table, ImmutableList.of(record(6L, "frank", "D")));
+ replaceFile(table, initialFile, ImmutableList.of(record(1L, "alicia",
"C")));
+
+ reloadTrigger.triggerReload().join();
+
+ assertThat(lookupFunction.lookup(keyRow(6L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 6L, "frank", "D"));
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .as("A reload must replace the rows cached for an overwritten key")
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alicia", "C"));
+ }
+
+ @Test
+ void lookupFunctionWithTriggerLoadsCacheLazily() throws Exception {
+ Table table = createTableWithRecords();
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, false, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ reloadTrigger.triggerReload().join();
+
+ appendRecords(table, ImmutableList.of(record(6L, "frank", "D")));
+
+ assertThat(lookupFunction.lookup(keyRow(6L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 6L, "frank", "D"));
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+
+ appendRecords(table, ImmutableList.of(record(7L, "grace", "E")));
+ reloadTrigger.triggerReload().join();
+ assertThat(lookupFunction.lookup(keyRow(7L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 7L, "grace", "E"));
+ }
+
+ @Test
+ void lookupFunctionSkipsReloadWhenSnapshotIsUnchanged() throws Exception {
+ Table table =
CATALOG_EXTENSION.catalog().createTable(TestFixtures.TABLE_IDENTIFIER, SCHEMA);
+ DataFile dataFile = appendRecords(table, ImmutableList.of(record(1L,
"alice", "A")));
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ table.io().deleteFile(dataFile.location());
+
+ assertThatCode(() -> reloadTrigger.triggerReload().join())
+ .as("A reload without a new snapshot must not read the table")
+ .doesNotThrowAnyException();
+
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .as("A reload without a new snapshot must keep serving the loaded
cache")
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+ }
+
+ @Test
+ void lookupFunctionFailsLookupsWhenReloadFails() throws Exception {
+ Table table = createTableWithRecords();
+ ManualCacheReloadTrigger reloadTrigger = new ManualCacheReloadTrigger();
+
+ lookupFunction = newLookupFunction(ID_KEY_INDEXES, true, reloadTrigger);
+ lookupFunction.open(new FunctionContext(null));
+
+ assertThat(lookupFunction.lookup(keyRow(1L)))
+ .singleElement()
+ .satisfies(row -> assertRow(row, 1L, "alice", "A"));
+
+ DataFile dataFile = appendRecords(table, ImmutableList.of(record(6L,
"frank", "D")));
+ table.io().deleteFile(dataFile.location());
+
+ assertThatThrownBy(() -> reloadTrigger.triggerReload().join())
+ .isInstanceOf(CompletionException.class)
+ .hasMessageContaining(dataFile.location());
+
+ assertThatThrownBy(() -> lookupFunction.lookup(keyRow(1L)))
+ .as("A failed reload must fail the lookup instead of serving the
previous cache")
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("Lookup cache reload failed");
+ }
+
private IcebergFullCachingLookupFunction newLookupFunction(
- int[] lookupKeyIndexes, boolean eagerLoad) {
+ int[] lookupKeyIndexes, boolean eagerLoad, @Nullable CacheReloadTrigger
reloadTrigger) {
return new IcebergFullCachingLookupFunction(
CATALOG_EXTENSION.tableLoader().clone(),
ROW_TYPE,
lookupKeyIndexes,
ImmutableList.of(),
false,
- eagerLoad);
+ eagerLoad,
+ reloadTrigger);
}
private static IcebergLookupReader lookupReader(
@@ -285,8 +394,18 @@ class TestIcebergLookup {
return table;
}
- private void appendRecords(Table table, List<Record> records) throws
Exception {
- new GenericAppenderHelper(table, FileFormat.PARQUET,
temporaryFolder).appendToTable(records);
+ private DataFile appendRecords(Table table, List<Record> records) throws
Exception {
+ GenericAppenderHelper helper =
+ new GenericAppenderHelper(table, FileFormat.PARQUET, temporaryFolder);
+ DataFile dataFile = helper.writeFile(records);
+ helper.appendToTable(dataFile);
+ return dataFile;
+ }
+
+ private void replaceFile(Table table, DataFile oldFile, List<Record>
records) throws Exception {
+ GenericAppenderHelper helper =
+ new GenericAppenderHelper(table, FileFormat.PARQUET, temporaryFolder);
+
table.newOverwrite().deleteFile(oldFile).addFile(helper.writeFile(records)).commit();
}
private static GenericRecord record(Long id, String data, String category) {
@@ -315,4 +434,20 @@ class TestIcebergLookup {
assertThat(row.getString(1)).hasToString(data);
assertThat(row.getString(2)).hasToString(category);
}
+
+ private static class ManualCacheReloadTrigger implements CacheReloadTrigger {
+ private Context context;
+
+ @Override
+ public void open(Context reloadContext) {
+ this.context = reloadContext;
+ }
+
+ @Override
+ public void close() {}
+
+ CompletableFuture<Void> triggerReload() {
+ return context.triggerReload();
+ }
+ }
}