This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new cc84f95737c [fix](iceberg) Backport #71202 to branch-4.2 (#71203)
cc84f95737c is described below
commit cc84f95737cda3395268d18f3e29b7f205f7d8f8
Author: Gabriel <[email protected]>
AuthorDate: Wed Dec 2 16:16:56 2026 +0800
[fix](iceberg) Backport #71202 to branch-4.2 (#71203)
### Background
Backport of #71202 to `branch-4.2`.
Doris optionally caches parsed Iceberg manifests per catalog. Iceberg V3
data files inherit row IDs from their manifest-list descriptor. A
physical manifest can be reused by snapshots whose inherited first row
IDs differ.
### What problem does this PR solve?
Issue Number: None
Related PR: #60937 (introduced the typed manifest cache), #61398
(introduced row-lineage reads), #71202 (backport from master)
PR Type: Bugfix
Problem Summary:
With `meta.cache.iceberg.manifest.enable=true` (default false), warming
a V2 manifest before upgrading to V3 can leave `_row_id` and
`_last_updated_sequence_number` NULL after the first V3 append.
Historical reads and branches can also borrow another descriptor's
inherited IDs. Include the nullable inherited first row ID in cache
identity so parsed files agree with the Iceberg SDK; most of the diff
adds tests.
### Details
- **Change map:** Production code +19/-5, tests +428/-0, generated
output +75/-0; most changes are tests. The production change adds the
inherited row-ID dimension and accounts for its retained boxed value in
cache weight.
- **Frequency:** Always when different row-ID descriptors reuse a warmed
physical manifest. A property-only format upgrade does not assign IDs;
the subsequent V3 commit does.
- **Root cause:** `IcebergManifestEntryKey.of` used path and content
alone, although parsed files retain descriptor-derived row IDs. The SDK
baseline expects 5 for a reused manifest where the warmed cache returns
NULL.
- **Why existing tests missed it:** `IcebergExternalMetaCacheTest`
covers cache loading and invalidation, but do not reuse an actual V2
manifest under new V3 descriptors. `test_iceberg_manifest_cache` covers
refresh/reuse and the V3 lineage suites cover reads/DML, without
preserving a warmed V2 parsed entry through this upgrade. The new
external regression asserts cache hits and independently reads committed
manifest-list descriptors to prove the trigger.
- **Fix:** Keep NULL distinct from zero and from every assigned ID.
Equivalent descriptors continue sharing cached files; table refresh
still preserves reusable immutable manifests. Cache weight includes the
additional retained Long.
- **Other paths and branches:** Shared cache identity covers loading,
prefetch and cache-only probes across formats/catalogs. This backport
applies the master fix in #71202 to branch-4.2. Branch-4.1 has the same
pattern and needs a separate backport; branch-3.1 and branch-4.0 lack
the row-lineage consumer. No wire or storage format changes.
### Testing
- `IcebergManifestRowLineageCacheTest`: all seven cases failed on the
baseline and passed after the fix. Real in-memory Iceberg tables and SDK
scans cover NULL/zero, upgrade, historical context, distinct branch IDs
and equivalent-descriptor reuse.
- 114 targeted FE tests passed locally, including all seven new cases,
104 cache cases and three native-prefetch cases.
- The same Parquet/ORC SQL regression and generated golden file are
included. Local manual checks used this branch's FE for cached/uncached
scans and master FE for writes: upgrade, both batch modes, historical
reads and post-UPDATE/MERGE lineage comparisons passed. The complete
suite passed on master.
### Notes for Reviewers
Branch-specific adaptation: branch-4.2 keeps this cache in `fe-core`, so
the nullable row-ID key field and its retained-value weight are added
there. Master already has that key field for V4; #71202 updates the
V2/V3 key factory in the connector module.
The standalone branch-4.2 SQL suite could not pass its initial INSERT
against the available master BE: `External-file writes require a
coordinator that acknowledges external-file reports`. A matching
branch-4.2 BE is still needed to execute all writes through this branch.
Native branch CI remains required. The regression uses the existing
external Iceberg fixture and `external` / `external_docker` groups with
`enableIcebergTest=true`.
### Release note
Fix incorrect Iceberg V3 row lineage when the parsed-manifest cache
reuses a manifest across format upgrades or snapshots with different
inherited row IDs.
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: standalone branch-4.2 SQL
regression needs a matching BE; unit tests and candidate-FE scan
comparisons passed
### AI Disclosure
- Tool: Codex / GPT-6
- Generated: Code, tests and this description
- Human review: not stated
---
.../iceberg/IcebergCacheSizeEstimator.java | 2 +
.../iceberg/IcebergExternalMetaCache.java | 2 +-
.../iceberg/IcebergManifestEntryKey.java | 20 +-
.../IcebergManifestRowLineageCacheTest.java | 234 +++++++++++++++++++++
.../test_iceberg_manifest_row_lineage_cache.out | 75 +++++++
.../test_iceberg_manifest_row_lineage_cache.groovy | 194 +++++++++++++++++
6 files changed, 522 insertions(+), 5 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergCacheSizeEstimator.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergCacheSizeEstimator.java
index 651398fa83d..480345c376b 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergCacheSizeEstimator.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergCacheSizeEstimator.java
@@ -128,6 +128,7 @@ final class IcebergCacheSizeEstimator {
*/
private static final long AUTHENTICATION_CONTEXT_WEIGHT = 16L * 1024L;
private static final long MANIFEST_ENTRY_BASE_WEIGHT = 512L;
+ private static final long MANIFEST_ROW_ID_WEIGHT = 24L;
private static final long DATA_FILE_WEIGHT = 1024L;
private static final long DELETE_FILE_WEIGHT = 1024L;
private static final long FILE_METRIC_ENTRY_WEIGHT = 128L;
@@ -213,6 +214,7 @@ final class IcebergCacheSizeEstimator {
long bytes = MetaCacheWeightUtils.saturatedAdd(
MANIFEST_ENTRY_BASE_WEIGHT,
MetaCacheWeightUtils.estimatedStringBytes(key.getManifestPath()));
+ bytes = MetaCacheWeightUtils.saturatedAdd(bytes, key.getFirstRowId()
== null ? 0L : MANIFEST_ROW_ID_WEIGHT);
bytes = addCount(bytes, value.getDataFiles().size(), DATA_FILE_WEIGHT);
bytes = addCount(bytes, value.getDeleteFiles().size(),
DELETE_FILE_WEIGHT);
bytes = addCount(bytes, value.getDataFileMetricEntryCount(),
FILE_METRIC_ENTRY_WEIGHT);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
index 5d4a43036a8..4eaed81a33f 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
@@ -84,7 +84,7 @@ import javax.annotation.Nullable;
* <li>{@code snapshot}: immutable snapshot projections keyed by a stable
metadata generation</li>
* <li>{@code view}: loaded Iceberg {@link View} instances</li>
* <li>{@code manifest}: parsed manifest payload ({@link
ManifestCacheValue}) keyed by
- * manifest path and content type</li>
+ * manifest path, content type and inherited first row ID</li>
* <li>{@code schema}: schema cache keyed by table identity + schema id</li>
* </ul>
*
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergManifestEntryKey.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergManifestEntryKey.java
index 3d6499333be..923dce17f2b 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergManifestEntryKey.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergManifestEntryKey.java
@@ -25,20 +25,27 @@ import java.util.Objects;
/**
* Cache key for one iceberg manifest entry.
*
- * <p>This key only contains stable identity dimensions (manifest path +
content type).
+ * <p>This key contains the manifest path, content type, and inherited first
row ID.
* Runtime loader context (manifest instance, table instance) must not be
stored here.
*/
public class IcebergManifestEntryKey {
private final String manifestPath;
private final ManifestContent content;
+ private final Long firstRowId;
public IcebergManifestEntryKey(String manifestPath, ManifestContent
content) {
+ this(manifestPath, content, null);
+ }
+
+ private IcebergManifestEntryKey(String manifestPath, ManifestContent
content, Long firstRowId) {
this.manifestPath = Objects.requireNonNull(manifestPath, "manifestPath
can not be null");
this.content = Objects.requireNonNull(content, "content can not be
null");
+ this.firstRowId = firstRowId;
}
public static IcebergManifestEntryKey of(ManifestFile manifest) {
- return new IcebergManifestEntryKey(manifest.path(),
manifest.content());
+ // A V2-to-V3 commit assigns row IDs without rewriting the manifest;
parsed files inherit that context.
+ return new IcebergManifestEntryKey(manifest.path(),
manifest.content(), manifest.firstRowId());
}
public String getManifestPath() {
@@ -49,6 +56,10 @@ public class IcebergManifestEntryKey {
return content;
}
+ Long getFirstRowId() {
+ return firstRowId;
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -59,11 +70,12 @@ public class IcebergManifestEntryKey {
}
IcebergManifestEntryKey that = (IcebergManifestEntryKey) o;
return Objects.equals(manifestPath, that.manifestPath)
- && content == that.content;
+ && content == that.content
+ && Objects.equals(firstRowId, that.firstRowId);
}
@Override
public int hashCode() {
- return Objects.hash(manifestPath, content);
+ return Objects.hash(manifestPath, content, firstRowId);
}
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergManifestRowLineageCacheTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergManifestRowLineageCacheTest.java
new file mode 100644
index 00000000000..6dae7ebf48b
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergManifestRowLineageCacheTest.java
@@ -0,0 +1,234 @@
+// 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.doris.datasource.iceberg;
+
+import org.apache.doris.datasource.ExternalTable;
+import org.apache.doris.datasource.NameMapping;
+import org.apache.doris.datasource.iceberg.cache.ManifestCacheValue;
+import org.apache.doris.datasource.metacache.MetaCacheEntry;
+
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.inmemory.InMemoryCatalog;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+class IcebergManifestRowLineageCacheTest {
+ private static final Schema SCHEMA = new Schema(
+ Types.NestedField.optional(1, "id", Types.IntegerType.get()));
+
+ @ParameterizedTest
+ @CsvSource({"0,false", "0,true", "5,false", "5,true"})
+ void upgradedManifestDoesNotReusePreUpgradeFiles(int addedRows, boolean
asynchronous) throws Exception {
+ try (InMemoryCatalog catalog = catalog(); LineageCache cache = new
LineageCache()) {
+ Table table = v2Table(catalog);
+ ManifestFile before =
table.currentSnapshot().dataManifests(table.io()).get(0);
+ ManifestCacheValue old = cache.getManifestCacheValue(before,
table);
+ Assertions.assertNull(old.getDataFiles().get(0).firstRowId());
+
+ table.updateProperties().set("format-version", "3").commit();
+ Assertions.assertSame(old, cache.getManifestCacheValue(before,
table),
+ "a property-only upgrade has not assigned row IDs to the
old snapshot");
+ append(table, "/data/new.parquet", addedRows);
+ ManifestFile upgraded = manifestAt(table, before.path());
+ Assertions.assertEquals((long) addedRows, upgraded.firstRowId());
+ Assertions.assertEquals(before.path(), upgraded.path());
+
+ ManifestCacheValue current = asynchronous
+ ? cache.getManifestCacheValueFuture(upgraded, table,
"upgraded").toCompletableFuture().join()
+ : cache.getManifestCacheValue(upgraded, table);
+ assertMatchesSdk(table, current,
table.currentSnapshot().snapshotId());
+ Assertions.assertNotSame(old, current);
+ Assertions.assertSame(current, cache.cached(upgraded));
+ Assertions.assertSame(old, cache.getManifestCacheValue(before,
table),
+ "the upgrade must not contaminate the historical manifest
context");
+ }
+ }
+
+ @Test
+ void warmProbeSeparatesHistoricalAndCurrentManifests() throws Exception {
+ try (InMemoryCatalog catalog = catalog(); LineageCache cache = new
LineageCache()) {
+ Table table = v2Table(catalog);
+ long oldSnapshot = table.currentSnapshot().snapshotId();
+ ManifestFile before =
table.currentSnapshot().dataManifests(table.io()).get(0);
+ table.updateProperties().set("format-version", "3").commit();
+ append(table, "/data/new.parquet", 5);
+ ManifestFile upgraded = manifestAt(table, before.path());
+
+ ManifestCacheValue current =
cache.getManifestCacheValueFuture(upgraded, table, "current")
+ .toCompletableFuture().join();
+ Assertions.assertNull(cache.cached(before),
+ "warming V3 must not make the V2 context a cache hit");
+ ManifestCacheValue historical =
cache.getManifestCacheValueFuture(before, table, "historical")
+ .toCompletableFuture().join();
+ assertMatchesSdk(table, historical, oldSnapshot);
+ assertMatchesSdk(table, current,
table.currentSnapshot().snapshotId());
+ Assertions.assertSame(historical,
cache.getManifestCacheValue(before, table));
+ Assertions.assertSame(current,
cache.getManifestCacheValue(upgraded, table));
+ }
+ }
+
+ @Test
+ void branchesSharingAManifestKeepTheirOwnInheritedRowIds() throws
Exception {
+ try (InMemoryCatalog catalog = catalog(); LineageCache cache = new
LineageCache()) {
+ Table table = v2Table(catalog);
+ long oldSnapshot = table.currentSnapshot().snapshotId();
+ String sharedPath =
table.currentSnapshot().dataManifests(table.io()).get(0).path();
+ table.updateProperties().set("format-version", "3").commit();
+ append(table, "/data/main.parquet", 5);
+ long mainSnapshot = table.currentSnapshot().snapshotId();
+ ManifestFile main = manifestAt(table, sharedPath);
+ table.manageSnapshots().createBranch("other",
oldSnapshot).commit();
+
table.newFastAppend().toBranch("other").appendFile(file("/data/other.parquet",
1)).commit();
+ long otherSnapshot = table.refs().get("other").snapshotId();
+ ManifestFile other =
table.snapshot(otherSnapshot).dataManifests(table.io()).stream()
+ .filter(manifest ->
manifest.path().equals(sharedPath)).findFirst().orElseThrow(IllegalStateException::new);
+ Assertions.assertNotEquals(main.firstRowId(), other.firstRowId());
+ ManifestCacheValue mainFiles = cache.getManifestCacheValue(main,
table);
+ ManifestCacheValue otherFiles =
cache.getManifestCacheValueFuture(other, table, "other")
+ .toCompletableFuture().join();
+ assertMatchesSdk(table, mainFiles, mainSnapshot);
+ assertMatchesSdk(table, otherFiles, otherSnapshot);
+ Assertions.assertNotSame(mainFiles, otherFiles);
+ Assertions.assertSame(mainFiles,
cache.getManifestCacheValue(main.copy(), table),
+ "equivalent descriptors must still share parsed files");
+ }
+ }
+
+ @Test
+ void keyFactoryDistinguishesNullAndZeroAndAccountsForTheBoxedId() throws
Exception {
+ try (InMemoryCatalog catalog = catalog()) {
+ Table table = v2Table(catalog);
+ ManifestFile before =
table.currentSnapshot().dataManifests(table.io()).get(0);
+ table.updateProperties().set("format-version", "3").commit();
+ append(table, "/data/empty.parquet", 0);
+ ManifestFile upgraded = manifestAt(table, before.path());
+ Assertions.assertEquals(0L, upgraded.firstRowId());
+ IcebergManifestEntryKey legacy =
IcebergManifestEntryKey.of(before);
+ IcebergManifestEntryKey zero =
IcebergManifestEntryKey.of(upgraded);
+ Assertions.assertNotEquals(legacy, zero);
+ HashSet<IcebergManifestEntryKey> contexts = new HashSet<>();
+ contexts.add(legacy);
+ contexts.add(zero);
+ contexts.add(IcebergManifestEntryKey.of(upgraded.copy()));
+ Assertions.assertEquals(2, contexts.size());
+ ManifestCacheValue empty =
ManifestCacheValue.forDataFiles(Collections.emptyList());
+
Assertions.assertTrue(IcebergCacheSizeEstimator.estimateManifestEntry(zero,
empty).getBytes()
+ > IcebergCacheSizeEstimator.estimateManifestEntry(legacy,
empty).getBytes());
+ }
+ }
+
+ private static void assertMatchesSdk(Table table, ManifestCacheValue
value, long snapshotId) throws Exception {
+ Map<String, DataFile> expected = new HashMap<>();
+ try (CloseableIterable<FileScanTask> tasks =
table.newScan().useSnapshot(snapshotId).planFiles()) {
+ for (FileScanTask task : tasks) {
+ expected.put(task.file().location(), task.file());
+ }
+ }
+ Assertions.assertFalse(value.getDataFiles().isEmpty());
+ for (DataFile file : value.getDataFiles()) {
+ DataFile sdk = expected.get(file.location());
+ Assertions.assertNotNull(sdk);
+ Assertions.assertEquals(sdk.firstRowId(), file.firstRowId(),
file.location());
+ Assertions.assertEquals(sdk.fileSequenceNumber(),
file.fileSequenceNumber(), file.location());
+ }
+ }
+
+ private static InMemoryCatalog catalog() {
+ InMemoryCatalog catalog = new InMemoryCatalog();
+ catalog.initialize("test", Collections.emptyMap());
+ catalog.createNamespace(Namespace.of("db"));
+ return catalog;
+ }
+
+ private static Table v2Table(InMemoryCatalog catalog) {
+ Table table = catalog.createTable(TableIdentifier.of("db", "lineage"),
SCHEMA,
+ PartitionSpec.unpartitioned(),
Collections.singletonMap("format-version", "2"));
+ append(table, "/data/old.parquet", 10);
+ return table;
+ }
+
+ private static void append(Table table, String path, int rows) {
+ table.newFastAppend().appendFile(file(path, rows)).commit();
+ }
+
+ private static DataFile file(String path, int rows) {
+ return DataFiles.builder(PartitionSpec.unpartitioned()).withPath(path)
+ .withFileSizeInBytes(100).withRecordCount(rows).build();
+ }
+
+ private static ManifestFile manifestAt(Table table, String path) {
+ return table.currentSnapshot().dataManifests(table.io()).stream()
+ .filter(manifest ->
manifest.path().equals(path)).findFirst().orElseThrow(IllegalStateException::new);
+ }
+
+ private static final class LineageCache implements AutoCloseable {
+ private final ExecutorService executor =
Executors.newFixedThreadPool(2);
+ private final IcebergExternalMetaCache delegate = new
IcebergExternalMetaCache(executor);
+ private final ExternalTable dorisTable =
Mockito.mock(ExternalTable.class);
+ private final MetaCacheEntry<IcebergManifestEntryKey,
ManifestCacheValue> entry;
+
+ private LineageCache() {
+ delegate.initCatalog(1L,
Collections.singletonMap("meta.cache.iceberg.manifest.enable", "true"));
+
Mockito.when(dorisTable.getOrBuildNameMapping()).thenReturn(NameMapping.createForTest(1L,
"db", "lineage"));
+ entry = delegate.entry(1L, IcebergExternalMetaCache.ENTRY_MANIFEST,
+ IcebergManifestEntryKey.class, ManifestCacheValue.class);
+ }
+
+ private ManifestCacheValue getManifestCacheValue(ManifestFile
manifest, Table table) {
+ return delegate.getManifestCacheValue(dorisTable, manifest, table,
null, ignored -> { });
+ }
+
+ private CompletableFuture<ManifestCacheValue>
getManifestCacheValueFuture(
+ ManifestFile manifest, Table table, String queryId) {
+ return CompletableFuture.supplyAsync(() ->
getManifestCacheValue(manifest, table), executor);
+ }
+
+ private ManifestCacheValue cached(ManifestFile manifest) {
+ return entry.getIfPresent(IcebergManifestEntryKey.of(manifest));
+ }
+
+ @Override
+ public void close() throws InterruptedException {
+ delegate.invalidateCatalog(1L);
+ executor.shutdownNow();
+ Assertions.assertTrue(executor.awaitTermination(10,
TimeUnit.SECONDS));
+ }
+ }
+}
diff --git
a/regression-test/data/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.out
b/regression-test/data/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.out
new file mode 100644
index 00000000000..cd37c3270e2
--- /dev/null
+++
b/regression-test/data/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.out
@@ -0,0 +1,75 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !parquet_property_only --
+1 \N \N
+2 \N \N
+3 \N \N
+
+-- !parquet_upgraded_false --
+1 true true
+2 true true
+3 true true
+4 true true
+5 true true
+
+-- !parquet_upgraded_true --
+1 true true
+2 true true
+3 true true
+4 true true
+5 true true
+
+-- !parquet_historical_0 --
+1 \N \N
+2 \N \N
+3 \N \N
+
+-- !parquet_historical_1 --
+1 \N \N
+2 \N \N
+3 \N \N
+
+-- !parquet_after_dml --
+1 11 true true
+2 22 true true
+3 30 true true
+4 40 true true
+5 50 true true
+6 60 true true
+
+-- !orc_property_only --
+1 \N \N
+2 \N \N
+3 \N \N
+
+-- !orc_upgraded_false --
+1 true true
+2 true true
+3 true true
+4 true true
+5 true true
+
+-- !orc_upgraded_true --
+1 true true
+2 true true
+3 true true
+4 true true
+5 true true
+
+-- !orc_historical_0 --
+1 \N \N
+2 \N \N
+3 \N \N
+
+-- !orc_historical_1 --
+1 \N \N
+2 \N \N
+3 \N \N
+
+-- !orc_after_dml --
+1 11 true true
+2 22 true true
+3 30 true true
+4 40 true true
+5 50 true true
+6 60 true true
+
diff --git
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.groovy
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.groovy
new file mode 100644
index 00000000000..a45645553a2
--- /dev/null
+++
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_manifest_row_lineage_cache.groovy
@@ -0,0 +1,194 @@
+// 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.
+
+import com.amazonaws.auth.AWSStaticCredentialsProvider
+import com.amazonaws.auth.BasicAWSCredentials
+import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
+import com.amazonaws.services.s3.AmazonS3ClientBuilder
+import groovy.json.JsonSlurper
+import org.apache.avro.file.DataFileStream
+import org.apache.avro.generic.GenericDatumReader
+
+suite("test_iceberg_manifest_row_lineage_cache",
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+ if
(!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest")))
{
+ return
+ }
+
+ String externalEnvIp = context.config.otherConfigs.get("externalEnvIp")
+ String restPort = context.config.otherConfigs.get("iceberg_rest_uri_port")
+ String minioPort = context.config.otherConfigs.get("iceberg_minio_port")
+ String writerCatalog = "manifest_lineage_writer"
+ String warmCatalog = "manifest_lineage_warm"
+ String coldCatalog = "manifest_lineage_cold"
+ String dbName = "manifest_row_lineage_cache_db"
+ def catalogs = [writerCatalog, warmCatalog, coldCatalog]
+ def oldBatchMode = sql("show variables like
'enable_external_table_batch_mode'")[0][1]
+ def oldBatchSize = sql("show variables like
'num_files_in_batch_mode'")[0][1]
+ def minio = AmazonS3ClientBuilder.standard()
+ .withEndpointConfiguration(new
EndpointConfiguration("http://${externalEnvIp}:${minioPort}", "us-east-1"))
+ .withPathStyleAccessEnabled(true)
+ .withCredentials(new AWSStaticCredentialsProvider(new
BasicAWSCredentials("admin", "password")))
+ .build()
+
+ def manifestState = { table ->
+ def connection = new
URL("http://${externalEnvIp}:${restPort}/v1/namespaces/${dbName}/tables/${table}")
+ .openConnection()
+ connection.connectTimeout = 10000
+ connection.readTimeout = 10000
+ def metadata
+ try {
+ metadata = connection.inputStream.withCloseable { new
JsonSlurper().parse(it).metadata }
+ } finally {
+ connection.disconnect()
+ }
+ def snapshot = metadata.snapshots.find { it['snapshot-id'] ==
metadata['current-snapshot-id'] }
+ assertTrue(snapshot != null)
+ def location = new URI(snapshot['manifest-list'].toString())
+ Map inheritedIds = [:]
+ // Read the committed descriptor independently of Doris's
parsed-manifest cache and metadata scanner.
+ minio.getObject(location.host,
location.path.substring(1)).withCloseable { object ->
+ new DataFileStream(object.objectContent, new
GenericDatumReader()).withCloseable { reader ->
+ reader.each { record ->
+ inheritedIds[record.get('manifest_path').toString()] =
+ record.schema.getField('first_row_id') == null ?
null : record.get('first_row_id')
+ }
+ }
+ }
+ return [snapshotId: metadata['current-snapshot-id'], firstRowIds:
inheritedIds]
+ }
+
+ def assertCacheHit = { query ->
+ String plan = sql("explain verbose ${query}").collect { it[0]
}.join("\n")
+ def stats = plan =~ /manifest cache: hits=(\d+), misses=(\d+),
failures=(\d+)/
+ assertTrue(stats.find(), plan)
+ assertTrue(stats.group(1).toLong() > 0, plan)
+ assertEquals(0L, stats.group(3).toLong())
+ }
+
+ def refresh = { catalog, table -> sql "refresh table
${catalog}.${dbName}.${table}" }
+ def lineage = { catalog, table, suffix = "" ->
+ return sql("""select id, _row_id, _last_updated_sequence_number
+ from ${catalog}.${dbName}.${table}${suffix} order by id""")
+ }
+ def assertSdkMatches = { table ->
+ refresh(writerCatalog, table)
+ def expected = lineage(writerCatalog, table)
+ [warmCatalog, coldCatalog].each { catalog ->
+ refresh(catalog, table)
+ assertEquals(expected, lineage(catalog, table))
+ }
+ return expected.collectEntries { row ->
+ [(row[0].toString().toInteger()): [row[1].toString().toLong(),
row[2].toString().toLong()]]
+ }
+ }
+
+ try {
+ catalogs.each { catalog ->
+ sql "drop catalog if exists ${catalog}"
+ sql """create catalog ${catalog} properties (
+ 'type' = 'iceberg',
+ 'iceberg.catalog.type' = 'rest',
+ 'uri' = 'http://${externalEnvIp}:${restPort}',
+ 's3.access_key' = 'admin',
+ 's3.secret_key' = 'password',
+ 's3.endpoint' = 'http://${externalEnvIp}:${minioPort}',
+ 's3.region' = 'us-east-1',
+ 'meta.cache.iceberg.manifest.enable' = '${catalog !=
writerCatalog}'
+ )"""
+ }
+ sql "create database if not exists ${writerCatalog}.${dbName}"
+ sql "set num_files_in_batch_mode = 1"
+
+ ["parquet", "orc"].each { format ->
+ String tableName = "upgrade_${format}"
+ String writer = "${writerCatalog}.${dbName}.${tableName}"
+ String warm = "${warmCatalog}.${dbName}.${tableName}"
+ String cold = "${coldCatalog}.${dbName}.${tableName}"
+ sql "drop table if exists ${writer}"
+ sql """create table ${writer} (id int, value int)
+ properties ('format-version' = '2', 'write.format.default' =
'${format}',
+ 'commit.manifest-merge.enabled' = 'false',
+ 'write.update.mode' = 'merge-on-read', 'write.merge.mode'
= 'merge-on-read')"""
+ sql "insert into ${writer} values (1, 10), (2, 20), (3, 30)"
+ def oldState = manifestState(tableName)
+ def oldSnapshot = oldState.snapshotId
+ assertTrue(!oldState.firstRowIds.isEmpty())
+ oldState.firstRowIds.values().each { id -> assertTrue(id == null) }
+
+ refresh(warmCatalog, tableName)
+ sql "set enable_external_table_batch_mode = false"
+ String warmQuery = "select id, value from ${warm} order by id"
+ sql warmQuery
+ assertCacheHit(warmQuery)
+
+ // Writing through a separate catalog leaves the warmed
parsed-manifest cache intact.
+ sql "alter table ${writer} set ('format-version' = '3')"
+ refresh(warmCatalog, tableName)
+ "qt_${format}_property_only"("""select id, _row_id,
_last_updated_sequence_number
+ from ${warm} order by id""")
+ sql "insert into ${writer} values (4, 40), (5, 50)"
+ def newState = manifestState(tableName)
+
assertTrue(newState.firstRowIds.keySet().containsAll(oldState.firstRowIds.keySet()),
+ "the trigger requires reusing the pre-upgrade physical
manifest")
+ oldState.firstRowIds.keySet().each { path ->
assertTrue(newState.firstRowIds[path] != null) }
+
+ [false, true].each { batchMode ->
+ sql "set enable_external_table_batch_mode = ${batchMode}"
+ refresh(warmCatalog, tableName)
+ "qt_${format}_upgraded_${batchMode}"("""select id,
+ _row_id is not null, _last_updated_sequence_number is not
null
+ from ${warm} order by id""")
+ assertEquals(lineage(writerCatalog, tableName),
lineage(warmCatalog, tableName))
+ if (!batchMode) {
+ assertCacheHit("select id, _row_id from ${warm} order by
id")
+ }
+ }
+
+ // This catalog first sees V3; a later historical read must not
borrow its inherited IDs.
+ refresh(coldCatalog, tableName)
+ lineage(coldCatalog, tableName)
+ [warm, cold].eachWithIndex { table, index ->
+ "qt_${format}_historical_${index}"("""select id, _row_id,
+ _last_updated_sequence_number from ${table}
+ for version as of ${oldSnapshot} order by id""")
+ }
+ Map before = assertSdkMatches(tableName)
+
+ sql "update ${warm} set value = value + 1 where id = 1"
+ Map updated = assertSdkMatches(tableName)
+ assertEquals(before[1][0], updated[1][0])
+ assertTrue(updated[1][1] > before[1][1])
+ [2, 3, 4, 5].each { id -> assertEquals(before[id], updated[id]) }
+
+ sql """merge into ${warm} t using
+ (select 2 as id, 22 as value union all select 6, 60) s
+ on t.id = s.id
+ when matched then update set value = s.value
+ when not matched then insert (id, value) values (s.id,
s.value)"""
+ Map merged = assertSdkMatches(tableName)
+ assertEquals(updated[2][0], merged[2][0])
+ assertTrue(merged[2][1] > updated[2][1])
+ [1, 3, 4, 5].each { id -> assertEquals(updated[id], merged[id]) }
+ "qt_${format}_after_dml"("""select id, value, _row_id is not null,
+ _last_updated_sequence_number is not null from ${warm} order
by id""")
+ }
+ } finally {
+ minio.shutdown()
+ sql "set enable_external_table_batch_mode = ${oldBatchMode}"
+ sql "set num_files_in_batch_mode = ${oldBatchSize}"
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]