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 1ca4950720c [fix](branch-4.2) Backport Iceberg cache/drop and TVF 
compression fixes (#71198)
1ca4950720c is described below

commit 1ca4950720c19549a988f88ce9db3e76c2179c2b
Author: Gabriel <[email protected]>
AuthorDate: Thu Dec 3 15:04:57 2026 +0800

    [fix](branch-4.2) Backport Iceberg cache/drop and TVF compression fixes 
(#71198)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Backport these master fixes to `branch-4.2`, in master merge order:
    
    1. #70936 — Include file-local predicates in external condition-cache
    identity.
    2. #70919 — Honor explicit TVF compression and keep stateful text/JSON
    parsing unsplit.
    3. #70967 — Allow Iceberg REST unregister-only drops with
    `iceberg.rest.drop-with-purge-enabled=false`.
    
    The requested dependency upgrade #71066 was merged into `branch-4.2`
    through #71069 while this backport was being validated. It is already
    present in the base and is not duplicated here.
    
    ### Branch adaptations
    
    - Reuse the 4.2 localized digest builder while preserving source-range
    coordinates, INT96 handling and positional-binding/cache exclusions.
    Adapt the new digest-count test to the branch's earlier
    adaptive-snapshot hashing.
    - Pass configured compression through the existing lazy splitter,
    keeping the legacy API, Lance path and count-pushdown gates. Preserve
    the original TVF test class and add adapted compression/stateful-format
    coverage using the branch's Java 8-compatible APIs.
    - Keep Hive text files unsplit when the UTF-8 line delimiter has a
    nonempty proper prefix/suffix overlap. Both Hive text scanners must
    preserve greedy delimiter alignment; non-overlapping Hive text
    delimiters and CSV/JSON retain their existing split policy.
    - Apply the REST option in legacy Iceberg metadata operations while
    retaining session-aware catalog access. Validate CREATE/ALTER statements
    without introducing replay validation; forced database drops use the
    same table-drop policy.
    
    ### Validation
    
    - Review fix: first reproduced the planner defect with 12 expected
    failures and no test errors. After the fix, a fresh FE build passed all
    109 targeted tests (`TVFExplicitCompressionTest`, `TVFScanNodeTest`,
    `FileSplitterTest`), with zero failures, errors or skips. The same tests
    cover S3/HDFS, explicit/inferred compression, encoded and multibyte
    delimiters, and count-pushdown gates.
    - Review fix: FE Checkstyle, clang-format 16 on all 5 affected C++
    files, and compilation of the updated TVF Groovy suite passed. Added
    complete-row regression checks for the reported 1,228-byte pipe boundary
    and an `aba` prefix/suffix overlap, for both scanner modes and
    with/without a `.gz` suffix.
    - Initial backport validation, before the review fix: repository FE
    build with the targeted tests enabled passed: 231 Java tests, 230 passed
    and 1 existing disabled case skipped; zero failures/errors. Includes 71
    compression/stateful-format cases, existing TVF/splitter tests, REST
    DROP/cascade/error propagation, property validation and dependency
    controls.
    - FE Checkstyle passed; clang-format 16 passed on all 5 affected C++
    sources/headers.
    - Four related C++ production/test translation units compiled with ASAN
    instrumentation. Existing deprecated-API warnings were left nonfatal for
    the local toolchain. This is compile coverage, not BE unit-test
    execution.
    - All three SQL Groovy suites compiled. The Iceberg fixture compiled and
    ran against the stock 1.11 SDK modules: all 8,192 rows verified
    before/after evolution, with unchanged historical snapshot/file identity
    and the new field default.
    
    The TVF SQL suite includes the additional delimiter-boundary checks; the
    other SQL suites and generated result snapshots are unchanged. Live
    external SQL regression and full BE unit-test execution were not run
    locally and remain for CI.
    
    ### Release note
    
    Fix stale Iceberg condition-cache results after nested-field evolution
    and invalid TVF file splitting when compression or parsing state
    requires whole files. Allow Iceberg REST catalogs to unregister tables
    without deleting files; purge remains enabled by default.
    
    ### Check List (For Author)
    
    - [x] Unit tests included
    - [x] Regression tests included
    - Behavior changed: Yes, as described above.
    - Documentation: The REST purge option needs documentation; other
    changes enforce existing contracts.
---
 be/src/format_v2/table/iceberg_reader.h            |  15 +-
 be/src/format_v2/table_reader.cpp                  |  31 ++-
 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            | 151 +++++++++-
 .../org/apache/doris/datasource/FileSplitter.java  |  26 +-
 .../datasource/iceberg/IcebergExternalCatalog.java |   7 +
 .../datasource/iceberg/IcebergMetadataOps.java     |  10 +-
 .../property/metastore/IcebergRestProperties.java  |   8 +
 .../doris/datasource/tvf/source/TVFScanNode.java   |  58 +++-
 .../iceberg/IcebergRestDropPurgeTest.java          | 236 ++++++++++++++++
 .../tvf/source/TVFExplicitCompressionTest.java     | 306 +++++++++++++++++++++
 .../test_iceberg_nested_predicate_cache.out        |  10 +
 .../test_iceberg_rest_drop_purge_option.out        |  21 ++
 .../tvf/test_tvf_explicit_compression_splits.out   |  82 ++++++
 .../CreateNestedPredicateCacheFixture.java         | 162 +++++++++++
 .../test_iceberg_nested_predicate_cache.groovy     | 160 +++++++++++
 .../test_iceberg_rest_drop_purge_option.groovy     | 195 +++++++++++++
 .../test_tvf_explicit_compression_splits.groovy    | 267 ++++++++++++++++++
 19 files changed, 1716 insertions(+), 42 deletions(-)

diff --git a/be/src/format_v2/table/iceberg_reader.h 
b/be/src/format_v2/table/iceberg_reader.h
index 3aecd776fc1..7741f96dc0f 100644
--- a/be/src/format_v2/table/iceberg_reader.h
+++ b/be/src/format_v2/table/iceberg_reader.h
@@ -97,12 +97,17 @@ protected:
     // Legacy FE plans retain name matching, and ORC retains its existing 
behavior.
     Status annotate_file_schema(std::vector<format::ColumnDefinition>* 
file_schema) override;
 
-    // Changing the name mapping can change a positional binding without 
changing the file or
-    // table-predicate digest. Such splits must neither read nor publish 
cached filter results.
-    bool _should_enable_condition_cache(
+    // 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
+    // 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 9e946ef65c2..990c21fc61d 100644
--- a/be/src/format_v2/table_reader.cpp
+++ b/be/src/format_v2/table_reader.cpp
@@ -1424,41 +1424,47 @@ 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,
     // and reusing an old all-false granule would silently discard matching 
rows.
-    if (!build_predicate_snapshot_digest(file_request.conjuncts).has_value()) {
-        return false;
+    const auto localized_digest = 
build_predicate_snapshot_digest(file_request.conjuncts);
+    if (!localized_digest.has_value()) {
+        return std::nullopt;
     }
     // Delete files/deletion vectors are table-format state. They may change 
independently of the
     // data file path/mtime/size used by the external cache key, so caching 
their result can become
     // 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();
     }
@@ -1475,7 +1481,12 @@ Status TableReader::_init_reader_condition_cache(const 
FileScanRequest& file_req
     const auto cache_size = _condition_cache_source_range.has_value()
                                     ? _condition_cache_source_range->second
                                     : file.range_size;
-    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 7ecf39b6f18..773fc3bd160 100644
--- a/be/src/format_v2/table_reader.h
+++ b/be/src/format_v2/table_reader.h
@@ -578,12 +578,11 @@ protected:
     Status _open_local_filter_exprs(const FileScanRequest& file_request);
     Status _init_reader_condition_cache(const FileScanRequest& file_request);
     void _finalize_reader_condition_cache();
-    // 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 a2bf5ee031d..4cd0190dff9 100644
--- a/be/test/format_v2/table/iceberg_reader_test.cpp
+++ b/be/test/format_v2/table/iceberg_reader_test.cpp
@@ -3541,7 +3541,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 7e9193a4bc4..42fec638033 100644
--- a/be/test/format_v2/table_reader_test.cpp
+++ b/be/test/format_v2/table_reader_test.cpp
@@ -410,6 +410,35 @@ VExprSPtr runtime_filter_wrapper_expr(VExprSPtr impl) {
     return RuntimeFilterExpr::create_shared(node, std::move(impl), 0, false, 
/*filter_id=*/1);
 }
 
+class RecordingDigestPredicate final : public VExpr {
+public:
+    RecordingDigestPredicate(size_t* calls, uint64_t value)
+            : VExpr(std::make_shared<DataTypeUInt8>(), false), _calls(calls), 
_value(value) {
+        set_node_type(TExprNodeType::FUNCTION_CALL);
+    }
+
+    Status execute_column_impl(VExprContext*, const Block*, const Selector*, 
size_t count,
+                               ColumnPtr& result_column) const override {
+        result_column = ColumnUInt8::create(count, 1);
+        return Status::OK();
+    }
+
+    const std::string& expr_name() const override { return _name; }
+    uint64_t get_digest(uint64_t seed) const override {
+        ++*_calls;
+        return _value == 0 ? 0 : seed ^ _value;
+    }
+    Status clone_node(VExprSPtr* cloned_expr) const override {
+        *cloned_expr = std::make_shared<RecordingDigestPredicate>(_calls, 
_value);
+        return Status::OK();
+    }
+
+private:
+    size_t* _calls;
+    uint64_t _value;
+    const std::string _name = "RecordingDigestPredicate";
+};
+
 class NonDeterministicPartitionPredicate final : public VExpr {
 public:
     explicit NonDeterministicPartitionPredicate(bool* executed)
@@ -1637,6 +1666,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());
@@ -4149,17 +4182,103 @@ 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());
 }
 
+// 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());
+        // Ignore earlier adaptive-snapshot hashes; measure only file-local 
cache admission.
+        calls = 0;
+        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 {
@@ -4367,6 +4486,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());
@@ -4488,12 +4611,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());
@@ -4614,12 +4733,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();
@@ -4672,9 +4792,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));
@@ -4726,7 +4847,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/fe/fe-core/src/main/java/org/apache/doris/datasource/FileSplitter.java 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/FileSplitter.java
index a8cede6dd6e..0e9ece590e9 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/FileSplitter.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/FileSplitter.java
@@ -92,10 +92,18 @@ public class FileSplitter {
     public List<Split> splitFile(LocationPath path, long 
specifiedFileSplitSize,
             BlockLocation[] blockLocations, long length, long 
modificationTime, boolean splittable,
             List<String> partitionValues, SplitCreator splitCreator) throws 
IOException {
+        return splitFile(path, specifiedFileSplitSize, blockLocations, length, 
modificationTime,
+                splittable, TFileCompressType.UNKNOWN, partitionValues, 
splitCreator);
+    }
+
+    public List<Split> splitFile(LocationPath path, long 
specifiedFileSplitSize,
+            BlockLocation[] blockLocations, long length, long 
modificationTime, boolean splittable,
+            TFileCompressType configuredCompression, List<String> 
partitionValues, SplitCreator splitCreator)
+            throws IOException {
         List<Split> result = Lists.newArrayList();
         try {
             splitFileIterator(path, specifiedFileSplitSize, blockLocations, 
length, modificationTime,
-                    splittable, partitionValues, 
splitCreator).forEachRemaining(result::add);
+                    splittable, configuredCompression, partitionValues, 
splitCreator).forEachRemaining(result::add);
         } catch (UncheckedIOException e) {
             throw e.getCause();
         }
@@ -106,14 +114,26 @@ public class FileSplitter {
     public Iterator<Split> splitFileIterator(LocationPath path, long 
specifiedFileSplitSize,
             BlockLocation[] blockLocations, long length, long 
modificationTime, boolean splittable,
             List<String> partitionValues, SplitCreator splitCreator) throws 
IOException {
+        return splitFileIterator(path, specifiedFileSplitSize, blockLocations, 
length, modificationTime,
+                splittable, TFileCompressType.UNKNOWN, partitionValues, 
splitCreator);
+    }
+
+    public Iterator<Split> splitFileIterator(LocationPath path, long 
specifiedFileSplitSize,
+            BlockLocation[] blockLocations, long length, long 
modificationTime, boolean splittable,
+            TFileCompressType configuredCompression, List<String> 
partitionValues, SplitCreator splitCreator)
+            throws IOException {
         if (length <= 0) {
             return Collections.emptyIterator();
         }
         long targetFileSplitSize = specifiedFileSplitSize > 0 ? 
specifiedFileSplitSize : maxSplitSize;
         BlockLocation[] locations = blockLocations == null
                 ? new BlockLocation[] {new BlockLocation(null, null, 0L, 
length)} : blockLocations;
-        boolean canSplit = splittable
-                && 
Util.inferFileCompressTypeByPath(path.getNormalizedLocation()) == 
TFileCompressType.PLAIN;
+        // Match schema inference and BE ranges while retaining lazy split 
construction.
+        // Parquet/ORC leave the envelope codec unset because their 
compression is internal.
+        TFileCompressType compressType = Util.getOrInferCompressType(
+                configuredCompression == null ? TFileCompressType.UNKNOWN : 
configuredCompression,
+                path.getNormalizedLocation());
+        boolean canSplit = splittable && compressType == 
TFileCompressType.PLAIN;
         ImmutableList.Builder<InternalBlock> blockBuilder = 
ImmutableList.builder();
         if (canSplit && specifiedFileSplitSize <= 0) {
             for (BlockLocation block : locations) {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
index d758c28b521..ac6ba0c0c67 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
@@ -136,6 +136,13 @@ public abstract class IcebergExternalCatalog extends 
ExternalCatalog {
     @Override
     protected void checkProperties(CatalogProperty property) throws 
DdlException {
         super.checkProperties(property);
+        if 
(ICEBERG_REST.equalsIgnoreCase(property.getOrDefault(ICEBERG_CATALOG_TYPE, 
""))) {
+            // Validate statements only; replay binding must keep accepting 
persisted properties.
+            String purge = 
property.getOrDefault(IcebergRestProperties.DROP_WITH_PURGE_ENABLED, null);
+            if (purge != null && !"true".equalsIgnoreCase(purge) && 
!"false".equalsIgnoreCase(purge)) {
+                throw new 
DdlException(IcebergRestProperties.DROP_WITH_PURGE_ENABLED + " must be true or 
false");
+            }
+        }
         
CacheSpec.checkBooleanProperty(property.getOrDefault(ICEBERG_TABLE_CACHE_ENABLE,
 null),
                 ICEBERG_TABLE_CACHE_ENABLE);
         
CacheSpec.checkLongProperty(property.getOrDefault(ICEBERG_TABLE_CACHE_TTL_SECOND,
 null),
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
index b200b40ea46..e0cbeb4be48 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
@@ -547,7 +547,15 @@ public class IcebergMetadataOps implements 
ExternalMetadataOps {
                 ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TABLE, 
remoteTblName, remoteDbName);
             }
         }
-        catalog(ctx).dropTable(getTableIdentifier(remoteDbName, 
remoteTblName), true);
+        catalog(ctx).dropTable(getTableIdentifier(remoteDbName, 
remoteTblName), shouldPurgeOnDrop());
+    }
+
+    private boolean shouldPurgeOnDrop() {
+        // REST can unregister without deleting files; HadoopCatalog may 
delete its directory even with purge=false.
+        Map<String, String> properties = catalogProperties;
+        return !IcebergExternalCatalog.ICEBERG_REST.equalsIgnoreCase(
+                properties.get(IcebergExternalCatalog.ICEBERG_CATALOG_TYPE))
+                || 
Boolean.parseBoolean(properties.getOrDefault(IcebergRestProperties.DROP_WITH_PURGE_ENABLED,
 "true"));
     }
 
     public void renameTableImpl(String dbName, String tblName, String 
newTblName) throws DdlException {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
index d6ac425f103..8668724d49b 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
@@ -53,6 +53,8 @@ import java.util.Map;
 
 public class IcebergRestProperties extends AbstractIcebergProperties {
 
+    public static final String DROP_WITH_PURGE_ENABLED = 
"iceberg.rest.drop-with-purge-enabled";
+
     private static final Logger LOG = 
LogManager.getLogger(IcebergRestProperties.class);
 
     // REST catalog property constants
@@ -76,6 +78,12 @@ public class IcebergRestProperties extends 
AbstractIcebergProperties {
     // instead of failing every request until the FE restarts.
     private BaseViewSessionCatalog restSessionCatalog;
 
+    @Getter
+    @ConnectorProperty(names = {DROP_WITH_PURGE_ENABLED},
+            required = false,
+            description = "Delete table data and metadata files when dropping 
an Iceberg REST table. Default: true.")
+    private boolean icebergRestDropWithPurgeEnabled = true;
+
     @Getter
     @ConnectorProperty(names = {"iceberg.rest.uri", "uri"},
             description = "The uri of the iceberg rest catalog service.")
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
index 297272cb582..a991e203208 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/tvf/source/TVFScanNode.java
@@ -34,6 +34,7 @@ import org.apache.doris.datasource.lance.source.LanceScanNode;
 import org.apache.doris.datasource.lance.source.LanceSplit;
 import org.apache.doris.datasource.lance.source.LanceSplitBuilder;
 import org.apache.doris.datasource.lance.storage.LanceStorageOptions;
+import org.apache.doris.datasource.property.fileformat.FileFormatProperties;
 import org.apache.doris.planner.PlanNodeId;
 import org.apache.doris.planner.ScanContext;
 import org.apache.doris.qe.SessionVariable;
@@ -55,6 +56,7 @@ import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -171,6 +173,7 @@ public class TVFScanNode extends FileQueryScanNode {
             needSplit = FileSplitter.needSplitForCountPushdown(parallelNum, 
numBackends, totalFileNum);
         }
 
+        boolean formatSplittable = isFormatSplittable();
         long targetFileSplitSize = determineTargetFileSplitSize(fileStatuses);
 
         for (TBrokerFileStatus fileStatus : fileStatuses) {
@@ -181,7 +184,8 @@ public class TVFScanNode extends FileQueryScanNode {
                         null,
                         fileStatus.getSize(),
                         fileStatus.getModificationTime(),
-                        fileStatus.isSplitable && needSplit,
+                        fileStatus.isSplitable && needSplit && 
formatSplittable,
+                        tableValuedFunction.getTFileCompressType(),
                         null,
                         FileSplitCreator.DEFAULT));
             } catch (IOException e) {
@@ -192,6 +196,58 @@ public class TVFScanNode extends FileQueryScanNode {
         return splits;
     }
 
+    private boolean isFormatSplittable() {
+        TFileFormatType format = tableValuedFunction.getTFileFormatType();
+        if (format == TFileFormatType.FORMAT_JSON) {
+            // Document mode parses each range as a complete JSON value, 
including implicit array mode.
+            return getFileAttributes().isReadJsonByLine();
+        }
+        if (Util.isCsvFormat(format) || format == TFileFormatType.FORMAT_TEXT) 
{
+            TFileAttributes attributes = getFileAttributes();
+            if (format == TFileFormatType.FORMAT_TEXT
+                    && 
hasSelfOverlappingDelimiter(attributes.getTextParams().getLineDelimiter())) {
+                // Neither Hive text scanner replays greedy delimiter matches 
before a split.
+                // A fixed lookbehind can restart in a different delimiter 
phase and change records.
+                return false;
+            }
+            if (Util.isCsvFormat(format) && 
attributes.getTextParams().getEnclose() != 0) {
+                // A byte boundary may lie inside a quoted multiline field; 
ranges cannot recover quote state.
+                return false;
+            }
+            int skippedLines = attributes.getSkipLines();
+            // Header modes override skip_lines in the reader.
+            if 
(FileFormatProperties.FORMAT_CSV_WITH_NAMES.equalsIgnoreCase(attributes.getHeaderType()))
 {
+                skippedLines = 1;
+            } else if (FileFormatProperties.FORMAT_CSV_WITH_NAMES_AND_TYPES
+                    .equalsIgnoreCase(attributes.getHeaderType())) {
+                skippedLines = 2;
+            }
+            // Non-first ranges skip one partial record, but cannot consume a 
remaining multi-record prefix.
+            return skippedLines <= 1;
+        }
+        return true;
+    }
+
+    private static boolean hasSelfOverlappingDelimiter(String delimiter) {
+        if (delimiter == null || delimiter.length() < 2) {
+            return false;
+        }
+        // Match the UTF-8 bytes sent to BE, including encoded and multibyte 
delimiters.
+        byte[] delimiterBytes = delimiter.getBytes(StandardCharsets.UTF_8);
+        int[] prefixLengths = new int[delimiterBytes.length];
+        int matched = 0;
+        for (int index = 1; index < delimiterBytes.length; index++) {
+            while (matched > 0 && delimiterBytes[index] != 
delimiterBytes[matched]) {
+                matched = prefixLengths[matched - 1];
+            }
+            if (delimiterBytes[index] == delimiterBytes[matched]) {
+                matched++;
+            }
+            prefixLengths[index] = matched;
+        }
+        return prefixLengths[delimiterBytes.length - 1] > 0;
+    }
+
     private List<Split> getLanceSplits() throws UserException {
         if (!sessionVariable.enableFileScannerV2) {
             throw new UserException("Lance TVF requires 
enable_file_scanner_v2=true");
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergRestDropPurgeTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergRestDropPurgeTest.java
new file mode 100644
index 00000000000..a13adc93657
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergRestDropPurgeTest.java
@@ -0,0 +1,236 @@
+// 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.common.DdlException;
+import org.apache.doris.common.security.authentication.ExecutionAuthenticator;
+import org.apache.doris.datasource.CatalogProperty;
+import org.apache.doris.datasource.ExternalDatabase;
+import org.apache.doris.datasource.ExternalTable;
+import org.apache.doris.datasource.property.metastore.IcebergRestProperties;
+import org.apache.doris.datasource.property.metastore.MetastoreProperties;
+
+import com.sun.net.httpserver.HttpServer;
+import org.apache.iceberg.CatalogProperties;
+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.catalog.ViewCatalog;
+import org.apache.iceberg.rest.RESTCatalog;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+public class IcebergRestDropPurgeTest {
+    private static final String PURGE_PROPERTY = 
"iceberg.rest.drop-with-purge-enabled";
+    private static final Namespace DB = Namespace.of("db");
+    private static final TableIdentifier FIRST = TableIdentifier.of(DB, "t1");
+    private static final TableIdentifier SECOND = TableIdentifier.of(DB, "t2");
+
+    @Test
+    public void restDropCanUnregisterWithoutPurging() throws Exception {
+        Fixture fixture = new Fixture("rest", "false");
+        fixture.ops.dropTableImpl(fixture.table, false);
+        Mockito.verify(fixture.catalog).dropTable(FIRST, false);
+    }
+
+    @Test
+    public void restDropStillPurgesByDefaultAndWhenExplicitlyEnabled() throws 
Exception {
+        for (String enabled : Arrays.asList(null, "true", "TRUE")) {
+            Fixture fixture = new Fixture("rest", enabled);
+            fixture.ops.dropTableImpl(fixture.table, false);
+            fixture.ops.dropDbImpl("db", false, true);
+            Mockito.verify(fixture.catalog, Mockito.times(2)).dropTable(FIRST, 
true);
+            Mockito.verify(fixture.catalog).dropTable(SECOND, true);
+        }
+    }
+
+    @Test
+    public void forceDropUnregistersEveryTableAndStillDropsViews() throws 
Exception {
+        Fixture fixture = new Fixture("rest", "false");
+        ViewCatalog views = (ViewCatalog) fixture.catalog;
+        TableIdentifier view = TableIdentifier.of(DB, "v");
+        
Mockito.when(views.listViews(DB)).thenReturn(Collections.singletonList(view));
+        fixture.ops.dropDbImpl("db", false, true);
+        InOrder order = Mockito.inOrder(fixture.catalog);
+        order.verify(fixture.catalog).dropTable(FIRST, false);
+        order.verify(fixture.catalog).dropTable(SECOND, false);
+        order.verify(views).dropView(view);
+        order.verify((SupportsNamespaces) fixture.catalog).dropNamespace(DB);
+    }
+
+    @Test
+    public void restOptionDoesNotChangeOtherCatalogDropSemantics() throws 
Exception {
+        for (String flavor : Arrays.asList("hms", "hadoop", "jdbc", "glue", 
"dlf", "s3tables")) {
+            Fixture fixture = new Fixture(flavor, "false");
+            fixture.ops.dropTableImpl(fixture.table, false);
+            fixture.ops.dropDbImpl("db", false, true);
+            Mockito.verify(fixture.catalog, Mockito.times(2)).dropTable(FIRST, 
true);
+            Mockito.verify(fixture.catalog).dropTable(SECOND, true);
+        }
+    }
+
+    @Test
+    public void rejectsInvalidBooleanDuringCreateAndAlterValidation() {
+        for (String invalid : Arrays.asList("", "yes", "0", " false ")) {
+            Map<String, String> raw = properties("rest", invalid);
+            IcebergRestExternalCatalog catalog = new 
IcebergRestExternalCatalog(1L, "rest", null, raw, "");
+            DdlException error = Assertions.assertThrows(DdlException.class, 
catalog::checkProperties);
+            Assertions.assertEquals(PURGE_PROPERTY + " must be true or false", 
error.getDetailMessage());
+            // The normal ALTER fallback temporarily publishes candidate 
properties before validation.
+            Map<String, String> updated = properties("rest", invalid);
+            IcebergRestExternalCatalog altered = new 
IcebergRestExternalCatalog(2L, "altered", null,
+                    properties("rest", "true"), "");
+            DdlException alterError = 
Assertions.assertThrows(DdlException.class, () -> {
+                if 
(!altered.validatePropertiesBeforeUpdate(altered.getProperties(), updated)) {
+                    altered.getCatalogProperty().modifyCatalogProps(updated);
+                    altered.checkProperties();
+                }
+            });
+            Assertions.assertEquals(PURGE_PROPERTY + " must be true or false", 
alterError.getDetailMessage());
+        }
+    }
+
+    @Test
+    public void validBooleansBindWithoutChangingSdkProperties() throws 
Exception {
+        for (String valid : Arrays.asList("true", "false", "TRUE", "FALSE")) {
+            IcebergRestProperties bound = (IcebergRestProperties) 
MetastoreProperties.create(properties("rest", valid));
+            Assertions.assertEquals(Boolean.parseBoolean(valid), 
bound.isIcebergRestDropWithPurgeEnabled());
+            
Assertions.assertFalse(bound.getIcebergRestCatalogProperties().containsKey(PURGE_PROPERTY));
+        }
+        // Replay binding must not introduce new statement-time validation.
+        Assertions.assertDoesNotThrow(() -> 
MetastoreProperties.create(properties("rest", "invalid")));
+    }
+
+    @Test
+    public void failedTableUnregisterStopsTheForceCascade() throws Exception {
+        Fixture fixture = new Fixture("rest", "false");
+        Mockito.when(fixture.catalog.dropTable(FIRST, false))
+                .thenThrow(new IllegalStateException("unregister rejected"));
+        DdlException error = Assertions.assertThrows(DdlException.class,
+                () -> fixture.ops.dropDbImpl("db", false, true));
+        Assertions.assertTrue(error.getMessage().contains("unregister 
rejected"), error.getMessage());
+        Mockito.verify(fixture.catalog, 
Mockito.never()).dropTable(Mockito.eq(SECOND), Mockito.anyBoolean());
+        Mockito.verify((SupportsNamespaces) fixture.catalog, 
Mockito.never()).dropNamespace(DB);
+    }
+
+    @Test
+    public void restServerThatRejectsPurgeAcceptsMetadataOnlyDrop() throws 
Exception {
+        List<String> queries = new CopyOnWriteArrayList<>();
+        HttpServer server = HttpServer.create(new 
InetSocketAddress("127.0.0.1", 0), 0);
+        server.createContext("/", exchange -> {
+            try {
+                exchange.getResponseHeaders().set("Content-Type", 
"application/json");
+                if ("GET".equals(exchange.getRequestMethod())) {
+                    byte[] config = 
"{\"defaults\":{},\"overrides\":{}}".getBytes(StandardCharsets.UTF_8);
+                    exchange.sendResponseHeaders(200, config.length);
+                    exchange.getResponseBody().write(config);
+                } else if ("DELETE".equals(exchange.getRequestMethod())) {
+                    String query = exchange.getRequestURI().getRawQuery();
+                    queries.add(query);
+                    if (query != null && 
query.contains("purgeRequested=true")) {
+                        byte[] error = ("{\"error\":{\"message\":\"purge 
disabled\","
+                                + 
"\"type\":\"ForbiddenException\",\"code\":403}}")
+                                .getBytes(StandardCharsets.UTF_8);
+                        exchange.sendResponseHeaders(403, error.length);
+                        exchange.getResponseBody().write(error);
+                    } else {
+                        exchange.sendResponseHeaders(204, -1);
+                    }
+                } else {
+                    exchange.sendResponseHeaders(405, -1);
+                }
+            } finally {
+                exchange.close();
+            }
+        });
+        server.start();
+        try (RESTCatalog catalog = Mockito.spy(new RESTCatalog())) {
+            catalog.initialize("test", 
Collections.singletonMap(CatalogProperties.URI,
+                    "http://127.0.0.1:"; + server.getAddress().getPort()));
+            
Mockito.doReturn(true).when(catalog).tableExists(Mockito.any(TableIdentifier.class));
+            
Mockito.doReturn(false).when(catalog).viewExists(Mockito.any(TableIdentifier.class));
+            Fixture defaultDrop = new Fixture("rest", null, catalog);
+            DdlException error = Assertions.assertThrows(DdlException.class,
+                    () -> defaultDrop.ops.dropTableImpl(defaultDrop.table, 
false));
+            Assertions.assertTrue(error.getMessage().contains("purge 
disabled"), error.getMessage());
+            Fixture metadataOnly = new Fixture("rest", "false", catalog);
+            metadataOnly.ops.dropTableImpl(metadataOnly.table, false);
+            Assertions.assertEquals(2, queries.size());
+            Assertions.assertEquals("purgeRequested=true", queries.get(0));
+            Assertions.assertNull(queries.get(1), "metadata-only REST drop 
must omit purgeRequested");
+        } finally {
+            server.stop(0);
+        }
+    }
+
+    private static Map<String, String> properties(String flavor, String 
enabled) {
+        Map<String, String> raw = new HashMap<>();
+        raw.put("type", "iceberg");
+        raw.put(IcebergExternalCatalog.ICEBERG_CATALOG_TYPE, flavor);
+        raw.put("iceberg.rest.uri", "http://127.0.0.1:8181";);
+        if (enabled != null) {
+            raw.put(PURGE_PROPERTY, enabled);
+        }
+        return raw;
+    }
+
+    private static class Fixture {
+        private final Catalog catalog;
+        private final IcebergMetadataOps ops;
+        private final ExternalTable table = Mockito.mock(ExternalTable.class);
+
+        Fixture(String flavor, String enabled) {
+            this(flavor, enabled, Mockito.mock(Catalog.class,
+                    
Mockito.withSettings().extraInterfaces(SupportsNamespaces.class, 
ViewCatalog.class)));
+            
Mockito.when(catalog.tableExists(Mockito.any(TableIdentifier.class))).thenReturn(true);
+            
Mockito.when(catalog.listTables(DB)).thenReturn(Arrays.asList(FIRST, SECOND));
+        }
+
+        Fixture(String flavor, String enabled, Catalog catalog) {
+            this.catalog = catalog;
+            Map<String, String> raw = properties(flavor, enabled);
+            IcebergExternalCatalog doris = 
Mockito.mock(IcebergExternalCatalog.class);
+            Mockito.when(doris.getProperties()).thenReturn(raw);
+            Mockito.when(doris.getCatalogProperty()).thenReturn(new 
CatalogProperty(null, raw));
+            Mockito.when(doris.getExecutionAuthenticator()).thenReturn(new 
ExecutionAuthenticator() {
+            });
+            ExternalDatabase db = Mockito.mock(ExternalDatabase.class);
+            Mockito.when(db.getRemoteName()).thenReturn("db");
+            Mockito.when(db.getFullName()).thenReturn("db");
+            Mockito.when(doris.getDbNullable("db")).thenReturn(db);
+            
Mockito.doReturn(db).when(doris).getDbForCatalogOperation(Mockito.any(), 
Mockito.eq("db"));
+            ops = new IcebergMetadataOps(doris, catalog);
+            Mockito.when(doris.getMetadataOps()).thenReturn(ops);
+            Mockito.when(table.getRemoteDbName()).thenReturn("db");
+            Mockito.when(table.getRemoteName()).thenReturn("t1");
+            Mockito.when(table.getName()).thenReturn("t1");
+        }
+    }
+}
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFExplicitCompressionTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFExplicitCompressionTest.java
new file mode 100644
index 00000000000..7ab5e326baf
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFExplicitCompressionTest.java
@@ -0,0 +1,306 @@
+// 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.tvf.source;
+
+import org.apache.doris.analysis.SlotId;
+import org.apache.doris.analysis.TupleDescriptor;
+import org.apache.doris.analysis.TupleId;
+import org.apache.doris.catalog.FunctionGenTable;
+import org.apache.doris.datasource.FileQueryScanNode;
+import org.apache.doris.datasource.FileSplit;
+import org.apache.doris.datasource.FileSplitter;
+import org.apache.doris.datasource.property.fileformat.FileFormatProperties;
+import org.apache.doris.planner.PlanNodeId;
+import org.apache.doris.planner.ScanContext;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.SessionVariable;
+import org.apache.doris.spi.Split;
+import org.apache.doris.tablefunction.ExternalFileTableValuedFunction;
+import org.apache.doris.thrift.TBrokerFileStatus;
+import org.apache.doris.thrift.TFileAttributes;
+import org.apache.doris.thrift.TFileCompressType;
+import org.apache.doris.thrift.TFileFormatType;
+import org.apache.doris.thrift.TFileTextScanRangeParams;
+import org.apache.doris.thrift.TFileType;
+import org.apache.doris.thrift.TPushAggOp;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class TVFExplicitCompressionTest {
+    private static final long MB = 1024L * 1024L;
+
+    private ConnectContext previousContext;
+
+    @BeforeEach
+    public void setUpContext() {
+        previousContext = ConnectContext.get();
+        new ConnectContext().setThreadLocalInfo();
+    }
+
+    @AfterEach
+    public void restoreContext() {
+        ConnectContext.remove();
+        if (previousContext != null) {
+            previousContext.setThreadLocalInfo();
+        }
+    }
+
+    private static Stream<Arguments> formatCases() {
+        return Stream.of(
+                Arguments.of("csv", ImmutableMap.of(), true),
+                Arguments.of("csv", ImmutableMap.of("enclose", ""), true),
+                Arguments.of("csv", ImmutableMap.of("enclose", "\""), false),
+                Arguments.of("csv", ImmutableMap.of("enclose", "0"), false),
+                Arguments.of("csv", ImmutableMap.of("skip_lines", "0"), true),
+                Arguments.of("csv", ImmutableMap.of("skip_lines", "1"), true),
+                Arguments.of("csv", ImmutableMap.of("skip_lines", "20"), 
false),
+                Arguments.of("hive_text", ImmutableMap.of("skip_lines", "0"), 
true),
+                Arguments.of("hive_text", ImmutableMap.of("skip_lines", "1"), 
true),
+                Arguments.of("hive_text", ImmutableMap.of("skip_lines", "20"), 
false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"||"), false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"aba"), false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"abab"), false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"aabaa"), false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"界|界"), false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"\\x7c\\x7c"), false),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"|"), true),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"\r\n"), true),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"|~"), true),
+                Arguments.of("hive_text", ImmutableMap.of("line_delimiter", 
"界尾"), true),
+                Arguments.of("csv", ImmutableMap.of("line_delimiter", "||"), 
true),
+                Arguments.of("json", ImmutableMap.of("line_delimiter", "||"), 
true),
+                Arguments.of("csv_with_names", ImmutableMap.of(), true),
+                Arguments.of("csv_with_names", ImmutableMap.of("skip_lines", 
"20"), true),
+                Arguments.of("csv_with_names_and_types", ImmutableMap.of(), 
false),
+                Arguments.of("csv_with_names_and_types", 
ImmutableMap.of("skip_lines", "0"), false),
+                Arguments.of("csv_with_names_and_types", 
ImmutableMap.of("skip_lines", "1"), false),
+                Arguments.of("json", ImmutableMap.of(), true),
+                Arguments.of("json", ImmutableMap.of("read_json_by_line", 
"true"), true),
+                Arguments.of("json", ImmutableMap.of("read_json_by_line", 
"false"), false),
+                Arguments.of("json", ImmutableMap.of("strip_outer_array", 
"true"), false),
+                Arguments.of("json", ImmutableMap.of("strip_outer_array", 
"false"), false),
+                Arguments.of("json", ImmutableMap.of("read_json_by_line", 
"true", "strip_outer_array", "true"), true));
+    }
+
+    @ParameterizedTest
+    @MethodSource("formatCases")
+    public void testSplitsPreserveFormatState(String format, Map<String, 
String> options, boolean splittable)
+            throws Exception {
+        FileFormatProperties properties = 
FileFormatProperties.createFileFormatProperties(format);
+        properties.analyzeFileFormatProperties(new HashMap<>(options), true);
+        TFileAttributes attributes = properties.toTFileAttributes();
+        for (TFileType storage : ImmutableList.of(TFileType.FILE_S3, 
TFileType.FILE_HDFS)) {
+            for (String suffix : ImmutableList.of("", ".gz")) {
+                for (TFileCompressType compression : 
ImmutableList.of(TFileCompressType.PLAIN, TFileCompressType.UNKNOWN)) {
+                    SessionVariable sv = new SessionVariable();
+                    sv.setFileSplitSize(1024);
+                    String path = (storage == TFileType.FILE_S3 ? 
"s3://example-bucket/" : "hdfs://example.test/")
+                            + "input" + suffix;
+                    TVFScanNode node = fileScanNode(sv, storage, 
properties.getFileFormatType(),
+                            splittableFile(path, 4096), compression, 
attributes);
+                    List<Split> splits = node.getSplits(1);
+                    boolean compressed = compression == 
TFileCompressType.UNKNOWN && suffix.equals(".gz");
+                    int expected = splittable && !compressed ? 4 : 1;
+                    Assertions.assertEquals(expected, splits.size(), format + 
options + suffix + compression);
+                    Assertions.assertEquals(0, splits.get(0).getStart());
+                    Assertions.assertEquals(4096, 
splits.stream().mapToLong(Split::getLength).sum());
+                    if (expected == 1) {
+                        Assertions.assertEquals(4096, 
splits.get(0).getLength());
+                    }
+                }
+            }
+        }
+    }
+
+    private static Stream<Arguments> statefulFormatCases() {
+        return formatCases().filter(args -> !(Boolean) args.get()[2]);
+    }
+
+    @ParameterizedTest
+    @MethodSource("statefulFormatCases")
+    public void testCountPushdownCannotEnableStatefulSplits(String format,
+            Map<String, String> options, boolean ignored) throws Exception {
+        FileFormatProperties properties = 
FileFormatProperties.createFileFormatProperties(format);
+        properties.analyzeFileFormatProperties(new HashMap<>(options), true);
+        for (boolean countStar : ImmutableList.of(false, true)) {
+            SessionVariable sv = new SessionVariable();
+            sv.setFileSplitSize(1024);
+            sv.parallelExecInstanceNum = 1;
+            TVFScanNode node = fileScanNode(sv, TFileType.FILE_S3, 
properties.getFileFormatType(),
+                    splittableFile("s3://example-bucket/input.gz", 4096), 
TFileCompressType.PLAIN,
+                    properties.toTFileAttributes());
+            node.setPushDownAggNoGrouping(TPushAggOp.COUNT);
+            node.setPushDownCountSlotIds(countStar ? Collections.emptyList() : 
ImmutableList.of(new SlotId(7)));
+            // Two backends make the independent COUNT(*) policy permit 
splitting this one file.
+            Assertions.assertEquals(1, node.getSplits(2).size(), format + 
options);
+        }
+    }
+
+    @Test
+    public void testStreamDoesNotInspectFileAttributesOrSplitFiles() throws 
Exception {
+        TVFScanNode node = fileScanNode(new SessionVariable(), 
TFileType.FILE_STREAM,
+                TFileFormatType.FORMAT_JSON, splittableFile("stream", 4096), 
TFileCompressType.PLAIN, null);
+        Assertions.assertTrue(node.getSplits(1).isEmpty());
+    }
+
+    private static Stream<Arguments> compressionCases() {
+        Stream.Builder<Arguments> cases = Stream.builder();
+        for (TFileType storage : ImmutableList.of(TFileType.FILE_S3, 
TFileType.FILE_HDFS)) {
+            for (TFileFormatType format : 
ImmutableList.of(TFileFormatType.FORMAT_CSV_PLAIN,
+                    TFileFormatType.FORMAT_JSON, TFileFormatType.FORMAT_TEXT)) 
{
+                for (String suffix : ImmutableList.of("", ".gz")) {
+                    for (TFileCompressType compression : 
ImmutableList.of(TFileCompressType.UNKNOWN,
+                            TFileCompressType.PLAIN, TFileCompressType.GZ)) {
+                        boolean gzip = compression == TFileCompressType.GZ
+                                || (compression == TFileCompressType.UNKNOWN 
&& suffix.equals(".gz"));
+                        cases.add(Arguments.of(storage, format, suffix, 
compression, gzip));
+                    }
+                }
+            }
+        }
+        return cases.build();
+    }
+
+    @ParameterizedTest
+    @MethodSource("compressionCases")
+    public void testSplitsUseEffectiveCompression(TFileType storage, 
TFileFormatType format,
+            String suffix, TFileCompressType compression, boolean gzip) throws 
Exception {
+        SessionVariable sv = new SessionVariable();
+        sv.setFileSplitSize(1024);
+        String path = (storage == TFileType.FILE_S3 ? "s3://example-bucket/" : 
"hdfs://example.test/")
+                + "input" + suffix;
+        TVFScanNode node = fileScanNode(sv, storage, format, 
splittableFile(path, 4096), compression);
+        List<Split> splits = node.getSplits(1);
+        Assertions.assertEquals(gzip ? 1 : 4, splits.size());
+        long nextOffset = 0;
+        for (Split split : splits) {
+            Assertions.assertEquals(nextOffset, split.getStart());
+            Assertions.assertEquals(gzip ? 4096 : 1024, split.getLength());
+            Assertions.assertEquals(path, ((FileSplit) split).getPathString());
+            Assertions.assertEquals(gzip ? TFileCompressType.GZ : 
TFileCompressType.PLAIN,
+                    node.getFileCompressType((FileSplit) split));
+            nextOffset += split.getLength();
+        }
+        Assertions.assertEquals(4096, nextOffset);
+    }
+
+    @Test
+    public void testExplicitPlainPreservesUnsplittableAndCountStarGates() 
throws Exception {
+        for (boolean countStar : ImmutableList.of(false, true)) {
+            SessionVariable sv = new SessionVariable();
+            sv.setFileSplitSize(1024);
+            sv.parallelExecInstanceNum = 1;
+            TBrokerFileStatus file = 
splittableFile("s3://example-bucket/input.gz", 4096);
+            file.setIsSplitable(countStar);
+            TVFScanNode node = fileScanNode(sv, TFileType.FILE_S3, 
TFileFormatType.FORMAT_CSV_PLAIN,
+                    file, TFileCompressType.PLAIN);
+            if (countStar) {
+                node.setPushDownAggNoGrouping(TPushAggOp.COUNT);
+                node.setPushDownCountSlotIds(Collections.emptyList());
+            }
+            List<Split> splits = node.getSplits(1);
+            Assertions.assertEquals(1, splits.size());
+            Assertions.assertEquals(0, splits.get(0).getStart());
+            Assertions.assertEquals(4096, splits.get(0).getLength());
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(value = TFileFormatType.class, names = {"FORMAT_PARQUET", 
"FORMAT_ORC"})
+    public void 
testColumnarFilesWithoutEnvelopeCodecKeepCoarseSplits(TFileFormatType format) 
throws Exception {
+        for (TFileType storage : ImmutableList.of(TFileType.FILE_S3, 
TFileType.FILE_HDFS)) {
+            SessionVariable sv = new SessionVariable();
+            sv.setFileSplitSize(16 * MB);
+            String path = storage == TFileType.FILE_S3
+                    ? "s3://example-bucket/input" : 
"hdfs://example.test/input";
+            TVFScanNode node = fileScanNode(sv, storage, format, 
splittableFile(path, 1536 * MB), null);
+            List<Split> splits = node.getSplits(1);
+            Assertions.assertEquals(3, splits.size());
+            for (int i = 0; i < splits.size(); ++i) {
+                Assertions.assertEquals(i * 512 * MB, 
splits.get(i).getStart());
+                Assertions.assertEquals(512 * MB, splits.get(i).getLength());
+            }
+        }
+    }
+
+
+
+
+
+    private static TVFScanNode fileScanNode(SessionVariable sv, TFileType type,
+            TFileFormatType format, TBrokerFileStatus file) throws Exception {
+        return fileScanNode(sv, type, format, file, null);
+    }
+
+    private static TVFScanNode fileScanNode(SessionVariable sv, TFileType type,
+            TFileFormatType format, TBrokerFileStatus file, TFileCompressType 
compression) throws Exception {
+        TFileAttributes defaults = new TFileAttributes();
+        defaults.setReadJsonByLine(true);
+        defaults.setTextParams(new TFileTextScanRangeParams());
+        return fileScanNode(sv, type, format, file, compression, defaults);
+    }
+
+    private static TVFScanNode fileScanNode(SessionVariable sv, TFileType type,
+            TFileFormatType format, TBrokerFileStatus file, TFileCompressType 
compression,
+            TFileAttributes attributes) throws Exception {
+        TupleDescriptor desc = new TupleDescriptor(new TupleId(0));
+        FunctionGenTable table = Mockito.mock(FunctionGenTable.class);
+        ExternalFileTableValuedFunction tvf = 
Mockito.mock(ExternalFileTableValuedFunction.class);
+        Mockito.when(table.getTvf()).thenReturn(tvf);
+        Mockito.when(tvf.getTFileType()).thenReturn(type);
+        Mockito.when(tvf.getTFileFormatType()).thenReturn(format);
+        Mockito.when(tvf.getTFileCompressType()).thenReturn(compression);
+        Mockito.when(tvf.getFileAttributes()).thenReturn(attributes);
+        Mockito.when(tvf.getFileStatuses()).thenReturn(ImmutableList.of(file));
+        desc.setTable(table);
+        TVFScanNode node = new TVFScanNode(new PlanNodeId(0), desc, false, sv, 
ScanContext.EMPTY);
+        setFileSplitter(node, new FileSplitter(32 * MB, 32 * MB, 0));
+        return node;
+    }
+
+    private static TBrokerFileStatus splittableFile(String path, long size) {
+        TBrokerFileStatus status = new TBrokerFileStatus();
+        status.setPath(path);
+        status.setSize(size);
+        status.setModificationTime(0);
+        status.setIsSplitable(true);
+        return status;
+    }
+
+    private static void setFileSplitter(TVFScanNode node, FileSplitter 
splitter) throws Exception {
+        java.lang.reflect.Field field = 
FileQueryScanNode.class.getDeclaredField("fileSplitter");
+        field.setAccessible(true);
+        field.set(node, splitter);
+    }
+}
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/data/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.out
 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.out
new file mode 100644
index 00000000000..ee579fecce2
--- /dev/null
+++ 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.out
@@ -0,0 +1,21 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !default_rows --
+1
+2
+
+-- !default_unregistered --
+
+-- !kept_rows --
+3
+4
+
+-- !kept_unregistered --
+
+-- !namespace_unregistered --
+
+-- !enabled_rows --
+5
+
+-- !purged_namespace_unregistered --
+
+-- !enabled_unregistered --
diff --git 
a/regression-test/data/external_table_p0/tvf/test_tvf_explicit_compression_splits.out
 
b/regression-test/data/external_table_p0/tvf/test_tvf_explicit_compression_splits.out
new file mode 100644
index 00000000000..ff89a7134fb
--- /dev/null
+++ 
b/regression-test/data/external_table_p0/tvf/test_tvf_explicit_compression_splits.out
@@ -0,0 +1,82 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !count --
+4096   4096    8386560
+
+-- !count --
+4096   4096    8386560
+
+-- !count --
+4096   4096    8386560
+
+-- !quoted_csv_no_suffix --
+2      3
+
+-- !quoted_csv_gzip_suffix --
+2      3
+
+-- !json_array_explicit_no_suffix --
+128    8128
+
+-- !json_array_explicit_gzip_suffix --
+128    8128
+
+-- !json_array_implicit_no_suffix --
+128    8128
+
+-- !json_array_implicit_gzip_suffix --
+128    8128
+
+-- !json_document_explicit_no_suffix --
+1      7
+
+-- !json_document_explicit_gzip_suffix --
+1      7
+
+-- !json_document_implicit_no_suffix --
+1      7
+
+-- !json_document_implicit_gzip_suffix --
+1      7
+
+-- !json_line_arrays_no_suffix --
+128    8128
+
+-- !json_line_arrays_gzip_suffix --
+128    8128
+
+-- !csv_prefix_no_suffix --
+1      7
+
+-- !csv_prefix_gzip_suffix --
+1      7
+
+-- !text_prefix_no_suffix --
+1      7
+
+-- !text_prefix_gzip_suffix --
+1      7
+
+-- !csv_type_header_no_suffix --
+1      7
+
+-- !csv_type_header_gzip_suffix --
+1      7
+
+-- !csv_name_header_no_suffix --
+1      7
+
+-- !csv_name_header_gzip_suffix --
+1      7
+
+-- !csv_single_prefix_no_suffix --
+1      7
+
+-- !csv_single_prefix_gzip_suffix --
+1      7
+
+-- !text_single_prefix_no_suffix --
+1      7
+
+-- !text_single_prefix_gzip_suffix --
+1      7
+
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)}"])
+        }
+    }
+}
diff --git 
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.groovy
 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.groovy
new file mode 100644
index 00000000000..8b98f8258d8
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.groovy
@@ -0,0 +1,195 @@
+// 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 com.amazonaws.services.s3.model.DeleteObjectsRequest
+import com.amazonaws.services.s3.model.ListObjectsV2Request
+
+suite("test_iceberg_rest_drop_purge_option", 
"p0,external,iceberg,external_docker,external_docker_iceberg,nonConcurrent") {
+    if 
(!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest")))
 {
+        logger.info("disable iceberg test")
+        return
+    }
+    String host = 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 endpoint = "http://${host}:${minioPort}";
+
+    sql "drop catalog if exists iceberg_rest_drop_purge_option"
+    sql """create catalog iceberg_rest_drop_purge_option properties (
+        "type" = "iceberg",
+        "iceberg.catalog.type" = "rest",
+        "uri" = "http://${host}:${restPort}";,
+        "s3.endpoint" = "${endpoint}",
+        "s3.access_key" = "admin",
+        "s3.secret_key" = "password",
+        "s3.region" = "us-east-1",
+        "use_path_style" = "true"
+    )"""
+    sql "switch iceberg_rest_drop_purge_option"
+    sql "drop database if exists rest_drop_purge_db force"
+    sql "drop database if exists rest_drop_purge_cascade_db force"
+    sql "drop database if exists rest_drop_purge_enabled_cascade_db force"
+    sql "create database rest_drop_purge_db"
+    sql "use rest_drop_purge_db"
+
+    def client = AmazonS3ClientBuilder.standard()
+            .withEndpointConfiguration(new EndpointConfiguration(endpoint, 
"us-east-1"))
+            .withPathStyleAccessEnabled(true)
+            .withCredentials(new AWSStaticCredentialsProvider(new 
BasicAWSCredentials("admin", "password")))
+            .build()
+    try {
+        List<String> cleanupPrefixes = [
+                "wh/rest_drop_purge_db/",
+                "wh/rest_drop_purge_cascade_db/",
+                "wh/rest_drop_purge_enabled_cascade_db/"
+        ]
+        // Three stale markers and two-entry pages exercise multi-batch 
cleanup on every run.
+        cleanupPrefixes.each { String prefix ->
+            (0..<3).each { int index ->
+                client.putObject("warehouse", 
"${prefix}cleanup-stale-${index}".toString(), "stale")
+            }
+        }
+        String neighborKey = "wh/rest_drop_purge_db_neighbor/cleanup-sentinel"
+        client.putObject("warehouse", neighborKey, "keep")
+        // SQL cannot discover files after unregister-only drops. Reclaim only 
this suite's previous runs,
+        // leaving current-run retained files available for debugging until 
the next invocation.
+        cleanupPrefixes.each { String prefix ->
+            while (true) {
+                def objects = client.listObjectsV2(new ListObjectsV2Request()
+                        
.withBucketName("warehouse").withPrefix(prefix).withMaxKeys(2)).objectSummaries
+                if (objects.isEmpty()) {
+                    break
+                }
+                // Re-list the first page after deletion instead of reusing an 
opaque continuation token.
+                client.deleteObjects(new 
DeleteObjectsRequest("warehouse").withKeys(objects.collect {
+                    new DeleteObjectsRequest.KeyVersion(it.key)
+                }))
+            }
+        }
+        cleanupPrefixes.each { String prefix ->
+            assertTrue(client.listObjectsV2("warehouse", 
prefix).objectSummaries.isEmpty(),
+                    "Previous-run objects remain under ${prefix}")
+        }
+        assertTrue(client.doesObjectExist("warehouse", neighborKey))
+        client.deleteObject("warehouse", neighborKey)
+
+        def captureObjects = { String table ->
+            def data = sql "select file_path from `${table}\$files` where 
content = 0"
+            def metadata = sql "select file from 
`${table}\$metadata_log_entries`"
+            assertTrue(!data.isEmpty(), "The table must have data files")
+            assertTrue(!metadata.isEmpty(), "The table must have metadata 
files")
+            def manifests = sql "select path from `${table}\$manifests`"
+            def snapshots = sql "select manifest_list from 
`${table}\$snapshots`"
+            assertTrue(!manifests.isEmpty(), "The table must have manifest 
files")
+            assertTrue(!snapshots.isEmpty(), "The table must have manifest 
lists")
+            def objects = (data + metadata + manifests + snapshots).collect { 
it[0].toString() }.unique()
+            objects.each { String object ->
+                URI uri = new URI(object)
+                assertTrue(uri.host == "warehouse" && cleanupPrefixes.any { 
uri.path.startsWith("/${it}") },
+                        "Table object is outside this suite's cleanup 
prefixes: ${object}")
+            }
+            return objects
+        }
+        def checkObjects = { List<String> objects, boolean present ->
+            objects.each { String object ->
+                URI uri = new URI(object)
+                assertTrue(uri.scheme in ["s3", "s3a", "s3n"], "Unexpected 
object URI: ${object}")
+                assertTrue(client.doesObjectExist(uri.host, 
uri.path.substring(1)) == present,
+                        "Unexpected object presence: ${object}, expected 
${present}")
+            }
+        }
+
+        sql "create table purge_default (id int)"
+        sql "insert into purge_default values (1), (2)"
+        qt_default_rows "select id from purge_default order by id"
+        def defaultObjects = captureObjects("purge_default")
+        checkObjects(defaultObjects, true)
+        sql "drop table purge_default"
+        checkObjects(defaultObjects, false)
+        qt_default_unregistered "show tables like 'purge_default'"
+
+        sql """alter catalog iceberg_rest_drop_purge_option set properties (
+            "iceberg.rest.drop-with-purge-enabled" = "false")"""
+        sql "use iceberg_rest_drop_purge_option.rest_drop_purge_db"
+        sql "create table keep_table (id int)"
+        sql "insert into keep_table values (3), (4)"
+        qt_kept_rows "select id from keep_table order by id"
+        def keptObjects = captureObjects("keep_table")
+        checkObjects(keptObjects, true)
+        sql "drop table keep_table"
+        checkObjects(keptObjects, true)
+        qt_kept_unregistered "show tables like 'keep_table'"
+
+        sql "create database rest_drop_purge_cascade_db"
+        sql "use rest_drop_purge_cascade_db"
+        sql "create table keep_first (id int)"
+        sql "create table keep_second (id int)"
+        sql "insert into keep_first values (10)"
+        sql "insert into keep_second values (20)"
+        def firstObjects = captureObjects("keep_first")
+        def secondObjects = captureObjects("keep_second")
+        checkObjects(firstObjects, true)
+        checkObjects(secondObjects, true)
+        sql "use rest_drop_purge_db"
+        sql "drop database rest_drop_purge_cascade_db force"
+        checkObjects(firstObjects, true)
+        checkObjects(secondObjects, true)
+        qt_namespace_unregistered "show databases like 
'rest_drop_purge_cascade_db'"
+
+        sql """alter catalog iceberg_rest_drop_purge_option set properties (
+            "iceberg.rest.drop-with-purge-enabled" = "true")"""
+        test {
+            sql """alter catalog iceberg_rest_drop_purge_option set properties 
(
+                "iceberg.rest.drop-with-purge-enabled" = "invalid")"""
+            exception "iceberg.rest.drop-with-purge-enabled must be true or 
false"
+        }
+        sql "use iceberg_rest_drop_purge_option.rest_drop_purge_db"
+        sql "create table purge_enabled (id int)"
+        sql "insert into purge_enabled values (5)"
+        qt_enabled_rows "select id from purge_enabled order by id"
+        def enabledObjects = captureObjects("purge_enabled")
+        checkObjects(enabledObjects, true)
+        sql "drop table purge_enabled"
+        checkObjects(enabledObjects, false)
+        sql "create database rest_drop_purge_enabled_cascade_db"
+        sql "use rest_drop_purge_enabled_cascade_db"
+        sql "create table purge_first (id int)"
+        sql "create table purge_second (id int)"
+        sql "insert into purge_first values (30)"
+        sql "insert into purge_second values (40)"
+        def purgedFirstObjects = captureObjects("purge_first")
+        def purgedSecondObjects = captureObjects("purge_second")
+        checkObjects(purgedFirstObjects, true)
+        checkObjects(purgedSecondObjects, true)
+        sql "use rest_drop_purge_db"
+        sql "drop database rest_drop_purge_enabled_cascade_db force"
+        checkObjects(purgedFirstObjects, false)
+        checkObjects(purgedSecondObjects, false)
+        qt_purged_namespace_unregistered "show databases like 
'rest_drop_purge_enabled_cascade_db'"
+        // Changing the option affects later drops, not objects deliberately 
retained by earlier ones.
+        checkObjects(keptObjects, true)
+        checkObjects(firstObjects, true)
+        checkObjects(secondObjects, true)
+        qt_enabled_unregistered "show tables like 'purge_enabled'"
+    } finally {
+        client.shutdown()
+    }
+}
diff --git 
a/regression-test/suites/external_table_p0/tvf/test_tvf_explicit_compression_splits.groovy
 
b/regression-test/suites/external_table_p0/tvf/test_tvf_explicit_compression_splits.groovy
new file mode 100644
index 00000000000..f183ecc812c
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/tvf/test_tvf_explicit_compression_splits.groovy
@@ -0,0 +1,267 @@
+// 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.services.s3.model.ObjectMetadata
+import com.azure.storage.blob.BlobClientBuilder
+import com.azure.storage.common.StorageSharedKeyCredential
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.FileSystem
+import org.apache.hadoop.fs.Path
+
+import java.nio.charset.StandardCharsets
+import java.util.zip.GZIPOutputStream
+
+suite("test_tvf_explicit_compression_splits", "p0,external") {
+    String provider = getS3Provider()
+    String endpoint = getS3Endpoint()
+    boolean azure = provider.equalsIgnoreCase("AZURE")
+    if (azure) {
+        endpoint = endpoint == "azure-endpoint" ? 
"https://${getS3AK()}.blob.core.windows.net" : endpoint
+        if (!endpoint.contains("://")) {
+            endpoint = "https://${endpoint}";
+        }
+    }
+    String bucket = context.config.otherConfigs.get("s3BucketName")
+    String prefix = "tvf_compression_split/${UUID.randomUUID()}/"
+    def s3Client = azure ? null : getS3Client()
+    def blob = { String key ->
+        new 
BlobClientBuilder().endpoint(endpoint).containerName(bucket).blobName(key)
+                .credential(new StorageSharedKeyCredential(getS3AK(), 
getS3SK())).buildClient()
+    }
+    List<String> keys = []
+    def hdfs = null
+    boolean hdfsDirectoryCreated = false
+    String hdfsUri = null
+    String hdfsUser = context.config.otherConfigs.get("hdfsUser") ?: "hadoop"
+    Path hdfsDirectory = new Path("/tmp/${prefix}")
+    Map<String, String> original = [:]
+    for (String variable : ["file_split_size", "enable_sql_cache", 
"enable_query_cache", "enable_file_scanner_v2"]) {
+        original[variable] = sql("SHOW VARIABLES LIKE 
'${variable}'")[0][1].toString()
+    }
+    try {
+        // The external lane enables Hive's HDFS, while its standalone 
enableHdfs flag is false.
+        if 
(context.config.otherConfigs.get("enableHiveTest")?.toString()?.equalsIgnoreCase("true"))
 {
+            hdfsUri = 
"hdfs://${context.config.otherConfigs.get('externalEnvIp')}:" +
+                    context.config.otherConfigs.get("hive2HdfsPort")
+            Configuration configuration = new Configuration()
+            configuration.set("fs.defaultFS", hdfsUri)
+            configuration.set("fs.hdfs.impl", 
"org.apache.hadoop.hdfs.DistributedFileSystem")
+            hdfs = FileSystem.newInstance(new URI(hdfsUri), configuration, 
hdfsUser)
+            assertTrue(hdfs.mkdirs(hdfsDirectory))
+            hdfsDirectoryCreated = true
+        }
+        sql "SET file_split_size = 1024"
+        sql "SET enable_sql_cache = false"
+        sql "SET enable_query_cache = false"
+        String expected = """SELECT number AS id, concat('payload_', 
CAST(number AS STRING), '_汉字') AS payload
+                FROM numbers("number"="4096")"""
+        def writeFixture = { String key, byte[] bytes, String hdfsName ->
+            keys.add(key)
+            if (azure) {
+                new ByteArrayInputStream(bytes).withCloseable {
+                    blob(key).upload(it, (long) bytes.length, true)
+                }
+            } else {
+                ObjectMetadata metadata = new ObjectMetadata()
+                metadata.setContentLength(bytes.length)
+                new ByteArrayInputStream(bytes).withCloseable { 
s3Client.putObject(bucket, key, it, metadata) }
+            }
+            if (hdfs != null) {
+                hdfs.create(new Path(hdfsDirectory, hdfsName), 
true).withCloseable { it.write(bytes) }
+            }
+        }
+        def fixtureSources = { String key, String format, String options, 
String hdfsName ->
+            String source = """S3("uri"="s3://${bucket}/${key}", 
"format"="${format}", ${options},
+                    "provider"="${provider}", "s3.endpoint"="${endpoint}", 
"s3.region"="${getS3Region()}",
+                    "s3.access_key"="${getS3AK()}", 
"s3.secret_key"="${getS3SK()}")"""
+            def sources = [s3: source]
+            if (hdfs != null) {
+                sources.hdfs = 
"""HDFS("uri"="${hdfsUri}${hdfsDirectory}/${hdfsName}",
+                        "hadoop.username"="${hdfsUser}", "format"="${format}", 
${options})"""
+            }
+            return sources
+        }
+        for (String format : ["csv", "json", "hive_text"]) {
+            StringBuilder contents = new StringBuilder()
+            for (int i = 0; i < 4096; ++i) {
+                String payload = "payload_${i}_汉字"
+                contents.append(format == "json" ? 
"{\"id\":${i},\"payload\":\"${payload}\"}\n"
+                        : "${i},${payload}\n")
+            }
+            byte[] plain = contents.toString().getBytes(StandardCharsets.UTF_8)
+            ByteArrayOutputStream output = new ByteArrayOutputStream()
+            new GZIPOutputStream(output).withCloseable { it.write(plain) }
+            byte[] gzip = output.toByteArray()
+            // A small gzip fixture can accidentally stay below the split 
threshold and miss the defect.
+            assertTrue(gzip.length > 1024)
+            def variants = [
+                    [name: "gzip_no_suffix", bytes: gzip, suffix: "", 
compression: "GZ"],
+                    [name: "gzip_inferred", bytes: gzip, suffix: ".gz", 
compression: null],
+                    [name: "plain_gzip_suffix", bytes: plain, suffix: ".gz", 
compression: "PLAIN"],
+                    [name: "plain_inferred", bytes: plain, suffix: "", 
compression: null]]
+            String canonical = null
+            for (def variant : variants) {
+                String key = 
"${prefix}${format}/${variant.name}${variant.suffix}"
+                byte[] bytes = variant.bytes
+                String hdfsName = "${format}_${variant.name}${variant.suffix}"
+                writeFixture(key, bytes, hdfsName)
+                String options = format == "json" ? 
'"read_json_by_line"="true"'
+                        : '"column_separator"=",", 
"csv_schema"="id:int;payload:string"'
+                if (variant.compression != null) {
+                    options += ", \"compress_type\"=\"${variant.compression}\""
+                }
+                def sources = fixtureSources(key, format, options, hdfsName)
+                sources.each { storage, table ->
+                    // Project every row, without LIMIT: COUNT(*) alone may 
suppress file splitting.
+                    quickTest("${storage}_${format}_${variant.name}",
+                            "SELECT CAST(id AS BIGINT), payload FROM ${table} 
ORDER BY 1",
+                            "SELECT id, payload FROM (${expected}) expected 
ORDER BY 1")
+                    quickTest("${storage}_${format}_${variant.name}_counts",
+                            "SELECT count(*), count(id), sum(CAST(id AS 
BIGINT)) FROM ${table}",
+                            "SELECT count(*), count(id), sum(id) FROM 
(${expected}) expected")
+                }
+                if (variant.name == "gzip_inferred") {
+                    canonical = sources.s3
+                }
+            }
+            qt_count "SELECT count(*), count(id), sum(CAST(id AS BIGINT)) FROM 
${canonical}"
+        }
+
+        String csvOptions = '"column_separator"=",", 
"csv_schema"="id:int;payload:string"'
+        String stringCsvOptions = '"column_separator"=",", 
"csv_schema"="id:string;payload:string"'
+        String quotedPayload = "a" * 1100 + "\n1,phantom\n2,tail"
+        String skippedPrefix = (0..<20).collect { "${1000 + it}," + "p" * 58 + 
"\n" }.join("")
+        String longHeader = "n" * 1300 + ",payload\n"
+        String singlePrefix = "1000," + "p" * 1400 + "\n"
+        def documentRows = (0..<128).collect { [id: it, payload: 
"doc_${it}_界".toString()] }
+        String document = groovy.json.JsonOutput.toJson(documentRows)
+        String singleDocument = groovy.json.JsonOutput.toJson([id: 7, payload: 
"d" * 2048])
+        String lineArrays = documentRows.collect { 
groovy.json.JsonOutput.toJson([it]) + "\n" }.join("")
+        String documentExpected = """SELECT number AS id, 
concat('doc_',CAST(number AS STRING),'_界') AS payload
+                FROM numbers("number"="128")"""
+        def modes = [
+                [name: "quoted_csv", format: "csv", contents: 
"0,\"${quotedPayload}\"\n3,real\n",
+                 options: csvOptions + ', "enclose"=\'"\'',
+                 expected: """SELECT 0 AS id, 
concat(repeat('a',1100),char(10),'1,phantom',char(10),'2,tail') AS payload
+                         UNION ALL SELECT 3,'real'"""],
+                [name: "json_array_explicit", format: "json", contents: 
document,
+                 options: '"read_json_by_line"="false", 
"strip_outer_array"="true"', expected: documentExpected],
+                [name: "json_array_implicit", format: "json", contents: 
document,
+                 options: '"strip_outer_array"="true"', expected: 
documentExpected],
+                [name: "json_document_explicit", format: "json", contents: 
singleDocument,
+                 options: '"read_json_by_line"="false"', expected: "SELECT 7 
AS id,repeat('d',2048) AS payload"],
+                [name: "json_document_implicit", format: "json", contents: 
singleDocument,
+                 options: '"strip_outer_array"="false"', expected: "SELECT 7 
AS id,repeat('d',2048) AS payload"],
+                [name: "json_line_arrays", format: "json", contents: 
lineArrays,
+                 options: '"read_json_by_line"="true", 
"strip_outer_array"="true"', expected: documentExpected],
+                [name: "csv_prefix", format: "csv", contents: skippedPrefix + 
"7,real\n",
+                 options: csvOptions + ', "skip_lines"="20"', expected: 
"SELECT 7 AS id,'real' AS payload"],
+                [name: "text_prefix", format: "hive_text", contents: 
skippedPrefix + "7,real\n",
+                 options: csvOptions + ', "skip_lines"="20"', expected: 
"SELECT 7 AS id,'real' AS payload"],
+                [name: "csv_type_header", format: "csv_with_names_and_types",
+                 contents: longHeader + "string,string\n7,real\n", options: 
stringCsvOptions,
+                 expected: "SELECT 7 AS id,'real' AS payload"],
+                [name: "csv_name_header", format: "csv_with_names", contents: 
longHeader + "7,real\n",
+                 options: stringCsvOptions + ', "skip_lines"="20"', expected: 
"SELECT 7 AS id,'real' AS payload"],
+                [name: "csv_single_prefix", format: "csv", contents: 
singlePrefix + "7,real\n",
+                 options: csvOptions + ', "skip_lines"="1"', expected: "SELECT 
7 AS id,'real' AS payload"],
+                [name: "text_single_prefix", format: "hive_text", contents: 
singlePrefix + "7,real\n",
+                 options: csvOptions + ', "skip_lines"="1"', expected: "SELECT 
7 AS id,'real' AS payload"]]
+        for (def mode : modes) {
+            for (String suffix : ["", ".gz"]) {
+                String tag = "${mode.name}_${suffix.isEmpty() ? 'no_suffix' : 
'gzip_suffix'}"
+                String key = "${prefix}modes/${mode.name}${suffix}"
+                byte[] bytes = mode.contents.getBytes(StandardCharsets.UTF_8)
+                assertTrue(bytes.length > 1126, "Fixture must produce multiple 
1-KiB ranges before the fix")
+                writeFixture(key, bytes, tag)
+                def sources = fixtureSources(key, mode.format, mode.options + 
', "compress_type"="PLAIN"', tag)
+                sources.each { storage, table ->
+                    // Full rows detect phantom quoted/preamble records; 
COUNT(*) may suppress splitting.
+                    quickTest("${storage}_${tag}",
+                            "SELECT CAST(id AS BIGINT),payload FROM ${table} 
ORDER BY 1",
+                            "SELECT id,payload FROM (${mode.expected}) 
expected ORDER BY 1")
+                }
+                "qt_${tag}" "SELECT count(*),sum(CAST(id AS BIGINT)) FROM 
${sources.s3}"
+            }
+        }
+        // Restarting inside a delimiter chain must preserve empty records and 
leading delimiter bytes.
+        def delimiterBoundaries = [
+                [name: "hive_overlap_pipes", delimiter: "||",
+                 contents: "a" * 1021 + "|||||" + "b" * 200 + "||",
+                 expected: { boolean scannerV2 ->
+                     // The legacy TVF reader uses an empty null marker; v2 
defaults to the Hive null marker.
+                     String emptyField = scannerV2 ? "''" : "CAST(NULL AS 
STRING)"
+                     "SELECT repeat('a',1021) AS payload UNION ALL SELECT 
${emptyField} " +
+                             "UNION ALL SELECT concat('|',repeat('b',200))"
+                 }],
+                [name: "hive_overlap_prefix_suffix", delimiter: "aba",
+                 contents: "x" * 1020 + "ababa" + "y" * 200 + "aba",
+                 expected: { boolean ignored ->
+                     "SELECT repeat('x',1020) AS payload " +
+                             "UNION ALL SELECT concat('ba',repeat('y',200))"
+                 }]]
+        for (def boundary : delimiterBoundaries) {
+            for (String suffix : ["", ".gz"]) {
+                String tag = "${boundary.name}_${suffix.isEmpty() ? 
'no_suffix' : 'gzip_suffix'}"
+                String key = "${prefix}delimiters/${tag}${suffix}"
+                byte[] bytes = 
boundary.contents.getBytes(StandardCharsets.UTF_8)
+                assertEquals(1228, bytes.length)
+                String hdfsName = tag + suffix
+                writeFixture(key, bytes, hdfsName)
+                String options = '"column_separator"=",", 
"csv_schema"="payload:string", ' +
+                        '"compress_type"="PLAIN", "line_delimiter"="' + 
boundary.delimiter + '"'
+                def sources = fixtureSources(key, "hive_text", options, 
hdfsName)
+                for (boolean scannerV2 : [false, true]) {
+                    sql "SET enable_file_scanner_v2 = ${scannerV2}"
+                    String expectedRowsSql = boundary.expected(scannerV2)
+                    sources.each { storage, table ->
+                        quickTest("${storage}_${tag}_${scannerV2 ? 'v2' : 
'v1'}",
+                                "SELECT payload FROM ${table} ORDER BY 1",
+                                "SELECT payload FROM (${expectedRowsSql}) 
expected ORDER BY 1")
+                    }
+                }
+            }
+        }
+    } finally {
+        try {
+            original.each { variable, value -> sql "SET ${variable} = 
${value}" }
+        } finally {
+            try {
+                keys.each { key ->
+                    if (azure) {
+                        blob(key).deleteIfExists()
+                    } else {
+                        s3Client.deleteObject(bucket, key)
+                    }
+                }
+            } finally {
+                if (s3Client != null) {
+                    s3Client.shutdown()
+                }
+                if (hdfs != null) {
+                    try {
+                        if (hdfsDirectoryCreated) {
+                            assertTrue(hdfs.delete(hdfsDirectory, true))
+                        }
+                    } finally {
+                        hdfs.close()
+                    }
+                }
+            }
+        }
+    }
+}


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

Reply via email to