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

mrhhsg 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 567cfa2694f [fix](fe) Align spill session variables with backend 
limits (#70876)
567cfa2694f is described below

commit 567cfa2694f5a5327e812b423672c61c5ed7efd9
Author: Jerry Hu <[email protected]>
AuthorDate: Tue Nov 24 15:06:20 2026 +0800

    [fix](fe) Align spill session variables with backend limits (#70876)
    
    ### Background
    
    Doris FE stores spill session variables and explicitly sends them to BE
    in query options. BE bounds several of these options before spill
    operators use them. The aggregation sink threshold controls proactive
    memory revocation after aggregation has started spilling.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #61212 (introduced the aggregation default mismatch)
    PR Type: Bugfix
    
    Problem Summary:
    
    FE initializes the aggregation spill sink threshold to 64 GiB instead of
    the protocol's 64 MiB, so BE silently caps it at 4 GiB. Six spill
    settings also retain out-of-range values in FE, making displayed and
    persisted values differ from execution. Restore the compiled aggregation
    default to 64 MiB and normalize FE assignments and historical reads to
    the existing BE ranges. Most of the diff is boundary and compatibility
    coverage.
    
    For the constructor's `spillAggregationSinkMemLimitBytes` value, the
    default-value test observes:
    
    | Before | After |
    |---|---|
    | 68719476736 (64 GiB) | 67108864 (64 MiB) |
    
    ### Details
    
    - **Change map:** Production code: +41/-13 in two FE files; tests:
    +309/-0; generated expected output: +234/-0; docs: 0. Production changes
    correct the default/descriptions and share normalization across
    assignment and deserialization.
    - **Frequency:** Always for the compiled aggregation default and
    parseable out-of-range values of the six settings.
    - **Root cause:** `SessionVariable` has an extra factor of 1024 in the
    aggregation initializer. FE storage paths omit the bounds already
    enforced by `RuntimeState` getters.
    - **Why existing tests missed it:** Unit tests in `VariableMgrTest`
    covered generic assignment/persistence, not spill defaults or effective
    ranges. The `aggregate_spill` regression checked query results, not
    configuration values or historical oversized settings.
    - **Fix:** Normalize three int and three long settings at FE storage
    boundaries, including SQL/GLOBAL, hints, forwarding, image JSON, job
    maps and journal replay. Preserve numeric parse failures and unrelated
    variables.
    - **Other paths and branches:** Historical and forwarded values use the
    same normalization. BE algorithms, Thrift fields and absent-field
    fallbacks are unchanged. #61212 introduced the initializer mismatch.
    Only master was validated; release branches were not assessed.
    - **Configs and defaults:** Existing variables remain runtime-settable
    through SESSION/GLOBAL and hints. Bounds and compiled defaults are
    below; only the aggregation default changes. For these six settings, 0
    and -1 retain their existing BE-effective lower-bound behavior.
    
    | Variable | Inclusive range | Compiled default |
    |---|---|---|
    | `spill_hash_join_partition_count` | [2, 32] | 4 |
    | `spill_aggregation_partition_count` | [2, 32] | 4 |
    | `spill_repartition_max_depth` | [1, 128] | 8 |
    | `spill_buffer_size_bytes` | [1 MiB, 256 MiB] | 8 MiB |
    | `spill_aggregation_sink_mem_limit_bytes` | [1 MiB, 4 GiB] | 64 MiB |
    | `spill_sort_merge_mem_limit_bytes` | [1 MiB, 4 GiB] | 64 MiB |
    
    - **Behavior change:** FE displays and persists normalized values.
    Historical 64 GiB aggregation values become 4 GiB, preserving their
    prior effective value. The 64 MiB default applies without a restored
    GLOBAL override or after explicit `SET
    spill_aggregation_sink_mem_limit_bytes=DEFAULT`; new and reset
    connections still inherit GLOBAL settings. This is not an initial spill
    trigger or query memory limit. The lower default may change revocation
    and spill I/O frequency; explicitly setting 4294967296 retains the old
    effective threshold.
    
    ### Testing
    
    All runs below were local:
    
    - Baseline `SessionVariableSpillContractTest`: 34 tests, 22 assertion
    failures, 0 errors. After the fix, all 34 pass.
    - `bash run-fe-ut.sh --run
    
org.apache.doris.qe.SessionVariableSpillContractTest,org.apache.doris.qe.VariableMgrTest,org.apache.doris.qe.SessionVariableParallelismTest`:
    61 tests passed, no failures/errors/skips.
    - `DISABLE_JAVA_CHECK_STYLE=OFF bash build.sh --fe -j 16`: passed, 0
    Checkstyle violations.
    - `bash build.sh --be -j 24`: ASAN build passed.
    - `./run-regression-test.sh --conf "$REG_CONF" --run -d
    query_p0/session_variable -s test_spill_session_variable_ranges`: passed
    using an isolated local config, after runner generation with
    `-forceGenOut` and independent verification of all 78 output sections.
    - `./run-regression-test.sh --conf "$REG_CONF" --run -d spill_p0 -s
    aggregate_spill`: passed as a compatibility smoke test, not a
    threshold-performance test.
    - `git diff --check`: passed for the committed diff.
    
    ### Release note
    
    The compiled aggregation spill sink threshold is corrected to 64 MiB.
    Six spill settings now display and persist the bounded values used by
    BE. Existing saved aggregation values retain their prior effective
    behavior, and restored GLOBAL settings remain authoritative for new
    connections.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: Yes (update the session-variable
    reference in apache/doris-website with the ranges and aggregation
    default).
    - Pre-submission status: Partially verified: full CI, BE unit tests,
    mixed-version upgrades, S3 and spill workload performance were not run.
    
    ### AI Disclosure
    
    - Tool: Codex
    - Generated: Code, tests, and this description.
    - Human review: No human review is claimed.
---
 .../java/org/apache/doris/qe/SessionVariable.java  |  52 +++--
 .../main/java/org/apache/doris/qe/VariableMgr.java |   2 +-
 .../doris/qe/SessionVariableSpillContractTest.java | 215 +++++++++++++++++++
 .../java/org/apache/doris/qe/VariableMgrTest.java  |  43 ++++
 .../test_spill_session_variable_ranges.out         | 234 +++++++++++++++++++++
 .../test_spill_session_variable_ranges.groovy      |  51 +++++
 6 files changed, 584 insertions(+), 13 deletions(-)

diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
index 1410ffbc1ac..7ed07cf469e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
@@ -3531,10 +3531,13 @@ public class SessionVariable implements Serializable, 
Writable {
     @VarAttrDef.VarAttr(name = SPILL_BUFFER_SIZE_BYTES, fuzzy = true, 
needForward = true,
             description = "Maximum block size for spill writes (in bytes). 
Blocks larger than this threshold are "
                     + "split before writing to disk. Also controls per-file 
read buffer size during merge sort. "
-                    + "Default is 8MB.")
+                    + "Default is 8 MiB. Range is [1 MiB, 256 MiB]; "
+                    + "out-of-range values are clamped to the nearest bound.")
     public long spillBufferSizeBytes = 8L * 1024L * 1024L;
 
-    @VarAttrDef.VarAttr(name = SPILL_AGGREGATION_PARTITION_COUNT, needForward 
= true, fuzzy = true)
+    @VarAttrDef.VarAttr(name = SPILL_AGGREGATION_PARTITION_COUNT, needForward 
= true, fuzzy = true,
+            description = "Number of partitions for aggregation spill. Default 
is 4. Range is [2, 32]; "
+                    + "out-of-range values are clamped to the nearest bound.")
     public int spillAggregationPartitionCount = 4;
 
     @VarAttrDef.VarAttr(name = LOW_MEMORY_MODE_BUFFER_LIMIT, needForward = 
true, fuzzy = false)
@@ -3547,12 +3550,14 @@ public class SessionVariable implements Serializable, 
Writable {
     @VarAttrDef.VarAttr(name = SPILL_STREAMING_AGG_MEM_LIMIT, needForward = 
true, fuzzy = false)
     public long spillStreamingAggMemLimit = 268435456; //256MB
 
-    @VarAttrDef.VarAttr(name = SPILL_HASH_JOIN_PARTITION_COUNT, needForward = 
true, fuzzy = true)
+    @VarAttrDef.VarAttr(name = SPILL_HASH_JOIN_PARTITION_COUNT, needForward = 
true, fuzzy = true,
+            description = "Number of partitions for hash join spill. Default 
is 4. Range is [2, 32]; "
+                    + "out-of-range values are clamped to the nearest bound.")
     public int spillHashJoinPartitionCount = 4;
 
     @VarAttrDef.VarAttr(name = SPILL_REPARTITION_MAX_DEPTH, fuzzy = true, 
needForward = true,
             description = "Maximum depth for repartition recursion. When 
exceeded, repartitioning will stop. Default "
-                    + "is 8.")
+                    + "is 8. Range is [1, 128]; out-of-range values are 
clamped to the nearest bound.")
     public int spillRepartitionMaxDepth = 8;
 
     @VarAttrDef.VarAttr(name = SPILL_JOIN_BUILD_SINK_MEM_LIMIT_BYTES, fuzzy = 
true, needForward = true,
@@ -3561,9 +3566,11 @@ public class SessionVariable implements Serializable, 
Writable {
     public long spillJoinBuildSinkMemLimitBytes = 64L * 1024L * 1024L;
 
     @VarAttrDef.VarAttr(name = SPILL_AGGREGATION_SINK_MEM_LIMIT_BYTES, fuzzy = 
true, needForward = true,
-            description = "After spill is triggered, aggregation sink will 
proactively spill when revocable memory "
-                    + "exceeds this threshold (in bytes). Default is 64GB.")
-    public long spillAggregationSinkMemLimitBytes = 64L * 1024L * 1024L * 
1024L;
+            description = "After aggregation starts spilling, the sink 
proactively spills when revocable memory "
+                    + "reaches this threshold (in bytes), not a query memory 
limit or the initial spill trigger. "
+                    + "Default is 64 MiB. Range is [1 MiB, 4 GiB]; "
+                    + "out-of-range values are clamped to the nearest bound.")
+    public long spillAggregationSinkMemLimitBytes = 64L * 1024L * 1024L;
 
     @VarAttrDef.VarAttr(name = SPILL_SORT_SINK_MEM_LIMIT_BYTES, fuzzy = true, 
needForward = true,
             description = "After spill is triggered, sort sink will 
proactively spill when revocable memory "
@@ -3576,9 +3583,10 @@ public class SessionVariable implements Serializable, 
Writable {
     public long spillAnalyticSinkMemLimitBytes = 64L * 1024L * 1024L;
 
     @VarAttrDef.VarAttr(name = SPILL_SORT_MERGE_MEM_LIMIT_BYTES, fuzzy = true, 
needForward = true,
-            description = "After spill is triggered, total memory budget for 
the sort merge phase (in bytes). "
-                    + "Divided by spill_buffer_size_bytes gives the number of 
files that can be merged "
-                    + "in parallel. Default is 64MB.")
+            description = "Budget used to derive spill sort merge fan-in (in 
bytes), not a hard memory limit. "
+                    + "Query sort merges up to max(8, floor(budget / 
spill_buffer_size_bytes)) files at a time. "
+                    + "Default is 64 MiB. Range is [1 MiB, 4 GiB]; "
+                    + "out-of-range values are clamped to the nearest bound.")
     public long spillSortMergeMemLimitBytes = 64L * 1024L * 1024L;
 
     @VarAttrDef.VarAttr(name = SPILL_REVOCABLE_MEMORY_HIGH_WATERMARK_PERCENT, 
fuzzy = true)
@@ -6174,7 +6182,7 @@ public class SessionVariable implements Serializable, 
Writable {
                         field.set(this, normalizeIntValue(attr.name(), 
root.get(attr.name()).toString()));
                         break;
                     case "long":
-                        field.set(this, (Long) root.get(attr.name()));
+                        field.set(this, normalizeLongValue(attr.name(), (Long) 
root.get(attr.name())));
                         break;
                     case "float":
                         field.set(this, root.get(attr.name()));
@@ -6228,7 +6236,8 @@ public class SessionVariable implements Serializable, 
Writable {
                         field.set(this, normalizeIntValue(attr.name(), 
sessionVarMap.get(attr.name())));
                         break;
                     case "long":
-                        field.set(this, 
Long.valueOf(sessionVarMap.get(attr.name())));
+                        field.set(this, normalizeLongValue(attr.name(),
+                                
Long.parseLong(sessionVarMap.get(attr.name()))));
                         break;
                     case "float":
                         field.set(this, 
Float.valueOf(sessionVarMap.get(attr.name())));
@@ -6256,6 +6265,12 @@ public class SessionVariable implements Serializable, 
Writable {
         switch (name.toLowerCase(Locale.ROOT)) {
             case RUNTIME_FILTER_TYPE:
                 return (int) 
RuntimeFilterTypeHelper.normalizeDeprecatedRuntimeFilterTypes(intValue);
+            // Match the spill ranges enforced by RuntimeState getters.
+            case SPILL_HASH_JOIN_PARTITION_COUNT:
+            case SPILL_AGGREGATION_PARTITION_COUNT:
+                return Math.max(2, Math.min(intValue, 32));
+            case SPILL_REPARTITION_MAX_DEPTH:
+                return Math.max(1, Math.min(intValue, 128));
             // Historical and forwarded values bypass statement-time 
validation. Keep them valid
             // before SET_VAR saves the original value for restoration through 
the strict setters.
             case PARALLEL_PIPELINE_TASK_NUM:
@@ -6276,6 +6291,19 @@ public class SessionVariable implements Serializable, 
Writable {
         }
     }
 
+    static long normalizeLongValue(String name, long value) {
+        // Match the spill ranges enforced by RuntimeState getters.
+        switch (name.toLowerCase(Locale.ROOT)) {
+            case SPILL_BUFFER_SIZE_BYTES:
+                return Math.max(1024L * 1024, Math.min(value, 256L * 1024 * 
1024));
+            case SPILL_AGGREGATION_SINK_MEM_LIMIT_BYTES:
+            case SPILL_SORT_MERGE_MEM_LIMIT_BYTES:
+                return Math.max(1024L * 1024, Math.min(value, 4L * 1024 * 1024 
* 1024));
+            default:
+                return value;
+        }
+    }
+
     /**
      * Get all variables which need to forward along with statement.
      **/
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/VariableMgr.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/VariableMgr.java
index 26eceaa849a..9d0e33b68b6 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/VariableMgr.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/VariableMgr.java
@@ -294,7 +294,7 @@ public class VariableMgr {
                 field.setInt(obj, SessionVariable.normalizeIntValue(name, 
value));
                 break;
             case "long":
-                field.setLong(obj, Long.parseLong(value));
+                field.setLong(obj, SessionVariable.normalizeLongValue(name, 
Long.parseLong(value)));
                 break;
             case "float":
                 field.setFloat(obj, Float.parseFloat(value));
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/qe/SessionVariableSpillContractTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/qe/SessionVariableSpillContractTest.java
new file mode 100644
index 00000000000..8c4b766b522
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/qe/SessionVariableSpillContractTest.java
@@ -0,0 +1,215 @@
+// 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.qe;
+
+import org.apache.doris.analysis.SetType;
+import org.apache.doris.analysis.SetVar;
+import org.apache.doris.analysis.StringLiteral;
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.io.Text;
+import org.apache.doris.persist.GlobalVarPersistInfo;
+import org.apache.doris.thrift.TQueryOptions;
+
+import org.junit.jupiter.api.Assertions;
+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.MethodSource;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.util.Collections;
+import java.util.Map;
+import java.util.stream.Stream;
+
+class SessionVariableSpillContractTest {
+    private static final long MIB = 1024L * 1024;
+    private static final long GIB = 1024L * MIB;
+
+    private static Stream<Arguments> ranges() {
+        // Variable, minimum, interior value, maximum, default.
+        return Stream.of(
+                Arguments.of(SessionVariable.SPILL_HASH_JOIN_PARTITION_COUNT, 
2L, 5L, 32L, 4L),
+                
Arguments.of(SessionVariable.SPILL_AGGREGATION_PARTITION_COUNT, 2L, 5L, 32L, 
4L),
+                Arguments.of(SessionVariable.SPILL_REPARTITION_MAX_DEPTH, 1L, 
5L, 128L, 8L),
+                Arguments.of(SessionVariable.SPILL_BUFFER_SIZE_BYTES, MIB, 2 * 
MIB, 256 * MIB, 8 * MIB),
+                
Arguments.of(SessionVariable.SPILL_AGGREGATION_SINK_MEM_LIMIT_BYTES, MIB, 2 * 
MIB, 4 * GIB, 64 * MIB),
+                Arguments.of(SessionVariable.SPILL_SORT_MERGE_MEM_LIMIT_BYTES, 
MIB, 2 * MIB, 4 * GIB, 64 * MIB));
+    }
+
+    @Test
+    void aggregationDefaultAgreesWithProtocolDefault() {
+        SessionVariable session = new SessionVariable();
+        Assertions.assertEquals(64 * MIB, 
session.spillAggregationSinkMemLimitBytes);
+        Assertions.assertEquals(new 
TQueryOptions().getSpillAggregationSinkMemLimitBytes(),
+                session.toThrift().getSpillAggregationSinkMemLimitBytes());
+        
Assertions.assertTrue(session.toThrift().isSetSpillAggregationSinkMemLimitBytes());
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("ranges")
+    void defaultsAndReset(String name, long min, long interior, long max, long 
defaultValue) throws Exception {
+        SessionVariable session = new SessionVariable();
+        assertStoredValue(session, name, defaultValue);
+        set(session, name, interior);
+        VariableMgr.setVar(session, new SetVar(SetType.SESSION, name, null));
+        assertStoredValue(session, name, defaultValue);
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("ranges")
+    void setStoresAndForwardsEffectiveValue(String name, long min, long 
interior, long max, long defaultValue)
+            throws Exception {
+        long[][] samples = {{min - 1, min}, {min, min}, {interior, interior}, 
{max, max},
+                {max + 1, max}, {0, min}, {-1, min}};
+        SessionVariable session = new SessionVariable();
+        for (long[] sample : samples) {
+            set(session, name, sample[0]);
+            assertStoredValue(session, name, sample[1]);
+            SessionVariable forwarded = new SessionVariable();
+            
forwarded.setForwardedSessionVariables(session.getForwardVariables());
+            assertStoredValue(forwarded, name, sample[1]);
+        }
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("ranges")
+    void historicalReadPathsAndHintRestoration(String name, long min, long 
interior, long max, long defaultValue)
+            throws Exception {
+        long[][] samples = {{max + 1, max}, {0, min}, {-1, min}};
+        for (long[] sample : samples) {
+            Map<String, String> raw = Collections.singletonMap(name, 
Long.toString(sample[0]));
+            SessionVariable fromJson = new SessionVariable();
+            fromJson.readFromJson("{\"" + name + "\":" + sample[0] + "}");
+            assertRestoredValue(fromJson, name, interior, sample[1]);
+
+            SessionVariable fromMap = new SessionVariable();
+            fromMap.readFromMap(raw);
+            assertRestoredValue(fromMap, name, interior, sample[1]);
+
+            SessionVariable forwarded = new SessionVariable();
+            forwarded.setForwardedSessionVariables(raw);
+            assertRestoredValue(forwarded, name, interior, sample[1]);
+        }
+    }
+
+    @Test
+    void historicalAggregationDefaultKeepsItsEffectiveValue() throws Exception 
{
+        String name = SessionVariable.SPILL_AGGREGATION_SINK_MEM_LIMIT_BYTES;
+        Map<String, String> raw = Collections.singletonMap(name, 
Long.toString(64 * GIB));
+        SessionVariable fromJson = new SessionVariable();
+        fromJson.readFromJson("{\"" + name + "\":" + 64 * GIB + "}");
+        assertRestoredValue(fromJson, name, 64 * MIB, 4 * GIB);
+        SessionVariable fromMap = new SessionVariable();
+        fromMap.readFromMap(raw);
+        assertRestoredValue(fromMap, name, 64 * MIB, 4 * GIB);
+        SessionVariable forwarded = new SessionVariable();
+        forwarded.setForwardedSessionVariables(raw);
+        assertRestoredValue(forwarded, name, 64 * MIB, 4 * GIB);
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("ranges")
+    void absentKeysPreserveExistingValue(String name, long min, long interior, 
long max, long defaultValue)
+            throws Exception {
+        SessionVariable session = new SessionVariable();
+        set(session, name, interior);
+        session.readFromJson("{}");
+        session.readFromMap(Collections.emptyMap());
+        session.setForwardedSessionVariables(Collections.emptyMap());
+        assertStoredValue(session, name, interior);
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("ranges")
+    void invalidNumbersStillFailWithoutChangingValue(String name, long min, 
long interior, long max, long defaultValue)
+            throws Exception {
+        SessionVariable session = new SessionVariable();
+        set(session, name, interior);
+        boolean isInt = VariableMgr.getVarContext(name).getField().getType() 
== int.class;
+        String overflow = isInt ? "2147483648" : "9223372036854775808";
+        for (String invalid : new String[] {"not_an_integer", "1.5", 
overflow}) {
+            Assertions.assertThrows(DdlException.class, () -> 
VariableMgr.setVar(session,
+                    new SetVar(SetType.SESSION, name, new 
StringLiteral(invalid))), name);
+            assertStoredValue(session, name, interior);
+        }
+        set(session, name, isInt ? Integer.MIN_VALUE : Long.MIN_VALUE);
+        assertStoredValue(session, name, min);
+        set(session, name, isInt ? Integer.MAX_VALUE : Long.MAX_VALUE);
+        assertStoredValue(session, name, max);
+    }
+
+    @Test
+    void historicalGlobalEditLogNormalizesBeforeNewSessions() throws Exception 
{
+        SessionVariable defaults = VariableMgr.getDefaultSessionVariable();
+        long aggregationBefore = defaults.spillAggregationSinkMemLimitBytes;
+        int partitionBefore = defaults.spillAggregationPartitionCount;
+        try {
+            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+            Text.writeString(new DataOutputStream(bytes), 
"{\"spill_aggregation_sink_mem_limit_bytes\":68719476736,"
+                    + "\"spill_aggregation_partition_count\":64}");
+            GlobalVarPersistInfo info = GlobalVarPersistInfo.read(
+                    new DataInputStream(new 
ByteArrayInputStream(bytes.toByteArray())));
+            VariableMgr.replayGlobalVariableV2(info, false);
+            SessionVariable session = VariableMgr.newSessionVariable();
+            assertStoredValue(session, 
SessionVariable.SPILL_AGGREGATION_SINK_MEM_LIMIT_BYTES, 4 * GIB);
+            assertStoredValue(session, 
SessionVariable.SPILL_AGGREGATION_PARTITION_COUNT, 32);
+        } finally {
+            defaults.spillAggregationSinkMemLimitBytes = aggregationBefore;
+            defaults.spillAggregationPartitionCount = partitionBefore;
+        }
+    }
+
+    @Test
+    void unrelatedLongVariablesAreNotNormalized() throws Exception {
+        SessionVariable session = new SessionVariable();
+        String name = SessionVariable.SPILL_JOIN_BUILD_SINK_MEM_LIMIT_BYTES;
+        set(session, name, 64 * GIB);
+        assertStoredValue(session, name, 64 * GIB);
+        session.readFromJson("{\"" + name + "\":0}");
+        assertStoredValue(session, name, 0);
+        session.readFromMap(Collections.singletonMap(name, "-1"));
+        assertStoredValue(session, name, -1);
+    }
+
+    private static void set(SessionVariable session, String name, long value) 
throws DdlException {
+        VariableMgr.setVar(session, new SetVar(SetType.SESSION, name, new 
StringLiteral(Long.toString(value))));
+    }
+
+    private static void assertStoredValue(SessionVariable session, String 
name, long expected) throws Exception {
+        Assertions.assertEquals(expected,
+                ((Number) 
VariableMgr.getVarContext(name).getField().get(session)).longValue(), name);
+        Assertions.assertEquals(expected, ((Number) 
session.toJson().get(name)).longValue(), name);
+        TQueryOptions options = session.toThrift();
+        TQueryOptions._Fields field = TQueryOptions._Fields.findByName(name);
+        Assertions.assertTrue(options.isSet(field), name);
+        Assertions.assertEquals(expected, ((Number) 
options.getFieldValue(field)).longValue(), name);
+        Assertions.assertEquals(Long.toString(expected), 
session.getForwardVariables().get(name), name);
+    }
+
+    private static void assertRestoredValue(SessionVariable session, String 
name, long temporary, long expected)
+            throws Exception {
+        assertStoredValue(session, name, expected);
+        Assertions.assertTrue(session.setVarOnce(name, 
Long.toString(temporary)), name);
+        assertStoredValue(session, name, temporary);
+        VariableMgr.revertSessionValue(session);
+        assertStoredValue(session, name, expected);
+    }
+}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/VariableMgrTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/qe/VariableMgrTest.java
index e4be2f342cb..bac6680fafd 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/VariableMgrTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/VariableMgrTest.java
@@ -89,6 +89,49 @@ public class VariableMgrTest extends TestWithFeService {
         Assertions.assertEquals(7890, 
VariableMgr.newSessionVariable().getMaxExecMemByte());
     }
 
+    @Test
+    public void testGlobalSpillVariablesPersistNormalizedValues() throws 
Exception {
+        String[][] samples = {
+                {SessionVariable.SPILL_AGGREGATION_SINK_MEM_LIMIT_BYTES, 
"68719476736", "4294967296"},
+                {SessionVariable.SPILL_HASH_JOIN_PARTITION_COUNT, "64", "32"},
+                {SessionVariable.SPILL_AGGREGATION_PARTITION_COUNT, "1", "2"},
+                {SessionVariable.SPILL_REPARTITION_MAX_DEPTH, "256", "128"},
+                {SessionVariable.SPILL_BUFFER_SIZE_BYTES, "1024", "1048576"},
+                {SessionVariable.SPILL_SORT_MERGE_MEM_LIMIT_BYTES, 
"8589934592", "4294967296"}
+        };
+        for (String[] sample : samples) {
+            String name = sample[0];
+            String originalGlobal = VariableMgr.getVarContext(name).getField()
+                    .get(VariableMgr.getDefaultSessionVariable()).toString();
+            String originalSession = VariableMgr.getVarContext(name).getField()
+                    .get(connectContext.getSessionVariable()).toString();
+            try {
+                SetOptionsCommand stmt = (SetOptionsCommand) 
UtFrameUtils.parseStmt(
+                        "set global " + name + "=" + sample[1], 
connectContext);
+                stmt.run(connectContext, null);
+                Assertions.assertEquals(sample[2], 
VariableMgr.getVarContext(name).getField()
+                        .get(VariableMgr.newSessionVariable()).toString());
+                Assertions.assertEquals(sample[2], 
VariableMgr.getVarContext(name).getField()
+                        .get(connectContext.getSessionVariable()).toString());
+
+                GlobalVarPersistInfo info = new GlobalVarPersistInfo(
+                        VariableMgr.getDefaultSessionVariable(), 
Lists.newArrayList(name));
+                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+                info.write(new DataOutputStream(bytes));
+                GlobalVarPersistInfo restored = GlobalVarPersistInfo.read(
+                        new DataInputStream(new 
ByteArrayInputStream(bytes.toByteArray())));
+                SessionVariable fromLog = new SessionVariable();
+                fromLog.readFromJson(restored.getPersistJsonString());
+                Assertions.assertEquals(sample[2], 
VariableMgr.getVarContext(name).getField().get(fromLog).toString());
+            } finally {
+                VariableMgr.setVar(connectContext.getSessionVariable(),
+                        new SetVar(SetType.GLOBAL, name, new 
StringLiteral(originalGlobal)));
+                VariableMgr.setVar(connectContext.getSessionVariable(),
+                        new SetVar(SetType.SESSION, name, new 
StringLiteral(originalSession)));
+            }
+        }
+    }
+
     @Test
     public void testReadOnly() {
         // Set global variable
diff --git 
a/regression-test/data/query_p0/session_variable/test_spill_session_variable_ranges.out
 
b/regression-test/data/query_p0/session_variable/test_spill_session_variable_ranges.out
new file mode 100644
index 00000000000..376626bcbfc
--- /dev/null
+++ 
b/regression-test/data/query_p0/session_variable/test_spill_session_variable_ranges.out
@@ -0,0 +1,234 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !spill_hash_join_partition_count_0 --
+2
+
+-- !spill_hash_join_partition_count_1 --
+2
+
+-- !spill_hash_join_partition_count_2 --
+5
+
+-- !spill_hash_join_partition_count_3 --
+32
+
+-- !spill_hash_join_partition_count_4 --
+32
+
+-- !spill_hash_join_partition_count_5 --
+2
+
+-- !spill_hash_join_partition_count_6 --
+2
+
+-- !spill_hash_join_partition_count_7 --
+32
+
+-- !spill_hash_join_partition_count_show --
+spill_hash_join_partition_count        32      4       1
+
+-- !spill_hash_join_partition_count_hint --
+32
+
+-- !spill_hash_join_partition_count_restored --
+5
+
+-- !spill_hash_join_partition_count_unchanged_after_invalid --
+5
+
+-- !spill_hash_join_partition_count_default --
+4
+
+-- !spill_aggregation_partition_count_0 --
+2
+
+-- !spill_aggregation_partition_count_1 --
+2
+
+-- !spill_aggregation_partition_count_2 --
+5
+
+-- !spill_aggregation_partition_count_3 --
+32
+
+-- !spill_aggregation_partition_count_4 --
+32
+
+-- !spill_aggregation_partition_count_5 --
+2
+
+-- !spill_aggregation_partition_count_6 --
+2
+
+-- !spill_aggregation_partition_count_7 --
+32
+
+-- !spill_aggregation_partition_count_show --
+spill_aggregation_partition_count      32      4       1
+
+-- !spill_aggregation_partition_count_hint --
+32
+
+-- !spill_aggregation_partition_count_restored --
+5
+
+-- !spill_aggregation_partition_count_unchanged_after_invalid --
+5
+
+-- !spill_aggregation_partition_count_default --
+4
+
+-- !spill_repartition_max_depth_0 --
+1
+
+-- !spill_repartition_max_depth_1 --
+1
+
+-- !spill_repartition_max_depth_2 --
+5
+
+-- !spill_repartition_max_depth_3 --
+128
+
+-- !spill_repartition_max_depth_4 --
+128
+
+-- !spill_repartition_max_depth_5 --
+1
+
+-- !spill_repartition_max_depth_6 --
+1
+
+-- !spill_repartition_max_depth_7 --
+128
+
+-- !spill_repartition_max_depth_show --
+spill_repartition_max_depth    128     8       1
+
+-- !spill_repartition_max_depth_hint --
+128
+
+-- !spill_repartition_max_depth_restored --
+5
+
+-- !spill_repartition_max_depth_unchanged_after_invalid --
+5
+
+-- !spill_repartition_max_depth_default --
+8
+
+-- !spill_buffer_size_bytes_0 --
+1048576
+
+-- !spill_buffer_size_bytes_1 --
+1048576
+
+-- !spill_buffer_size_bytes_2 --
+2097152
+
+-- !spill_buffer_size_bytes_3 --
+268435456
+
+-- !spill_buffer_size_bytes_4 --
+268435456
+
+-- !spill_buffer_size_bytes_5 --
+1048576
+
+-- !spill_buffer_size_bytes_6 --
+1048576
+
+-- !spill_buffer_size_bytes_7 --
+1048576
+
+-- !spill_buffer_size_bytes_show --
+spill_buffer_size_bytes        1048576 8388608 1
+
+-- !spill_buffer_size_bytes_hint --
+1048576
+
+-- !spill_buffer_size_bytes_restored --
+2097152
+
+-- !spill_buffer_size_bytes_unchanged_after_invalid --
+2097152
+
+-- !spill_buffer_size_bytes_default --
+8388608
+
+-- !spill_aggregation_sink_mem_limit_bytes_0 --
+1048576
+
+-- !spill_aggregation_sink_mem_limit_bytes_1 --
+1048576
+
+-- !spill_aggregation_sink_mem_limit_bytes_2 --
+2097152
+
+-- !spill_aggregation_sink_mem_limit_bytes_3 --
+4294967296
+
+-- !spill_aggregation_sink_mem_limit_bytes_4 --
+4294967296
+
+-- !spill_aggregation_sink_mem_limit_bytes_5 --
+1048576
+
+-- !spill_aggregation_sink_mem_limit_bytes_6 --
+1048576
+
+-- !spill_aggregation_sink_mem_limit_bytes_7 --
+4294967296
+
+-- !spill_aggregation_sink_mem_limit_bytes_show --
+spill_aggregation_sink_mem_limit_bytes 4294967296      67108864        1
+
+-- !spill_aggregation_sink_mem_limit_bytes_hint --
+4294967296
+
+-- !spill_aggregation_sink_mem_limit_bytes_restored --
+2097152
+
+-- !spill_aggregation_sink_mem_limit_bytes_unchanged_after_invalid --
+2097152
+
+-- !spill_aggregation_sink_mem_limit_bytes_default --
+67108864
+
+-- !spill_sort_merge_mem_limit_bytes_0 --
+1048576
+
+-- !spill_sort_merge_mem_limit_bytes_1 --
+1048576
+
+-- !spill_sort_merge_mem_limit_bytes_2 --
+2097152
+
+-- !spill_sort_merge_mem_limit_bytes_3 --
+4294967296
+
+-- !spill_sort_merge_mem_limit_bytes_4 --
+4294967296
+
+-- !spill_sort_merge_mem_limit_bytes_5 --
+1048576
+
+-- !spill_sort_merge_mem_limit_bytes_6 --
+1048576
+
+-- !spill_sort_merge_mem_limit_bytes_7 --
+4294967296
+
+-- !spill_sort_merge_mem_limit_bytes_show --
+spill_sort_merge_mem_limit_bytes       4294967296      67108864        1
+
+-- !spill_sort_merge_mem_limit_bytes_hint --
+4294967296
+
+-- !spill_sort_merge_mem_limit_bytes_restored --
+2097152
+
+-- !spill_sort_merge_mem_limit_bytes_unchanged_after_invalid --
+2097152
+
+-- !spill_sort_merge_mem_limit_bytes_default --
+67108864
diff --git 
a/regression-test/suites/query_p0/session_variable/test_spill_session_variable_ranges.groovy
 
b/regression-test/suites/query_p0/session_variable/test_spill_session_variable_ranges.groovy
new file mode 100644
index 00000000000..b26b4bbbb2c
--- /dev/null
+++ 
b/regression-test/suites/query_p0/session_variable/test_spill_session_variable_ranges.groovy
@@ -0,0 +1,51 @@
+// 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_spill_session_variable_ranges", "p0") {
+    // Variable, minimum, interior value, maximum, historical out-of-range 
value.
+    def ranges = [
+        ["spill_hash_join_partition_count", 2L, 5L, 32L, 64L],
+        ["spill_aggregation_partition_count", 2L, 5L, 32L, 64L],
+        ["spill_repartition_max_depth", 1L, 5L, 128L, 256L],
+        ["spill_buffer_size_bytes", 1048576L, 2097152L, 268435456L, 1024L],
+        ["spill_aggregation_sink_mem_limit_bytes", 1048576L, 2097152L, 
4294967296L, 68719476736L],
+        ["spill_sort_merge_mem_limit_bytes", 1048576L, 2097152L, 4294967296L, 
8589934592L]
+    ]
+    ranges.each { bounds ->
+        def (variable, minimum, interior, maximum, historical) = bounds
+        def saved = sql("SHOW VARIABLES LIKE '${variable}'")[0][1]
+        try {
+            [minimum - 1, minimum, interior, maximum, maximum + 1, 0L, -1L, 
historical].eachWithIndex { value, index ->
+                sql "SET SESSION ${variable}=${value}"
+                "order_qt_${variable}_${index}"("SELECT @@${variable}")
+            }
+            "order_qt_${variable}_show"("SHOW VARIABLES LIKE '${variable}'")
+            sql "SET SESSION ${variable}=${interior}"
+            "order_qt_${variable}_hint"("SELECT /*+ 
SET_VAR(${variable}=${historical}) */ @@${variable}")
+            "order_qt_${variable}_restored"("SELECT @@${variable}")
+            test {
+                sql "SET SESSION ${variable}='not_an_integer'"
+                exception "Incorrect argument type to variable '${variable}'"
+            }
+            "order_qt_${variable}_unchanged_after_invalid"("SELECT 
@@${variable}")
+            sql "SET SESSION ${variable}=DEFAULT"
+            "order_qt_${variable}_default"("SELECT @@${variable}")
+        } finally {
+            sql "SET SESSION ${variable}=${saved}"
+        }
+    }
+}


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

Reply via email to