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 ae8accfc7b7 [fix](iceberg) Include localized predicates in external 
condition cache keys (#70936)
ae8accfc7b7 is described below

commit ae8accfc7b7490c288bd13c4225a1ea77e7a2d29
Author: Gabriel <[email protected]>
AuthorDate: Wed Nov 25 15:00:32 2026 +0800

    [fix](iceberg) Include localized predicates in external condition cache 
keys (#70936)
    
    ### Background
    
    The external condition cache stores whether each file granule has
    surviving rows after file-level predicates run. Its scanner digest
    carries query, session and runtime-filter identity, while schema mapping
    determines which predicates actually run against each physical file.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #65046 (introduced the file scanner v2 path), #65496
    (source-range granule cache coordination)
    PR Type: Bugfix
    
    Problem Summary:
    
    Iceberg can delete a nested field and recreate its name with a new field
    ID and initial default without rewriting historical files. A predicate
    that previously ran in the file reader then becomes residual, but its
    old cache bitmap can still suppress rows before the default is
    materialized. Include localized predicates in cache identity; most
    changes are tests.
    
    For one unchanged file, query the whole struct and filter
    `mod(element_at(s,'x'),2)=1 AND mod(k,3)=1`. Replacing the old `x=0`
    child with a new BIGINT child defaulting to `9` gives:
    
    | Evolved schema query | Before fix | After fix |
    |---|---|---|
    | Condition cache disabled | 4096 rows | 4096 rows |
    | Condition cache enabled after warming the old schema | 0 rows | 4096
    rows |
    
    ### Details
    
    - **Change map:** Production code +31/-21 lines; tests +435/-20;
    generated regression output +10/-0; no documentation changes. The
    production change reuses one eligibility digest and preserves the
    Iceberg positional-binding exclusion. Publication tests now inspect
    complete keys.
    - **Frequency:** Always when a cached false granule from local
    predicates P AND Q is reused after schema evolution leaves only Q
    localized under the same scanner digest.
    - **Root cause:** `TableReader` computed a localized digest only to
    decide cache eligibility, then keyed the bitmap solely by the scanner
    digest. It misses the changed file-local subset.
    - **Why existing tests missed it:** `TableReaderTest.ConditionCache*`
    omits localized-subset changes under one scanner seed.
    `IcebergV2ReaderTest.ReusedNestedNameReadsNewFieldInitialDefault`
    verifies default materialization without warming condition cache.
    Iceberg schema-evolution regressions verify binding without requiring a
    positive cache hit across child replacement.
    - **Fix:** Return the existing localized digest from cache admission and
    mix it into the scanner seed before the existing INT96 key adjustment.
    Existing cache exclusions are preserved. Do not use the separately
    memoized scanner predicate snapshot digest or hash large RF payloads
    twice.
    - **Other paths and branches:** The native `TableReader` key is shared
    by ORC/Parquet table-format readers. Iceberg's positional fallback still
    rejects unstable field bindings. Internal-table cache is separate;
    legacy external readers have no condition-cache integration. Static
    inspection finds the scanner-only key on branch-4.1 and branch-4.2;
    branch-3.1 and branch-4.0 lack this native path. Release branches were
    not executed locally.
    
    ### Testing
    
    - Local ASAN: 277 tests passed across `TableReaderTest`,
    `IcebergV2ReaderTest` and ORC condition-cache tests. Two new tests cover
    P AND Q versus Q under the same seed, different scanner seeds with the
    same local predicates, positive reuse, zero-digest rejection and exactly
    one localized hash. The identity test fails against the original key.
    - Local launcher reproduction: interpolated Groovy arguments fail before
    normalization and pass after it, including literal argument preservation
    and child-command errors.
    - Local native SQL: `test_iceberg_nested_predicate_cache` fails before
    the fix with 4096 rows from the cache-disabled oracle versus zero with
    the warmed cache. The candidate passes full-row comparison after
    evolution and positive cache-hit/pruning assertions; generated output is
    independently checked and replayed normally.
    - Standard Iceberg 1.12 and stock 1.10.1 SDK helpers author and read
    back all 8192 rows before and after public delete/add-column operations.
    Assertions preserve the parent ID, replace the child ID, retain the data
    snapshot/path/size, and check the new default, NULL parents and
    nonmatching granules.
    
    ### Notes for Reviewers
    
    BIGINT inputs avoid the implicit modulo cast whose zero digest
    deliberately disables caching. It supports an existing Spark/REST Docker
    environment or an explicitly configured local SDK/file warehouse.
    External CI exposed the launcher’s GString failure.
    
    ### Release note
    
    Fix missing Iceberg query results caused by stale condition-cache
    bitmaps after a nested field is deleted and recreated with an initial
    default.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Partially verified: full Docker fixture
    execution after argument normalization awaits CI; command-boundary
    checks and the SQL suite passed locally
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6)
    - Generated: Code, unit tests, regression tests and this description
    - Human review: not stated
---
 be/src/format_v2/table/iceberg_reader.h            |  13 +-
 be/src/format_v2/table_reader.cpp                  |  28 ++--
 be/src/format_v2/table_reader.h                    |  11 +-
 be/test/format_v2/table/iceberg_reader_test.cpp    |   2 +-
 be/test/format_v2/table_reader_test.cpp            | 131 ++++++++++++++---
 .../test_iceberg_nested_predicate_cache.out        |  10 ++
 .../CreateNestedPredicateCacheFixture.java         | 162 +++++++++++++++++++++
 .../test_iceberg_nested_predicate_cache.groovy     | 160 ++++++++++++++++++++
 8 files changed, 476 insertions(+), 41 deletions(-)

diff --git a/be/src/format_v2/table/iceberg_reader.h 
b/be/src/format_v2/table/iceberg_reader.h
index 19ac9d7acd5..360d3d25e1c 100644
--- a/be/src/format_v2/table/iceberg_reader.h
+++ b/be/src/format_v2/table/iceberg_reader.h
@@ -97,13 +97,14 @@ protected:
     // Iceberg's positional fallback matches an ID-less Parquet file by 
physical ordinals, so the
     // same table column can bind a different file column when the table's
     // `schema.name-mapping.default` is added or removed without touching the 
data file. The
-    // condition cache key covers the file identity and the table-level 
predicate digest only, so it
-    // cannot tell those bindings apart; keep such splits out of the cache 
(neither read nor
-    // written) instead of reusing a verdict produced by the other binding.
-    bool _should_enable_condition_cache(
+    // localized predicate still names the same physical ordinal; neither 
digest represents the
+    // changed table-field binding. Keep these splits out of the cache 
entirely.
+    std::optional<uint64_t> _condition_cache_localized_digest(
             const format::FileScanRequest& file_request) const override {
-        return !_positional_id_fallback &&
-               
format::TableReader::_should_enable_condition_cache(file_request);
+        if (_positional_id_fallback) {
+            return std::nullopt;
+        }
+        return 
format::TableReader::_condition_cache_localized_digest(file_request);
     }
 
     void configure_mapper_options(format::TableColumnMapperOptions* options) 
const override {
diff --git a/be/src/format_v2/table_reader.cpp 
b/be/src/format_v2/table_reader.cpp
index 6e94fb17658..324ab826650 100644
--- a/be/src/format_v2/table_reader.cpp
+++ b/be/src/format_v2/table_reader.cpp
@@ -1273,16 +1273,17 @@ Status TableReader::_open_local_filter_exprs(const 
FileScanRequest& file_request
     return Status::OK();
 }
 
-bool TableReader::_should_enable_condition_cache(const FileScanRequest& 
file_request) const {
+std::optional<uint64_t> TableReader::_condition_cache_localized_digest(
+        const FileScanRequest& file_request) const {
     if (_condition_cache_digest == 0 || _push_down_agg_type == 
TPushAggOp::type::COUNT ||
         _current_file_description == std::nullopt || _data_reader.reader == 
nullptr) {
-        return false;
+        return std::nullopt;
     }
     // Condition cache is populated by file readers after evaluating 
file-local row-level
     // conjuncts. Metadata pruning can skip row groups/pages, but it does not 
produce a per-row
     // survivor bitmap that can safely populate the cache.
     if (file_request.conjuncts.empty()) {
-        return false;
+        return std::nullopt;
     }
     // Localization may inject schema-evolution casts absent from the 
scanner's digest. Honor
     // their uncacheable contract: an unchanged field ID can acquire different 
timestamp semantics,
@@ -1291,7 +1292,7 @@ bool TableReader::_should_enable_condition_cache(const 
FileScanRequest& file_req
     for (const auto& conjunct : file_request.conjuncts) {
         localized_digest = conjunct->get_digest(localized_digest);
         if (localized_digest == 0) {
-            return false;
+            return std::nullopt;
         }
     }
     // Delete files/deletion vectors are table-format state. They may change 
independently of the
@@ -1299,19 +1300,23 @@ bool TableReader::_should_enable_condition_cache(const 
FileScanRequest& file_req
     // stale. Keep delete filtering enabled, but do not read or write 
condition cache.
     if (_delete_rows != nullptr || _deletion_vector != nullptr ||
         !file_request.delete_conjuncts.empty()) {
-        return false;
+        return std::nullopt;
     }
     // Only scanner-driven splits provide a digest rebuilt from the exact RF 
snapshot. Keep the
     // conservative behavior for standalone TableReader callers: their initial 
digest may describe
     // only static predicate P and must not store P AND RF under that key.
-    return _condition_cache_digest_covers_current_split ||
-           !contains_runtime_filter(file_request.conjuncts);
+    if (!_condition_cache_digest_covers_current_split &&
+        contains_runtime_filter(file_request.conjuncts)) {
+        return std::nullopt;
+    }
+    return localized_digest;
 }
 
 Status TableReader::_init_reader_condition_cache(const FileScanRequest& 
file_request) {
     _condition_cache = nullptr;
     _condition_cache_ctx = nullptr;
-    if (!_should_enable_condition_cache(file_request)) {
+    const auto localized_digest = 
_condition_cache_localized_digest(file_request);
+    if (!localized_digest.has_value()) {
         _condition_cache_split_invalid = _condition_cache_split_participating;
         return Status::OK();
     }
@@ -1322,7 +1327,12 @@ Status TableReader::_init_reader_condition_cache(const 
FileScanRequest& file_req
         return Status::OK();
     }
     const auto& file = *_current_file_description;
-    auto cache_digest = _condition_cache_digest;
+    // Iceberg can keep the scanner predicate P AND Q while a recreated nested 
child moves P
+    // to residual evaluation. A bitmap for local P AND Q must not be reused 
for local Q alone.
+    // Retain the scanner seed as well: it carries session and runtime-filter 
identity.
+    auto cache_digest =
+            HashUtil::xxHash64WithSeed(reinterpret_cast<const 
char*>(&*localized_digest),
+                                       sizeof(*localized_digest), 
_condition_cache_digest);
     if (_format == FileFormat::PARQUET) {
         const auto timezone = _get_int96_timezone_override(_scan_params);
         if (timezone.has_value()) {
diff --git a/be/src/format_v2/table_reader.h b/be/src/format_v2/table_reader.h
index d68afacdc69..5146a9b5e04 100644
--- a/be/src/format_v2/table_reader.h
+++ b/be/src/format_v2/table_reader.h
@@ -591,12 +591,11 @@ protected:
     Status _init_reader_condition_cache(const FileScanRequest& file_request);
     void _finalize_reader_condition_cache();
     std::optional<uint64_t> _current_predicate_snapshot_digest() const;
-    // The condition cache key covers the file identity plus the table-level 
predicate/session
-    // digest only. A table format whose file-column binding can change 
without changing that digest
-    // (Iceberg's positional fallback resolves an ID-less file by physical 
ordinals) must override
-    // this to false: a stale all-false granule would silently drop matching 
rows, because the
-    // cached verdict was produced by a different physical binding.
-    virtual bool _should_enable_condition_cache(const FileScanRequest& 
file_request) const;
+    // Return the file-local predicate digest only when its row bitmap is 
cacheable. Table formats
+    // must reject unstable physical bindings (such as Iceberg positional ID 
fallback), even when
+    // the scanner and localized expression digests stay unchanged.
+    virtual std::optional<uint64_t> _condition_cache_localized_digest(
+            const FileScanRequest& file_request) const;
 
     Status _evaluate_constant_filters(bool* can_filter_all) {
         DORIS_CHECK(can_filter_all != nullptr);
diff --git a/be/test/format_v2/table/iceberg_reader_test.cpp 
b/be/test/format_v2/table/iceberg_reader_test.cpp
index 3ff994a9977..f97a1229aca 100644
--- a/be/test/format_v2/table/iceberg_reader_test.cpp
+++ b/be/test/format_v2/table/iceberg_reader_test.cpp
@@ -3728,7 +3728,7 @@ public:
     }
     bool TEST_condition_cache_enabled_for_current_split() const {
         DORIS_CHECK(_file_scan_request != nullptr);
-        return _should_enable_condition_cache(*_file_scan_request);
+        return 
_condition_cache_localized_digest(*_file_scan_request).has_value();
     }
 };
 
diff --git a/be/test/format_v2/table_reader_test.cpp 
b/be/test/format_v2/table_reader_test.cpp
index c9388869b41..1cafd738188 100644
--- a/be/test/format_v2/table_reader_test.cpp
+++ b/be/test/format_v2/table_reader_test.cpp
@@ -1769,6 +1769,10 @@ public:
                     std::shared_ptr<FakeFileReaderState> state)
             : _file_schema(std::move(file_schema)), _state(std::move(state)) {}
 
+    const segment_v2::ConditionCache::ExternalCacheKey& 
TEST_condition_cache_key() const {
+        return _condition_cache_key;
+    }
+
     VExprContextSPtr TEST_mapping_projection(size_t index) const {
         DORIS_CHECK(_data_reader.column_mapper != nullptr);
         DORIS_CHECK_LT(index, _data_reader.column_mapper->mappings().size());
@@ -4448,6 +4452,94 @@ TEST(TableReaderTest, 
ConditionCacheSkipsRequestWithoutFileLocalConjuncts) {
     ASSERT_TRUE(reader.close().ok());
 }
 
+// A scanner predicate can localize to P AND Q in one schema and only Q after 
evolution.
+// Both the localized subset and the scanner/session/RF seed must distinguish 
cached bitmaps.
+TEST(TableReaderTest, 
ConditionCacheSeparatesLocalizedPredicatesAndScannerSeeds) {
+    ScopedConditionCacheForTest cache;
+    std::vector<ColumnDefinition> schema {
+            make_file_column(0, "id", std::make_shared<DataTypeInt32>())};
+    std::vector<ColumnDefinition> columns {
+            make_table_column(0, "id", std::make_shared<DataTypeInt32>())};
+    set_name_identifiers(&columns);
+    RuntimeState state {TQueryOptions(), TQueryGlobals()};
+    auto scan = [&](bool include_p, uint64_t seed, bool expect_hit) {
+        auto fake = std::make_shared<FakeFileReaderState>();
+        fake->total_rows = ConditionCacheContext::GRANULE_SIZE;
+        FakeTableReader reader(schema, fake);
+        VExprContextSPtrs conjuncts;
+        if (include_p) {
+            conjuncts.push_back(prepared_conjunct(&state, 
table_int32_greater_than_expr(0, 0, 9)));
+        }
+        conjuncts.push_back(prepared_conjunct(&state, 
table_int32_greater_than_expr(0, 0, 0)));
+        ASSERT_TRUE(reader.init({.projected_columns = columns,
+                                 .conjuncts = std::move(conjuncts),
+                                 .format = FileFormat::PARQUET,
+                                 .scan_params = nullptr,
+                                 .io_ctx = nullptr,
+                                 .runtime_state = &state,
+                                 .scanner_profile = nullptr,
+                                 .condition_cache_digest = 7})
+                            .ok());
+        SplitReadOptions split;
+        split.current_range.__set_path("localized-subset-input");
+        split.condition_cache_digest = seed;
+        ASSERT_TRUE(reader.prepare_split(split).ok());
+        Block block = build_table_block(columns);
+        bool eos = false;
+        ASSERT_TRUE(reader.get_block(&block, &eos).ok());
+        ASSERT_NE(fake->last_request, nullptr);
+        EXPECT_EQ(fake->last_request->conjuncts.size(), include_p ? 2 : 1);
+        ASSERT_NE(fake->condition_cache_ctx, nullptr);
+        EXPECT_EQ(fake->condition_cache_ctx->is_hit, expect_hit);
+        EXPECT_EQ(reader.condition_cache_hit_count(), expect_hit ? 1 : 0);
+        ASSERT_TRUE(reader.close().ok());
+    };
+    scan(true, 11, false);
+    scan(true, 11, true);
+    scan(false, 11, false);
+    scan(false, 11, true);
+    scan(false, 19, false);
+    scan(false, 19, true);
+}
+
+TEST(TableReaderTest, 
ConditionCacheHashesLocalPredicatesOnceAndRejectsZeroDigest) {
+    ScopedConditionCacheForTest cache;
+    std::vector<ColumnDefinition> schema {
+            make_file_column(0, "id", std::make_shared<DataTypeInt32>())};
+    std::vector<ColumnDefinition> columns {
+            make_table_column(0, "id", std::make_shared<DataTypeInt32>())};
+    set_name_identifiers(&columns);
+    RuntimeState state {TQueryOptions(), TQueryGlobals()};
+    for (uint64_t digest : {17, 0}) {
+        size_t calls = 0;
+        auto predicate = std::make_shared<RecordingDigestPredicate>(&calls, 
digest);
+        predicate->add_child(table_int32_greater_than_expr(0, 0, 0));
+        auto fake = std::make_shared<FakeFileReaderState>();
+        fake->total_rows = ConditionCacheContext::GRANULE_SIZE;
+        FakeTableReader reader(schema, fake);
+        ASSERT_TRUE(reader.init({.projected_columns = columns,
+                                 .conjuncts = {prepared_conjunct(&state, 
predicate)},
+                                 .format = FileFormat::PARQUET,
+                                 .scan_params = nullptr,
+                                 .io_ctx = nullptr,
+                                 .runtime_state = &state,
+                                 .scanner_profile = nullptr,
+                                 .condition_cache_digest = 7})
+                            .ok());
+        SplitReadOptions split;
+        split.current_range.__set_path("localized-digest-input");
+        split.condition_cache_digest = 11;
+        ASSERT_TRUE(reader.prepare_split(split).ok());
+        Block block = build_table_block(columns);
+        bool eos = false;
+        ASSERT_TRUE(reader.get_block(&block, &eos).ok());
+        // Reuse the admission digest instead of hashing a potentially large 
RF payload twice.
+        EXPECT_EQ(calls, 1);
+        EXPECT_EQ(fake->condition_cache_ctx != nullptr, digest != 0);
+        ASSERT_TRUE(reader.close().ok());
+    }
+}
+
 TEST(TableReaderTest, ConditionCacheSeparatesInt96TimezoneContracts) {
     ScopedConditionCacheForTest cache;
     std::vector<ColumnDefinition> file_schema {
@@ -4690,12 +4782,8 @@ TEST(TableReaderTest, 
ConditionCacheAllowsRuntimeFilterCoveredBySplitDigest) {
     EXPECT_FALSE(fake_state->condition_cache_ctx->is_hit);
 
     segment_v2::ConditionCacheHandle handle;
-    segment_v2::ConditionCache::ExternalCacheKey initial_digest_key(
-            "fake-table-reader-input", 0, -1, 7, 0, -1,
-            
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
-    EXPECT_FALSE(cache.get()->lookup(initial_digest_key, &handle));
     segment_v2::ConditionCache::ExternalCacheKey split_digest_key(
-            "fake-table-reader-input", 0, -1, 11, 0, -1,
+            "fake-table-reader-input", 0, -1, 
reader.TEST_condition_cache_key().digest, 0, -1,
             
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
     EXPECT_TRUE(cache.get()->lookup(split_digest_key, &handle));
     ASSERT_TRUE(reader.close().ok());
@@ -4750,6 +4838,10 @@ TEST(TableReaderTest, 
ConditionCacheRefinedChildrenPublishOneSourceRangeEntry) {
         Block block = build_table_block(projected_columns);
         bool eos = false;
         ASSERT_TRUE(reader.get_block(&block, &eos).ok());
+        if (child == 0) {
+            source_key.digest = reader.TEST_condition_cache_key().digest;
+        }
+        EXPECT_EQ(reader.TEST_condition_cache_key().encode(), 
source_key.encode());
         segment_v2::ConditionCacheHandle handle;
         EXPECT_EQ(cache.get()->lookup(source_key, &handle), child == 1);
         ASSERT_TRUE(reader.close().ok());
@@ -4817,6 +4909,10 @@ TEST(TableReaderTest, 
ConditionCacheRefinedChildrenAssembleFragmentsOnceInAnyOrd
             bool eos = false;
             ASSERT_TRUE(reader.get_block(&block, &eos).ok());
             buffers.push_back(fake->condition_cache_ctx->filter_result.get());
+            if (completed == 0) {
+                key.digest = reader.TEST_condition_cache_key().digest;
+            }
+            EXPECT_EQ(reader.TEST_condition_cache_key().encode(), 
key.encode());
             segment_v2::ConditionCacheHandle handle;
             EXPECT_EQ(cache.get()->lookup(key, &handle), completed == CHILDREN 
- 1);
             if (completed != CHILDREN - 1) {
@@ -4852,6 +4948,7 @@ TEST(TableReaderTest, 
ConditionCacheRefinedChildrenRejectMismatchedOrIncompleteF
                 make_table_column(0, "id", std::make_shared<DataTypeInt32>())};
         set_name_identifiers(&columns);
         auto context = std::make_shared<ConditionCacheSplitContext>(2);
+        std::vector<segment_v2::ConditionCache::ExternalCacheKey> keys;
         for (int child = 0; child < 2; ++child) {
             auto fake = std::make_shared<FakeFileReaderState>();
             fake->total_rows = ConditionCacheContext::GRANULE_SIZE;
@@ -4883,14 +4980,12 @@ TEST(TableReaderTest, 
ConditionCacheRefinedChildrenRejectMismatchedOrIncompleteF
             Block block = build_table_block(columns);
             bool eos = false;
             ASSERT_TRUE(reader.get_block(&block, &eos).ok());
+            keys.push_back(reader.TEST_condition_cache_key());
             ASSERT_TRUE(reader.close().ok());
         }
         EXPECT_EQ(context->remaining_children, 0);
         EXPECT_FALSE(context->valid);
-        for (uint64_t digest : {23, 29}) {
-            segment_v2::ConditionCache::ExternalCacheKey key(
-                    "incomplete-fragment-input", 0, -1, digest, 0, 200,
-                    
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
+        for (const auto& key : keys) {
             segment_v2::ConditionCacheHandle handle;
             EXPECT_FALSE(cache.get()->lookup(key, &handle));
         }
@@ -5006,12 +5101,8 @@ TEST(TableReaderTest, 
ConditionCacheLateRefreshBeforeOpenUsesRefreshedDigest) {
     bool eos = false;
     ASSERT_TRUE(reader.get_block(&block, &eos).ok());
     segment_v2::ConditionCacheHandle handle;
-    segment_v2::ConditionCache::ExternalCacheKey stale_key(
-            "late-runtime-filter-input", 0, -1, 11, 0, -1,
-            
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
-    EXPECT_FALSE(cache.get()->lookup(stale_key, &handle));
     segment_v2::ConditionCache::ExternalCacheKey refreshed_key(
-            "late-runtime-filter-input", 0, -1, 19, 0, -1,
+            "late-runtime-filter-input", 0, -1, 
reader.TEST_condition_cache_key().digest, 0, -1,
             
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
     EXPECT_TRUE(cache.get()->lookup(refreshed_key, &handle));
     ASSERT_TRUE(reader.close().ok());
@@ -5132,12 +5223,13 @@ TEST(TableReaderTest, 
ConditionCacheMissPublishesBitmapAfterReaderEof) {
     ASSERT_NE(fake_state->condition_cache_ctx, nullptr);
     EXPECT_FALSE(fake_state->condition_cache_ctx->is_hit);
 
-    segment_v2::ConditionCache::ExternalCacheKey 
legacy_key("fake-table-reader-input", 0, -1, 7, 0,
-                                                            -1);
+    const auto consumed_key = reader.TEST_condition_cache_key();
+    segment_v2::ConditionCache::ExternalCacheKey 
legacy_key("fake-table-reader-input", 0, -1,
+                                                            
consumed_key.digest, 0, -1);
     segment_v2::ConditionCacheHandle handle;
     EXPECT_FALSE(cache.get()->lookup(legacy_key, &handle));
     segment_v2::ConditionCache::ExternalCacheKey key(
-            "fake-table-reader-input", 0, -1, 7, 0, -1,
+            "fake-table-reader-input", 0, -1, consumed_key.digest, 0, -1,
             
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
     ASSERT_TRUE(cache.get()->lookup(key, &handle));
     const auto cached_bitmap = handle.get_filter_result();
@@ -5190,9 +5282,10 @@ TEST(TableReaderTest, 
ConditionCacheMissIsDroppedWhenReaderClosesBeforeEof) {
     ASSERT_NE(fake_state->condition_cache_ctx, nullptr);
     EXPECT_FALSE(fake_state->condition_cache_ctx->is_hit);
 
+    const auto consumed_key = reader.TEST_condition_cache_key();
     ASSERT_TRUE(reader.close().ok());
     segment_v2::ConditionCache::ExternalCacheKey key(
-            "fake-table-reader-input", 0, -1, 7, 0, -1,
+            "fake-table-reader-input", 0, -1, consumed_key.digest, 0, -1,
             
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
     segment_v2::ConditionCacheHandle handle;
     EXPECT_FALSE(cache.get()->lookup(key, &handle));
@@ -5244,7 +5337,7 @@ TEST(TableReaderTest, 
ConditionCacheMissIsDroppedWhenStopTurnsReadIntoEof) {
     EXPECT_FALSE(fake_state->condition_cache_ctx->is_hit);
 
     segment_v2::ConditionCache::ExternalCacheKey key(
-            "fake-table-reader-input", 0, -1, 7, 0, -1,
+            "fake-table-reader-input", 0, -1, 
reader.TEST_condition_cache_key().digest, 0, -1,
             
segment_v2::ConditionCache::ExternalCacheKey::BASE_GRANULE_AWARE_VERSION);
     segment_v2::ConditionCacheHandle handle;
     EXPECT_FALSE(cache.get()->lookup(key, &handle));
diff --git 
a/regression-test/data/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.out
 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.out
new file mode 100644
index 00000000000..8af2632ede7
--- /dev/null
+++ 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.out
@@ -0,0 +1,10 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !original_rows --
+0
+
+-- !evolved_defaults --
+9      7       1       4096
+
+-- !null_parents --
+2048
+
diff --git 
a/regression-test/suites/external_table_p0/iceberg/cache_data/CreateNestedPredicateCacheFixture.java
 
b/regression-test/suites/external_table_p0/iceberg/cache_data/CreateNestedPredicateCacheFixture.java
new file mode 100644
index 00000000000..f065fc750cd
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/iceberg/cache_data/CreateNestedPredicateCacheFixture.java
@@ -0,0 +1,162 @@
+// 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 java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.Catalog;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.SupportsNamespaces;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.IcebergGenerics;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.data.parquet.GenericParquetWriter;
+import org.apache.iceberg.expressions.Literal;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.parquet.Parquet;
+import org.apache.iceberg.types.Types;
+
+/** Normal schema evolution leaves the historical data file untouched. */
+public final class CreateNestedPredicateCacheFixture {
+    private CreateNestedPredicateCacheFixture() {
+    }
+
+    private static DataFile dataFile(Table table) throws Exception {
+        try (var files = table.newScan().planFiles()) {
+            var iterator = files.iterator();
+            DataFile file = iterator.next().file().copy();
+            if (iterator.hasNext()) {
+                throw new IllegalStateException("Expected one historical data 
file");
+            }
+            return file;
+        }
+    }
+
+    private static void create(Catalog catalog, TableIdentifier identifier) 
throws Exception {
+        catalog.dropTable(identifier, true);
+        // BIGINT avoids an implicit INT-to-BIGINT modulo cast, which is 
deliberately uncacheable.
+        Schema schema = new Schema(Types.NestedField.optional(1, "s", 
Types.StructType.of(
+                Types.NestedField.optional(3, "x", Types.LongType.get()),
+                Types.NestedField.optional(4, "keep", 
Types.IntegerType.get()))),
+                Types.NestedField.optional(2, "k", Types.LongType.get()));
+        Table table = catalog.createTable(identifier, schema, 
PartitionSpec.unpartitioned(),
+                Map.of("format-version", "3", "write.format.default", 
"parquet"));
+        OutputFile output = table.io().newOutputFile(table.location() + 
"/data/" + UUID.randomUUID() + ".parquet");
+        FileAppender<Record> appender = Parquet.write(output).schema(schema)
+                .createWriterFunc(GenericParquetWriter::create).build();
+        try (FileAppender<Record> writer = appender) {
+            for (int id = 0; id < 8192; ++id) {
+                GenericRecord row = GenericRecord.create(schema);
+                if (id < 4096 || id >= 6144) {
+                    GenericRecord nested = 
GenericRecord.create(schema.findType("s").asStructType());
+                    nested.setField("x", 0L);
+                    nested.setField("keep", 7);
+                    row.setField("s", nested);
+                }
+                row.setField("k", id < 6144 ? 1L : 0L);
+                writer.add(row);
+            }
+        }
+        
table.newAppend().appendFile(DataFiles.builder(table.spec()).withPath(output.location())
+                .withFormat(FileFormat.PARQUET).withRecordCount(8192)
+                .withFileSizeInBytes(appender.length()).build()).commit();
+        verify(table, 0L);
+    }
+
+    private static void verify(Table table, long expectedX) throws Exception {
+        int rows = 0;
+        try (CloseableIterable<Record> records = 
IcebergGenerics.read(table).build()) {
+            for (Record row : records) {
+                Record nested = (Record) row.getField("s");
+                boolean nullParent = rows >= 4096 && rows < 6144;
+                if (nullParent != (nested == null)
+                        || !Objects.equals(row.getField("k"), rows < 6144 ? 1L 
: 0L)
+                        || (nested != null && 
(!Objects.equals(nested.getField("x"), expectedX)
+                                || !Objects.equals(nested.getField("keep"), 
7)))) {
+                    throw new IllegalStateException("SDK row mismatch at " + 
rows);
+                }
+                ++rows;
+            }
+        }
+        if (rows != 8192) {
+            throw new IllegalStateException("SDK row count mismatch: " + rows);
+        }
+        System.out.println("CACHE_FIXTURE rows=" + rows + " x=" + expectedX);
+    }
+
+    public static void main(String[] args) throws Exception {
+        Map<String, String> properties = new HashMap<>();
+        if (args.length == 3) {
+            properties.put("type", "hadoop");
+            properties.put("warehouse", args[2]);
+        } else {
+            properties.put("type", "rest");
+            properties.put("uri", "http://rest:8181";);
+            properties.put("warehouse", "s3://warehouse/wh/");
+            properties.put("io-impl", "org.apache.iceberg.aws.s3.S3FileIO");
+            properties.put("s3.endpoint", "http://minio:9000";);
+            properties.put("s3.path-style-access", "true");
+            properties.put("s3.region", "us-east-1");
+        }
+        Catalog catalog = CatalogUtil.buildIcebergCatalog("nested_cache", 
properties, new Configuration());
+        try (AutoCloseable ignored = (AutoCloseable) catalog) {
+            Namespace namespace = Namespace.of(args[1]);
+            SupportsNamespaces namespaces = (SupportsNamespaces) catalog;
+            if (!namespaces.namespaceExists(namespace)) {
+                namespaces.createNamespace(namespace);
+            }
+            TableIdentifier identifier = TableIdentifier.of(namespace, 
"nested_default");
+            if (args[0].equals("create")) {
+                create(catalog, identifier);
+            } else if (args[0].equals("evolve")) {
+                Table table = catalog.loadTable(identifier);
+                DataFile before = dataFile(table);
+                int root = table.schema().findField("s").fieldId();
+                int old = table.schema().findField("s.x").fieldId();
+                long snapshot = table.currentSnapshot().snapshotId();
+                table.updateSchema().deleteColumn("s.x").commit();
+                table.updateSchema().addColumn("s", "x", Types.LongType.get(), 
Literal.of(9L)).commit();
+                DataFile after = dataFile(table);
+                var child = table.schema().findField("s.x");
+                if (root != table.schema().findField("s").fieldId() || old == 
child.fieldId()
+                        || !Objects.equals(child.initialDefault(), 9L)
+                        || snapshot != table.currentSnapshot().snapshotId()
+                        || !before.path().equals(after.path())
+                        || before.fileSizeInBytes() != 
after.fileSizeInBytes()) {
+                    throw new IllegalStateException("Schema evolution changed 
historical file identity");
+                }
+                verify(table, 9L);
+                System.out.println("CACHE_EVOLVED root=" + root + " old=" + 
old + " new=" + child.fieldId());
+            } else {
+                throw new IllegalArgumentException("Expected create or 
evolve");
+            }
+        }
+    }
+}
diff --git 
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.groovy
 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.groovy
new file mode 100644
index 00000000000..b17e782452c
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_nested_predicate_cache.groovy
@@ -0,0 +1,160 @@
+// 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 org.apache.doris.regression.action.ProfileAction
+
+suite("test_iceberg_nested_predicate_cache", 
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+    String sdk = context.config.otherConfigs.get("icebergFixtureSdkDir")
+    String warehouse = 
context.config.otherConfigs.get("icebergFixtureWarehouse")
+    boolean local = sdk != null && warehouse != null
+    assertTrue((sdk == null) == (warehouse == null), "Set both local fixture 
SDK and warehouse")
+    if (!local && 
!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest"))) 
{
+        logger.info("disable iceberg test")
+        return
+    }
+    def execute = { List<String> command ->
+        StringBuilder stdout = new StringBuilder()
+        StringBuilder stderr = new StringBuilder()
+        // List<String> can still contain GStrings; ProcessBuilder copies its 
elements into String[].
+        def process = new ProcessBuilder(command.collect { it.toString() 
}).start()
+        Thread outputReader = process.consumeProcessOutputStream(stdout)
+        Thread errorReader = process.consumeProcessErrorStream(stderr)
+        process.waitForOrKill(300000)
+        // Process exit can precede output-consumer completion; read every SDK 
marker before checking.
+        outputReader.join()
+        errorReader.join()
+        assertEquals(0, process.exitValue(), "SDK command failed: 
${stderr}\n${stdout}")
+        return stdout.toString()
+    }
+    def shellQuote = { String value -> "'" + value.replace("'", "'\"'\"'") + 
"'" }
+    File source = new File(context.file.parentFile, 
"cache_data/CreateNestedPredicateCacheFixture.java")
+    File classes
+    String container
+    String directory = "/tmp/doris_nested_cache_${UUID.randomUUID()}"
+    String docker = context.config.otherConfigs.get("externalDockerCommand") 
?: "docker"
+    def sdkRun = { String phase ->
+        if (local) {
+            String bin = System.getProperty("java.home") + "/bin/"
+            return execute([bin + "java", "-cp", classes.absolutePath + ":" + 
sdk + "/*",
+                    "CreateNestedPredicateCacheFixture", phase, 
"nested_predicate_cache", warehouse])
+        }
+        String command = "java -cp \"${directory}:/opt/spark/jars/*\" " +
+                "CreateNestedPredicateCacheFixture ${phase} 
nested_predicate_cache"
+        return execute(["bash", "-c", "${docker} exec ${shellQuote(container)} 
bash -lc ${shellQuote(command)}"])
+    }
+    def settings = ["enable_sql_cache", "enable_query_cache", 
"enable_condition_cache", "enable_profile", "profile_level", 
"enable_file_scanner_v2"]
+            .collectEntries { name -> [(name): (sql "SELECT 
@@${name}")[0][0].toString()] }
+    try {
+        if (local) {
+            assertTrue(warehouse.startsWith("file:"), "Local SDK mode requires 
a shared file warehouse")
+            classes = new File(context.file.parentFile, 
".nested_cache_${UUID.randomUUID()}")
+            assertTrue(classes.mkdirs())
+            execute([System.getProperty("java.home") + "/bin/javac", "-cp", 
sdk + "/*", "-d",
+                    classes.absolutePath, source.absolutePath])
+        } else {
+            container = 
context.config.otherConfigs.get("icebergSparkContainer")
+            if (container == null || container.isEmpty()) {
+                def candidates = execute(["bash", "-c", "${docker} ps --format 
'{{.ID}}'"]).readLines()
+                def matches = candidates.findAll { String candidate ->
+                    def probe = new ProcessBuilder("bash", "-c", "${docker} 
exec ${shellQuote(candidate)} " +
+                            "bash -lc 'test -f /mnt/SUCCESS && command -v 
spark-sql >/dev/null'").start()
+                    probe.consumeProcessOutput(new StringBuilder(), new 
StringBuilder())
+                    probe.waitForOrKill(30000)
+                    return probe.exitValue() == 0
+                }
+                assertEquals(1, matches.size(), "Set icebergSparkContainer to 
the Spark Iceberg container")
+                container = matches[0]
+            }
+            String encoded = 
source.getText("UTF-8").getBytes("UTF-8").encodeBase64().toString()
+            String command = "mkdir -p ${directory} && echo ${encoded} | 
base64 -d > ${directory}/${source.name} && " +
+                    "javac -cp \"/opt/spark/jars/*\" -d ${directory} 
${directory}/${source.name}"
+            execute(["bash", "-c", "${docker} exec ${shellQuote(container)} 
bash -lc ${shellQuote(command)}"])
+        }
+        assertTrue(sdkRun("create").contains("CACHE_FIXTURE rows=8192 x=0"))
+        sql "DROP CATALOG IF EXISTS nested_predicate_cache_catalog"
+        if (local) {
+            sql """CREATE CATALOG nested_predicate_cache_catalog PROPERTIES (
+                    'type'='iceberg', 'iceberg.catalog.type'='hadoop',
+                    'warehouse'='${warehouse.replace("'", "''")}')"""
+        } else {
+            String host = context.config.otherConfigs.get("externalEnvIp")
+            String rest = 
context.config.otherConfigs.get("iceberg_rest_uri_port")
+            String minio = 
context.config.otherConfigs.get("iceberg_minio_port")
+            sql """CREATE CATALOG nested_predicate_cache_catalog PROPERTIES (
+                    'type'='iceberg', 'iceberg.catalog.type'='rest', 
'uri'='http://${host}:${rest}',
+                    's3.access_key'='admin', 's3.secret_key'='password',
+                    's3.endpoint'='http://${host}:${minio}', 
's3.region'='us-east-1')"""
+        }
+        sql "SET enable_sql_cache=false"
+        sql "SET enable_query_cache=false"
+        sql "SET enable_condition_cache=true"
+        sql "SET enable_file_scanner_v2=true"
+        sql "SET profile_level=2"
+        def profileAction = new ProfileAction(context)
+        def assertCacheHit = { String token, boolean expectPruning ->
+            String profile = profileAction.getProfileBySql(token, 
["ConditionCacheHit", "ConditionCacheFilteredRows"])
+            def hits = profile =~ /ConditionCacheHit:\s*([0-9,]+)/
+            assertTrue(hits.findAll().any { Long.parseLong(it[1].replace(",", 
"")) > 0 },
+                    "No positive condition-cache hit; the regression must 
exercise cache reuse: ${profile}")
+            if (expectPruning) {
+                def filtered = profile =~ 
/ConditionCacheFilteredRows:\s*([0-9,]+)/
+                assertTrue(filtered.findAll().any { 
Long.parseLong(it[1].replace(",", "")) > 0 },
+                        "The Q-only bitmap must still prune nonmatching 
granules: ${profile}")
+            }
+        }
+        String table = 
"nested_predicate_cache_catalog.nested_predicate_cache.nested_default"
+        String predicate = "mod(element_at(s,'x'),2)=1 AND mod(k,3)=1"
+        String warmToken = "nested_cache_warm_${UUID.randomUUID()}"
+        // Project the whole parent: its field ID must stay stable while the 
child's ID changes.
+        String warm = "SELECT /* ${warmToken} */ s,k FROM ${table} WHERE 
${predicate}"
+        sql "SET enable_profile=false"
+        5.times { sql warm }
+        sql "SET enable_profile=true"
+        sql warm
+        assertCacheHit(warmToken, true)
+        qt_original_rows "SELECT count(*) FROM ${table} WHERE ${predicate}"
+
+        String evolved = sdkRun("evolve")
+        assertTrue(evolved.contains("CACHE_FIXTURE rows=8192 x=9"))
+        assertTrue(evolved.contains("CACHE_EVOLVED root=1 old=3 new=5"))
+        sql "REFRESH TABLE ${table}"
+        String evolvedToken = "nested_cache_evolved_${UUID.randomUUID()}"
+        String query = "SELECT /* ${evolvedToken} */ s,k FROM ${table} WHERE 
${predicate}"
+        sql "SET enable_profile=false"
+        sql "SET enable_condition_cache=false"
+        def expected = sql(query)
+        qt_evolved_defaults """SELECT 
element_at(s,'x'),element_at(s,'keep'),k,count(*)
+                FROM ${table} WHERE ${predicate} GROUP BY 1,2,3 ORDER BY 
1,2,3"""
+        qt_null_parents "SELECT count(*) FROM ${table} WHERE s IS NULL"
+        sql "SET enable_condition_cache=true"
+        def first = sql(query)
+        assertTrue(expected == first, "A Q-only request reused a P AND Q 
bitmap: " +
+                "expected ${expected.size()} rows, got ${first.size()}; sample 
${first.take(3)}")
+        sql "SET enable_profile=true"
+        def repeated = sql(query)
+        assertTrue(expected == repeated, "Cached rows differ from the full 
scan: " +
+                "expected ${expected.size()} rows, got ${repeated.size()}; 
sample ${repeated.take(3)}")
+        assertCacheHit(evolvedToken, true)
+    } finally {
+        settings.each { name, value -> sql "SET ${name}=${value}" }
+        if (local && classes != null) {
+            assertTrue(classes.deleteDir())
+        } else if (container != null) {
+            execute(["bash", "-c", "${docker} exec ${shellQuote(container)} rm 
-rf ${shellQuote(directory)}"])
+        }
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to