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

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


The following commit(s) were added to refs/heads/master by this push:
     new 3dcb76856be [fix](function) Preserve numeric bounds for function 
arguments (#70844)
3dcb76856be is described below

commit 3dcb76856be63e3a10c422177a672b31581ce5b4
Author: TengJianPing <[email protected]>
AuthorDate: Mon Nov 23 15:46:17 2026 +0800

    [fix](function) Preserve numeric bounds for function arguments (#70844)
    
    ### Background
    
    FE checks and folds constant function arguments. BE evaluates row
    arguments and resolves STRUCT ordinals for execution.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #64027 (retained STRUCT ordinal narrowing)
    PR Type: Bugfix
    
    Problem Summary:
    
    Some function arguments lose high bits, change sign, or overflow before
    validation. For example, element_at(struct(7), 4294967297) returns 7
    instead of an error. This change extracts six fixes and their tests.
    Valid boundary inputs return correct results; invalid arguments report
    errors.
    
    ### Details
    
    - **Change map:** 173 production lines: STRUCT lookup and pruning 68,
    substring counts 6, array lengths 14, bitmap elements 54, funnel windows
    16, ngram sizes 7, and the shared range helper 8. Tests change 390
    lines; generated results add 23. No documentation or protocol changes.
    - **Frequency:** Always for the reported boundary inputs. BE substring
    behavior can depend on compiler handling of signed overflow.
    - **Root cause:** STRUCT and ngram narrow integers before checks.
    SUBSTRING_INDEX negates INT_MIN. ARRAY_SLICE adds length before
    clamping. Bitmap functions convert negative elements to unsigned values.
    An empty funnel event list bypasses window validation.
    - **Why existing tests missed it:** StructOrdinal coverage was absent.
    Existing STRUCT, StringArithmetic, bitmap and funnel UTs use ordinary
    values. The closest SQL suites omit wide aliases and signed minima;
    test_ngram_search_gram_num covers ordinary negative sizes but not values
    beyond INT or BIGINT.
    - **Fix:** Check full-width values before conversion. Widen before
    negation or absolute value. Clamp length before addition. Reject
    negative elements and windows before execution shortcuts.
    - **Other paths and branches:** Cover STRUCT normalization and pruning,
    both bitmap functions, FE constants, and BE rows. ARRAY_SLICE INT64_MIN
    positions remain outside this extraction. Source commits are
    62eaf86047e, 9d5800474da, and d73c2e12a5d. Release-branch applicability
    was not rechecked.
    - **Behavior change:** Invalid ordinals, bitmap elements, funnel
    windows, and ngram sizes report errors. Extreme valid substring counts
    and array lengths return correct results. No configuration or
    storage-format change.
    
    ### Testing
    
    Local checks on master 0a6b84b5a88 plus this patch:
    
    - build.sh --be --fe: passed with ASAN; FE Checkstyle passed.
    - run-fe-ut.sh: 109 tests passed across five selected classes.
    - run-be-ut.sh: 35 tests passed, including all five new BE cases.
    - run-regression-test.sh: generated two new result files, checked their
    values, then passed test_struct_field_ordinal,
    test_selected_function_parameters, and test_ngram_search_gram_num. No
    skips.
    - C++ formatting, header hygiene, and clang-tidy on eight changed files
    passed.
    
    Supplied reports reproduce the old results on the same master baseline.
    That baseline was not rebuilt during this extraction. Runtime checks
    used the candidate artifacts from this worktree.
    
    ### Release note
    
    Fix incorrect results and missing argument errors in STRUCT access,
    SUBSTRING_INDEX, ARRAY_SLICE, BITMAP_CONTAINS, BITMAP_REMOVE,
    WINDOW_FUNNEL_V2, and NGRAM_SEARCH.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6 family).
    - Generated: Selected patch, scoped tests, review notes, and this
    description.
    - Human review: The author has not supplied a human-review statement.
    
    <!-- Recommended: develop the change with the develop-with-evidence
    skill and write this description with the doris-pr-description skill,
    both from https://github.com/apache/doris-skills (the doris-skills
    submodule of this repository). -->
    
    ### Background
    
    <!-- How the feature or module this PR touches works today, in two to
    four plain sentences, for a reviewer who doesn't know it. Link the user
    doc if there is one. Leave the problem and the fix to Problem Summary.
    -->
    
    ### What problem does this PR solve?
    
    <!-- Issue Number: "close #N" if this PR resolves the issue, "#N" if it
    only relates to it, "None" if there is none. A Feature needs an issue.
    -->
    <!-- Related PR: "#N (relation)" for each PR a reviewer should know
    about, such as "#123 (introduced the bug)", separated by commas. Write
    "None" if no related PR is known. -->
    <!-- PR Type: Bugfix, Performance, Feature, Enhancement, Refactor, Test,
    Build/CI/Chore, Revert, Release/Dependency, or Other. -->
    
    Issue Number:
    Related PR:
    PR Type:
    
    Problem Summary:
    
    <!-- Two to five sentences: the problem or need and who is affected; the
    approach in one sentence; when the diff is larger than that suggests,
    what else it had to handle, or that most of it is tests; and what
    existing users see after an upgrade. -->
    
    ### Details
    
    <!--
    For a diff of more than about 300 changed lines, start with "- **Change
    map:**": how many lines are production code, tests, generated files, and
    docs, then the code in parts, each with the problem it handles and its
    size.
    Then answer each field of your PR type on its own line, as "- **Field:**
    answer", in this order:
    Bugfix: Frequency, Root cause, Why existing tests missed it, Fix, Other
    paths and branches
    Performance: Why it was slow, Optimization, Results, Applicability and
    cost
      Feature: Scope, Design, Usage, Default behavior, Compatibility
    Enhancement: Before and after, Configs and defaults, Impact on existing
    users
    Refactor: Moves vs. logic changes, Behavior change, Compatibility,
    Performance impact, Rollback
    Test, adding tests: Scenarios, What existing tests miss, Fails when
    broken
      Test, fixing a test: Failure, Cause, Stability evidence
    Build/CI/Chore: Affected, Developer and release impact, License and
    third-party, Rollback
      Revert: Why not fix forward, Original author notified, Follow-up
    Release/Dependency: Versions, Upstream changes, Compatibility, Rollback
      Other: Why Other
    "None" is a valid answer when it is true. Don't restate the diff.
    -->
    
    ### Testing
    
    <!-- The tests, suites, or commands that ran, what each shows, and where
    it ran (locally or in CI). For a fix, the test that fails before it and
    passes after. -->
    
    ### Notes for Reviewers
    
    <!-- Optional; delete this section if there is nothing to say. Why each
    non-obvious edit was made, what you are unsure about, and where to start
    reading if Details has no Change map. -->
    
    ### Release note
    
    <!-- One paragraph on what users will notice, or None. -->
    
    ### Check List (For Author)
    
    <!-- Behavior changed: "No", or "Yes (see Details)" with a Behavior
    change field in Details. -->
    <!-- Does this need documentation: "No", or "Yes" with the
    apache/doris-website PR or the plan. -->
    <!-- Pre-submission status: "Ready"; "Partially verified: " and what is
    not verified; or "Not ready: " and why, for a Draft PR. -->
    
    - Behavior changed:
    - Does this need documentation:
    - Pre-submission status:
    
    ### AI Disclosure
    
    <!-- Tool: the agent and model, or None. Generated: the parts it wrote
    (code, tests, this description), or None. Human review: what you
    reviewed of the generated parts, or "Not applicable" without AI tools.
    You may add "- Prompts:" to summarize how you directed the agent. -->
    
    - Tool:
    - Generated:
    - Human review:
---
 .../aggregate_function_window_funnel_v2.h          |   6 +
 .../exprs/function/array/function_array_element.h  |  13 +-
 .../exprs/function/array/function_array_utils.cpp  |  14 ++-
 be/src/exprs/function/function_bitmap.cpp          |  44 +++++--
 be/src/exprs/function/function_string_search.cpp   |   3 +-
 .../exprs/aggregate/agg_state_parameters_test.cpp  |   5 +-
 .../exprs/aggregate/vec_window_funnel_v2_test.cpp  |  31 +++++
 .../function/function_element_at_struct_test.cpp   |  25 +++-
 .../function/function_parameter_boundary_test.cpp  | 139 +++++++++++++++++++++
 .../rules/expression/rules/NormalizeElementAt.java |   7 +-
 .../rewrite/AccessPathExpressionCollector.java     |  32 ++---
 .../doris/nereids/rules/rewrite/InApplyToJoin.java |  34 ++++-
 .../expressions/functions/agg/WindowFunnelV2.java  |   9 ++
 .../functions/executable/StringArithmetic.java     |   3 +-
 .../functions/scalar/BitmapContains.java           |  14 +++
 .../expressions/functions/scalar/BitmapRemove.java |  14 +++
 .../expressions/functions/scalar/ElementAt.java    |   6 +-
 .../expressions/functions/scalar/NgramSearch.java  |   7 +-
 .../expressions/literal/IntegerLikeLiteral.java    |   8 ++
 .../org/apache/doris/nereids/types/StructType.java |  10 ++
 .../rules/analysis/AnalyzeWhereSubqueryTest.java   |  24 ++++
 .../analysis/ConstantFunctionArgumentTest.java     |  23 ++++
 .../rewrite/AccessPathExpressionCollectorTest.java |  19 +++
 .../rules/rewrite/PruneNestedColumnTest.java       |  12 ++
 .../functions/executable/StringArithmeticTest.java |   8 ++
 .../doris/nereids/types/StructOrdinalTest.java     |  71 +++++++++++
 .../query_p0/join/test_bitmap_signed_probe.out     |  30 +++++
 .../struct_functions/test_struct_field_ordinal.out |   4 +
 .../data/query_p0/test_bitmap_nullable_element.out |   9 ++
 .../query_p0/test_selected_function_parameters.out |  19 +++
 .../query_p0/join/test_bitmap_signed_probe.groovy  |  52 ++++++++
 .../test_struct_field_ordinal.groovy               |  30 +++++
 .../query_p0/test_bitmap_nullable_element.groovy   |  31 +++++
 .../test_selected_function_parameters.groovy       |  80 ++++++++++++
 34 files changed, 774 insertions(+), 62 deletions(-)

diff --git a/be/src/exprs/aggregate/aggregate_function_window_funnel_v2.h 
b/be/src/exprs/aggregate/aggregate_function_window_funnel_v2.h
index b8e1014d335..34c4efd171b 100644
--- a/be/src/exprs/aggregate/aggregate_function_window_funnel_v2.h
+++ b/be/src/exprs/aggregate/aggregate_function_window_funnel_v2.h
@@ -662,6 +662,12 @@ public:
              Arena&) const override {
         const auto& win = assert_cast<const ColumnInt64&, 
TypeCheckOnRelease::DISABLE>(*columns[0])
                                   .get_data()[row_num];
+        // A false event still has a window argument. Reject -1 before an 
empty event list
+        // can bypass get()'s check. The internal WINDOW_UNSET state remains 
valid.
+        if (win < 0) {
+            throw Exception(ErrorCode::INVALID_ARGUMENT,
+                            "the sliding time window must be a positive 
integer, but got: {}", win);
+        }
         StringRef mode = columns[1]->get_data_at(row_num);
         this->data(place).add(columns, row_num, win,
                               string_to_window_funnel_mode(mode.to_string()));
diff --git a/be/src/exprs/function/array/function_array_element.h 
b/be/src/exprs/function/array/function_array_element.h
index 253853c9f0f..9ff04c2a13e 100644
--- a/be/src/exprs/function/array/function_array_element.h
+++ b/be/src/exprs/function/array/function_array_element.h
@@ -213,15 +213,18 @@ private:
         }
         size_t index = 0;
         if (is_int_or_bool(index_type->get_primitive_type())) {
-            int64_t offset = index_column->get_int(0);
-            size_t limit = struct_type.get_elements().size() + 1;
-            if (offset < 1 || offset >= static_cast<int64_t>(limit)) {
+            // get_int() returns 64 bits. It would turn a LARGEINT such as 
2^64 + 1 into 1.
+            const Int128 offset = index_type->get_primitive_type() == 
TYPE_LARGEINT
+                                          ? 
(*index_column)[0].get<TYPE_LARGEINT>()
+                                          : 
static_cast<Int128>(index_column->get_int(0));
+            const auto limit = 
static_cast<Int128>(struct_type.get_elements().size());
+            if (offset < 1 || offset > limit) {
                 return Status::RuntimeError(
                         "Index out of bound for function {}: index {} should 
base from 1 and less "
                         "than {}.",
-                        get_name(), offset, limit);
+                        get_name(), offset, limit + 1);
             }
-            index = offset - 1; // the index starts from 1
+            index = static_cast<size_t>(offset - 1);
         } else if (is_string_type(index_type->get_primitive_type())) {
             std::string field_name = index_column->get_data_at(0).to_string();
             std::optional<size_t> pos = 
struct_type.try_get_position_by_name(field_name);
diff --git a/be/src/exprs/function/array/function_array_utils.cpp 
b/be/src/exprs/function/array/function_array_utils.cpp
index 8fa2e4199ae..e10f5fd300d 100644
--- a/be/src/exprs/function/array/function_array_utils.cpp
+++ b/be/src/exprs/function/array/function_array_utils.cpp
@@ -96,12 +96,16 @@ void slice_array(ColumnArrayMutableData& dst, 
ColumnArrayExecutionData& src,
             dst.offsets_ptr->push_back(cur);
             continue;
         }
-        Int64 end;
+        Int64 end = off + len;
         if (length_column) {
-            Int64 size = length_column->get_int(row);
-            end = std::max((Int64)off, std::min((Int64)(off + len), start + 
size));
-        } else {
-            end = off + len;
+            const Int64 size = length_column->get_int(row);
+            // Nonpositive lengths produce an empty array. Do not add them to 
start.
+            if (size <= 0) {
+                dst.offsets_ptr->push_back(cur);
+                continue;
+            }
+            // Clamp before addition. For [1, 2], position 2 and INT64_MAX 
length select [2].
+            end = start + std::min(size, end - start);
         }
         for (size_t pos = start; pos < end; ++pos) {
             if (src.nested_nullmap_data && src.nested_nullmap_data[pos]) {
diff --git a/be/src/exprs/function/function_bitmap.cpp 
b/be/src/exprs/function/function_bitmap.cpp
index 6ba5974cd41..f673ee64dc3 100644
--- a/be/src/exprs/function/function_bitmap.cpp
+++ b/be/src/exprs/function/function_bitmap.cpp
@@ -34,6 +34,7 @@
 #include <vector>
 
 #include "common/compiler_util.h" // IWYU pragma: keep
+#include "common/exception.h"
 #include "common/status.h"
 #include "core/assert_cast.h"
 #include "core/block/block.h"
@@ -773,6 +774,17 @@ public:
     }
 };
 
+namespace {
+uint64_t checked_bitmap_element(Int64 value, const char* function_name) {
+    // -1 is not UINT64_MAX. Reject it before contains/remove can access a 
different element.
+    if (value < 0) {
+        throw Exception(ErrorCode::INVALID_ARGUMENT, "{} element must be >= 0, 
but was {}",
+                        function_name, value);
+    }
+    return static_cast<uint64_t>(value);
+}
+} // namespace
+
 struct NameBitmapContains {
     static constexpr auto name = "bitmap_contains";
 };
@@ -789,19 +801,20 @@ struct BitmapContains {
     static void vector_vector(const LTData& lvec, const RTData& rvec, 
ResTData& res) {
         size_t size = lvec.size();
         for (size_t i = 0; i < size; ++i) {
-            res[i] = lvec[i].contains(rvec[i]);
+            res[i] = lvec[i].contains(checked_bitmap_element(rvec[i], 
"bitmap_contains"));
         }
     }
     static void vector_scalar(const LTData& lvec, const T1& rval, ResTData& 
res) {
+        const auto element = checked_bitmap_element(rval, "bitmap_contains");
         size_t size = lvec.size();
         for (size_t i = 0; i < size; ++i) {
-            res[i] = lvec[i].contains(rval);
+            res[i] = lvec[i].contains(element);
         }
     }
     static void scalar_vector(const BitmapValue& lval, const RTData& rvec, 
ResTData& res) {
         size_t size = rvec.size();
         for (size_t i = 0; i < size; ++i) {
-            res[i] = lval.contains(rvec[i]);
+            res[i] = lval.contains(checked_bitmap_element(rvec[i], 
"bitmap_contains"));
         }
     }
 };
@@ -823,21 +836,22 @@ struct BitmapRemove {
         size_t size = lvec.size();
         for (size_t i = 0; i < size; ++i) {
             res[i] = lvec[i];
-            res[i].remove(rvec[i]);
+            res[i].remove(checked_bitmap_element(rvec[i], "bitmap_remove"));
         }
     }
     static void vector_scalar(const LTData& lvec, const T1& rval, ResTData& 
res) {
+        const auto element = checked_bitmap_element(rval, "bitmap_remove");
         size_t size = lvec.size();
         for (size_t i = 0; i < size; ++i) {
             res[i] = lvec[i];
-            res[i].remove(rval);
+            res[i].remove(element);
         }
     }
     static void scalar_vector(const BitmapValue& lval, const RTData& rvec, 
ResTData& res) {
         size_t size = rvec.size();
         for (size_t i = 0; i < size; ++i) {
             res[i] = lval;
-            res[i].remove(rvec[i]);
+            res[i].remove(checked_bitmap_element(rvec[i], "bitmap_remove"));
         }
     }
 };
@@ -1202,10 +1216,20 @@ using FunctionBitmapToBase64 = 
FunctionUnaryToType<BitmapToBase64, NameBitmapToB
 using FunctionBitmapFromBase64 = FunctionBitmapAlwaysNull<BitmapFromBase64>;
 using FunctionBitmapNot =
         FunctionBinaryToType<DataTypeBitMap, DataTypeBitMap, BitmapNot, 
NameBitmapNot>;
-using FunctionBitmapContains =
-        FunctionBinaryToType<DataTypeBitMap, DataTypeInt64, BitmapContains, 
NameBitmapContains>;
-using FunctionBitmapRemove =
-        FunctionBinaryToType<DataTypeBitMap, DataTypeInt64, BitmapRemove, 
NameBitmapRemove>;
+
+template <template <typename, typename> typename Impl, typename Name>
+class FunctionBitmapElement
+        : public FunctionBinaryToType<DataTypeBitMap, DataTypeInt64, Impl, 
Name> {
+public:
+    static FunctionPtr create() { return 
std::make_shared<FunctionBitmapElement>(); }
+
+    // NULLIF([-1, 1], -1) keeps [-1, 1] under null map [1, 0]. Clear the 
hidden -1
+    // before the binary implementation validates elements. The wrapper 
restores NULL.
+    bool need_replace_null_data_to_default() const override { return true; }
+};
+
+using FunctionBitmapContains = FunctionBitmapElement<BitmapContains, 
NameBitmapContains>;
+using FunctionBitmapRemove = FunctionBitmapElement<BitmapRemove, 
NameBitmapRemove>;
 
 using FunctionBitmapHasAny =
         FunctionBinaryToType<DataTypeBitMap, DataTypeBitMap, BitmapHasAny, 
NameBitmapHasAny>;
diff --git a/be/src/exprs/function/function_string_search.cpp 
b/be/src/exprs/function/function_string_search.cpp
index 2183494f811..ac139818b98 100644
--- a/be/src/exprs/function/function_string_search.cpp
+++ b/be/src/exprs/function/function_string_search.cpp
@@ -497,7 +497,8 @@ public:
                     }
                 }
             } else {
-                int neg_part_number = -part_number;
+                // INT_MIN has magnitude 2147483648. Keep that value when 
counting from the end.
+                int64_t neg_part_number = -static_cast<int64_t>(part_number);
                 auto str_str = str.to_string();
                 int32_t offset = str.size;
                 int32_t pre_offset = offset;
diff --git a/be/test/exprs/aggregate/agg_state_parameters_test.cpp 
b/be/test/exprs/aggregate/agg_state_parameters_test.cpp
index aa8a3a8cda4..e84bc224e70 100644
--- a/be/test/exprs/aggregate/agg_state_parameters_test.cpp
+++ b/be/test/exprs/aggregate/agg_state_parameters_test.cpp
@@ -711,9 +711,12 @@ TEST(AggregateStateParametersTest, 
WindowFunnelEventlessParameters) {
             }
         }
     }
+    // The input window must be nonnegative even when all events are false.
+    // Use 0 to check that an eventless state ignores an invalid mode.
+    // NegativeWindowWithFalseEvent separately checks that a window of -1 is 
rejected.
     check_ignored_parameters(
             "window_funnel_v2",
-            {argument<DataTypeInt64>(-1), argument<DataTypeString>("invalid"), 
timestamp, no, no},
+            {argument<DataTypeInt64>(0), argument<DataTypeString>("invalid"), 
timestamp, no, no},
             {argument<DataTypeInt64>(0), argument<DataTypeString>("default"), 
timestamp, no, no});
 }
 } // namespace doris
diff --git a/be/test/exprs/aggregate/vec_window_funnel_v2_test.cpp 
b/be/test/exprs/aggregate/vec_window_funnel_v2_test.cpp
index 652b826cb77..6e0765abab6 100644
--- a/be/test/exprs/aggregate/vec_window_funnel_v2_test.cpp
+++ b/be/test/exprs/aggregate/vec_window_funnel_v2_test.cpp
@@ -68,6 +68,37 @@ public:
     Arena arena;
 };
 
+TEST(VWindowFunnelV2ParameterTest, NegativeWindowWithFalseEvent) {
+    // One false event used to bypass the window check in result calculation.
+    DataTypes types = {std::make_shared<DataTypeInt64>(), 
std::make_shared<DataTypeString>(),
+                       std::make_shared<DataTypeDateTimeV2>(), 
std::make_shared<DataTypeUInt8>()};
+    auto function = AggregateFunctionSimpleFactory::instance().get(
+            "window_funnel_v2", types, nullptr, false, 
BeExecVersionManager::get_newest_version());
+    ASSERT_NE(function, nullptr);
+    auto window = ColumnInt64::create();
+    window->insert_value(-1);
+    auto mode = ColumnString::create();
+    mode->insert_data("default", 7);
+    auto timestamp = ColumnDateTimeV2::create();
+    DateV2Value<DateTimeV2ValueType> time;
+    time.unchecked_set_time(2024, 1, 1, 0, 0, 0, 0);
+    timestamp->insert_value(time);
+    auto event = ColumnUInt8::create();
+    event->insert_value(0);
+    const IColumn* columns[] = {window.get(), mode.get(), timestamp.get(), 
event.get()};
+    std::unique_ptr<char[]> memory(new char[function->size_of_data()]);
+    function->create(memory.get());
+    Arena arena;
+    EXPECT_THROW(function->add(memory.get(), columns, 0, arena), Exception);
+    // A zero window remains valid. The rejected row must not alter the state.
+    window->get_data()[0] = 0;
+    EXPECT_NO_THROW(function->add(memory.get(), columns, 0, arena));
+    auto result = ColumnInt32::create();
+    function->insert_result_into(memory.get(), *result);
+    EXPECT_EQ(result->get_int(0), 0);
+    function->destroy(memory.get());
+}
+
 TEST(VWindowFunnelV2TimeStampNsTest, FactoryCreatesFunction) {
     AggregateFunctionSimpleFactory factory = 
AggregateFunctionSimpleFactory::instance();
     DataTypes data_types = {std::make_shared<DataTypeInt64>(), 
std::make_shared<DataTypeString>(),
diff --git a/be/test/exprs/function/function_element_at_struct_test.cpp 
b/be/test/exprs/function/function_element_at_struct_test.cpp
index 2e0e5352e95..e1d3e892b1e 100644
--- a/be/test/exprs/function/function_element_at_struct_test.cpp
+++ b/be/test/exprs/function/function_element_at_struct_test.cpp
@@ -166,4 +166,27 @@ TEST(FunctionElementAtStructTest, test_field_not_found) {
     EXPECT_TRUE(err.find("not found") != std::string::npos);
 }
 
-} // namespace doris
\ No newline at end of file
+TEST(FunctionElementAtStructTest, large_integer_ordinal_keeps_high_bits) {
+    // One row and one field suffice. Both invalid ordinals become 1 through 
get_int().
+    auto type = std::make_shared<DataTypeStruct>(DataTypes 
{std::make_shared<DataTypeInt32>()},
+                                                 Strings {"a"});
+    auto index_type = std::make_shared<DataTypeInt128>();
+    const Int128 high = Int128 {1} << 64;
+    for (Int128 index : {high + 1, -high + 1}) {
+        ColumnPtr index_column =
+                
ColumnConst::create(ColumnHelper::create_column<DataTypeInt128>({index}), 1);
+        ColumnsWithTypeAndName args {{nullptr, type, "s"}, {index_column, 
index_type, "i"}};
+        EXPECT_THROW(SimpleFunctionFactory::instance().get_function(
+                             "element_at", args, 
make_nullable(std::make_shared<DataTypeInt32>())),
+                     Exception);
+    }
+    ColumnPtr index_column =
+            
ColumnConst::create(ColumnHelper::create_column<DataTypeInt128>({1}), 1);
+    ColumnsWithTypeAndName args {{nullptr, type, "s"}, {index_column, 
index_type, "i"}};
+    auto function = SimpleFunctionFactory::instance().get_function(
+            "element_at", args, 
make_nullable(std::make_shared<DataTypeInt32>()));
+    ASSERT_NE(function, nullptr);
+    EXPECT_EQ(function->get_return_type()->get_name(), "Nullable(INT)");
+}
+
+} // namespace doris
diff --git a/be/test/exprs/function/function_parameter_boundary_test.cpp 
b/be/test/exprs/function/function_parameter_boundary_test.cpp
new file mode 100644
index 00000000000..4a30e7e1e6f
--- /dev/null
+++ b/be/test/exprs/function/function_parameter_boundary_test.cpp
@@ -0,0 +1,139 @@
+// 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.
+
+#include <gtest/gtest.h>
+
+#include <limits>
+#include <string>
+#include <string_view>
+
+#include "core/data_type/data_type_bitmap.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/types.h"
+#include "core/value/bitmap_value.h"
+#include "exprs/function/array/function_array_utils.h"
+#include "exprs/function/function_test_util.h"
+
+namespace doris {
+using namespace ut_type;
+
+TEST(FunctionParameterBoundaryTest, SubstringIndexMinimumCount) {
+    // With no separator, an excessive negative count returns the entire 
one-character string.
+    InputTypeSet types = {PrimitiveType::TYPE_VARCHAR, 
PrimitiveType::TYPE_VARCHAR,
+                          PrimitiveType::TYPE_INT};
+    DataSet rows = {{{std::string("a"), std::string(","), 
std::numeric_limits<Int32>::min()},
+                     std::string("a")}};
+    check_function_all_arg_comb<DataTypeString, true>("substring_index", 
types, rows);
+}
+
+TEST(FunctionParameterBoundaryTest, ArraySliceLengthBounds) {
+    // Two elements are the minimum needed for start + INT64_MAX to overflow.
+    auto values = ColumnInt32::create();
+    values->insert_value(1);
+    values->insert_value(2);
+    auto ends = ColumnArray::ColumnOffsets::create();
+    ends->insert_value(2);
+    auto array = ColumnArray::create(std::move(values), std::move(ends));
+    ColumnArrayExecutionData source;
+    ASSERT_TRUE(extract_column_array_info(*array, source));
+    for (Int64 offset : {Int64(2), Int64(-1)}) {
+        auto offsets = ColumnInt64::create();
+        offsets->insert_value(offset);
+        auto lengths = ColumnInt64::create();
+        lengths->insert_value(std::numeric_limits<Int64>::max());
+        auto result = create_mutable_data(source.nested_col.get(), false);
+        slice_array(result, source, *offsets, lengths.get());
+        ASSERT_EQ(result.nested_col->size(), 1);
+        EXPECT_EQ((*result.offsets_ptr)[0], 1);
+        EXPECT_EQ(result.nested_col->get_int(0), 2);
+    }
+}
+
+TEST(FunctionParameterBoundaryTest, BitmapNegativeElement) {
+    // A single UINT64_MAX element makes the old -1 conversion observable in 
both functions.
+    BitmapValue bitmap(std::numeric_limits<UInt64>::max());
+    for (bool const_bitmap : {false, true}) {
+        for (bool const_element : {false, true}) {
+            InputTypeSet types = {PrimitiveType::TYPE_BITMAP, 
PrimitiveType::TYPE_BIGINT};
+            if (const_bitmap) {
+                types[0] = Consted {PrimitiveType::TYPE_BITMAP};
+            }
+            if (const_element) {
+                types[1] = Consted {PrimitiveType::TYPE_BIGINT};
+            }
+            DataSet contains = {{{&bitmap, Int64(-1)}, UInt8(0)}};
+            auto status = check_function<DataTypeUInt8, 
true>("bitmap_contains", types, contains,
+                                                              -1, -1, true);
+            EXPECT_NE(status.to_string().find("element must be >= 0"), 
std::string::npos);
+            DataSet remove = {{{&bitmap, Int64(-1)}, &bitmap}};
+            status = check_function<DataTypeBitMap, true>("bitmap_remove", 
types, remove, -1, -1,
+                                                          true);
+            EXPECT_NE(status.to_string().find("element must be >= 0"), 
std::string::npos);
+            EXPECT_TRUE(bitmap.contains(std::numeric_limits<UInt64>::max()));
+        }
+    }
+}
+
+namespace {
+void check_bitmap_null_element_payload(const char* name, bool const_bitmap) {
+    auto bitmaps = ColumnBitmap::create();
+    bitmaps->get_data().assign(const_bitmap ? 1 : 2, BitmapValue(1));
+    ColumnPtr bitmap_column = std::move(bitmaps);
+    if (const_bitmap) {
+        bitmap_column = ColumnConst::create(bitmap_column, 2);
+    }
+    auto elements = ColumnInt64::create();
+    elements->get_data() = {-1, 1};
+    auto nulls = ColumnUInt8::create();
+    nulls->get_data() = {1, 0};
+    ColumnPtr nullable_elements = ColumnNullable::create(std::move(elements), 
std::move(nulls));
+    const bool contains = std::string_view(name) == "bitmap_contains";
+    DataTypePtr result_type = contains ? 
make_nullable(std::make_shared<DataTypeUInt8>())
+                                       : 
make_nullable(std::make_shared<DataTypeBitMap>());
+    Block block {{bitmap_column, std::make_shared<DataTypeBitMap>(), "bitmap"},
+                 {nullable_elements, 
make_nullable(std::make_shared<DataTypeInt64>()), "element"}};
+    auto function = SimpleFunctionFactory::instance().get_function(
+            name, block.get_columns_with_type_and_name(), result_type);
+    ASSERT_NE(function, nullptr);
+    block.insert({nullptr, result_type, "result"});
+    auto status = function->execute(nullptr, block, {0, 1}, 2, 2);
+    ASSERT_TRUE(status.ok()) << status;
+    const auto& result = assert_cast<const 
ColumnNullable&>(*block.get_by_position(2).column);
+    EXPECT_TRUE(result.is_null_at(0));
+    EXPECT_FALSE(result.is_null_at(1));
+    if (contains) {
+        EXPECT_EQ(result.get_nested_column().get_int(1), 1);
+    } else {
+        const auto& values =
+                assert_cast<const 
ColumnBitmap&>(result.get_nested_column()).get_data();
+        EXPECT_TRUE(values[1].empty());
+    }
+}
+} // namespace
+
+TEST(FunctionParameterBoundaryTest, BitmapNullElementPayload) {
+    // Two rows reproduce NULLIF(k, -1): the first -1 is hidden by NULL and 
the second
+    // element is valid. Check a constant bitmap and a bitmap column for both 
functions.
+    for (const auto* name : {"bitmap_contains", "bitmap_remove"}) {
+        for (bool const_bitmap : {false, true}) {
+            check_bitmap_null_element_payload(name, const_bitmap);
+        }
+    }
+}
+
+} // namespace doris
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/NormalizeElementAt.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/NormalizeElementAt.java
index 6388c1830ae..47feca42553 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/NormalizeElementAt.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/NormalizeElementAt.java
@@ -52,14 +52,13 @@ public class NormalizeElementAt implements 
ExpressionPatternRuleFactory {
         }
         Expression field = elementAt.getArgument(1);
         if (field instanceof IntegerLikeLiteral) {
-            int fieldIndex = ((Number) ((IntegerLikeLiteral) 
field).getValue()).intValue();
             StructType structType = (StructType) 
elementAt.child(0).getDataType();
-            List<StructField> fields = structType.getFields();
-            if (fieldIndex >= 1 && fieldIndex <= fields.size()) {
+            StructField selected = 
structType.getFieldByOrdinal(((IntegerLikeLiteral) field).getBigDecimalValue());
+            if (selected != null) {
                 return elementAt.withChildren(
                         ImmutableList.of(
                                 elementAt.child(0),
-                                new StringLiteral(fields.get(fieldIndex - 
1).getName())
+                                new StringLiteral(selected.getName())
                         )
                 );
             }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollector.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollector.java
index 4c5c32378cb..f62ef04f5a9 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollector.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollector.java
@@ -58,6 +58,7 @@ import 
org.apache.doris.nereids.trees.expressions.functions.scalar.MapEntries;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.MapKeys;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.MapSize;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.MapValues;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLikeLiteral;
 import org.apache.doris.nereids.trees.expressions.literal.Literal;
 import 
org.apache.doris.nereids.trees.expressions.visitor.DefaultExpressionVisitor;
 import org.apache.doris.nereids.types.ArrayType;
@@ -404,14 +405,12 @@ public class AccessPathExpressionCollector extends 
DefaultExpressionVisitor<Void
         } else if (first.getDataType().isStructType()) {
             // struct field access (formerly struct_element): collect the 
selected field as the path
             Expression fieldName = arguments.get(1);
-            DataType fieldType = fieldName.getDataType();
-            if (fieldName.isLiteral() && (fieldType.isIntegerLikeType() || 
fieldType.isStringLikeType())) {
+            StructField field = resolveStructField((StructType) 
first.getDataType(), fieldName);
+            if (field != null) {
                 // Only emit META [s, field, NULL] when the selected field 
itself is nullable.
                 if (context.type == ColumnAccessPathType.META
                         && 
isUnderIsNull(context.accessPathBuilder.getPathList())) {
-                    StructField field = resolveStructField(
-                            (StructType) first.getDataType(), fieldName);
-                    if (field == null || !field.isNullable()) {
+                    if (!field.isNullable()) {
                         // Non-nullable leaf: no META NULL path for the field 
is needed.
                         // However the field must still appear in the type so 
pruneDataType
                         // preserves it — the filter expression still 
references
@@ -423,17 +422,7 @@ public class AccessPathExpressionCollector extends 
DefaultExpressionVisitor<Void
                     // Nullable leaf: fall through to add field prefix → META 
[s, field, NULL]
                 }
 
-                if (fieldType.isIntegerLikeType()) {
-                    int fieldIndex = ((Number) ((Literal) 
fieldName).getValue()).intValue();
-                    List<StructField> fields = ((StructType) 
first.getDataType()).getFields();
-                    if (fieldIndex >= 1 && fieldIndex <= fields.size()) {
-                        String realFieldName = fields.get(fieldIndex - 
1).getName();
-                        context.accessPathBuilder.addPrefix(realFieldName);
-                        return continueCollectAccessPath(first, context);
-                    }
-                }
-                context.accessPathBuilder.addPrefix(
-                        ((Literal) 
fieldName).getStringValue().toLowerCase(Locale.ROOT));
+                context.accessPathBuilder.addPrefix(field.getName());
                 return continueCollectAccessPath(first, context);
             }
             return visit(elementAt, context);
@@ -820,16 +809,11 @@ public class AccessPathExpressionCollector extends 
DefaultExpressionVisitor<Void
         if (!fieldExpr.isLiteral()) {
             return null;
         }
-        if (fieldExpr.getDataType().isIntegerLikeType()) {
-            int index = ((Number) ((Literal) fieldExpr).getValue()).intValue();
-            List<StructField> fields = structType.getFields();
-            if (index >= 1 && index <= fields.size()) {
-                return fields.get(index - 1);
-            }
-            return null;
+        if (fieldExpr instanceof IntegerLikeLiteral) {
+            return structType.getFieldByOrdinal(((IntegerLikeLiteral) 
fieldExpr).getBigDecimalValue());
         }
         if (fieldExpr.getDataType().isStringLikeType()) {
-            String name = ((Literal) fieldExpr).getStringValue().toLowerCase();
+            String name = ((Literal) fieldExpr).getStringValue();
             return structType.getField(name);
         }
         return null;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/InApplyToJoin.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/InApplyToJoin.java
index a2a3c860757..8b65a599560 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/InApplyToJoin.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/InApplyToJoin.java
@@ -22,19 +22,26 @@ import org.apache.doris.nereids.hint.DistributeHint;
 import org.apache.doris.nereids.rules.Rule;
 import org.apache.doris.nereids.rules.RuleType;
 import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.And;
 import org.apache.doris.nereids.trees.expressions.EqualTo;
 import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
 import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.LessThan;
 import org.apache.doris.nereids.trees.expressions.NamedExpression;
 import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.Slot;
 import org.apache.doris.nereids.trees.expressions.functions.agg.BitmapUnion;
 import 
org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapContains;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.If;
+import org.apache.doris.nereids.trees.expressions.literal.BigIntLiteral;
 import org.apache.doris.nereids.trees.plans.DistributeType;
 import org.apache.doris.nereids.trees.plans.JoinType;
 import org.apache.doris.nereids.trees.plans.Plan;
 import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
 import org.apache.doris.nereids.trees.plans.logical.LogicalApply;
 import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
 import org.apache.doris.nereids.util.ExpressionUtils;
 
 import com.google.common.collect.ImmutableList;
@@ -63,7 +70,7 @@ public class InApplyToJoin extends OneRewriteRuleFactory {
                 select t1.k1 from bigtable t1 where t1.k1 in (select 
bitmap_union(k2) from bitmap_table t2);
                 =>
                 select t1.k1 from bigtable t1 left semi join (select 
bitmap_union(k2) x from bitmap_table ) t2
-                on bitmap_contains(x, t1.k1);
+                on t1.k1 >= 0 and bitmap_contains(x, if(t1.k1 < 0, 0, t1.k1));
 
                 case 2: not in
                 select t1.k1 from bigtable t1 where t1.k1 not in (select t2.k2 
from bitmap_table t2);
@@ -71,7 +78,7 @@ public class InApplyToJoin extends OneRewriteRuleFactory {
                 select t1.k1 from bigtable t1 where t1.k1 not in (select 
bitmap_union(k2) from bitmap_table t2);
                 =>
                 select t1.k1 from bigtable t1 left semi join (select 
bitmap_union(k2) x from bitmap_table ) t2
-                on not bitmap_contains(x, t1.k1);
+                on not (t1.k1 >= 0 and bitmap_contains(x, if(t1.k1 < 0, 0, 
t1.k1)));
                  */
                 List<Expression> groupExpressions = ImmutableList.of();
                 Expression bitmapCol = apply.right().getOutput().get(0);
@@ -81,15 +88,32 @@ public class InApplyToJoin extends OneRewriteRuleFactory {
 
                 LogicalAggregate agg = new LogicalAggregate(groupExpressions, 
outputExpressions, apply.right());
                 Expression compareExpr = apply.getCompareExpr().get();
-                Expression expr = new BitmapContains(agg.getOutput().get(0), 
compareExpr);
+                Plan left = apply.left();
+                // The guard and the lookup share one probe value. Materialize 
expressions such as
+                // cast(rand() * 2 as bigint) - 1 once, so the two checks 
cannot see different values.
+                if (!(compareExpr instanceof Slot)) {
+                    Alias probe = new Alias(compareExpr);
+                    left = new 
LogicalProject<>(ImmutableList.<NamedExpression>builder()
+                            .addAll(left.getOutput()).add(probe).build(), 
left);
+                    compareExpr = probe.toSlot();
+                }
+                BigIntLiteral zero = new BigIntLiteral(0);
+                // IN accepts signed probes, but direct bitmap_contains 
rejects negative elements.
+                // Clamp before the call: AND does not guarantee short-circuit 
evaluation. The guard
+                // prevents -1 from matching bitmap element 0. Keep NULL in 
the IF's else branch.
+                Expression safeProbe = new If(new LessThan(compareExpr, zero), 
zero, compareExpr);
+                Expression expr = new And(new GreaterThanEqual(compareExpr, 
zero),
+                        new BitmapContains(agg.getOutput().get(0), safeProbe));
                 if (apply.isNot()) {
                     expr = new Not(expr);
                 }
-                return new LogicalJoin<>(JoinType.LEFT_SEMI_JOIN, 
Lists.newArrayList(),
+                LogicalJoin<Plan, Plan> join = new 
LogicalJoin<>(JoinType.LEFT_SEMI_JOIN, Lists.newArrayList(),
                         Lists.newArrayList(expr),
                         new DistributeHint(DistributeType.NONE),
                         apply.getMarkJoinSlotReference(),
-                        apply.left(), agg, null);
+                        left, agg, null);
+                // Remove the temporary probe slot while preserving the mark 
slot, when present.
+                return new 
LogicalProject<>(ImmutableList.copyOf(apply.getOutput()), join);
             }
 
             //in-predicate to equal
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/WindowFunnelV2.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/WindowFunnelV2.java
index c5d321caf70..405a1d2c74c 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/WindowFunnelV2.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/WindowFunnelV2.java
@@ -19,8 +19,10 @@ package 
org.apache.doris.nereids.trees.expressions.functions.agg;
 
 import org.apache.doris.catalog.FunctionSignature;
 import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.rules.expression.rules.FoldConstantRuleOnFE;
 import org.apache.doris.nereids.trees.expressions.Expression;
 import 
org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLikeLiteral;
 import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
 import org.apache.doris.nereids.types.BigIntType;
 import org.apache.doris.nereids.types.BooleanType;
@@ -105,6 +107,13 @@ public class WindowFunnelV2 extends 
NullableAggregateFunction
         if (!getArgument(0).isConstant()) {
             throw new AnalysisException("The window parameter of " + 
functionName + " must be a constant");
         }
+        // A negative window is invalid even when every event is false or the 
input is pruned.
+        Expression window = 
FoldConstantRuleOnFE.evaluateWithoutContext(getArgument(0));
+        if (window instanceof IntegerLikeLiteral
+                && !((IntegerLikeLiteral) window).isValueInRange(0, 
Long.MAX_VALUE)) {
+            throw new AnalysisException("the sliding time window must be a 
positive integer, but got: "
+                    + window.toSql());
+        }
         if (!getArgument(1).isConstant()) {
             throw new AnalysisException("The mode parameter of " + 
functionName + " must be a constant");
         }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
index 68e18fee9c0..6875b08ea7d 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
@@ -866,7 +866,8 @@ public class StringArithmetic {
             return chr;
         }
         String[] parts = first.getValue().split(Pattern.quote(chr.getValue()), 
-1);
-        if (Math.abs(number.getValue()) >= parts.length) {
+        // Widen before abs. A count of INT_MIN exceeds every valid part count 
and returns the full string.
+        if (Math.abs((long) number.getValue()) >= parts.length) {
             return first;
         }
         int leftIndex;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapContains.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapContains.java
index fcba10cee68..e72c93dbeef 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapContains.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapContains.java
@@ -18,9 +18,12 @@
 package org.apache.doris.nereids.trees.expressions.functions.scalar;
 
 import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.rules.expression.rules.FoldConstantRuleOnFE;
 import org.apache.doris.nereids.trees.expressions.Expression;
 import 
org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
 import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLikeLiteral;
 import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
 import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
 import org.apache.doris.nereids.types.BigIntType;
@@ -63,6 +66,17 @@ public class BitmapContains extends ScalarFunction
         return new BitmapContains(getFunctionParams(children));
     }
 
+    @Override
+    public void checkLegalityBeforeTypeCoercion() {
+        // -1 must not address UINT64_MAX. Check constants before coercion or 
NULL propagation.
+        Expression element = 
FoldConstantRuleOnFE.evaluateWithoutContext(getArgument(1));
+        if (element instanceof IntegerLikeLiteral
+                && !((IntegerLikeLiteral) element).isValueInRange(0, 
Long.MAX_VALUE)) {
+            throw new AnalysisException(getName() + " element must be between 
0 and " + Long.MAX_VALUE
+                    + ", but was " + element.toSql());
+        }
+    }
+
     @Override
     public List<FunctionSignature> getSignatures() {
         return SIGNATURES;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapRemove.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapRemove.java
index f1e7ef36680..42460e77bc5 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapRemove.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/BitmapRemove.java
@@ -18,9 +18,12 @@
 package org.apache.doris.nereids.trees.expressions.functions.scalar;
 
 import org.apache.doris.catalog.FunctionSignature;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.rules.expression.rules.FoldConstantRuleOnFE;
 import org.apache.doris.nereids.trees.expressions.Expression;
 import 
org.apache.doris.nereids.trees.expressions.functions.ExplicitlyCastableSignature;
 import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLikeLiteral;
 import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
 import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
 import org.apache.doris.nereids.types.BigIntType;
@@ -62,6 +65,17 @@ public class BitmapRemove extends ScalarFunction
         return new BitmapRemove(getFunctionParams(children));
     }
 
+    @Override
+    public void checkLegalityBeforeTypeCoercion() {
+        // -1 must not address UINT64_MAX. Check constants before coercion or 
NULL propagation.
+        Expression element = 
FoldConstantRuleOnFE.evaluateWithoutContext(getArgument(1));
+        if (element instanceof IntegerLikeLiteral
+                && !((IntegerLikeLiteral) element).isValueInRange(0, 
Long.MAX_VALUE)) {
+            throw new AnalysisException(getName() + " element must be between 
0 and " + Long.MAX_VALUE
+                    + ", but was " + element.toSql());
+        }
+    }
+
     @Override
     public List<FunctionSignature> getSignatures() {
         return SIGNATURES;
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ElementAt.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ElementAt.java
index e748df1eb59..5873ee6e7bf 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ElementAt.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/ElementAt.java
@@ -148,11 +148,11 @@ public class ElementAt extends ScalarFunction
     private DataType structFieldType(StructType structType) {
         Expression field = getArgument(1);
         if (field instanceof IntegerLikeLiteral) {
-            int offset = ((IntegerLikeLiteral) field).getIntValue();
-            if (offset <= 0 || offset > structType.getFields().size()) {
+            StructField selected = 
structType.getFieldByOrdinal(((IntegerLikeLiteral) field).getBigDecimalValue());
+            if (selected == null) {
                 throw new AnalysisException("the specified field index out of 
bound: " + this.toSql());
             }
-            return structType.getFields().get(offset - 1).getDataType();
+            return selected.getDataType();
         } else if (field instanceof StringLikeLiteral) {
             String name = ((StringLikeLiteral) field).getStringValue();
             StructField structField = structType.getField(name);
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/NgramSearch.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/NgramSearch.java
index 9f2616dbd2d..48367570c9c 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/NgramSearch.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/scalar/NgramSearch.java
@@ -86,9 +86,12 @@ public class NgramSearch extends ScalarFunction
             throw new AnalysisException(
                     "ngram_search(text,pattern,gram_num): gram_num support 
const value only.");
         }
-        if (gramNum instanceof IntegerLikeLiteral && ((IntegerLikeLiteral) 
gramNum).getLongValue() <= 0) {
+        // Check the complete value before the INT signature can narrow a 
LARGEINT argument.
+        if (gramNum instanceof IntegerLikeLiteral
+                && !((IntegerLikeLiteral) gramNum).isValueInRange(1, 
Integer.MAX_VALUE)) {
             throw new AnalysisException(
-                    "ngram_search(text,pattern,gram_num): gram_num must be a 
positive constant.");
+                    "ngram_search(text,pattern,gram_num): gram_num must be a 
positive constant"
+                            + " no greater than 2147483647.");
         }
     }
 
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/literal/IntegerLikeLiteral.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/literal/IntegerLikeLiteral.java
index 62d90bea06c..100e4dc38eb 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/literal/IntegerLikeLiteral.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/literal/IntegerLikeLiteral.java
@@ -36,6 +36,14 @@ public abstract class IntegerLikeLiteral extends 
NumericLiteral {
         super(dataType);
     }
 
+    /** Check inclusive bounds without narrowing LARGEINT values to long. */
+    public boolean isValueInRange(long minimum, long maximum) {
+        // For example, -18446744073709551615 must not become the valid 
positive value 1.
+        BigDecimal value = getBigDecimalValue();
+        return value.compareTo(BigDecimal.valueOf(minimum)) >= 0
+                && value.compareTo(BigDecimal.valueOf(maximum)) <= 0;
+    }
+
     public int getIntValue() {
         return getNumber().intValue();
     }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/types/StructType.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/types/StructType.java
index d8ca95e869b..a6d7bd496df 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/types/StructType.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/types/StructType.java
@@ -25,6 +25,7 @@ import 
org.apache.doris.nereids.types.coercion.ComplexDataType;
 
 import com.google.common.collect.ImmutableList;
 
+import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -78,6 +79,15 @@ public class StructType extends DataType implements 
ComplexDataType, NestedColum
         return nameToFields;
     }
 
+    /** Resolve a one-based integer selector at its SQL precision. */
+    public StructField getFieldByOrdinal(BigDecimal ordinal) {
+        // For example, 4294967297 becomes 1 if converted to int before this 
comparison.
+        if (ordinal.signum() <= 0 || 
ordinal.compareTo(BigDecimal.valueOf(fields.size())) > 0) {
+            return null;
+        }
+        return fields.get(ordinal.intValueExact() - 1);
+    }
+
     /** Get a field by its case-insensitive runtime name. */
     public StructField getField(String name) {
         StructField field = nameToFields.get(name.toLowerCase(Locale.ROOT));
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeWhereSubqueryTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeWhereSubqueryTest.java
index bc8748ea7c8..6c3a6093f85 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeWhereSubqueryTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeWhereSubqueryTest.java
@@ -35,11 +35,14 @@ import 
org.apache.doris.nereids.rules.rewrite.UnCorrelatedApplyProjectFilter;
 import org.apache.doris.nereids.trees.expressions.Alias;
 import org.apache.doris.nereids.trees.expressions.EqualTo;
 import org.apache.doris.nereids.trees.expressions.ExprId;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
 import org.apache.doris.nereids.trees.expressions.LessThan;
 import org.apache.doris.nereids.trees.expressions.SlotReference;
 import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
 import org.apache.doris.nereids.trees.expressions.functions.agg.Max;
 import org.apache.doris.nereids.trees.expressions.functions.agg.Sum;
+import 
org.apache.doris.nereids.trees.expressions.functions.scalar.BitmapContains;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.If;
 import org.apache.doris.nereids.trees.plans.JoinType;
 import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
 import org.apache.doris.nereids.types.BigIntType;
@@ -271,6 +274,27 @@ public class AnalyzeWhereSubqueryTest extends 
TestWithFeService implements MemoP
                 );
     }
 
+    @Test
+    public void testBitmapInMaterializesVolatileProbe() {
+        // The signed-domain guard and bitmap lookup must read one value. 
Duplicating RAND
+        // can make the guard accept one value while the lookup tests a 
different value.
+        // No table rows are needed: inspect the rewrite before later 
optimizer rules run.
+        for (String operator : ImmutableList.of("in", "not in")) {
+            PlanChecker.from(connectContext)
+                    .analyze("select k1 from t6 where cast(rand() * 2 as 
bigint) - 1 "
+                            + operator + " (select to_bitmap(1))")
+                    .applyBottomUp(new InApplyToJoin())
+                    .matches(logicalJoin(
+                            logicalProject().when(project -> 
project.getProjects().stream()
+                                    .filter(expression -> 
expression.containsVolatileExpression()).count() == 1),
+                            logicalAggregate())
+                            .when(join -> 
!join.getOtherJoinConjuncts().get(0).containsVolatileExpression())
+                            .when(join -> 
join.getOtherJoinConjuncts().get(0).containsType(GreaterThanEqual.class))
+                            .when(join -> 
join.getOtherJoinConjuncts().get(0).containsType(BitmapContains.class))
+                            .when(join -> 
join.getOtherJoinConjuncts().get(0).containsType(If.class)));
+        }
+    }
+
     @Test
     public void testInSql4AfterInToJoin() {
         PlanChecker.from(connectContext)
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/ConstantFunctionArgumentTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/ConstantFunctionArgumentTest.java
index 13dc6f3b93e..687781a3fcd 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/ConstantFunctionArgumentTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/ConstantFunctionArgumentTest.java
@@ -73,6 +73,29 @@ import java.util.List;
  */
 public class ConstantFunctionArgumentTest {
 
+    @Test
+    public void testSelectedFunctionParameterBounds() {
+        // This negative LARGEINT has low 64 bits equal to 1. Check it before 
INT coercion.
+        assertAnalysisError("select ngram_search('a', 'a', 
-18446744073709551615)",
+                "gram_num must be a positive constant");
+        assertAnalysisError("select ngram_search('a', 'a', 2147483648)",
+                "gram_num must be a positive constant");
+        // A NULL bitmap must not remove a known invalid element argument 
during folding.
+        for (String function : new String[] {"bitmap_contains", 
"bitmap_remove"}) {
+            assertAnalysisError("select " + function + "(null, -1)", "element 
must be between 0");
+            assertAnalysisError("select " + function + "(null, 
-18446744073709551615)",
+                    "element must be between 0");
+            assertAnalysisError("select " + function + "(null, 
9223372036854775808)",
+                    "element must be between 0");
+        }
+        // A false event does not make a negative window valid. No input table 
is needed.
+        assertAnalysisError("select window_funnel_v2(-1, 'default',"
+                + " cast('2024-01-01' as datetime), false)", "window must be a 
positive integer");
+        // WINDOW_FUNNEL_V2 rejects LARGEINT at its type check, before the 
value check.
+        assertAnalysisError("select window_funnel_v2(9223372036854775808, 
'default',"
+                + " cast('2024-01-01' as datetime), false)", "must be 
integer");
+    }
+
     @Test
     public void testPrepareFoldsArgumentsTheSignatureDependsOn() {
         Now now = analyze("select now(1 + 2)", Now.class);
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollectorTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollectorTest.java
index d06e6905109..1af819f79a7 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollectorTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollectorTest.java
@@ -23,6 +23,7 @@ import 
org.apache.doris.nereids.rules.rewrite.NestedColumnPruning.DataTypeAccess
 import org.apache.doris.nereids.trees.expressions.Cast;
 import org.apache.doris.nereids.trees.expressions.SlotReference;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.ElementAt;
+import org.apache.doris.nereids.trees.expressions.literal.LargeIntLiteral;
 import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
 import org.apache.doris.nereids.types.IntegerType;
 import org.apache.doris.nereids.types.StringType;
@@ -35,12 +36,30 @@ import com.google.common.collect.Multimap;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
+import java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
 
 public class AccessPathExpressionCollectorTest {
 
+    @Test
+    public void testWideOrdinalDoesNotPruneToWrappedField() {
+        StructType type = new StructType(List.of(new StructField("a", 
IntegerType.INSTANCE, true, "")));
+        SlotReference slot = new SlotReference("s", type);
+        // Direct collection reaches the rule that SQL type analysis would 
reject first.
+        // An invalid ordinal must retain the root path instead of selecting 
field a.
+        for (String value : List.of("1", "4294967297", 
"-18446744073709551615")) {
+            Multimap<Integer, CollectAccessPathResult> paths = 
ArrayListMultimap.create();
+            new AccessPathExpressionCollector(null, paths, false, 
false).collect(
+                    new ElementAt(slot, new LargeIntLiteral(new 
BigInteger(value))));
+            List<CollectAccessPathResult> results = new 
ArrayList<>(paths.get(slot.getExprId().asInt()));
+            Assertions.assertEquals(1, results.size());
+            Assertions.assertEquals(value.equals("1") ? List.of("s", "a") : 
List.of("s"),
+                    results.get(0).getPath());
+        }
+    }
+
     @Test
     public void testStructAccessPathUsesRootLocale() {
         Locale originalLocale = Locale.getDefault();
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/PruneNestedColumnTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/PruneNestedColumnTest.java
index ce5e499ebdc..6e4cc8635de 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/PruneNestedColumnTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/PruneNestedColumnTest.java
@@ -1928,6 +1928,18 @@ public class PruneNestedColumnTest extends 
TestWithFeService implements MemoPatt
                 type, new 
org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral(99));
         Assertions.assertNull(outOfBounds);
 
+        // These ordinals have low bits equal to one. Resolve the original 
value before pruning.
+        for (String value : List.of("4294967297", "-18446744073709551615")) {
+            
Assertions.assertNull(AccessPathExpressionCollector.resolveStructField(type,
+                    new 
org.apache.doris.nereids.trees.expressions.literal.LargeIntLiteral(
+                            new java.math.BigInteger(value))));
+        }
+        // The path must use the schema name, even when the query uses 
different letter case.
+        StructField caseInsensitive = 
AccessPathExpressionCollector.resolveStructField(type,
+                new 
org.apache.doris.nereids.trees.expressions.literal.VarcharLiteral("NOT_NULL_F"));
+        Assertions.assertNotNull(caseInsensitive);
+        Assertions.assertEquals("not_null_f", caseInsensitive.getName());
+
         // Non-literal returns null
         StructField nonLiteral = 
AccessPathExpressionCollector.resolveStructField(
                 type, NullLiteral.INSTANCE);
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
index 51bafdac632..c3a24eac4f7 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
@@ -36,6 +36,14 @@ import org.junit.jupiter.api.Test;
 
 class StringArithmeticTest {
 
+    @Test
+    void testSubstringIndexMinimumCount() {
+        // One character without a separator is enough. INT_MIN must select 
the full string.
+        IntegerLiteral minimum = new IntegerLiteral(Integer.MIN_VALUE);
+        Assertions.assertEquals(new StringLiteral("a"),
+                StringArithmetic.substringIndex(new StringLiteral("a"), new 
StringLiteral(","), minimum));
+    }
+
     @Test
     void testFieldMatchesFloatNaN() {
         IntegerLiteral result = (IntegerLiteral) 
StringArithmetic.fieldFloat(new FloatLiteral(Float.NaN),
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/types/StructOrdinalTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/types/StructOrdinalTest.java
new file mode 100644
index 00000000000..ac90a90005d
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/types/StructOrdinalTest.java
@@ -0,0 +1,71 @@
+// 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.nereids.types;
+
+import org.apache.doris.common.jmockit.Deencapsulation;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.rules.expression.rules.NormalizeElementAt;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.ElementAt;
+import org.apache.doris.nereids.trees.expressions.literal.BigIntLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLikeLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.LargeIntLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigInteger;
+import java.util.List;
+
+class StructOrdinalTest {
+    @Test
+    void normalizationMustNotBindWrappedOrdinals() {
+        StructType type = new StructType(List.of(new StructField("a", 
IntegerType.INSTANCE, true, "")));
+        SlotReference slot = new SlotReference("s", type);
+        // Call the rewrite directly. SQL analysis rejects these values before 
this rule runs.
+        for (String text : List.of("4294967297", "-4294967295",
+                "18446744073709551617", "-18446744073709551615")) {
+            ElementAt expression = new ElementAt(slot, new LargeIntLiteral(new 
BigInteger(text)));
+            Expression rewritten = 
Deencapsulation.invoke(NormalizeElementAt.class, "normalize", expression);
+            Assertions.assertSame(expression, rewritten);
+        }
+        Expression legal = Deencapsulation.invoke(NormalizeElementAt.class, 
"normalize",
+                new ElementAt(slot, new LargeIntLiteral(BigInteger.ONE)));
+        Assertions.assertEquals(new StringLiteral("a"), legal.child(1));
+    }
+
+    @Test
+    void preserveSelectorPrecision() {
+        // One field is enough. These out-of-range values have low 32 or 64 
bits equal to 1.
+        StructType type = new StructType(List.of(new StructField("a", 
IntegerType.INSTANCE, true, "")));
+        SlotReference slot = new SlotReference("s", type);
+        for (String text : List.of("4294967297", "-4294967295",
+                "18446744073709551617", "-18446744073709551615")) {
+            IntegerLikeLiteral index = new LargeIntLiteral(new 
BigInteger(text));
+            
Assertions.assertNull(type.getFieldByOrdinal(index.getBigDecimalValue()));
+            Assertions.assertThrows(AnalysisException.class, () -> new 
ElementAt(slot, index).getDataType());
+        }
+        Assertions.assertThrows(AnalysisException.class,
+                () -> new ElementAt(slot, new 
BigIntLiteral(4294967297L)).getDataType());
+        // A legal LARGEINT selector must retain the same field type.
+        Assertions.assertEquals(IntegerType.INSTANCE,
+                new ElementAt(slot, new 
LargeIntLiteral(BigInteger.ONE)).getDataType());
+    }
+}
diff --git a/regression-test/data/query_p0/join/test_bitmap_signed_probe.out 
b/regression-test/data/query_p0/join/test_bitmap_signed_probe.out
new file mode 100644
index 00000000000..66cb1b4125d
--- /dev/null
+++ b/regression-test/data/query_p0/join/test_bitmap_signed_probe.out
@@ -0,0 +1,30 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !in --
+1
+
+-- !not_in --
+-1
+
+-- !literal --
+-1
+1
+
+-- !null_probe --
+
+-- !mark --
+-1
+1
+
+-- !null_mark --
+1
+
+-- !expression --
+-1
+1
+
+-- !empty --
+-1
+1
+
+-- !unsigned_boundary --
+
diff --git 
a/regression-test/data/query_p0/sql_functions/struct_functions/test_struct_field_ordinal.out
 
b/regression-test/data/query_p0/sql_functions/struct_functions/test_struct_field_ordinal.out
new file mode 100644
index 00000000000..83f5861bd4a
--- /dev/null
+++ 
b/regression-test/data/query_p0/sql_functions/struct_functions/test_struct_field_ordinal.out
@@ -0,0 +1,4 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !valid --
+7      7       7
+
diff --git a/regression-test/data/query_p0/test_bitmap_nullable_element.out 
b/regression-test/data/query_p0/test_bitmap_nullable_element.out
new file mode 100644
index 00000000000..c5eae51b5d0
--- /dev/null
+++ b/regression-test/data/query_p0/test_bitmap_nullable_element.out
@@ -0,0 +1,9 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !contains --
+-1     \N
+1      true
+
+-- !remove --
+-1     \N
+1      
+
diff --git 
a/regression-test/data/query_p0/test_selected_function_parameters.out 
b/regression-test/data/query_p0/test_selected_function_parameters.out
new file mode 100644
index 00000000000..d57a24889dc
--- /dev/null
+++ b/regression-test/data/query_p0/test_selected_function_parameters.out
@@ -0,0 +1,19 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !substring_literal --
+a
+
+-- !substring_column --
+a
+
+-- !array_length --
+[2]    [2]     []      []
+
+-- !bitmap_zero --
+true   0
+
+-- !zero_window --
+0
+
+-- !ngram_one --
+1
+
diff --git 
a/regression-test/suites/query_p0/join/test_bitmap_signed_probe.groovy 
b/regression-test/suites/query_p0/join/test_bitmap_signed_probe.groovy
new file mode 100644
index 00000000000..07762c1dde4
--- /dev/null
+++ b/regression-test/suites/query_p0/join/test_bitmap_signed_probe.groovy
@@ -0,0 +1,52 @@
+// 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.
+
+suite("test_bitmap_signed_probe", "p0") {
+    // Reuse one two-row table for probes and bitmap input. The union contains 
only 1.
+    sql "drop table if exists test_bitmap_signed_probe"
+    sql """create table test_bitmap_signed_probe (k bigint not null, b bitmap 
bitmap_union)
+        aggregate key(k) distributed by hash(k) buckets 1
+        properties ("replication_num" = "1")"""
+    sql "insert into test_bitmap_signed_probe values (-1, to_bitmap(1)), (1, 
to_bitmap(1))"
+
+    // A negative SQL integer cannot equal an unsigned bitmap element. IN 
excludes -1;
+    // NOT IN keeps it. Neither predicate is an invalid direct bitmap_contains 
call.
+    order_qt_in """select k from test_bitmap_signed_probe
+        where k in (select b from test_bitmap_signed_probe)"""
+    order_qt_not_in """select k from test_bitmap_signed_probe
+        where k not in (select b from test_bitmap_signed_probe)"""
+    // Constants must also pass planning without the direct-call 
negative-element check.
+    order_qt_literal """select k from test_bitmap_signed_probe
+        where -1 not in (select b from test_bitmap_signed_probe)"""
+    // NULL probes must keep the existing NULL result and must not pass NOT IN.
+    order_qt_null_probe """select k from test_bitmap_signed_probe
+        where nullif(k, -1) not in (select b from test_bitmap_signed_probe)"""
+    // Exercise the mark-join path and a computed probe, not only a slot in a 
filter.
+    order_qt_mark """select k from test_bitmap_signed_probe
+        where k not in (select b from test_bitmap_signed_probe) or k = 1"""
+    // A NULL probe must also remain NULL inside a mark join; only k = 1 
passes the OR.
+    order_qt_null_mark """select k from test_bitmap_signed_probe
+        where nullif(k, -1) not in (select b from test_bitmap_signed_probe) or 
k = 1"""
+    order_qt_expression """select k from test_bitmap_signed_probe
+        where k - 1 not in (select b from test_bitmap_signed_probe)"""
+    // An empty union does not contain any non-NULL probe, including negative 
values.
+    order_qt_empty """select k from test_bitmap_signed_probe
+        where k not in (select b from test_bitmap_signed_probe where false)"""
+    // Clamping a probe must not make -1 match 0 or UINT64_MAX.
+    order_qt_unsigned_boundary """select k from test_bitmap_signed_probe
+        where k in (select bitmap_from_string('0,18446744073709551615'))"""
+}
diff --git 
a/regression-test/suites/query_p0/sql_functions/struct_functions/test_struct_field_ordinal.groovy
 
b/regression-test/suites/query_p0/sql_functions/struct_functions/test_struct_field_ordinal.groovy
new file mode 100644
index 00000000000..71dfedb73ed
--- /dev/null
+++ 
b/regression-test/suites/query_p0/sql_functions/struct_functions/test_struct_field_ordinal.groovy
@@ -0,0 +1,30 @@
+// 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.
+
+suite("test_struct_field_ordinal") {
+    // One field suffices. Each BIGINT has low 32 bits equal to 1.
+    // Both LARGEINTs also have low 64 bits equal to 1. Each selector must 
fail in analysis.
+    ["element_at(struct(7), 4294967297)", "struct(7)[-4294967295]",
+     "struct_element(struct(7), 18446744073709551617)", 
"struct(7)[-18446744073709551615]"].each { expr ->
+        test {
+            sql "select ${expr}"
+            exception "field index out of bound"
+        }
+    }
+    // Legal ordinals exercise both names and the subscript syntax without any 
table data.
+    order_qt_valid "select element_at(struct(7), 1), struct_element(struct(7), 
1), struct(7)[1]"
+}
diff --git 
a/regression-test/suites/query_p0/test_bitmap_nullable_element.groovy 
b/regression-test/suites/query_p0/test_bitmap_nullable_element.groovy
new file mode 100644
index 00000000000..b15349e01c9
--- /dev/null
+++ b/regression-test/suites/query_p0/test_bitmap_nullable_element.groovy
@@ -0,0 +1,31 @@
+// 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.
+
+suite("test_bitmap_nullable_element", "p0") {
+    // Two rows are required: one hidden -1 payload and one non-NULL element 
in the same block.
+    sql "drop table if exists test_bitmap_nullable_element"
+    sql """create table test_bitmap_nullable_element (k bigint not null)
+        duplicate key(k) distributed by hash(k) buckets 1
+        properties ("replication_num" = "1")"""
+    sql "insert into test_bitmap_nullable_element values (-1), (1)"
+
+    // NULLIF retains k below its null map. Both functions must ignore that 
hidden -1.
+    order_qt_contains """select k, bitmap_contains(to_bitmap(1), nullif(k, -1))
+        from test_bitmap_nullable_element"""
+    order_qt_remove """select k, bitmap_to_string(bitmap_remove(to_bitmap(1), 
nullif(k, -1)))
+        from test_bitmap_nullable_element"""
+}
diff --git 
a/regression-test/suites/query_p0/test_selected_function_parameters.groovy 
b/regression-test/suites/query_p0/test_selected_function_parameters.groovy
new file mode 100644
index 00000000000..f455a524123
--- /dev/null
+++ b/regression-test/suites/query_p0/test_selected_function_parameters.groovy
@@ -0,0 +1,80 @@
+// 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.
+
+suite("test_selected_function_parameters", "p0") {
+    // One stored row reaches the BE column paths. Each value is a boundary 
for its function.
+    sql "drop table if exists test_selected_function_parameters"
+    sql """create table test_selected_function_parameters (i int not null, n 
bigint not null)
+        duplicate key(i) distributed by hash(i) buckets 1
+        properties ("replication_num" = "1")"""
+    sql "insert into test_selected_function_parameters values (-2147483648, 
-1)"
+
+    // A one-character string has no delimiter. Both FE and BE must return the 
full string.
+    order_qt_substring_literal "select substring_index('a', ',', -2147483648)"
+    order_qt_substring_column """select substring_index('a', ',', i)
+        from test_selected_function_parameters"""
+
+    // Two elements are needed to make the zero-based start nonzero. Clamp 
length before addition.
+    // Zero and negative lengths keep the existing empty-array result.
+    order_qt_array_length """select array_slice([1,2], 2, 9223372036854775807),
+        array_slice([1,2], -1, 9223372036854775807), array_slice([1,2], 2, 0),
+        array_slice([1,2], 2, -1)"""
+
+    // One UINT64_MAX element exposes the old -1 alias. Check both functions 
with BE columns
+    // and with literals. A NULL bitmap must not hide an invalid known element 
during FE folding.
+    ["bitmap_contains", "bitmap_remove"].each { function ->
+        test {
+            sql """select ${function}(to_bitmap('18446744073709551615'), n)
+                from test_selected_function_parameters"""
+            exception "element must be >= 0"
+        }
+        test {
+            sql "select ${function}(to_bitmap('18446744073709551615'), -1)"
+            exception "element must be between 0"
+        }
+        test {
+            sql "select ${function}(null, -1)"
+            exception "element must be between 0"
+        }
+    }
+    order_qt_bitmap_zero """select bitmap_contains(to_bitmap(0), 0),
+        bitmap_count(bitmap_remove(to_bitmap(0), 0))"""
+
+    test {
+        // CRC32 has no FE executor. Its zero result makes BE receive -1 with 
one false event.
+        sql """select window_funnel_v2(cast(crc32('') as bigint) - 1, 
'default',
+            cast('2024-01-01' as datetime), false)"""
+        exception "window must be a positive integer"
+    }
+    test {
+        // The literal takes the FE validation path. The same negative window 
must fail there.
+        sql """select window_funnel_v2(-1, 'default',
+            cast('2024-01-01' as datetime), false)"""
+        exception "window must be a positive integer"
+    }
+    order_qt_zero_window """select window_funnel_v2(0, 'default',
+        cast('2024-01-01' as datetime), false)"""
+
+    // The negative LARGEINT has low 64 bits equal to 1. Check before 
narrowing to INT.
+    ["-18446744073709551615", "2147483648", "0"].each { size ->
+        test {
+            sql "select ngram_search('a', 'a', ${size})"
+            exception "gram_num must be a positive constant"
+        }
+    }
+    order_qt_ngram_one "select ngram_search('a', 'a', 1)"
+}


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

Reply via email to