This is an automated email from the ASF dual-hosted git repository.

Gabriel39 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 9bfd9456e90 [fix](iceberg) Isolate manifest caches by inherited row 
IDs (#71202)
9bfd9456e90 is described below

commit 9bfd9456e909e4e58b2683a4f136a24d12450d99
Author: Gabriel <[email protected]>
AuthorDate: Tue Dec 1 15:53:34 2026 +0800

    [fix](iceberg) Isolate manifest caches by inherited row IDs (#71202)
    
    ### Background
    
    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), #64304 (connector migration), #70869 (V4
    cache provenance retained), #71203 (companion branch fix)
    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 +9/-5, tests +392/-2, generated output
    +75/-0; most changes are tests. The production change supplies inherited
    row IDs to the existing key and updates its documentation.
    - **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:** `IcebergManifestCacheTest` and
    `IcebergManifestEntryKeyTest` cover cache reuse and key identity, 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. Existing V4 provenance
    dimensions remain intact.
    - **Other paths and branches:** Shared cache identity covers loading,
    prefetch and cache-only probes across formats/catalogs. Master and
    branch-4.2 receive companion fixes. 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.
    - 206 targeted connector tests passed locally, including all seven new
    cases and 133 V4 read cases.
    - `test_iceberg_manifest_row_lineage_cache`: generated and independently
    checked 12 result sections / 50 rows, then replayed successfully
    locally. Parquet and ORC cover property-only upgrade, reused manifests,
    both batch modes, historical reads, SDK equality, UPDATE and MERGE
    lineage preservation.
    
    ### Notes for Reviewers
    
    Local SQL verification used the candidate-built FE and a prebuilt ASAN
    BE at `dc02018bb2`, with execution protocol 19. No BE code changes are
    included. 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: Ready
    
    ### AI Disclosure
    
    - Tool: Codex / GPT-6
    - Generated: Code, tests and this description
    - Human review: not stated
---
 .../iceberg/IcebergCacheSizeEstimator.java         |   2 +-
 .../connector/iceberg/IcebergManifestCache.java    |   3 +-
 .../connector/iceberg/IcebergManifestEntryKey.java |   9 +-
 .../iceberg/IcebergManifestEntryKeyTest.java       |   4 +-
 .../IcebergManifestRowLineageCacheTest.java        | 196 +++++++++++++++++++++
 .../test_iceberg_manifest_row_lineage_cache.out    |  75 ++++++++
 .../test_iceberg_manifest_row_lineage_cache.groovy | 194 ++++++++++++++++++++
 7 files changed, 476 insertions(+), 7 deletions(-)

diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergCacheSizeEstimator.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergCacheSizeEstimator.java
index 3f922f318ce..933e9f34d39 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergCacheSizeEstimator.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergCacheSizeEstimator.java
@@ -247,7 +247,7 @@ final class IcebergCacheSizeEstimator {
 
     static long estimateManifestKey(IcebergManifestEntryKey key) {
         long bytes = add(MANIFEST_KEY_SHALLOW_BYTES, 
JvmSizeUtils.stringSize(key.getManifestPath()));
-        // The shallow key size excludes V4's retained table base and boxed 
inherited descriptor fields.
+        // The shallow key size excludes the retained table base and boxed 
inherited descriptor fields.
         bytes = add(bytes, JvmSizeUtils.stringSize(key.getTableLocation()));
         bytes = add(bytes, key.getSnapshotId() == null ? 0 : 
JvmSizeUtils.instanceSize(Long.class));
         bytes = add(bytes, key.getSequenceNumber() == null ? 0 : 
JvmSizeUtils.instanceSize(Long.class));
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestCache.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestCache.java
index 903744e4bdb..7c0beb7e4cb 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestCache.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestCache.java
@@ -42,7 +42,8 @@ import java.util.function.Supplier;
 
 /**
  * Per-catalog cache of an iceberg manifest's parsed files, keyed by {@link 
IcebergManifestEntryKey}
- * (manifest path + content). Ported from the legacy fe-core {@code 
IcebergExternalMetaCache} manifest entry +
+ * (manifest path + content + inherited first row ID). Ported from the legacy 
fe-core
+ * {@code IcebergExternalMetaCache} manifest entry +
  * {@code IcebergManifestCacheLoader}, now backed by the shared {@link 
MetaCache} framework
  * (independent-copy meta-cache migration).
  *
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKey.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKey.java
index d6243819c06..0ddd0f44d15 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKey.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKey.java
@@ -25,8 +25,9 @@ import java.util.Objects;
 /**
  * Cache key for one iceberg manifest entry (T08).
  *
- * <p>Legacy keys retain the manifest path and content type. V4 keys also 
identify the table base, raw reference
- * and descriptor fields inherited by parsed files. Physical aliases alone 
cannot identify those cached values.
+ * <p>Keys retain the manifest path, content type, and inherited first row ID. 
V4 keys also identify the table
+ * base, raw reference and other descriptor fields inherited by parsed files. 
Physical aliases alone cannot
+ * identify those cached values.
  * Table-level invalidation (REFRESH TABLE) intentionally does not drop 
immutable manifest entries. Runtime
  * loader context (the manifest/table instances) must not be stored here.
  */
@@ -53,7 +54,9 @@ public class IcebergManifestEntryKey {
     }
 
     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(),
+                null, null, null, manifest.firstRowId());
     }
 
     public String getManifestPath() {
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKeyTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKeyTest.java
index 96371cfa606..f72a4e84c53 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKeyTest.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestEntryKeyTest.java
@@ -22,8 +22,8 @@ import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
 /**
- * Unit tests for {@link IcebergManifestEntryKey} (T08). The key is path + 
content; two manifests that share a
- * path (across tables) hit the same cache entry, which is what lets a REFRESH 
TABLE keep the manifest cache.
+ * Unit tests for {@link IcebergManifestEntryKey} (T08). Two manifests sharing 
a path, content type and row-ID
+ * context can reuse an entry across tables, which lets REFRESH TABLE keep the 
manifest cache.
  */
 public class IcebergManifestEntryKeyTest {
 
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestRowLineageCacheTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestRowLineageCacheTest.java
new file mode 100644
index 00000000000..5821804edf6
--- /dev/null
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergManifestRowLineageCacheTest.java
@@ -0,0 +1,196 @@
+// 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.connector.iceberg;
+
+import org.apache.doris.connector.cache.CatalogMetaCache;
+
+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 java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+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(); CatalogMetaCache owner = 
CatalogMetaCache.unmanaged()) {
+            Table table = v2Table(catalog);
+            ManifestFile before = 
table.currentSnapshot().dataManifests(table.io()).get(0);
+            IcebergManifestCache cache = new IcebergManifestCache(owner, 
Collections.emptyMap());
+            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.getCachedManifestValue(upgraded, table, null));
+            Assertions.assertSame(old, cache.getManifestCacheValue(before, 
table),
+                    "the upgrade must not contaminate the historical manifest 
context");
+            Assertions.assertEquals(2, cache.size());
+        }
+    }
+
+    @Test
+    void statementReaderAndWarmProbeSeparateHistoricalAndCurrentManifests() 
throws Exception {
+        try (InMemoryCatalog catalog = catalog(); CatalogMetaCache owner = 
CatalogMetaCache.unmanaged()) {
+            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());
+            IcebergManifestCache cache = new IcebergManifestCache(owner, 
Collections.emptyMap());
+
+            try (IcebergManifestReader reader = new 
IcebergManifestReader(cache, table, "lineage", () -> { })) {
+                ManifestCacheValue current = 
reader.readFuture(upgraded).toCompletableFuture().join();
+                Assertions.assertNull(reader.cachedOnly(before),
+                        "warming V3 must not make the V2 context a cache hit");
+                ManifestCacheValue historical = 
reader.readFuture(before).toCompletableFuture().join();
+                assertMatchesSdk(table, historical, oldSnapshot);
+                assertMatchesSdk(table, current, 
table.currentSnapshot().snapshotId());
+                Assertions.assertSame(historical, reader.read(before));
+                Assertions.assertSame(current, reader.read(upgraded));
+                Assertions.assertEquals(0, reader.inFlightCount());
+            }
+        }
+    }
+
+    @Test
+    void branchesSharingAManifestKeepTheirOwnInheritedRowIds() throws 
Exception {
+        try (InMemoryCatalog catalog = catalog(); CatalogMetaCache owner = 
CatalogMetaCache.unmanaged()) {
+            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();
+            Assertions.assertNotEquals(main.firstRowId(), other.firstRowId());
+            IcebergManifestCache cache = new IcebergManifestCache(owner, 
Collections.emptyMap());
+            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());
+            
Assertions.assertTrue(IcebergCacheSizeEstimator.estimateManifestKey(zero)
+                    > IcebergCacheSizeEstimator.estimateManifestKey(legacy));
+        }
+    }
+
+    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();
+    }
+}
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]

Reply via email to