You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by "jt2594838 (via GitHub)" <gi...@apache.org> on 2026/09/09 02:06:50 UTC

[PR] Refactor TSDataType switches to use TypeService [iotdb]

jt2594838 opened a new pull request, #18606:
URL: https://github.com/apache/iotdb/pull/18606

   ## What is changed
   
   - Refactor TSDataType switch handling into TypeService implementations.
   - Add an ArchUnit check that rejects TSDataType switch usage outside TypeService.
   - Update Tablet decoding and AlignedTVList WAL handling for TsFile 2.4.1-SNAPSHOT.
   - Merge the latest master branch changes.
   
   ## Validation
   
   - DataNode and related regression tests passed.
   - ArchUnit TSDataType switch checks passed without a baseline.
   - REST Chinese-locale test compilation passed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#issuecomment-5631143998

   ## [Codecov](https://app.codecov.io/gh/apache/iotdb/pull/18606?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `30.33769%` with `1279 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 43.46%. Comparing base ([`c2ead3b`](https://app.codecov.io/gh/apache/iotdb/commit/c2ead3be72f8944ef6c8d1349087cdb8377d0160?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`bda01e8`](https://app.codecov.io/gh/apache/iotdb/commit/bda01e82869503a7b74dec1cbf53fc1ad0bddb5c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 8 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/iotdb/pull/18606?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...gation/grouped/GroupedMaxMinByBaseAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedMaxMinByBaseAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZE1heE1pbkJ5QmFzZUFjY3VtdWxhdG9yLmphdmE=) | 0.00% | [103 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...apache/iotdb/rest/protocol/utils/TypeServices.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=external-service-impl%2Frest%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Frest%2Fprotocol%2Futils%2FTypeServices.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZXh0ZXJuYWwtc2VydmljZS1pbXBsL3Jlc3Qvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL3Jlc3QvcHJvdG9jb2wvdXRpbHMvVHlwZVNlcnZpY2VzLmphdmE=) | 0.00% | [67 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...aggregation/grouped/GroupedFirstByAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedFirstByAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZEZpcnN0QnlBY2N1bXVsYXRvci5qYXZh) | 0.00% | [58 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [.../aggregation/grouped/GroupedLastByAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedLastByAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZExhc3RCeUFjY3VtdWxhdG9yLmphdmE=) | 0.00% | [58 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...al/aggregation/grouped/GroupedModeAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedModeAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZE1vZGVBY2N1bXVsYXRvci5qYXZh) | 0.00% | [58 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...e/relational/aggregation/TableModeAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2FTableModeAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL1RhYmxlTW9kZUFjY3VtdWxhdG9yLmphdmE=) | 0.00% | [57 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...source/relational/aggregation/LastAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2FLastAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL0xhc3RBY2N1bXVsYXRvci5qYXZh) | 9.61% | [47 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...l/aggregation/grouped/GroupedFirstAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedFirstAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZEZpcnN0QWNjdW11bGF0b3IuamF2YQ==) | 25.80% | [46 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...al/aggregation/grouped/GroupedLastAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedLastAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZExhc3RBY2N1bXVsYXRvci5qYXZh) | 25.80% | [46 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...nal/aggregation/grouped/GroupedMinAccumulator.java](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&filepath=iotdb-core%2Fcalc-commons%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fiotdb%2Fcalc%2Fexecution%2Foperator%2Fsource%2Frelational%2Faggregation%2Fgrouped%2FGroupedMinAccumulator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aW90ZGItY29yZS9jYWxjLWNvbW1vbnMvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2lvdGRiL2NhbGMvZXhlY3V0aW9uL29wZXJhdG9yL3NvdXJjZS9yZWxhdGlvbmFsL2FnZ3JlZ2F0aW9uL2dyb3VwZWQvR3JvdXBlZE1pbkFjY3VtdWxhdG9yLmphdmE=) | 0.00% | [44 Missing :warning: ](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | ... and [72 more](https://app.codecov.io/gh/apache/iotdb/pull/18606?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #18606      +/-   ##
   ============================================
   + Coverage     42.71%   43.46%   +0.75%     
     Complexity      442      442              
   ============================================
     Files          5441     5452      +11     
     Lines        394511   390855    -3656     
     Branches      51718    50645    -1073     
   ============================================
   + Hits         168518   169892    +1374     
   + Misses       225993   220963    -5030     
   ```
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/iotdb/pull/18606?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 merged PR #18606:
URL: https://github.com/apache/iotdb/pull/18606


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r3965396128


##########
iotdb-client/isession/src/main/java/org/apache/iotdb/isession/TypeServices.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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.iotdb.isession;
+
+import org.apache.iotdb.rpc.IoTDBRpcDataSet;
+import org.apache.iotdb.rpc.StatementExecutionException;
+
+import org.apache.tsfile.read.common.Field;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+
+/** Type-specific RPC result readers that preserve primitive access without intermediate boxing. */
+final class TypeServices {
+
+  static final TypeService<FieldValueReader> FIELD_VALUE_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (dataSet, columnIndex, field) -> field.setBoolV(dataSet.getBoolean(columnIndex));
+            case INT32, DATE ->
+                (dataSet, columnIndex, field) -> field.setIntV(dataSet.getInt(columnIndex));
+            case INT64, TIMESTAMP ->
+                (dataSet, columnIndex, field) -> field.setLongV(dataSet.getLong(columnIndex));
+            case FLOAT ->
+                (dataSet, columnIndex, field) -> field.setFloatV(dataSet.getFloat(columnIndex));
+            case DOUBLE ->
+                (dataSet, columnIndex, field) -> field.setDoubleV(dataSet.getDouble(columnIndex));
+            case TEXT, BLOB, STRING, OBJECT ->
+                (dataSet, columnIndex, field) -> field.setBinaryV(dataSet.getBinary(columnIndex));
+            case ROW, UNKNOWN, VECTOR ->
+                (dataSet, columnIndex, field) -> {
+                  throw new UnSupportedDataTypeException(
+                      String.format("Data type %s is not supported.", type.getTypeEnum()));

Review Comment:
   This user-visible exception bypasses the module's English/Chinese message bundles, so Chinese-locale builds will still emit English. Add a matching constant to both `ISessionMessages` locale files and reference it here.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java:
##########
@@ -603,6 +603,10 @@ private DataNodeMiscMessages() {}
   public static final String INPUT_DOUBLE_INFINITY = "The input double value is Infinity";
   public static final String BOOLEAN_PARSE_ERROR =
       "The BOOLEAN should be true/TRUE, false/FALSE or 0/1";
+  public static final String DATA_TYPE_NOT_CONSISTENT_FMT =
+      "data type is not consistent, input %s, registered %s";
+  public static final String DATA_TYPE_NOT_CONSISTENT_WITH_CAUSE_FMT =
+      "data type is not consistent, input %s, registered %s because %s";

Review Comment:
   These new exception message keys do not follow the repository's generated exception-message naming convention. Rename them consistently in both locale files and update their call sites.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java:
##########
@@ -1541,6 +1541,12 @@ public final class DataNodePipeMessages {
   public static final String FAILED_TO_UNBIND_FROM_PIPE_TSFILE_TO =
       "Failed to unbind from pipe tsfile to tablets metrics, pipe map is not empty, pipe: {}";
 
+  // ---------------------------------------------------------------------------
+  // pipe – PipeRow
+  // ---------------------------------------------------------------------------
+  public static final String UNSUPPORTED_DATA_TYPE_FOR_COLUMN_FMT =
+      "unsupported data type %s for column %s";

Review Comment:
   This new exception message key does not follow the repository's generated exception-message naming convention. Rename it consistently in both locale files and update its call sites.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java:
##########
@@ -1393,6 +1407,8 @@ public final class DataNodeQueryMessages {
       "Error occurred during getting UDF access strategy";
   public static final String TRANSFORMUTILS_SHOULD_NOT_BE_INSTANTIATED =
       "TransformUtils should not be instantiated.";
+  public static final String INVALID_DATA_TYPE_FOR_STATE_WINDOW_STRATEGY =
+      "The data type of the state window strategy is not valid.";

Review Comment:
   This new exception message key does not follow the repository's generated naming convention. Rename it consistently in both locale files and update its call sites.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java:
##########
@@ -1020,6 +1032,8 @@ public final class DataNodeQueryMessages {
       "Unexpected expression: ";
   public static final String FAILED_TO_FETCH_SUBQUERY_RESULT =
       "Failed to Fetch Subquery Result.";
+  public static final String UNSUPPORTED_SCALAR_SUBQUERY_RESULT_DATA_TYPE_FMT =
+      "Unsupported data type for scalar subquery result: %s";

Review Comment:
   This new exception message key does not follow the repository's generated naming convention. Rename it consistently in both locale files and update its call sites.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -60,6 +60,9 @@ public final class LibraryUdfMessages {
   public static final String ALL_VALUES_ARE_NAN = "All values are NaN";
 
   // UDFEnvelopeAnalysis
+  public static final String FREQUENCY_MUST_BE_POSITIVE = "The param 'frequency' must > 0.";
+  public static final String AMPLIFICATION_MUST_BE_AT_LEAST_1 =
+      "The param 'amplification' must >= 1.";

Review Comment:
   The English validation text is ungrammatical. Use “must be greater than” / “must be greater than or equal to” so the errors read clearly to users.



##########
iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/TSDataTypeSwitchArchitectureTest.java:
##########
@@ -0,0 +1,39 @@
+/*
+ * 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.iotdb.db.utils;
+
+import com.tngtech.archunit.core.importer.ClassFileImporter;
+import com.tngtech.archunit.core.importer.ImportOption;
+import org.junit.Test;
+
+public class TSDataTypeSwitchArchitectureTest {
+
+  @Test
+  public void productionCodeMustUseTypeService() {
+    // Scan IoTDB production classes on this module's classpath, including its dependencies.
+    // Do not freeze violations or swallow failures: existing violations must fail this test too.
+    TSDataTypeSwitchRule.RULE.check(
+        new ClassFileImporter()
+            .withImportOption(new ImportOption.DoNotIncludeTests())
+            // Avoid building the entire server dependency graph: only switch owners need checking.
+            .withImportOption(location -> TSDataTypeSwitchRule.hasSwitch(location.asURI()))
+            .importPackages("org.apache.iotdb"));

Review Comment:
   This check only imports production classes visible from the datanode test classpath, so it does not enforce the stated repository-wide rule in modules such as `library-udf`, JDBC, or examples. A future `TSDataType` switch in an unreferenced module will pass; place equivalent checks in each independent module or run the rule from an aggregate test classpath.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -100,6 +103,16 @@ public final class LibraryUdfMessages {
   // UDAFPatternMatch, UDAFDTWMatch
   public static final String UNSUPPORTED_DATATYPE = "Unsupported datatype %s";
 
+  // ExactOrderStatistics
+  public static final String UNSUPPORTED_DATA_TYPE = "Unsupported data type: %s";
+
+  // UDAFQuantile
+  public static final String UNSUPPORTED_DATA_TYPE_IN_QUANTILE = "Unsupported data type";

Review Comment:
   These newly added message keys also use ad hoc names rather than the repository's generated exception-message naming convention. Rename them consistently in both locale files and update their call sites.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -60,6 +60,9 @@ public final class LibraryUdfMessages {
   public static final String ALL_VALUES_ARE_NAN = "All values are NaN";
 
   // UDFEnvelopeAnalysis
+  public static final String FREQUENCY_MUST_BE_POSITIVE = "The param 'frequency' must > 0.";
+  public static final String AMPLIFICATION_MUST_BE_AT_LEAST_1 =
+      "The param 'amplification' must >= 1.";

Review Comment:
   These newly introduced message keys do not follow the repository's generated exception-message naming convention (prefix plus normalized text and hash). Rename the new keys consistently in both locale files and their call sites to avoid collisions and keep generated message keys uniform.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -100,6 +103,16 @@ public final class LibraryUdfMessages {
   // UDAFPatternMatch, UDAFDTWMatch
   public static final String UNSUPPORTED_DATATYPE = "Unsupported datatype %s";
 
+  // ExactOrderStatistics
+  public static final String UNSUPPORTED_DATA_TYPE = "Unsupported data type: %s";
+
+  // UDAFQuantile
+  public static final String UNSUPPORTED_DATA_TYPE_IN_QUANTILE = "Unsupported data type";
+  public static final String QUANTILE_K_MUST_BE_AT_LEAST_100 =
+      "Size K has to be greater than or equal to 100.";
+  public static final String QUANTILE_RANK_MUST_BE_IN_RANGE =
+      "rank has to be greater than 0 and less than or equal to 1.";

Review Comment:
   These newly added validation-message keys do not follow the repository's generated exception-message naming convention. Rename them consistently in both locale files and update their call sites.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java:
##########
@@ -528,6 +528,18 @@ public final class DataNodeQueryMessages {
       "TIMESTAMP does not support REGEXP/NOT REGEXP";
   public static final String GROUPBYTIME_FILTER_CANNOT_EXIST_IN_VALUE_FILTER =
       "GroupByTime filter cannot exist in value filter.";
+  public static final String VALUE_CANNOT_BE_CAST_TO_DATA_TYPE_FMT =
+      "\"%s\" cannot be cast to [%s]";
+  public static final String UNSUPPORTED_DATA_TYPE_FMT =
+      "Unsupported data type %s";

Review Comment:
   The new message keys use ad hoc `_FMT` names instead of the repository's generated exception-message naming convention. Rename all newly added keys in this block consistently in both locale files and their call sites.
   
   This issue also appears in the following locations of the same file:
   - line 535
   - line 539



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4023237185


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedVarianceAccumulator.java:
##########
@@ -52,6 +55,10 @@ public class GroupedVarianceAccumulator implements GroupedAccumulator {
   public GroupedVarianceAccumulator(
       TSDataType seriesDataType, VarianceAccumulator.VarianceType varianceType) {
     this.seriesDataType = seriesDataType;
+    this.doubleValueConverter =
+        TypeServices.NUMERIC_BATCH_READER_SERVICE

Review Comment:
   Use the native numeric batch reader for grouped variance, retaining the existing recurrence callback and logical row order rather than changing the numerical algorithm. NumericMomentBatchTest covers moments/variance across tree, table and grouped implementations, including masked/null inputs. This candidate was retained after mixed-type and fixed-DOUBLE measurements; related candidates with measured regressions were restored.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/TableCentralMomentAccumulator.java:
##########
@@ -51,47 +54,21 @@ public class TableCentralMomentAccumulator implements TableAccumulator {
   public TableCentralMomentAccumulator(
       TSDataType seriesDataType, CentralMomentAccumulator.MomentType momentType) {
     this.seriesDataType = seriesDataType;
+    this.doubleValueConverter =
+        TypeServices.NUMERIC_BATCH_READER_SERVICE

Review Comment:
   Use the native numeric batch reader for table central moment, retaining the existing recurrence callback and logical row order rather than changing the numerical algorithm. NumericMomentBatchTest covers moments/variance across tree, table and grouped implementations, including masked/null inputs. This candidate was retained after mixed-type and fixed-DOUBLE measurements; related candidates with measured regressions were restored.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/rate/GroupedNaiveDeltaAccumulator.java:
##########
@@ -59,31 +61,28 @@ public void setGroupCount(long groupCount) {
   @Override
   public void addInput(int[] groupIds, Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.DELTA);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      int groupId = groupIds[position];
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.DELTA);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.DELTA, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(
-              arguments[2], position, RateFunctionType.DELTA, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(
-              arguments[3], position, RateFunctionType.DELTA, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.DELTA, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(groupId, currentWindowStart, currentWindowEnd);
-      samples.add(groupId, time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   GroupedNaiveDeltaAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/rate/GroupedNaiveIncreaseAccumulator.java:
##########
@@ -59,31 +61,28 @@ public void setGroupCount(long groupCount) {
   @Override
   public void addInput(int[] groupIds, Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.INCREASE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      int groupId = groupIds[position];
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.INCREASE);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.INCREASE, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(
-              arguments[2], position, RateFunctionType.INCREASE, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(
-              arguments[3], position, RateFunctionType.INCREASE, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.INCREASE, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(groupId, currentWindowStart, currentWindowEnd);
-      samples.add(groupId, time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   GroupedNaiveIncreaseAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/rate/GroupedNaiveIrateAccumulator.java:
##########
@@ -58,22 +60,19 @@ public void setGroupCount(long groupCount) {
   @Override
   public void addInput(int[] groupIds, Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.IRATE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      int groupId = groupIds[position];
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.IRATE);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.IRATE, 2);
-      samples.add(groupId, time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   GroupedNaiveIrateAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/rate/GroupedNaiveRateAccumulator.java:
##########
@@ -59,28 +61,28 @@ public void setGroupCount(long groupCount) {
   @Override
   public void addInput(int[] groupIds, Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.RATE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      int groupId = groupIds[position];
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.RATE);
-      long time =
-          RateFunctionValidation.readRequiredTime(arguments[1], position, RateFunctionType.RATE, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(arguments[2], position, RateFunctionType.RATE, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(arguments[3], position, RateFunctionType.RATE, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.RATE, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(groupId, currentWindowStart, currentWindowEnd);
-      samples.add(groupId, time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   GroupedNaiveRateAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/rate/GroupedOrderedIrateAccumulator.java:
##########
@@ -68,22 +70,19 @@ public void setGroupCount(long groupCount) {
   @Override
   public void addInput(int[] groupIds, Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.IRATE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      int groupId = groupIds[position];
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.IRATE);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.IRATE, 2);
-      update(groupId, time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   GroupedOrderedIrateAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/NaiveDeltaAccumulator.java:
##########
@@ -58,30 +60,27 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.DELTA);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.DELTA);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.DELTA, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(
-              arguments[2], position, RateFunctionType.DELTA, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(
-              arguments[3], position, RateFunctionType.DELTA, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.DELTA, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(currentWindowStart, currentWindowEnd);
-      samples.add(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   NaiveDeltaAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4023489570


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/aggregation/VarianceAccumulator.java:
##########
@@ -52,37 +55,31 @@ public enum VarianceType {
 
   public VarianceAccumulator(TSDataType seriesDataType, VarianceType varianceType) {
     this.seriesDataType = seriesDataType;
+    this.doubleValueConverter =
+        TypeServices.NUMERIC_BATCH_READER_SERVICE

Review Comment:
   Use the native numeric batch reader for tree variance, retaining the existing recurrence callback and logical row order rather than changing the numerical algorithm. NumericMomentBatchTest covers moments/variance across tree, table and grouped implementations, including masked/null inputs. This candidate was retained after mixed-type and fixed-DOUBLE measurements; related candidates with measured regressions were restored.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "Caideyipi (via GitHub)" <gi...@apache.org>.
Caideyipi commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4043789477


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/TypeServices.java:
##########
@@ -0,0 +1,4478 @@
+/*
+ * 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.iotdb.db.utils;
+
+import org.apache.iotdb.calc.exception.QueryProcessException;
+import org.apache.iotdb.calc.execution.aggregation.Accumulator;
+import org.apache.iotdb.calc.execution.aggregation.BinaryModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.BooleanModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.DoubleModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.FloatModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.IntModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.LongModeAccumulator;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.TypeServices.PrimitiveColumnValueSetter;
+import org.apache.iotdb.calc.utils.constant.SqlConstant;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.exception.pipe.PipeRuntimeNonCriticalException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
+import org.apache.iotdb.db.pipe.processor.aggregate.TimeSeriesRuntimeState;
+import org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.AbstractSameTypeNumericOperator;
+import org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.WindowOutput;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBinaryWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBooleanWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowParameter;
+import org.apache.iotdb.db.queryengine.statistics.StatisticsManager;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.ArithmeticNegationTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.InTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.DiffFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.RoundFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.datastructure.util.ValueRecorder;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.IWALByteBufferView;
+import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALWriteUtils;
+import org.apache.iotdb.db.storageengine.rescon.memory.PrimitiveArrayManager;
+import org.apache.iotdb.db.utils.datastructure.AlignedTVList;
+import org.apache.iotdb.db.utils.datastructure.BinaryTVList;
+import org.apache.iotdb.db.utils.datastructure.BooleanTVList;
+import org.apache.iotdb.db.utils.datastructure.DoubleTVList;
+import org.apache.iotdb.db.utils.datastructure.FloatTVList;
+import org.apache.iotdb.db.utils.datastructure.IntTVList;
+import org.apache.iotdb.db.utils.datastructure.LongTVList;
+import org.apache.iotdb.db.utils.datastructure.TVList;
+import org.apache.iotdb.db.utils.windowing.window.EvictableBatchList;
+import org.apache.iotdb.db.utils.windowing.window.WindowImpl;
+import org.apache.iotdb.pipe.api.access.Row;
+import org.apache.iotdb.rpc.RpcUtils;
+
+import com.google.common.io.BaseEncoding;
+import com.sun.jna.platform.win32.OaIdl;
+import com.sun.jna.platform.win32.OleAuto;
+import com.sun.jna.platform.win32.Variant;
+import com.sun.jna.platform.win32.WTypes;
+import com.sun.jna.platform.win32.WinDef;
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.encoding.decoder.Decoder;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.external.commons.lang3.StringUtils;
+import org.apache.tsfile.file.metadata.IChunkMetadata;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.file.metadata.statistics.DateStatistics;
+import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.BatchData;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.read.common.block.column.BinaryColumnBuilder;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.read.filter.basic.Filter;
+import org.apache.tsfile.read.reader.series.PaginationController;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.RamUsageEstimator;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ValueChunkWriter;
+import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.sql.Date;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import java.util.function.ToDoubleFunction;
+import java.util.function.ToIntFunction;
+import java.util.function.ToLongFunction;
+
+public class TypeServices {
+
+  public static final int DEFAULT_DATE =
+      DateUtils.parseDateExpressionToInt(LocalDate.of(1970, 1, 1));
+  private static final LocalDate EMPTY_LOCAL_DATE = LocalDate.of(1000, 1, 1);
+
+  public static final class Memory {
+
+    public static final TypeService<LongSupplier> STATEMENT_VALUE_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::estimateValueSize;
+              case TEXT, BLOB, STRING ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        CalcMessages.UNKNOWN_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToLongFunction<Object>> INSERT_NODE_VALUE_SIZE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  value ->
+                      RamUsageEstimator.alignObjectSize(
+                          type.estimateValueSize() + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER);
+              case TEXT, BLOB, STRING ->
+                  value -> Objects.nonNull(value) ? ((Binary) value).ramBytesUsed() : 0L;
+              case OBJECT, ROW, UNKNOWN, VECTOR -> value -> 0L;
+            };
+
+    static {
+      STATEMENT_VALUE_SIZE_PER_LINE_SERVICE.check();
+      INSERT_NODE_VALUE_SIZE_SERVICE.check();
+    }
+
+    private Memory() {
+      // Utility class
+    }
+  }
+
+  public static final class Transformation {
+
+    public static final TypeService<Function<Object, Column>> CONSTANT_COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT ->
+                  value -> {
+                    final ColumnBuilder builder = type.createColumnBuilder(1);
+                    type.writeObject(builder, value);
+                    return builder.build();
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<
+            Function<org.apache.iotdb.db.queryengine.plan.statement.literal.Literal, IFill>>
+        CONSTANT_FILL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> literal -> new BooleanConstantFill(literal.getBoolean());
+                  case INT32 -> literal -> new IntConstantFill(literal.getInt());
+                  case DATE -> literal -> new IntConstantFill(literal.getDate());
+                  case INT64, TIMESTAMP -> literal -> new LongConstantFill(literal.getLong());
+                  case FLOAT -> literal -> new FloatConstantFill(literal.getFloat());
+                  case DOUBLE -> literal -> new DoubleConstantFill(literal.getDouble());
+                  case TEXT, BLOB, STRING -> literal -> new BinaryConstantFill(literal.getBinary());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      literal -> {
+                        throw new IllegalArgumentException(
+                            CommonOperatorUtils.UNKNOWN_DATATYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<ColumnBuilder>> COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createColumnBuilder;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()))
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ColumnToDoubleConverter> VALUE_TO_DOUBLE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> type::getInt;
+              case INT64, TIMESTAMP -> type::getLong;
+              case FLOAT -> type::getFloat;
+              case DOUBLE -> type::getDouble;
+              case BOOLEAN -> (column, index) -> type.getBoolean(column, index) ? 1 : 0;
+              case TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (column, index) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ColumnValueWriter> TRANSFORM_COLUMN_VALUE_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::write;
+              case ROW, UNKNOWN, VECTOR ->
+                  (builder, column, index) -> {
+                    throw new UnSupportedDataTypeException(
+                        String.format(
+                            DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                            type.getTypeEnum()));
+                  };
+            };
+
+    // Schema evolution keeps physically compatible columns, widens supported values, and exposes
+    // incompatible historical values as nulls instead of interpreting their raw storage.
+    public static final TypeService<AlteredDataTypeColumnTransformer>
+        ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      INT64,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      STRING,
+                      TIMESTAMP,
+                      DATE,
+                      BLOB -> {
+                    final TSDataType targetType = TSDataType.valueOf(type.getTypeEnum().name());
+                    yield (source, positionCount) -> {
+                      final TSDataType sourceType = source.getDataType();
+                      // DATE shares INT32's physical column but was historically incompatible with
+                      // a schema change to INT32, while the other shared-column pairs are reusable.
+                      if (sourceType == targetType
+                          || (targetType != TSDataType.INT32
+                              && SchemaUtils.isUsingSameColumn(sourceType, targetType))) {
+                        return source;
+                      }
+                      return targetType.isCompatible(sourceType)
+                          ? source.convertTo(targetType)
+                          : type.createNullColumn(positionCount);
+                    };
+                  }
+                  case OBJECT -> (source, positionCount) -> source;
+                  case ROW, UNKNOWN, VECTOR -> (source, positionCount) -> null;
+                };
+
+    public static final TypeService<RoundTransformer> ROUND_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> RoundFunctionTransformer::transformInt;
+              case INT64 -> RoundFunctionTransformer::transformLong;
+              case FLOAT -> RoundFunctionTransformer::transformFloat;
+              case DOUBLE -> RoundFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new UnsupportedOperationException(
+                        String.format("Unsupported source dataType: %s", type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<DiffTransformer> DIFF_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> DiffFunctionTransformer::transformInt;
+              case INT64 -> DiffFunctionTransformer::transformLong;
+              case FLOAT -> DiffFunctionTransformer::transformFloat;
+              case DOUBLE -> DiffFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<NegationTransformer> NEGATION_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> ArithmeticNegationTransformer::transformInt;
+              case INT64 -> ArithmeticNegationTransformer::transformLong;
+              case FLOAT -> ArithmeticNegationTransformer::transformFloat;
+              case DOUBLE -> ArithmeticNegationTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<StateWindowSplitter> STATE_WINDOW_SPLITTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordInt(type.getInt(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getInt(values, index) - valueRecorder.getInt()) > delta;
+                    if (split) {
+                      valueRecorder.recordInt(type.getInt(values, index));
+                    }
+                    return split;
+                  };
+              case INT64 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordLong(type.getLong(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getLong(values, index) - valueRecorder.getLong()) > delta;
+                    if (split) {
+                      valueRecorder.recordLong(type.getLong(values, index));
+                    }
+                    return split;
+                  };
+              case FLOAT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordFloat(type.getFloat(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getFloat(values, index) - valueRecorder.getFloat()) > delta;
+                    if (split) {
+                      valueRecorder.recordFloat(type.getFloat(values, index));
+                    }
+                    return split;
+                  };
+              case DOUBLE ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordDouble(type.getDouble(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getDouble(values, index) - valueRecorder.getDouble()) > delta;
+                    if (split) {
+                      valueRecorder.recordDouble(type.getDouble(values, index));
+                    }
+                    return split;
+                  };
+              case BOOLEAN ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        type.getBoolean(values, index) != valueRecorder.getBoolean();
+                    if (split) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index));
+                    }
+                    return split;
+                  };
+              case TEXT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordString(type.getBinary(values, index - 1).toString());
+                      valueRecorder.setRecorded(true);
+                    }
+                    final String value = type.getBinary(values, index).toString();
+                    final boolean split = !value.equals(valueRecorder.getString());
+                    if (split) {
+                      valueRecorder.recordString(value);
+                    }
+                    return split;
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (valueRecorder, delta, values, index) -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages
+                            .EXCEPTION_THE_DATA_TYPE_OF_THE_STATE_WINDOW_STRATEGY_IS_NOT_VALID_61F4E273);
+                  };
+            };
+
+    public static final TypeService<InTransformerSetInitializer>
+        IN_TRANSFORMER_SET_INITIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::initIntSet;
+                  case INT64, TIMESTAMP -> InTransformer::initLongSet;
+                  case FLOAT -> InTransformer::initFloatSet;
+                  case DOUBLE -> InTransformer::initDoubleSet;
+                  case BOOLEAN -> InTransformer::initBooleanSet;
+                  case TEXT, STRING -> InTransformer::initStringSet;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, values) -> {
+                        throw new UnsupportedOperationException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<InTransformerColumnTransformer>
+        IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::transformInt;
+                  case INT64, TIMESTAMP -> InTransformer::transformLong;
+                  case FLOAT -> InTransformer::transformFloat;
+                  case DOUBLE -> InTransformer::transformDouble;
+                  case BOOLEAN -> InTransformer::transformBoolean;
+                  case TEXT, STRING -> InTransformer::transformBinary;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, columns, builder) -> {
+                        throw new QueryProcessException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<TypeService<CastColumnStrategy>> CAST_COLUMN_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(builder, type.getInt(column, index)));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getInt(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getInt(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getInt(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getInt(column, index) != 0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getInt(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case INT64 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castLongToInt(
+                                            type.getLong(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getLong(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getLong(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getLong(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getLong(column, index) != 0L));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getLong(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case FLOAT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castFloatToInt(
+                                            type.getFloat(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castFloatToLong(
+                                            type.getFloat(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getFloat(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getFloat(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getFloat(column, index) != 0.0f));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getFloat(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DOUBLE ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToInt(
+                                            type.getDouble(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToLong(
+                                            type.getDouble(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToFloat(
+                                            type.getDouble(column, index))));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getDouble(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getDouble(column, index) != 0.0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getDouble(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case BOOLEAN ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder, type.getBoolean(column, index) ? 1 : 0));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder, type.getBoolean(column, index) ? 1L : 0L));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder, type.getBoolean(column, index) ? 1.0f : 0.0f));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(
+                                        builder, type.getBoolean(column, index) ? 1.0 : 0.0));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getBoolean(column, index)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getBoolean(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case TEXT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeInt(builder, Integer.parseInt(value)));
+                        case INT64 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeLong(builder, Long.parseLong(value)));
+                        case FLOAT ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeFloat(
+                                        builder, CastFunctionUtils.castTextToFloat(value)));
+                        case DOUBLE ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeDouble(
+                                        builder, CastFunctionUtils.castTextToDouble(value)));
+                        case BOOLEAN ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, CastFunctionUtils.castTextToBoolean(value)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(builder, type.getBinary(column, index)));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  targetType -> unsupportedSourceCastStrategy(type);
+            };
+
+    private static CastColumnStrategy castColumnStrategy(
+        final Type targetType, final CastColumnWriter writer) {
+      return new CastColumnStrategy(() -> {}, targetType::createColumnBuilder, writer);
+    }
+
+    private static CastColumnStrategy castBinaryColumnStrategy(
+        final Type sourceType, final Type targetType, final BinaryStringCastWriter writer) {
+      return castColumnStrategy(
+          targetType,
+          (column, index, builder) ->
+              writer.write(
+                  sourceType.getBinary(column, index).getStringValue(TSFileConfig.STRING_CHARSET),
+                  builder));
+    }
+
+    private static CastColumnStrategy unsupportedSourceCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported source dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedTargetCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported target dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedCastStrategy(final String message) {
+      return new CastColumnStrategy(
+          () -> {
+            throw new UnsupportedOperationException(message);
+          },
+          ignored -> {
+            throw new UnsupportedOperationException(message);
+          },
+          (column, index, builder) -> {
+            throw new UnsupportedOperationException(message);
+          });
+    }
+
+    public static final class CastColumnStrategy {
+      private final Runnable validator;
+      private final IntFunction<ColumnBuilder> builderFactory;
+      private final CastColumnWriter writer;
+
+      private CastColumnStrategy(
+          final Runnable validator,
+          final IntFunction<ColumnBuilder> builderFactory,
+          final CastColumnWriter writer) {
+        this.validator = validator;
+        this.builderFactory = builderFactory;
+        this.writer = writer;
+      }
+
+      public void validate() {
+        validator.run();
+      }
+
+      public ColumnBuilder createBuilder(final int expectedEntries) {
+        return builderFactory.apply(expectedEntries);
+      }
+
+      public void cast(final Column column, final int index, final ColumnBuilder builder) {
+        writer.write(column, index, builder);
+      }
+    }
+
+    @FunctionalInterface
+    private interface CastColumnWriter {
+      void write(Column column, int index, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    private interface BinaryStringCastWriter {
+      void write(String value, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    public interface ColumnToDoubleConverter {
+      double convert(Column column, int index) throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface ColumnValueWriter {
+      void write(ColumnBuilder builder, Column column, int index);
+    }
+
+    @FunctionalInterface
+    public interface AlteredDataTypeColumnTransformer {
+      Column transform(Column source, int positionCount);
+    }
+
+    @FunctionalInterface
+    public interface RoundTransformer {
+      void transform(RoundFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface DiffTransformer {
+      void transform(DiffFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface NegationTransformer {
+      void transform(
+          ArithmeticNegationTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface StateWindowSplitter {
+      boolean split(ValueRecorder valueRecorder, double delta, Column values, int index);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerSetInitializer {
+      void initialize(InTransformer transformer, Set<String> values);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerColumnTransformer {
+      void transform(InTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    static {
+      CONSTANT_COLUMN_BUILDER_SERVICE.check();
+      CONSTANT_FILL_SERVICE.check();
+      COLUMN_BUILDER_SERVICE.check();
+      VALUE_TO_DOUBLE_SERVICE.check();
+      TRANSFORM_COLUMN_VALUE_WRITER_SERVICE.check();
+      ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE.check();
+      ROUND_TRANSFORMER_SERVICE.check();
+      DIFF_TRANSFORMER_SERVICE.check();
+      NEGATION_TRANSFORMER_SERVICE.check();
+      STATE_WINDOW_SPLITTER_SERVICE.check();
+      IN_TRANSFORMER_SET_INITIALIZER_SERVICE.check();
+      IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE.check();
+      CAST_COLUMN_SERVICE.check();
+    }
+
+    private Transformation() {
+      // Utility class
+    }
+  }
+
+  public static final class Aggregation {
+
+    public static final TypeService<ExtremeValueAccumulatorStrategy>
+        EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateIntResult(column.getInt(index)),
+                          (accumulator, value) ->
+                              accumulator.updateIntResult(((Number) value).intValue()),
+                          (accumulator, column) -> accumulator.getResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateLongResult(column.getLong(index)),
+                          (accumulator, value) ->
+                              accumulator.updateLongResult(((Number) value).longValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateFloatResult(column.getFloat(index)),
+                          (accumulator, value) ->
+                              accumulator.updateFloatResult(((Number) value).floatValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateDoubleResult(column.getDouble(index)),
+                          (accumulator, value) ->
+                              accumulator.updateDoubleResult(((Number) value).doubleValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case STRING ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateBinaryResult(column.getBinary(index)),
+                          (accumulator, value) -> accumulator.updateBinaryResult((Binary) value),
+                          (accumulator, column) ->
+                              accumulator.getResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN, TEXT, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      ExtremeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<TimeValueAccumulatorStrategy>
+        TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateIntResult(column.getInt(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateIntResult(
+                                  ((Number) getStatisticsValue(statistics, first)).intValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateLongResult(column.getLong(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateLongResult(
+                                  ((Number) getStatisticsValue(statistics, first)).longValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateFloatResult(column.getFloat(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateFloatResult(
+                                  ((Number) getStatisticsValue(statistics, first)).floatValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateDoubleResult(column.getDouble(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateDoubleResult(
+                                  ((Number) getStatisticsValue(statistics, first)).doubleValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBinaryResult(column.getBinary(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBinaryResult(
+                                  getBinaryStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBooleanResult(column.getBoolean(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBooleanResult(
+                                  (boolean) getStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBoolean(column.getBoolean(0)),
+                          (builder, result) -> builder.writeBoolean(result.getBoolean()));
+                  case ROW, UNKNOWN, VECTOR -> TimeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<MaxMinByAccumulatorStrategy>
+        MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateIntResult(
+                                  time, yColumn.getInt(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateIntResult(
+                                  time,
+                                  BytesUtils.bytesToInt(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Integer.BYTES),
+                                  0));
+                  case INT64, TIMESTAMP ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateLongResult(
+                                  time, yColumn.getLong(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateLongResult(
+                                  time,
+                                  BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Long.BYTES),
+                                  0));
+                  case FLOAT ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateFloatResult(
+                                  time, yColumn.getFloat(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateFloatResult(
+                                  time,
+                                  BytesUtils.bytesToFloat(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Float.BYTES),
+                                  0));
+                  case DOUBLE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateDoubleResult(
+                                  time, yColumn.getDouble(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateDoubleResult(
+                                  time,
+                                  BytesUtils.bytesToDouble(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Double.BYTES),
+                                  0));
+                  case STRING ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateBinaryResult(
+                                  time, yColumn.getBinary(yIndex), xColumn, xIndex),
+                          TypeServices.Aggregation::updateBinaryIntermediate);
+                  case TEXT, BLOB, OBJECT -> maxMinByAccumulatorStrategy(type, null, null);
+                  case BOOLEAN -> maxMinByAccumulatorStrategy(type, null, null);
+                  case ROW, UNKNOWN, VECTOR -> MaxMinByAccumulatorStrategy.unsupported(type);
+                };
+
+    public static final TypeService<EventWindowManagerProvider>
+        EVENT_WINDOW_MANAGER_PROVIDER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      eventWindowManagerProvider(
+                          EqualIntWindowManager::new, VariationIntWindowManager::new);
+                  case INT64 ->
+                      eventWindowManagerProvider(
+                          EqualLongWindowManager::new, VariationLongWindowManager::new);
+                  case FLOAT ->
+                      eventWindowManagerProvider(
+                          EqualFloatWindowManager::new, VariationFloatWindowManager::new);
+                  case DOUBLE ->
+                      eventWindowManagerProvider(
+                          EqualDoubleWindowManager::new, VariationDoubleWindowManager::new);
+                  case TEXT -> eventWindowManagerProvider(EqualBinaryWindowManager::new, null);
+                  case BOOLEAN -> eventWindowManagerProvider(EqualBooleanWindowManager::new, null);
+                  case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      EventWindowManagerProvider.unsupported();
+                };
+
+    private static EventWindowManagerProvider eventWindowManagerProvider(
+        final EventWindowManagerFactory equalFactory,
+        final EventWindowManagerFactory variationFactory) {
+      return new EventWindowManagerProvider(equalFactory, variationFactory);
+    }
+
+    private static void updateBinaryIntermediate(
+        final MaxMinByAccumulator accumulator,
+        final long time,
+        final byte[] bytes,
+        final int offset) {
+      final int length = BytesUtils.bytesToInt(bytes, offset);
+      final int valueOffset = offset + Integer.BYTES;
+      accumulator.updateBinaryResult(
+          time,
+          new Binary(BytesUtils.subBytes(bytes, valueOffset, length)),
+          accumulator.readXFromBytesIntermediateInput(bytes, valueOffset + length),
+          0);
+    }
+
+    private static MaxMinByAccumulatorStrategy maxMinByAccumulatorStrategy(
+        final Type type,
+        final MaxMinByYColumnUpdater yColumnUpdater,
+        final MaxMinByYBytesUpdater yBytesUpdater) {
+      return new MaxMinByAccumulatorStrategy(type, true, yColumnUpdater, yBytesUpdater);
+    }
+
+    private static TimeValueAccumulatorStrategy timeValueAccumulatorStrategy(
+        final TimeValueColumnUpdater columnUpdater,
+        final TimeValueStatisticsUpdater statisticsUpdater,
+        final TimeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new TimeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    private static Object getStatisticsValue(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getFirstValue() : statistics.getLastValue();
+    }
+
+    private static long getStatisticsTime(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getStartTime() : statistics.getEndTime();
+    }
+
+    private static Binary getBinaryStatisticsValue(
+        final Statistics<?> statistics, final boolean first) {
+      final Object value = getStatisticsValue(statistics, first);
+      if (statistics instanceof DateStatistics) {
+        return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+      }
+      return value instanceof Binary
+          ? (Binary) value
+          : new Binary(String.valueOf(value), StandardCharsets.UTF_8);
+    }
+
+    public static final class TimeValueAccumulatorStrategy {
+      private final TimeValueColumnUpdater columnUpdater;
+      private final TimeValueStatisticsUpdater statisticsUpdater;
+      private final TimeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private TimeValueAccumulatorStrategy(
+          final TimeValueColumnUpdater columnUpdater,
+          final TimeValueStatisticsUpdater statisticsUpdater,
+          final TimeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static TimeValueAccumulatorStrategy unsupported() {
+        return new TimeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final TimeValueAccumulator accumulator,
+          final Column[] columns,
+          final BitMap bitMap,
+          final boolean stopAfterFirstValue,
+          final boolean bitmapMarksSelected) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && bitmapMarksSelected != bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i, columns[0].getLong(i));
+            if (stopAfterFirstValue) {
+              return;
+            }
+          }
+        }
+      }
+
+      public void addIntermediate(
+          final TimeValueAccumulator accumulator,
+          final Column valueColumn,
+          final Column timeColumn) {
+        columnUpdater.update(accumulator, valueColumn, 0, timeColumn.getLong(0));
+      }
+
+      public void addStatistics(
+          final TimeValueAccumulator accumulator,
+          final Statistics<?> statistics,
+          final boolean first) {
+        statisticsUpdater.update(accumulator, statistics, first);
+      }
+
+      public void setFinal(final TimeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final class MaxMinByAccumulatorStrategy {
+      private final Type type;
+      private final PrimitiveColumnValueSetter xValueSetter;
+      private final boolean xSupported;
+      private final MaxMinByYColumnUpdater yColumnUpdater;
+      private final MaxMinByYBytesUpdater yBytesUpdater;
+
+      private MaxMinByAccumulatorStrategy(
+          final Type type,
+          final boolean xSupported,
+          final MaxMinByYColumnUpdater yColumnUpdater,
+          final MaxMinByYBytesUpdater yBytesUpdater) {
+        this.type = type;
+        this.xValueSetter =
+            org.apache.iotdb.calc.utils.TypeServices.PRIMITIVE_COLUMN_VALUE_SETTER_SERVICE.call(
+                type);
+        this.xSupported = xSupported;
+        this.yColumnUpdater = yColumnUpdater;
+        this.yBytesUpdater = yBytesUpdater;
+      }
+
+      private static MaxMinByAccumulatorStrategy unsupported(final Type type) {
+        return new MaxMinByAccumulatorStrategy(type, false, null, null);
+      }
+
+      public boolean isXSupported() {
+        return xSupported;
+      }
+
+      public boolean isYSupported() {
+        return yColumnUpdater != null;
+      }
+
+      public void addInput(
+          final MaxMinByAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[2].isNull(i)) {
+            yColumnUpdater.update(accumulator, columns[0].getLong(i), columns[2], i, columns[1], i);
+          }
+        }
+      }
+
+      public void setXResult(final TsPrimitiveType result, final Column column, final int index) {
+        // Type.setTo copies the primitive into the column; aggregation must read the input instead.
+        xValueSetter.set(result, column, index);
+      }
+
+      public void writeXResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        type.write(builder, result);
+      }
+
+      public void writeSerializedValue(
+          final byte[] bytes, final int offset, final ColumnBuilder builder) {
+        type.write(builder, bytes, offset);
+      }
+
+      public void updateIntermediate(
+          final MaxMinByAccumulator accumulator,
+          final long time,
+          final byte[] bytes,
+          final int offset) {
+        yBytesUpdater.update(accumulator, time, bytes, offset);
+      }
+    }
+
+    public static final class EventWindowManagerProvider {
+      private static final EventWindowManagerProvider UNSUPPORTED =
+          new EventWindowManagerProvider(null, null);
+
+      private final EventWindowManagerFactory equalFactory;
+      private final EventWindowManagerFactory variationFactory;
+
+      private EventWindowManagerProvider(
+          final EventWindowManagerFactory equalFactory,
+          final EventWindowManagerFactory variationFactory) {
+        this.equalFactory = equalFactory;
+        this.variationFactory = variationFactory;
+      }
+
+      private static EventWindowManagerProvider unsupported() {
+        return UNSUPPORTED;
+      }
+
+      public VariationWindowManager createEqual(
+          final VariationWindowParameter parameter, final boolean ascending) {
+        if (equalFactory == null) {
+          throw new UnSupportedDataTypeException(
+              String.format(
+                  DataNodeQueryMessages
+                      .EXCEPTION_UNSUPPORTED_DATA_TYPE_IN_EQUAL_EVENT_AGGREGATION_ARG_77E085EB,
+                  parameter.getDataType()));
+        }
+        return equalFactory.create(parameter, ascending);
+      }
+
+      public VariationWindowManager createVariation(
+          final VariationWindowParameter parameter, final boolean ascending) {
+        if (variationFactory == null) {
+          throw new UnSupportedDataTypeException(
+              String.format(
+                  DataNodeQueryMessages
+                      .EXCEPTION_UNSUPPORTED_DATA_TYPE_IN_VARIATION_EVENT_AGGREGATION_ARG_3D0F0388,
+                  parameter.getDataType()));
+        }
+        return variationFactory.create(parameter, ascending);
+      }
+    }
+
+    private static ExtremeValueAccumulatorStrategy extremeValueAccumulatorStrategy(
+        final ExtremeValueColumnUpdater columnUpdater,
+        final ExtremeValueStatisticsUpdater statisticsUpdater,
+        final ExtremeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new ExtremeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    public static final class ExtremeValueAccumulatorStrategy {
+      private final ExtremeValueColumnUpdater columnUpdater;
+      private final ExtremeValueStatisticsUpdater statisticsUpdater;
+      private final ExtremeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private ExtremeValueAccumulatorStrategy(
+          final ExtremeValueColumnUpdater columnUpdater,
+          final ExtremeValueStatisticsUpdater statisticsUpdater,
+          final ExtremeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static ExtremeValueAccumulatorStrategy unsupported() {
+        return new ExtremeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final ExtremeValueAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i);
+          }
+        }
+      }
+
+      public void addIntermediate(final ExtremeValueAccumulator accumulator, final Column column) {
+        columnUpdater.update(accumulator, column, 0);
+      }
+
+      public void addStatistics(
+          final ExtremeValueAccumulator accumulator, final Object statisticsValue) {
+        statisticsUpdater.update(accumulator, statisticsValue);
+      }
+
+      public void setFinal(final ExtremeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final TypeService<LongSupplier> OUTPUT_COLUMN_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  () -> type.estimateValueSize() + Byte.BYTES;
+              case TEXT, BLOB, STRING, OBJECT ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages.UNKNOWN_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Supplier<Accumulator>> MODE_ACCUMULATOR_PROVIDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> BooleanModeAccumulator::new;
+              case TEXT, BLOB, STRING -> BinaryModeAccumulator::new;
+              case INT32, DATE -> IntModeAccumulator::new;
+              case INT64, TIMESTAMP -> LongModeAccumulator::new;
+              case FLOAT -> FloatModeAccumulator::new;
+              case DOUBLE -> DoubleModeAccumulator::new;
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new IllegalArgumentException(
+                        DataNodeQueryMessages.UNKNOWN_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    static {
+      EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE.check();
+      TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE.check();
+      MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE.check();
+      EVENT_WINDOW_MANAGER_PROVIDER_SERVICE.check();
+      OUTPUT_COLUMN_SIZE_PER_LINE_SERVICE.check();
+      MODE_ACCUMULATOR_PROVIDER_SERVICE.check();
+    }
+
+    private Aggregation() {
+      // Utility class
+    }
+
+    public interface ExtremeValueAccumulator {
+      TsPrimitiveType getResult();
+
+      void updateIntResult(int value);
+
+      void updateLongResult(long value);
+
+      void updateFloatResult(float value);
+
+      void updateDoubleResult(double value);
+
+      void updateBinaryResult(Binary value);
+    }
+
+    public interface TimeValueAccumulator {
+      TsPrimitiveType getTimeValueResult();
+
+      void updateIntResult(int value, long time);
+
+      void updateLongResult(long value, long time);
+
+      void updateFloatResult(float value, long time);
+
+      void updateDoubleResult(double value, long time);
+
+      void updateBinaryResult(Binary value, long time);
+
+      void updateBooleanResult(boolean value, long time);
+    }
+
+    public interface MaxMinByAccumulator {
+      Column readXFromBytesIntermediateInput(byte[] bytes, int offset);
+
+      void updateIntResult(long time, int yValue, Column xColumn, int xIndex);
+
+      void updateLongResult(long time, long yValue, Column xColumn, int xIndex);
+
+      void updateFloatResult(long time, float yValue, Column xColumn, int xIndex);
+
+      void updateDoubleResult(long time, double yValue, Column xColumn, int xIndex);
+
+      void updateBinaryResult(long time, Binary yValue, Column xColumn, int xIndex);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueColumnUpdater {
+      void update(ExtremeValueAccumulator accumulator, Column column, int index);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueStatisticsUpdater {
+      void update(ExtremeValueAccumulator accumulator, Object value);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueFinalSetter {
+      void set(ExtremeValueAccumulator accumulator, Column column);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueColumnUpdater {
+      void update(TimeValueAccumulator accumulator, Column column, int index, long time);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueStatisticsUpdater {
+      void update(TimeValueAccumulator accumulator, Statistics<?> statistics, boolean first);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueFinalSetter {
+      void set(TimeValueAccumulator accumulator, Column column);
+    }
+
+    @FunctionalInterface
+    private interface MaxMinByYColumnUpdater {
+      void update(
+          MaxMinByAccumulator accumulator,
+          long time,
+          Column yColumn,
+          int yIndex,
+          Column xColumn,
+          int xIndex);
+    }
+
+    @FunctionalInterface
+    private interface MaxMinByYBytesUpdater {
+      void update(MaxMinByAccumulator accumulator, long time, byte[] bytes, int offset);
+    }
+
+    @FunctionalInterface
+    private interface EventWindowManagerFactory {
+      VariationWindowManager create(VariationWindowParameter parameter, boolean ascending);
+    }
+  }
+
+  public static final class ValueConversion {
+
+    public static final TypeService<Function<String, Object>> VALUE_PARSER_NO_EXCEPTION_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> Boolean::parseBoolean;
+              case INT32 -> TypeServices::parseInteger;
+              case INT64 -> TypeServices::parseLong;
+              case FLOAT -> TypeServices::parseFloat;
+              case DOUBLE -> TypeServices::parseDouble;
+              case TEXT -> TypeServices::parseText;
+              case TIMESTAMP -> TypeServices::parseTimestamp;
+              case DATE -> TypeServices::parseDate;
+              case BLOB -> TypeServices::parseBlob;
+              case STRING -> TypeServices::parseString;
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ContextualValueParser> VALUE_PARSER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (value, zoneId) -> CommonUtils.parseBoolean(value);
+              case INT32 ->
+                  (value, zoneId) -> {
+                    try {
+                      return Integer.parseInt(StringUtils.trim(value));
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                  };
+              case INT64 ->
+                  (value, zoneId) -> {
+                    try {
+                      return Long.parseLong(StringUtils.trim(value));
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                  };
+              case TIMESTAMP ->
+                  (value, zoneId) -> {
+                    try {
+                      return TypeInferenceUtils.isNumber(value)
+                          ? Long.parseLong(value)
+                          : DataNodeDateTimeUtils.parseDateTimeExpressionToLong(
+                              StringUtils.trim(value), zoneId);
+                    } catch (final Throwable e) {
+                      throw new NumberFormatException(
+                          String.format(
+                              DataNodeMiscMessages
+                                  .EXCEPTION_DATA_TYPE_IS_NOT_CONSISTENT_INPUT_ARG_REGISTERED_ARG_BECAUSE_ARG_C8637858,
+                              value,
+                              type.getTypeEnum(),
+                              e.getMessage()));
+                    }
+                  };
+              case DATE -> (value, zoneId) -> CommonUtils.parseIntFromString(value);
+              case FLOAT ->
+                  (value, zoneId) -> {
+                    final float result;
+                    try {
+                      result = Float.parseFloat(value);
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                    if (Float.isInfinite(result)) {
+                      throw new NumberFormatException(DataNodeMiscMessages.INPUT_FLOAT_INFINITY);
+                    }
+                    return result;
+                  };
+              case DOUBLE ->
+                  (value, zoneId) -> {
+                    final double result;
+                    try {
+                      result = Double.parseDouble(value);
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                    if (Double.isInfinite(result)) {
+                      throw new NumberFormatException(DataNodeMiscMessages.INPUT_DOUBLE_INFINITY);
+                    }
+                    return result;
+                  };
+              case TEXT, STRING ->
+                  (value, zoneId) ->
+                      new Binary(stripQuotesIfPresent(value), TSFileConfig.STRING_CHARSET);
+              case BLOB ->
+                  (value, zoneId) ->
+                      new Binary(
+                          CommonUtils.parseBlobStringToByteArray(stripQuotesIfPresent(value)));
+              case OBJECT ->
+                  (value, zoneId) -> {
+                    throw inconsistentValueException(value, type);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  (value, zoneId) -> {
+                    throw new QueryProcessException(
+                        DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<java.util.function.Predicate<TSDataType>> AUTO_CAST_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      targetType == TSDataType.INT64
+                          || targetType == TSDataType.FLOAT
+                          || targetType == TSDataType.DOUBLE;
+              case INT64, FLOAT -> targetType -> targetType == TSDataType.DOUBLE;
+              case BOOLEAN, DATE, TIMESTAMP, DOUBLE, TEXT, BLOB, STRING, OBJECT ->
+                  targetType -> false;
+              case ROW, UNKNOWN, VECTOR ->
+                  targetType -> {
+                    throw new IllegalArgumentException(
+                        DataNodeMiscMessages.UNKNOWN_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Function<Object, Pair<Literal, String>>>
+        PREPARED_PARAMETER_LITERAL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      value -> {
+                        final String text = Boolean.toString((Boolean) value);
+                        return new Pair<>(new BooleanLiteral(text), text);
+                      };
+                  case INT32, INT64 ->
+                      value -> {
+                        final String text = String.valueOf(value);
+                        return new Pair<>(new LongLiteral(text), text);
+                      };
+                  case FLOAT ->
+                      value -> new Pair<>(new DoubleLiteral((Float) value), String.valueOf(value));
+                  case DOUBLE ->
+                      value -> new Pair<>(new DoubleLiteral((Double) value), String.valueOf(value));
+                  case TEXT, STRING ->
+                      value -> {
+                        final String text = (String) value;
+                        return new Pair<>(
+                            new StringLiteral(text), "'" + text.replace("'", "''") + "'");
+                      };
+                  case BLOB ->
+                      value -> {
+                        final BinaryLiteral literal = new BinaryLiteral((byte[]) value);
+                        return new Pair<>(literal, "X'" + literal.toHexString() + "'");
+                      };
+                  case DATE, TIMESTAMP, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new IllegalArgumentException(
+                            DataNodeMiscMessages.UNKNOWN_PARAMETER_TYPE + type.getTypeEnum());
+                      };
+                };
+
+    static {
+      VALUE_PARSER_NO_EXCEPTION_SERVICE.check();
+      VALUE_PARSER_SERVICE.check();
+      AUTO_CAST_SERVICE.check();
+      PREPARED_PARAMETER_LITERAL_SERVICE.check();
+    }
+
+    private static NumberFormatException inconsistentValueException(
+        final String value, final Type type) {
+      return new NumberFormatException(
+          String.format(
+              DataNodeMiscMessages
+                  .EXCEPTION_DATA_TYPE_IS_NOT_CONSISTENT_INPUT_ARG_REGISTERED_ARG_0EF32FD3,
+              value,
+              type.getTypeEnum()));
+    }
+
+    private static String stripQuotesIfPresent(final String value) {
+      if ((value.startsWith(SqlConstant.QUOTE) && value.endsWith(SqlConstant.QUOTE))
+          || (value.startsWith(SqlConstant.DQUOTE) && value.endsWith(SqlConstant.DQUOTE))) {
+        return value.length() == 1 ? value : value.substring(1, value.length() - 1);
+      }
+      return value;
+    }
+
+    @FunctionalInterface
+    public interface ContextualValueParser {
+      Object parse(String value, ZoneId zoneId) throws QueryProcessException;
+    }
+
+    private ValueConversion() {
+      // Utility class
+    }
+  }
+
+  public static final class StorageEngine {
+
+    public static final TypeService<ToIntFunction<Object>>
+        INSERT_ROW_SERIALIZED_VALUE_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> value -> Byte.BYTES;
+                  case INT32, DATE, FLOAT -> value -> Integer.BYTES;
+                  case INT64, TIMESTAMP, DOUBLE -> value -> Long.BYTES;
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      value -> ReadWriteIOUtils.sizeToWrite((Binary) value);
+                  case ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnSupportedDataTypeException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<SerializedColumnSizeCalculator>
+        INSERT_TABLET_SERIALIZED_COLUMN_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (column, start, end) -> (end - start) * Byte.BYTES;
+                  case INT32, DATE, FLOAT -> (column, start, end) -> (end - start) * Integer.BYTES;
+                  case INT64, TIMESTAMP, DOUBLE ->
+                      (column, start, end) -> (end - start) * Long.BYTES;
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (column, start, end) -> {
+                        int size = 0;
+                        Binary[] values = (Binary[]) column;
+                        // Tablet and WAL use a length prefix without TsFile's presence byte.
+                        // Count only the selected range, including placeholders for null values.
+                        for (int i = start; i < end; i++) {
+                          byte[] bytes =
+                              values == null || values[i] == null ? null : values[i].getValues();
+                          size += Integer.BYTES + (bytes == null ? 0 : bytes.length);
+                        }
+                        return size;
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      (column, start, end) -> {
+                        throw new UnSupportedDataTypeException(
+                            String.format(
+                                DataNodeQueryMessages
+                                    .QUERY_EXCEPTION_DATA_TYPE_S_IS_NOT_SUPPORTED_5D5C02E4,
+                                type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<RawArrayByteBufferSerializer>
+        RAW_ARRAY_BYTE_BUFFER_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                      type::serializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (column, rows, buffer) -> {
+                        Binary[] values = (Binary[]) column;
+                        // Preserve the Tablet wire format: nullness lives in the separate bitmap.
+                        for (int i = 0; i < rows; i++) {
+                          if (values[i] != null && values[i].getValues() != null) {
+                            ReadWriteIOUtils.write(values[i], buffer);
+                          } else {
+                            buffer.putInt(0);
+                          }
+                        }
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<RawArrayOutputStreamSerializer>
+        RAW_ARRAY_OUTPUT_STREAM_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                      type::serializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (column, rows, stream) -> {
+                        Binary[] values = (Binary[]) column;
+                        // Match the ByteBuffer writer, including zero-length null placeholders.
+                        for (int i = 0; i < rows; i++) {
+                          if (values[i] != null && values[i].getValues() != null) {
+                            ReadWriteIOUtils.write(values[i], stream);
+                          } else {
+                            stream.writeInt(0);
+                          }
+                        }
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Boolean> TABLET_PLAIN_FAST_PATH_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, DATE, INT32, TIMESTAMP, INT64, FLOAT, DOUBLE, STRING, BLOB, TEXT ->
+                  true;
+              case ROW, VECTOR, UNKNOWN, OBJECT -> false;
+            };
+
+    public static final TypeService<AlignedTVListColumnWriter>
+        ALIGNED_TV_LIST_COLUMN_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, !isNull && list.getBooleanByValueIndex(row, column), isNull);
+                  case INT32, DATE ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0 : list.getIntByValueIndex(row, column), isNull);
+                  case INT64, TIMESTAMP ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0L : list.getLongByValueIndex(row, column), isNull);
+                  case FLOAT ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0F : list.getFloatByValueIndex(row, column), isNull);
+                  case DOUBLE ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0D : list.getDoubleByValueIndex(row, column), isNull);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time,
+                              isNull ? null : list.getBinaryByValueIndex(row, column),
+                              isNull);
+                  // Preserve the flush path's no-op behavior for non-value types.
+                  case ROW, UNKNOWN, VECTOR -> (writer, time, list, row, column, isNull) -> {};
+                };
+
+    private static final Binary EMPTY_BINARY = new Binary("", StandardCharsets.UTF_8);
+
+    public static final TypeService<ChunkMetadataStatisticsConverter>
+        CHUNK_METADATA_STATISTICS_CONVERTER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, INT64, TIMESTAMP, FLOAT, DOUBLE, BOOLEAN ->
+                      StorageEngine::convertNumericOrBooleanStatistics;
+                  case DATE -> StorageEngine::convertDateStatistics;
+                  case STRING -> StorageEngine::convertStringStatistics;
+                  case TEXT -> StorageEngine::convertTextStatistics;
+                  case BLOB -> StorageEngine::convertBlobStatistics;
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (chunkMetadata, targetDataType, statistics) -> statistics;
+                };
+
+    public static final TypeService<BiConsumer<Object, IWALByteBufferView>>
+        WAL_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (value, buffer) -> WALWriteUtils.write((Boolean) value, buffer);
+                  case INT32, DATE ->
+                      (value, buffer) -> WALWriteUtils.write((Integer) value, buffer);
+                  case INT64, TIMESTAMP ->
+                      (value, buffer) -> WALWriteUtils.write((Long) value, buffer);
+                  case FLOAT -> (value, buffer) -> WALWriteUtils.write((Float) value, buffer);
+                  case DOUBLE -> (value, buffer) -> WALWriteUtils.write((Double) value, buffer);
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (value, buffer) -> WALWriteUtils.write((Binary) value, buffer);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    // Unmaterialized blocks still write zero placeholders; the bitmap carries nullness in WAL.
+    public static final TypeService<WALColumnWriter> WAL_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (column, buffer, start, end) -> {
+                    int[] values = (int[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putInt(values == null ? 0 : values[i]);
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (column, buffer, start, end) -> {
+                    long[] values = (long[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putLong(values == null ? 0L : values[i]);
+                    }
+                  };
+              case FLOAT ->
+                  (column, buffer, start, end) -> {
+                    float[] values = (float[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putFloat(values == null ? 0F : values[i]);
+                    }
+                  };
+              case DOUBLE ->
+                  (column, buffer, start, end) -> {
+                    double[] values = (double[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putDouble(values == null ? 0D : values[i]);
+                    }
+                  };
+              case BOOLEAN ->
+                  (column, buffer, start, end) -> {
+                    boolean[] values = (boolean[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.put((byte) (values != null && values[i] ? 1 : 0));
+                    }
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (column, buffer, start, end) -> {
+                    Binary[] values = (Binary[]) column;
+                    for (int i = start; i < end; i++) {
+                      if (values != null && values[i] != null && values[i].getValues() != null) {
+                        WALWriteUtils.write(values[i], buffer);
+                      } else {
+                        buffer.putInt(0);
+                      }
+                    }
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedValueChunkWriter> DECODED_VALUE_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0 : ReadWriteIOUtils.readInt(stream), isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0L : ReadWriteIOUtils.readLong(stream), isNull);
+              case FLOAT ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0F : ReadWriteIOUtils.readFloat(stream), isNull);
+              case DOUBLE ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0D : ReadWriteIOUtils.readDouble(stream), isNull);
+              case BOOLEAN ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, !isNull && ReadWriteIOUtils.readBool(stream), isNull);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(
+                          time, isNull ? null : ReadWriteIOUtils.readBinary(stream), isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<SegmentedArraySerializedSizeCalculator>
+        SEGMENTED_ARRAY_SERIALIZED_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (valueArrays, rowCount, arraySize) -> rowCount * Byte.BYTES;
+                  case INT32, DATE ->
+                      (valueArrays, rowCount, arraySize) -> rowCount * Integer.BYTES;
+                  case INT64, TIMESTAMP ->
+                      (valueArrays, rowCount, arraySize) -> rowCount * Long.BYTES;
+                  case FLOAT -> (valueArrays, rowCount, arraySize) -> rowCount * Float.BYTES;
+                  case DOUBLE -> (valueArrays, rowCount, arraySize) -> rowCount * Double.BYTES;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (valueArrays, rowCount, arraySize) -> {
+                        int size = 0;
+                        int remaining = rowCount;
+                        for (Object valueArray : valueArrays) {
+                          int length = Math.min(remaining, arraySize);
+                          // WAL uses length-prefixed binaries, without TsFile array presence bytes.
+                          Binary[] binaryValues = (Binary[]) valueArray;
+                          for (int i = 0; i < length; i++) {
+                            Binary value = binaryValues == null ? null : binaryValues[i];
+                            size += Integer.BYTES;
+                            if (value != null && value.getValues() != null) {
+                              size += value.getLength();
+                            }
+                          }
+                          remaining -= length;
+                          if (remaining == 0) {
+                            break;
+                          }
+                        }
+                        return size;
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<ArrayValueColumnWriter> ARRAY_VALUE_COLUMN_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeBoolean(((boolean[]) values)[index]);
+              case INT32 ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeInt(((int[]) values)[index]);
+              case DATE ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    int value = ((int[]) values)[index];
+                    if (builder instanceof BinaryColumnBuilder) {
+                      ((BinaryColumnBuilder) builder).writeDate(value);
+                    } else {
+                      builder.writeInt(value);
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeLong(((long[]) values)[index]);
+              case FLOAT ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    float value = ((float[]) values)[index];
+                    if (encoding != null
+                        && !Float.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    builder.writeFloat(value);
+                  };
+              case DOUBLE ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    double value = ((double[]) values)[index];
+                    if (encoding != null
+                        && !Double.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    builder.writeDouble(value);
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeBinary(((Binary[]) values)[index]);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    @FunctionalInterface
+    public interface AlignedWalBatchWriter {
+      void write(
+          AlignedTVList list,
+          int columnIndex,
+          List<Object> arrays,
+          int rowCount,
+          IWALByteBufferView buffer);
+    }
+
+    // Aligned WAL interleaves values with null flags. Cast once per physical segment while keeping
+    // bitmap positions relative to the whole list; unmaterialized segments still write
+    // placeholders.
+    public static final TypeService<AlignedWalBatchWriter> ALIGNED_WAL_BATCH_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (list, columnIndex, arrays, rowCount, buffer) -> {
+                    for (int start = 0;
+                        start < rowCount;
+                        start += PrimitiveArrayManager.ARRAY_SIZE) {
+                      int[] values = (int[]) arrays.get(start / PrimitiveArrayManager.ARRAY_SIZE);
+                      int count = Math.min(PrimitiveArrayManager.ARRAY_SIZE, rowCount - start);
+                      for (int i = 0; i < count; i++) {
+                        buffer.putInt(values == null ? 0 : values[i]);
+                        WALWriteUtils.write(list.isNullValue(start + i, columnIndex), buffer);
+                      }
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (list, columnIndex, arrays, rowCount, buffer) -> {
+                    for (int start = 0;
+                        start < rowCount;
+                        start += PrimitiveArrayManager.ARRAY_SIZE) {
+                      long[] values = (long[]) arrays.get(start / PrimitiveArrayManager.ARRAY_SIZE);
+                      int count = Math.min(PrimitiveArrayManager.ARRAY_SIZE, rowCount - start);
+                      for (int i = 0; i < count; i++) {
+                        buffer.putLong(values == null ? 0L : values[i]);
+                        WALWriteUtils.write(list.isNullValue(start + i, columnIndex), buffer);
+                      }
+                    }
+                  };
+              case FLOAT ->
+                  (list, columnIndex, arrays, rowCount, buffer) -> {
+                    for (int start = 0;
+                        start < rowCount;
+                        start += PrimitiveArrayManager.ARRAY_SIZE) {
+                      float[] values =
+                          (float[]) arrays.get(start / PrimitiveArrayManager.ARRAY_SIZE);
+                      int count = Math.min(PrimitiveArrayManager.ARRAY_SIZE, rowCount - start);
+                      for (int i = 0; i < count; i++) {
+                        buffer.putFloat(values == null ? 0F : values[i]);
+                        WALWriteUtils.write(list.isNullValue(start + i, columnIndex), buffer);
+                      }
+                    }
+                  };
+              case DOUBLE ->
+                  (list, columnIndex, arrays, rowCount, buffer) -> {
+                    for (int start = 0;
+                        start < rowCount;
+                        start += PrimitiveArrayManager.ARRAY_SIZE) {
+                      double[] values =
+                          (double[]) arrays.get(start / PrimitiveArrayManager.ARRAY_SIZE);
+                      int count = Math.min(PrimitiveArrayManager.ARRAY_SIZE, rowCount - start);
+                      for (int i = 0; i < count; i++) {
+                        buffer.putDouble(values == null ? 0D : values[i]);
+                        WALWriteUtils.write(list.isNullValue(start + i, columnIndex), buffer);
+                      }
+                    }
+                  };
+              case BOOLEAN ->
+                  (list, columnIndex, arrays, rowCount, buffer) -> {
+                    for (int start = 0;
+                        start < rowCount;
+                        start += PrimitiveArrayManager.ARRAY_SIZE) {
+                      boolean[] values =
+                          (boolean[]) arrays.get(start / PrimitiveArrayManager.ARRAY_SIZE);
+                      int count = Math.min(PrimitiveArrayManager.ARRAY_SIZE, rowCount - start);
+                      for (int i = 0; i < count; i++) {
+                        buffer.put((byte) (values != null && values[i] ? 1 : 0));
+                        WALWriteUtils.write(list.isNullValue(start + i, columnIndex), buffer);
+                      }
+                    }
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (list, columnIndex, arrays, rowCount, buffer) -> {
+                    for (int start = 0;
+                        start < rowCount;
+                        start += PrimitiveArrayManager.ARRAY_SIZE) {
+                      Binary[] values =
+                          (Binary[]) arrays.get(start / PrimitiveArrayManager.ARRAY_SIZE);
+                      int count = Math.min(PrimitiveArrayManager.ARRAY_SIZE, rowCount - start);
+                      for (int i = 0; i < count; i++) {
+                        if (values != null && values[i] != null && values[i].getValues() != null) {
+                          WALWriteUtils.write(values[i], buffer);
+                        } else {
+                          buffer.putInt(0);
+                        }
+                        WALWriteUtils.write(list.isNullValue(start + i, columnIndex), buffer);
+                      }
+                    }
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<BatchDataColumnWriter> BATCH_DATA_COLUMN_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (batchData, time, column, index) ->
+                      batchData.putBoolean(time, type.getBoolean(column, index));
+              case INT32, DATE ->
+                  (batchData, time, column, index) ->
+                      batchData.putInt(time, type.getInt(column, index));
+              case INT64, TIMESTAMP ->
+                  (batchData, time, column, index) ->
+                      batchData.putLong(time, type.getLong(column, index));
+              case FLOAT ->
+                  (batchData, time, column, index) ->
+                      batchData.putFloat(time, type.getFloat(column, index));
+              case DOUBLE ->
+                  (batchData, time, column, index) ->
+                      batchData.putDouble(time, type.getDouble(column, index));
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (batchData, time, column, index) ->
+                      batchData.putBinary(time, type.getBinary(column, index));
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueSerializer<Object>> OBJECT_VALUE_SERIALIZER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> (value, stream) -> ReadWriteIOUtils.write((int) value, stream);
+              case INT64, TIMESTAMP ->
+                  (value, stream) -> ReadWriteIOUtils.write((long) value, stream);
+              case FLOAT -> (value, stream) -> ReadWriteIOUtils.write((float) value, stream);
+              case DOUBLE -> (value, stream) -> ReadWriteIOUtils.write((double) value, stream);
+              case BOOLEAN -> (value, stream) -> ReadWriteIOUtils.write((boolean) value, stream);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (value, stream) -> ReadWriteIOUtils.write((Binary) value, stream);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueSerializer<TsPrimitiveType>>
+        TS_PRIMITIVE_VALUE_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getInt(), stream);
+                  case INT64, TIMESTAMP ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getLong(), stream);
+                  case FLOAT -> (value, stream) -> ReadWriteIOUtils.write(value.getFloat(), stream);
+                  case DOUBLE ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getDouble(), stream);
+                  case BOOLEAN ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getBoolean(), stream);
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getBinary(), stream);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Supplier<TsPrimitiveType>>
+        EMPTY_TS_PRIMITIVE_TYPE_FACTORY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, FLOAT, DOUBLE -> type::getTsPrimitiveType;
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::getTsPrimitiveType;
+                  case TIMESTAMP -> Type.fromTsDataType(TSDataType.INT64)::getTsPrimitiveType;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      () ->
+                          Type.fromTsDataType(TSDataType.TEXT)
+                              .getTsPrimitiveType(new Binary("", TSFileConfig.STRING_CHARSET));
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Function<IoTDBConfig, TSEncoding>> DEFAULT_ENCODING_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> IoTDBConfig::getDefaultBooleanEncoding;
+              case INT32, DATE -> IoTDBConfig::getDefaultInt32Encoding;
+              case INT64, TIMESTAMP -> IoTDBConfig::getDefaultInt64Encoding;
+              case FLOAT -> IoTDBConfig::getDefaultFloatEncoding;
+              case DOUBLE -> IoTDBConfig::getDefaultDoubleEncoding;
+              case TEXT, BLOB, STRING, OBJECT -> IoTDBConfig::getDefaultTextEncoding;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TabletColumnDecoder> TABLET_COLUMN_DECODER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    int[] values = new int[rowCount];
+                    // PlainEncoder uses var int, which may cause compatibility problems.
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] =
+                          encoding == TSEncoding.PLAIN
+                              ? ReadWriteIOUtils.readInt(buffer)
+                              : decoder.readInt(buffer);
+                    }
+                    return values;
+                  };
+              case INT64, TIMESTAMP ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    long[] values = new long[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readLong(buffer);
+                    }
+                    return values;
+                  };
+              case FLOAT ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    float[] values = new float[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readFloat(buffer);
+                    }
+                    return values;
+                  };
+              case DOUBLE ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    double[] values = new double[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readDouble(buffer);
+                    }
+                    return values;
+                  };
+              case BOOLEAN ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    boolean[] values = new boolean[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readBoolean(buffer);
+                    }
+                    return values;
+                  };
+              case TEXT, BLOB, STRING ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    Binary[] values = new Binary[rowCount];
+                    // PlainEncoder uses var int, which may cause compatibility problems.
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] =
+                          encoding == TSEncoding.PLAIN
+                              ? ReadWriteIOUtils.readBinary(buffer)
+                              : decoder.readBinary(buffer);
+                    }
+                    return values;
+                  };
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedArrayValueReader> DECODED_ARRAY_VALUE_READER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (values, index, stream) ->
+                      ((int[]) values)[index] = ReadWriteIOUtils.readInt(stream);
+              case INT64, TIMESTAMP ->
+                  (values, index, stream) ->
+                      ((long[]) values)[index] = ReadWriteIOUtils.readLong(stream);
+              case FLOAT ->
+                  (values, index, stream) ->
+                      ((float[]) values)[index] = ReadWriteIOUtils.readFloat(stream);
+              case DOUBLE ->
+                  (values, index, stream) ->
+                      ((double[]) values)[index] = ReadWriteIOUtils.readDouble(stream);
+              case BOOLEAN ->
+                  (values, index, stream) ->
+                      ((boolean[]) values)[index] = ReadWriteIOUtils.readBool(stream);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (values, index, stream) ->
+                      ((Binary[]) values)[index] = ReadWriteIOUtils.readBinary(stream);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedChunkWriter> DECODED_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readInt(stream));
+              case INT64, TIMESTAMP ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readLong(stream));
+              case FLOAT ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readFloat(stream));
+              case DOUBLE ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readDouble(stream));
+              case BOOLEAN ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readBool(stream));
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readBinary(stream));
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListArrayWriter> TV_LIST_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putBooleans(times, (boolean[]) values, bitMap, start, end);
+              case INT32, DATE ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putInts(times, (int[]) values, bitMap, start, end);
+              case INT64, TIMESTAMP ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putLongs(times, (long[]) values, bitMap, start, end);
+              case FLOAT ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putFloats(times, (float[]) values, bitMap, start, end);
+              case DOUBLE ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putDoubles(times, (double[]) values, bitMap, start, end);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putBinaries(times, (Binary[]) values, bitMap, start, end);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListObjectWriter> TV_LIST_OBJECT_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (tvList, time, value) -> tvList.putBoolean(time, (boolean) value);
+              case INT32, DATE -> (tvList, time, value) -> tvList.putInt(time, (int) value);
+              case INT64, TIMESTAMP -> (tvList, time, value) -> tvList.putLong(time, (long) value);
+              case FLOAT -> (tvList, time, value) -> tvList.putFloat(time, (float) value);
+              case DOUBLE -> (tvList, time, value) -> tvList.putDouble(time, (double) value);
+              case TEXT, BLOB, STRING ->
+                  (tvList, time, value) -> tvList.putBinary(time, (Binary) value);
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    private static final TVListProvider UNSUPPORTED_TV_LIST_PROVIDER =
+        new TVListProvider(() -> null, stream -> null, stream -> null);
+
+    public static final TypeService<TVListProvider> TV_LIST_PROVIDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  new TVListProvider(
+                      BooleanTVList::newList,
+                      BooleanTVList::deserialize,
+                      BooleanTVList::deserializeWithoutBitMap);
+              case INT32 ->
+                  new TVListProvider(
+                      () -> IntTVList.newList(TSDataType.INT32),
+                      stream -> IntTVList.deserialize(stream, TSDataType.INT32),
+                      stream -> IntTVList.deserializeWithoutBitMap(stream, TSDataType.INT32));
+              case DATE ->
+                  new TVListProvider(
+                      () -> IntTVList.newList(TSDataType.DATE),
+                      stream -> IntTVList.deserialize(stream, TSDataType.DATE),
+                      stream -> IntTVList.deserializeWithoutBitMap(stream, TSDataType.DATE));
+              case INT64, TIMESTAMP ->
+                  new TVListProvider(
+                      LongTVList::newList,
+                      LongTVList::deserialize,
+                      LongTVList::deserializeWithoutBitMap);
+              case FLOAT ->
+                  new TVListProvider(
+                      FloatTVList::newList,
+                      FloatTVList::deserialize,
+                      FloatTVList::deserializeWithoutBitMap);
+              case DOUBLE ->
+                  new TVListProvider(
+                      DoubleTVList::newList,
+                      DoubleTVList::deserialize,
+                      DoubleTVList::deserializeWithoutBitMap);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  new TVListProvider(
+                      BinaryTVList::newList,
+                      BinaryTVList::deserialize,
+                      BinaryTVList::deserializeWithoutBitMap);
+              case ROW, UNKNOWN, VECTOR -> UNSUPPORTED_TV_LIST_PROVIDER;
+            };
+
+    public static final TypeService<TVListChunkWriter> TV_LIST_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getBoolean(index));
+                    return 8L + 1L;
+                  };
+              case INT32, DATE ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getInt(index));
+                    return 8L + 4L;
+                  };
+              case INT64, TIMESTAMP ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getLong(index));
+                    return 8L + 8L;
+                  };
+              case FLOAT ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getFloat(index));
+                    return 8L + 4L;
+                  };
+              case DOUBLE ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getDouble(index));
+                    return 8L + 8L;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, tvList, index) -> {
+                    Binary value = tvList.getBinary(index);
+                    writer.write(time, value);
+                    return 8L + MemUtils.getBinarySize(value);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListBatchWriter> TV_LIST_BATCH_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    boolean value = tvList.getBoolean(index);
+                    if (filter != null && !filter.satisfyBoolean(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeBoolean(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case INT32, DATE ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    int value = tvList.getInt(index);
+                    if (filter != null && !filter.satisfyInteger(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeInt(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case INT64, TIMESTAMP ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    long value = tvList.getLong(index);
+                    if (filter != null && !filter.satisfyLong(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeLong(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case FLOAT ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    float value = tvList.getFloat(index);
+                    if (!Float.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    if (filter != null && !filter.satisfyFloat(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeFloat(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case DOUBLE ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    double value = tvList.getDouble(index);
+                    if (!Double.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    if (filter != null && !filter.satisfyDouble(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeDouble(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    Binary value = tvList.getBinary(index);
+                    if (filter != null && !filter.satisfyBinary(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeBinary(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    private static boolean consumeOffset(PaginationController paginationController) {
+      if (paginationController != null && paginationController.hasCurOffset()) {
+        paginationController.consumeOffset();
+        return true;
+      }
+      return false;
+    }
+
+    private static void consumeLimit(PaginationController paginationController) {
+      if (paginationController != null) {
+        paginationController.consumeLimit();
+      }
+    }
+
+    public static final TypeService<AlignedTVListChunkWriter> ALIGNED_TV_LIST_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? false : tvList.getBooleanByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case INT32, DATE ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0 : tvList.getIntByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0L : tvList.getLongByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case FLOAT ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0F : tvList.getFloatByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case DOUBLE ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0D : tvList.getDoubleByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? null : tvList.getBinaryByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueChunkArrayWriter> VALUE_CHUNK_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, !isNull && values != null && ((boolean[]) values)[index], isNull);
+              case INT32, DATE ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0 : ((int[]) values)[index], isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0L : ((long[]) values)[index], isNull);
+              case FLOAT ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0F : ((float[]) values)[index], isNull);
+              case DOUBLE ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0D : ((double[]) values)[index], isNull);
+              case TEXT, STRING, BLOB, OBJECT ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time,
+                          isNull || values == null ? null : ((Binary[]) values)[index],
+                          isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueChunkArrayBatchWriter>
+        VALUE_CHUNK_ARRAY_BATCH_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (boolean[]) values, nulls, count, offset);
+                  case INT32, DATE ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (int[]) values, nulls, count, offset);
+                  case INT64, TIMESTAMP ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (long[]) values, nulls, count, offset);
+                  case FLOAT ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (float[]) values, nulls, count, offset);
+                  case DOUBLE ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (double[]) values, nulls, count, offset);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (Binary[]) values, nulls, count, offset);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    // Preserve the bitmap path so nulls do not require a temporary boolean array or value encoding.
+    public static final TypeService<ValueChunkArrayBitmapWriter>
+        VALUE_CHUNK_ARRAY_BITMAP_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (boolean[]) values, bitMap, offset, count, offset);
+                  case INT32, DATE ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (int[]) values, bitMap, offset, count, offset);
+                  case INT64, TIMESTAMP ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (long[]) values, bitMap, offset, count, offset);
+                  case FLOAT ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (float[]) values, bitMap, offset, count, offset);
+                  case DOUBLE ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (double[]) values, bitMap, offset, count, offset);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (Binary[]) values, bitMap, offset, count, offset);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<IntFunction<Object>> PRIMITIVE_ARRAY_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE, TEXT, BLOB, STRING, OBJECT ->
+                  type::createArray;
+              case DATE -> Type.fromTsDataType(TSDataType.INT32)::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<SourceColumnToTabletValueWriter>
+        SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((boolean[]) targetColumn)[targetIndex] =
+                              sourceType.getBoolean(sourceColumn, sourceIndex);
+                  case INT32, DATE ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((int[]) targetColumn)[targetIndex] =
+                              sourceType.getInt(sourceColumn, sourceIndex);
+                  case INT64, TIMESTAMP ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((long[]) targetColumn)[targetIndex] =
+                              sourceType.getLong(sourceColumn, sourceIndex);
+                  case FLOAT ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((float[]) targetColumn)[targetIndex] =
+                              sourceType.getFloat(sourceColumn, sourceIndex);
+                  case DOUBLE ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((double[]) targetColumn)[targetIndex] =
+                              sourceType.getDouble(sourceColumn, sourceIndex);
+                  case TEXT, BLOB, STRING ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((Binary[]) targetColumn)[targetIndex] =
+                              sourceType.getBinary(sourceColumn, sourceIndex);
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) -> {
+                        throw new UnSupportedDataTypeException(
+                            DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<Object>> TABLET_COLUMN_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<IntFunction<Object>> EMPTY_TABLET_COLUMN_FACTORY_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::createArray;
+              case DATE ->
+                  size -> {
+                    LocalDate[] values = (LocalDate[]) type.createArray(size);
+                    Arrays.fill(values, LocalDate.of(1000, 1, 1));
+                    return values;
+                  };
+              case TEXT, BLOB, STRING ->
+                  size -> {
+                    Binary[] values = (Binary[]) type.createArray(size);
+                    Arrays.fill(values, Binary.EMPTY_VALUE);
+                    return values;
+                  };
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<WindowValueArrayBuilder> WINDOW_VALUE_ARRAY_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (window, list, begin, size) -> {
+                    int[] values = new int[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getIntByIndex(begin + i);
+                    }
+                    window.setIntValues(values);
+                  };
+              case INT64, TIMESTAMP ->
+                  (window, list, begin, size) -> {
+                    long[] values = new long[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getLongByIndex(begin + i);
+                    }
+                    window.setLongValues(values);
+                  };
+              case FLOAT ->
+                  (window, list, begin, size) -> {
+                    float[] values = new float[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getFloatByIndex(begin + i);
+                    }
+                    window.setFloatValues(values);
+                  };
+              case DOUBLE ->
+                  (window, list, begin, size) -> {
+                    double[] values = new double[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getDoubleByIndex(begin + i);
+                    }
+                    window.setDoubleValues(values);
+                  };
+              case BOOLEAN ->
+                  (window, list, begin, size) -> {
+                    boolean[] values = new boolean[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getBooleanByIndex(begin + i);
+                    }
+                    window.setBooleanValues(values);
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (window, list, begin, size) -> {
+                    Binary[] values = new Binary[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getBinaryByIndex(begin + i);
+                    }
+                    window.setBinaryValues(values);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<BiFunction<ByteBuffer, Integer, Object>>
+        RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::deserializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (buffer, size) -> {
+                        // Tablet RPC has no per-value presence byte; nulls use a separate bitmap.
+                        Binary[] values = new Binary[size];
+                        for (int i = 0; i < size; i++) {
+                          values[i] = ReadWriteIOUtils.readBinary(buffer);
+                        }
+                        return values;
+                      };
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::deserializeArray;
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<RawArrayInputStreamDeserializer>
+        RAW_ARRAY_INPUT_STREAM_DESERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::deserializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (stream, size) -> {
+                        // Match the ByteBuffer tablet reader, not TsFile's array wire format.
+                        Binary[] values = new Binary[size];
+                        for (int i = 0; i < size; i++) {
+                          values[i] = ReadWriteIOUtils.readBinary(stream);
+                        }
+                        return values;
+                      };
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::deserializeArray;
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    @FunctionalInterface
+    public interface ArrayPrefixHasher {
+      int hash(Object column, int rowCount);
+    }
+
+    /** Hash active rows directly, matching tablet equality without copying backing arrays. */
+    public static final TypeService<ArrayPrefixHasher> ARRAY_PREFIX_HASHER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  (column, rowCount) -> {
+                    int[] values = (int[]) column;
+                    int hash = 1;
+                    for (int i = 0; i < rowCount; i++) {
+                      hash = 31 * hash + Integer.hashCode(values[i]);
+                    }
+                    return hash;
+                  };
+              case INT64, TIMESTAMP ->
+                  (column, rowCount) -> {
+                    long[] values = (long[]) column;
+                    int hash = 1;
+                    for (int i = 0; i < rowCount; i++) {
+                      hash = 31 * hash + Long.hashCode(values[i]);
+                    }
+                    return hash;
+                  };
+              case FLOAT ->
+                  (column, rowCount) -> {
+                    float[] values = (float[]) column;
+                    int hash = 1;
+                    for (int i = 0; i < rowCount; i++) {
+                      hash = 31 * hash + Float.hashCode(values[i]);
+                    }
+                    return hash;
+                  };
+              case DOUBLE ->
+                  (column, rowCount) -> {
+                    double[] values = (double[]) column;
+                    int hash = 1;
+                    for (int i = 0; i < rowCount; i++) {
+                      hash = 31 * hash + Double.hashCode(values[i]);
+                    }
+                    return hash;
+                  };
+              case BOOLEAN ->
+                  (column, rowCount) -> {
+                    boolean[] values = (boolean[]) column;
+                    int hash = 1;
+                    for (int i = 0; i < rowCount; i++) {
+                      hash = 31 * hash + Boolean.hashCode(values[i]);
+                    }
+                    return hash;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (column, rowCount) -> {
+                    Object[] values = (Object[]) column;
+                    int hash = 1;
+                    for (int i = 0; i < rowCount; i++) {
+                      hash = 31 * hash + Objects.hashCode(values[i]);
+                    }
+                    return hash;
+                  };
+              case DATE ->
+                  (column, rowCount) -> {
+                    int hash = 1;
+                    if (column instanceof LocalDate[] values) {
+                      // DATE equality also accepts the equivalent integer representation.
+                      for (int i = 0; i < rowCount; i++) {
+                        hash =
+                            31 * hash
+                                + (values[i] == null
+                                    ? DateUtils.EMPTY_DATE_INT
+                                    : DateUtils.parseDateExpressionToInt(values[i]));
+                      }
+                    } else {
+                      int[] values = (int[]) column;
+                      for (int i = 0; i < rowCount; i++) {
+                        hash = 31 * hash + Integer.hashCode(values[i]);
+                      }
+                    }
+                    return hash;
+                  };
+              case ROW, VECTOR, UNKNOWN -> (column, rowCount) -> Objects.hashCode(column);
+            };
+
+    public static final TypeService<ArrayValueGetter> ARRAY_VALUE_GETTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (array, index) -> ((boolean[]) array)[index];
+              case INT32, DATE -> (array, index) -> ((int[]) array)[index];
+              case INT64, TIMESTAMP -> (array, index) -> ((long[]) array)[index];
+              case FLOAT -> (array, index) -> ((float[]) array)[index];
+              case DOUBLE -> (array, index) -> ((double[]) array)[index];
+              case TEXT, BLOB, STRING, OBJECT -> (array, index) -> ((Binary[]) array)[index];
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    static {
+      CHUNK_METADATA_STATISTICS_CONVERTER_SERVICE.check();
+      INSERT_ROW_SERIALIZED_VALUE_SIZE_SERVICE.check();
+      INSERT_TABLET_SERIALIZED_COLUMN_SIZE_SERVICE.check();
+      RAW_ARRAY_BYTE_BUFFER_SERIALIZER_SERVICE.check();
+      RAW_ARRAY_OUTPUT_STREAM_SERIALIZER_SERVICE.check();
+      TABLET_PLAIN_FAST_PATH_SERVICE.check();
+      ALIGNED_TV_LIST_COLUMN_WRITER_SERVICE.check();
+      TV_LIST_ARRAY_WRITER_SERVICE.check();
+      TV_LIST_OBJECT_WRITER_SERVICE.check();
+      TV_LIST_PROVIDER_SERVICE.check();
+      TV_LIST_CHUNK_WRITER_SERVICE.check();
+      TV_LIST_BATCH_WRITER_SERVICE.check();
+      ALIGNED_TV_LIST_CHUNK_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_BATCH_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_BITMAP_WRITER_SERVICE.check();
+      PRIMITIVE_ARRAY_ALLOCATOR_SERVICE.check();
+      SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE.check();
+      TABLET_COLUMN_ALLOCATOR_SERVICE.check();
+      EMPTY_TABLET_COLUMN_FACTORY_SERVICE.check();
+      WINDOW_VALUE_ARRAY_BUILDER_SERVICE.check();
+      RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE.check();
+      RAW_ARRAY_INPUT_STREAM_DESERIALIZER_SERVICE.check();
+      ARRAY_VALUE_GETTER_SERVICE.check();
+      ARRAY_PREFIX_HASHER_SERVICE.check();
+      DECODED_VALUE_CHUNK_WRITER_SERVICE.check();
+      SEGMENTED_ARRAY_SERIALIZED_SIZE_SERVICE.check();
+      ARRAY_VALUE_COLUMN_WRITER_SERVICE.check();
+      ALIGNED_WAL_BATCH_WRITER_SERVICE.check();
+      BATCH_DATA_COLUMN_WRITER_SERVICE.check();
+      OBJECT_VALUE_SERIALIZER_SERVICE.check();
+      TS_PRIMITIVE_VALUE_SERIALIZER_SERVICE.check();
+      EMPTY_TS_PRIMITIVE_TYPE_FACTORY_SERVICE.check();
+      DEFAULT_ENCODING_SERVICE.check();
+      TABLET_COLUMN_DECODER_SERVICE.check();
+      DECODED_ARRAY_VALUE_READER_SERVICE.check();
+      DECODED_CHUNK_WRITER_SERVICE.check();
+    }
+
+    private static Statistics<?> convertNumericOrBooleanStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING) {
+        Binary[] binaryValues = new Binary[4];
+        binaryValues[0] =
+            new Binary(
+                chunkMetadata.getStatistics().getFirstValue().toString(), StandardCharsets.UTF_8);
+        binaryValues[1] =
+            new Binary(
+                chunkMetadata.getStatistics().getLastValue().toString(), StandardCharsets.UTF_8);
+        if (chunkMetadata.getDataType() == TSDataType.BOOLEAN) {
+          binaryValues[2] = new Binary(Boolean.FALSE.toString(), StandardCharsets.UTF_8);
+          binaryValues[3] = new Binary(Boolean.TRUE.toString(), StandardCharsets.UTF_8);
+        } else {
+          binaryValues[2] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8);
+          binaryValues[3] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8);
+        }
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.TEXT) {
+        Binary[] binaryValues = new Binary[2];
+        if (chunkMetadata.getDataType() == TSDataType.BOOLEAN) {
+          binaryValues[0] = new Binary(Boolean.FALSE.toString(), StandardCharsets.UTF_8);
+          binaryValues[1] = new Binary(Boolean.TRUE.toString(), StandardCharsets.UTF_8);
+        } else {
+          binaryValues[0] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8);
+          binaryValues[1] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8);
+        }
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertDateStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType != TSDataType.STRING && targetDataType != TSDataType.TEXT) {
+        return statistics;
+      }
+      int valueCount = targetDataType == TSDataType.STRING ? 4 : 2;
+      Binary[] binaryValues = new Binary[valueCount];
+      binaryValues[0] = toDateBinary(chunkMetadata.getStatistics().getFirstValue());
+      binaryValues[1] = toDateBinary(chunkMetadata.getStatistics().getLastValue());
+      if (targetDataType == TSDataType.STRING) {
+        binaryValues[2] = toDateBinary(chunkMetadata.getStatistics().getMinValue());
+        binaryValues[3] = toDateBinary(chunkMetadata.getStatistics().getMaxValue());
+      }
+      updateStatistics(statistics, chunkMetadata, binaryValues);
+      return statistics;
+    }
+
+    private static Statistics<?> convertStringStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.TEXT) {
+        Binary[] binaryValues = {
+          new Binary(
+              chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8),
+          new Binary(chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8)
+        };
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.BLOB) {
+        statistics.update(
+            chunkMetadata.getStatistics().getStartTime(),
+            new Binary(
+                chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8));
+        statistics.update(
+            chunkMetadata.getStatistics().getEndTime(),
+            new Binary(
+                chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8));
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertTextStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING) {
+        Binary[] binaryValues = {
+          (Binary) chunkMetadata.getStatistics().getFirstValue(),
+          (Binary) chunkMetadata.getStatistics().getLastValue()
+        };
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.BLOB) {
+        statistics.update(chunkMetadata.getStatistics().getStartTime(), EMPTY_BINARY);
+        statistics.update(chunkMetadata.getStatistics().getEndTime(), EMPTY_BINARY);
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertBlobStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING || targetDataType == TSDataType.TEXT) {
+        updateStatistics(statistics, chunkMetadata, new Binary[] {EMPTY_BINARY, EMPTY_BINARY});
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Binary toDateBinary(Object value) {
+      return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+    }
+
+    private static void updateStatistics(
+        Statistics<?> statistics, IChunkMetadata chunkMetadata, Binary[] binaryValues) {
+      long[] longValues = new long[binaryValues.length];
+      longValues[0] = chunkMetadata.getStatistics().getStartTime();
+      longValues[1] = chunkMetadata.getStatistics().getEndTime();
+      Arrays.fill(longValues, 2, longValues.length, longValues[1]);
+      statistics.update(longValues, binaryValues, binaryValues.length);
+    }
+
+    private StorageEngine() {
+      // Utility class
+    }
+  }
+
+  public static final class Predicate {
+
+    public static final TypeService<Function<String, Comparable<?>>>
+        CONVERT_PREDICATE_VALUE_PARSER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> Integer::valueOf;
+                  case INT64, TIMESTAMP -> Long::valueOf;
+                  case FLOAT -> Float::valueOf;
+                  case DOUBLE -> Double::valueOf;
+                  case BOOLEAN ->
+                      valueString -> {
+                        if (valueString.equalsIgnoreCase("true")) {
+                          return Boolean.TRUE;
+                        } else if (valueString.equalsIgnoreCase("false")) {
+                          return Boolean.FALSE;
+                        }
+                        throw new IllegalArgumentException(
+                            String.format(
+                                DataNodeQueryMessages.EXCEPTION_ARG_CANNOT_BE_CAST_TO_ARG_28F0C5FC,
+                                valueString,
+                                type.getTypeEnum()));
+                      };
+                  case BLOB -> valueString -> new Binary(BaseEncoding.base16().decode(valueString));
+                  case TEXT, STRING ->
+                      valueString -> new Binary(valueString, TSFileConfig.STRING_CHARSET);
+                  case DATE -> DateTimeUtils::parseDateExpressionToInt;
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new UnsupportedOperationException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()));
+                };
+
+    public static final TypeService<Function<Literal, Comparable<?>>>
+        RELATIONAL_CONVERT_PREDICATE_VALUE_PARSER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> Integer.valueOf((int) getLongValue(value));
+                  case DATE -> value -> Integer.valueOf(((GenericLiteral) value).getValue());
+                  case INT64 -> value -> Long.valueOf(getLongValue(value));
+                  case TIMESTAMP -> TypeServices::getTimestampValue;
+                  case FLOAT -> value -> Float.valueOf((float) getDoubleValue(value));
+                  case DOUBLE -> value -> Double.valueOf(getDoubleValue(value));
+                  case BOOLEAN -> value -> Boolean.valueOf(((BooleanLiteral) value).getValue());
+                  case TEXT, STRING ->
+                      value ->
+                          new Binary(
+                              ((StringLiteral) value).getValue(), TSFileConfig.STRING_CHARSET);
+                  case BLOB -> value -> new Binary(((BinaryLiteral) value).getValue());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new UnsupportedOperationException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()));
+                };
+
+    public static final TypeService<Function<Column, Literal>>
+        UNCORRELATED_SCALAR_SUBQUERY_RESULT_LITERAL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      column -> new LongLiteral(Long.toString(type.getInt(column, 0)));
+                  case INT64, TIMESTAMP ->
+                      column -> new LongLiteral(Long.toString(type.getLong(column, 0)));
+                  case FLOAT -> column -> new FloatLiteral(type.getFloat(column, 0));
+                  case DOUBLE ->
+                      column -> new DoubleLiteral(Double.toString(type.getDouble(column, 0)));
+                  case BOOLEAN ->
+                      column -> new BooleanLiteral(Boolean.toString(type.getBoolean(column, 0)));
+                  case BLOB -> column -> new BinaryLiteral(type.getBinary(column, 0).toString());
+                  case TEXT, STRING ->
+                      column -> new StringLiteral(type.getBinary(column, 0).toString());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new IllegalArgumentException(
+                          String.format(
+                              DataNodeQueryMessages
+                                  .EXCEPTION_UNSUPPORTED_DATA_TYPE_FOR_SCALAR_SUBQUERY_RESULT_ARG_D58CBB00,
+                              type.getTypeEnum()));
+                };
+
+    private Predicate() {
+      // Utility class
+    }
+  }
+
+  public static final class Pipe {
+
+    public static final TypeService<Function<Object, Object>> OPC_UA_LAST_VALUE_CONVERTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case DATE ->
+                  value ->
+                      new DateTime(
+                          new java.util.Date(
+                              DateUtils.parseIntToDate(((Number) value).intValue()).getTime()));
+              case TIMESTAMP ->
+                  value ->
+                      new DateTime(
+                          TimestampPrecisionUtils.currPrecision.toNanos(
+                                      ((Number) value).longValue())
+                                  / 100L
+                              + 116444736000000000L);
+              case TEXT, BLOB, STRING -> String::valueOf;
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE -> Function.identity();
+              case ROW, VECTOR, OBJECT, UNKNOWN ->
+                  value -> {
+                    throw new UnSupportedDataTypeException(
+                        DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<SameTypeNumericOperatorStrategy>
+        SAME_TYPE_NUMERIC_OPERATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.INT32,
+                          AbstractSameTypeNumericOperator::getIntValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getIntValue(), stream),
+                          (operator, buffer) ->
+                              operator.setIntValue(ReadWriteIOUtils.readInt(buffer)));
+                  case INT64 ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.INT64,
+                          AbstractSameTypeNumericOperator::getLongValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getLongValue(), stream),
+                          (operator, buffer) ->
+                              operator.setLongValue(ReadWriteIOUtils.readLong(buffer)));
+                  case FLOAT ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.FLOAT,
+                          AbstractSameTypeNumericOperator::getFloatValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getFloatValue(), stream),
+                          (operator, buffer) ->
+                              operator.setFloatValue(ReadWriteIOUtils.readFloat(buffer)));
+                  case DOUBLE ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.DOUBLE,
+                          AbstractSameTypeNumericOperator::getDoubleValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getDoubleValue(), stream),
+                          (operator, buffer) ->
+                              operator.setDoubleValue(ReadWriteIOUtils.readDouble(buffer)));
+                  case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      unsupportedSameTypeNumericOperatorStrategy(
+                          TSDataType.valueOf(type.getTypeEnum().name()));
+                };
+
+    private static SameTypeNumericOperatorStrategy sameTypeNumericOperatorStrategy(
+        final TSDataType dataType,
+        final Function<AbstractSameTypeNumericOperator, Object> valueGetter,
+        final SameTypeNumericOperatorSerializer serializer,
+        final SameTypeNumericOperatorDeserializer deserializer) {
+      return new SameTypeNumericOperatorStrategy(dataType, valueGetter, serializer, deserializer);
+    }
+
+    private static SameTypeNumericOperatorStrategy unsupportedSameTypeNumericOperatorStrategy(
+        final TSDataType dataType) {
+      return new SameTypeNumericOperatorStrategy(
+          dataType,
+          operator -> null,
+          (operator, stream) -> {
+            throw new IOException(
+                String.format(DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT, dataType));
+          },
+          (operator, buffer) -> {
+            throw new IOException(
+                String.format(DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT, dataType));
+          });
+    }
+
+    public static final class SameTypeNumericOperatorStrategy {
+      private final TSDataType dataType;
+      private final Function<AbstractSameTypeNumericOperator, Object> valueGetter;
+      private final SameTypeNumericOperatorSerializer serializer;
+      private final SameTypeNumericOperatorDeserializer deserializer;
+
+      private SameTypeNumericOperatorStrategy(
+          final TSDataType dataType,
+          final Function<AbstractSameTypeNumericOperator, Object> valueGetter,
+          final SameTypeNumericOperatorSerializer serializer,
+          final SameTypeNumericOperatorDeserializer deserializer) {
+        this.dataType = dataType;
+        this.valueGetter = valueGetter;
+        this.serializer = serializer;
+        this.deserializer = deserializer;
+      }
+
+      public Pair<TSDataType, Object> getResult(final AbstractSameTypeNumericOperator operator) {
+        final Object value = valueGetter.apply(operator);
+        return value == null ? null : new Pair<>(dataType, value);
+      }
+
+      public void serialize(
+          final AbstractSameTypeNumericOperator operator, final DataOutputStream stream)
+          throws IOException {
+        serializer.serialize(operator, stream);
+      }
+
+      public void deserialize(
+          final AbstractSameTypeNumericOperator operator, final ByteBuffer buffer)
+          throws IOException {
+        deserializer.deserialize(operator, buffer);
+      }
+    }
+
+    @FunctionalInterface
+    private interface SameTypeNumericOperatorSerializer {
+      void serialize(AbstractSameTypeNumericOperator operator, DataOutputStream stream)
+          throws IOException;
+    }
+
+    @FunctionalInterface
+    private interface SameTypeNumericOperatorDeserializer {
+      void deserialize(AbstractSameTypeNumericOperator operator, ByteBuffer buffer)
+          throws IOException;
+    }
+
+    public static final TypeService<Short> OPC_DA_VARIANT_TYPE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> Variant.VT_BOOL;
+              case INT32 -> Variant.VT_I4;
+              case INT64 -> Variant.VT_I8;
+              case DATE, TIMESTAMP -> Variant.VT_DATE;
+              case FLOAT -> Variant.VT_R4;
+              case DOUBLE -> Variant.VT_R8;
+              // Note that "Variant" does not support "VT_BLOB" data, and not all the DA servers
+              // support this, thus we use "VT_BSTR" to substitute.
+              case TEXT, STRING, BLOB, OBJECT -> Variant.VT_BSTR;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<OpcDaTabletValueSetter> OPC_DA_TABLET_VALUE_SETTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_BOOL, new OaIdl.VARIANT_BOOL(((boolean[]) column)[rowIndex]));
+                    return null;
+                  };
+              case INT32 ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_I4, new WinDef.LONG(((int[]) column)[rowIndex]));
+                    return null;
+                  };
+              case DATE ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_DATE,
+                        new OaIdl.DATE(Date.valueOf(((LocalDate[]) column)[rowIndex])));
+                    return null;
+                  };
+              case INT64 ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_I8, new WinDef.LONGLONG(((long[]) column)[rowIndex]));
+                    return null;
+                  };
+              case TIMESTAMP ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_DATE,
+                        new OaIdl.DATE(new java.util.Date(((long[]) column)[rowIndex])));
+                    return null;
+                  };
+              case FLOAT ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_R4, ((float[]) column)[rowIndex]);
+                    return null;
+                  };
+              case DOUBLE ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_R8, ((double[]) column)[rowIndex]);
+                    return null;
+                  };
+              case TEXT, STRING, BLOB, OBJECT ->
+                  (value, column, rowIndex) -> {
+                    final WTypes.BSTR bstr =
+                        OleAuto.INSTANCE.SysAllocString(((Binary[]) column)[rowIndex].toString());
+                    value.setValue(Variant.VT_BSTR, bstr);
+                    return bstr;
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  (value, column, rowIndex) -> {
+                    throw new UnSupportedDataTypeException(
+                        DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Function<Object, String>> OPC_UA_VALUE_STRINGIFIER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT, BLOB, STRING -> Object::toString;
+              case DATE ->
+                  value -> ((LocalDate) value).atStartOfDay(ZoneId.systemDefault()).toString();
+              case TIMESTAMP -> value -> DateTimeUtils.convertLongToDate((long) value);
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  value -> {
+                    throw new PipeRuntimeNonCriticalException(
+                        DataNodePipeMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToIntFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_INT_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (int) (long) value;
+                  case FLOAT -> value -> (int) (float) value;
+                  case DOUBLE -> value -> (int) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to int.", type.getTypeEnum()));

Review Comment:
   [P2] Preserve localized errors in the extracted type services
   
   This branch replaces `DataNodePipeMessages.PIPE_EXCEPTION_THE_TYPE_S_CANNOT_BE_CASTED_TO_INT_659069CC` with a raw English string. In a `-P with-zh-locale` build, calling `CustomizedReadableIntermediateResults.getInt()` for a `BOOLEAN` intermediate result now emits `The type BOOLEAN cannot be casted to int.` instead of the existing Chinese message.
   
   Please reuse the existing `DataNodePipeMessages` constants for these conversion errors. The long/float/double/string strategies below have the same regression. The extracted `ROUND_TRANSFORMER_SERVICE`, `unsupportedSourceCastStrategy`, and `unsupportedTargetCastStrategy` also replace `DataNodeQueryMessages` constants with English literals; please restore those localized messages as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r3977848270


##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java:
##########
@@ -603,6 +603,10 @@ private DataNodeMiscMessages() {}
   public static final String INPUT_DOUBLE_INFINITY = "The input double value is Infinity";
   public static final String BOOLEAN_PARSE_ERROR =
       "The BOOLEAN should be true/TRUE, false/FALSE or 0/1";
+  public static final String DATA_TYPE_NOT_CONSISTENT_FMT =
+      "data type is not consistent, input %s, registered %s";
+  public static final String DATA_TYPE_NOT_CONSISTENT_WITH_CAUSE_FMT =
+      "data type is not consistent, input %s, registered %s because %s";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). The two newly introduced inconsistent-type messages now use the generated EXCEPTION_<normalized text>_<hash> names in both locale files, with their TypeServices call sites updated together. The existing unrelated UNSUPPORTED_DATA_TYPE_FMT key is retained. English and Chinese source reactor builds pass.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java:
##########
@@ -1541,6 +1541,12 @@ public final class DataNodePipeMessages {
   public static final String FAILED_TO_UNBIND_FROM_PIPE_TSFILE_TO =
       "Failed to unbind from pipe tsfile to tablets metrics, pipe map is not empty, pipe: {}";
 
+  // ---------------------------------------------------------------------------
+  // pipe – PipeRow
+  // ---------------------------------------------------------------------------
+  public static final String UNSUPPORTED_DATA_TYPE_FOR_COLUMN_FMT =
+      "unsupported data type %s for column %s";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9): the key is now EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_FOR_COLUMN_ARG_4C4CCA6D in both locale files, and both pipe row-reading call sites use it. The message placeholders are preserved; English and Chinese source reactor builds pass.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java:
##########
@@ -528,6 +528,18 @@ public final class DataNodeQueryMessages {
       "TIMESTAMP does not support REGEXP/NOT REGEXP";
   public static final String GROUPBYTIME_FILTER_CANNOT_EXIST_IN_VALUE_FILTER =
       "GroupByTime filter cannot exist in value filter.";
+  public static final String VALUE_CANNOT_BE_CAST_TO_DATA_TYPE_FMT =
+      "\"%s\" cannot be cast to [%s]";
+  public static final String UNSUPPORTED_DATA_TYPE_FMT =
+      "Unsupported data type %s";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). All newly added keys in this block now follow the generated exception-message naming convention in both locales, including the cast, unsupported type, MaxBy/MinBy, equal/variation event and TIMESTAMP IN-list messages. The associated aggregation, predicate-conversion and TypeServices call sites and message assertions were updated together. English and Chinese source reactor builds pass.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java:
##########
@@ -1020,6 +1032,8 @@ public final class DataNodeQueryMessages {
       "Unexpected expression: ";
   public static final String FAILED_TO_FETCH_SUBQUERY_RESULT =
       "Failed to Fetch Subquery Result.";
+  public static final String UNSUPPORTED_SCALAR_SUBQUERY_RESULT_DATA_TYPE_FMT =
+      "Unsupported data type for scalar subquery result: %s";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9): both locale files and the scalar-subquery conversion call site now use EXCEPTION_UNSUPPORTED_DATA_TYPE_FOR_SCALAR_SUBQUERY_RESULT_ARG_D58CBB00. English and Chinese source reactor builds pass.



##########
iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java:
##########
@@ -1393,6 +1407,8 @@ public final class DataNodeQueryMessages {
       "Error occurred during getting UDF access strategy";
   public static final String TRANSFORMUTILS_SHOULD_NOT_BE_INSTANTIATED =
       "TransformUtils should not be instantiated.";
+  public static final String INVALID_DATA_TYPE_FOR_STATE_WINDOW_STRATEGY =
+      "The data type of the state window strategy is not valid.";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9): both locale files and the state-window strategy call site now use EXCEPTION_THE_DATA_TYPE_OF_THE_STATE_WINDOW_STRATEGY_IS_NOT_VALID_61F4E273. English and Chinese source reactor builds pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4023234546


##########
pom.xml:
##########
@@ -146,7 +147,7 @@
         <thrift.version>0.24.0</thrift.version>
         <xz.version>1.9</xz.version>
         <zstd-jni.version>1.5.6-3</zstd-jni.version>
-        <tsfile.version>2.4.1-260909-SNAPSHOT</tsfile.version>
+        <tsfile.version>2.4.1-260915-SNAPSHOT</tsfile.version>

Review Comment:
   Upgrade to the published TsFile snapshot containing apache/tsfile#961 so the generic Column access used by this refactor supports TimeColumn and dictionary logical positions. Both P1 threads contain the old/new artifact verification and its class-level scope.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/AvgAccumulator.java:
##########
@@ -62,65 +66,15 @@ public void addInput(Column[] arguments, AggregationMask mask) {
     checkArgument(
         arguments.length == 1,
         CalcMessages.EXCEPTION_ARGUMENT_OF_AVG_SHOULD_BE_ONE_COLUMN_82162B82);
-    switch (argumentDataType) {
-      case INT32:
-        addIntInput(arguments[0], mask);
-        return;
-      case INT64:
-        addLongInput(arguments[0], mask);
-        return;
-      case FLOAT:
-        addFloatInput(arguments[0], mask);
-        return;
-      case DOUBLE:
-        addDoubleInput(arguments[0], mask);
-        return;
-      case TEXT:
-      case BLOB:
-      case OBJECT:
-      case STRING:
-      case BOOLEAN:
-      case DATE:
-      case TIMESTAMP:
-      default:
-        throw new UnSupportedDataTypeException(
-            String.format(
-                CalcMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_AGGREGATION_AVG_ARG_4E63A3C3,
-                argumentDataType));
-    }
+    inputStrategy.addInput(this, arguments[0], mask);

Review Comment:
   Move AVG add/remove scans into native TypeService strategies and write sum/count back once per batch. Starting from the existing sum preserves floating-point order. NumericBatchAggregationTest covers masks, nulls, removal and ordering. Local mixed-type kernels improved 6.13–8.78x; fixed DOUBLE was approximately flat for full selection and improved with masks.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedSumAccumulator.java:
##########
@@ -22,24 +22,28 @@
 import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BooleanBigArray;
 import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.DoubleBigArray;
 import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.utils.TypeServices;
 
 import org.apache.tsfile.block.column.Column;
 import org.apache.tsfile.block.column.ColumnBuilder;
 import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.read.common.type.Type;
 import org.apache.tsfile.utils.RamUsageEstimator;
-import org.apache.tsfile.write.UnSupportedDataTypeException;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
 public class GroupedSumAccumulator implements GroupedAccumulator {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(GroupedSumAccumulator.class);
   private final TSDataType argumentDataType;
+  private final TypeServices.GroupedSumInput inputStrategy;
   private final BooleanBigArray initResult = new BooleanBigArray();
   private final DoubleBigArray sumValues = new DoubleBigArray();
 
   public GroupedSumAccumulator(TSDataType argumentDataType) {
     this.argumentDataType = argumentDataType;
+    Type type = Type.fromTsDataType(argumentDataType);
+    this.inputStrategy = TypeServices.GROUPED_SUM_INPUT_SERVICE.call(type);

Review Comment:
   Use a typed batch loop for grouped SUM, indexing groupIds by the logical selected position and preserving null/initialization behavior. NumericBatchAggregationTest covers masks and group placement. Local mixed-type kernels improved 3.11–3.56x, with a tradeoff: fixed-DOUBLE full/masked runs were about 3.5%/7.4% slower. These are warmed local microbenchmarks, not SQL throughput.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedAvgAccumulator.java:
##########
@@ -42,11 +43,14 @@ public class GroupedAvgAccumulator implements GroupedAccumulator {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(GroupedAvgAccumulator.class);
   private final TSDataType argumentDataType;
+  private final TypeServices.GroupedAvgInput inputStrategy;
   private final LongBigArray countValues = new LongBigArray();
   private final DoubleBigArray sumValues = new DoubleBigArray();
 
   public GroupedAvgAccumulator(TSDataType argumentDataType) {
     this.argumentDataType = argumentDataType;
+    Type type = Type.fromTsDataType(argumentDataType);
+    this.inputStrategy = TypeServices.GROUPED_AVG_INPUT_SERVICE.call(type);

Review Comment:
   Use a typed batch loop for grouped AVG so input type dispatch is outside the row loop. Group IDs still use logical input positions, and count/sum updates preserve input order. NumericBatchAggregationTest verifies masks, group placement and floating-point order; local mixed-type kernels improved 3.08–3.38x, with fixed-DOUBLE performance flat or better.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/MinAccumulator.java:
##########
@@ -20,31 +20,38 @@
 package org.apache.iotdb.calc.execution.operator.source.relational.aggregation;
 
 import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.utils.TypeServices;
 
 import org.apache.tsfile.block.column.Column;
 import org.apache.tsfile.block.column.ColumnBuilder;
 import org.apache.tsfile.enums.TSDataType;
-import org.apache.tsfile.file.metadata.statistics.BinaryStatistics;
 import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.type.Type;
 import org.apache.tsfile.utils.Binary;
 import org.apache.tsfile.utils.RamUsageEstimator;
 import org.apache.tsfile.utils.TsPrimitiveType;
 import org.apache.tsfile.write.UnSupportedDataTypeException;
 
-import java.nio.charset.StandardCharsets;
+import java.util.function.Supplier;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
 public class MinAccumulator implements TableAccumulator {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(MinAccumulator.class);
   private final TSDataType seriesDataType;
+  private final Type type;
+  private final TypeServices.ColumnBatchUpdater valueUpdater;
+  private final TypeServices.StatisticsValueUpdater statisticsValueUpdater;
   private final TsPrimitiveType minResult;
   private boolean initResult;
 
   public MinAccumulator(TSDataType seriesDataType) {
     this.seriesDataType = seriesDataType;
-    this.minResult = TsPrimitiveType.getByType(seriesDataType);
+    this.type = Type.fromTsDataType(seriesDataType);
+    this.minResult = type.getTsPrimitiveType();
+    this.valueUpdater = TypeServices.MIN_COLUMN_BATCH_UPDATER_SERVICE.call(type);

Review Comment:
   MIN now selects a TypeService strategy containing the native scan, removing the shared per-value updater dispatch. NumericBatchAggregationTest verifies masked/null inputs and the existing NaN, signed-zero and integer-boundary behavior. The local mixed-type benchmark improved; fixed-DOUBLE results were smaller or approximately flat.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/MaxAccumulator.java:
##########
@@ -20,31 +20,38 @@
 package org.apache.iotdb.calc.execution.operator.source.relational.aggregation;
 
 import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.utils.TypeServices;
 
 import org.apache.tsfile.block.column.Column;
 import org.apache.tsfile.block.column.ColumnBuilder;
 import org.apache.tsfile.enums.TSDataType;
-import org.apache.tsfile.file.metadata.statistics.BinaryStatistics;
 import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.type.Type;
 import org.apache.tsfile.utils.Binary;
 import org.apache.tsfile.utils.RamUsageEstimator;
 import org.apache.tsfile.utils.TsPrimitiveType;
 import org.apache.tsfile.write.UnSupportedDataTypeException;
 
-import java.nio.charset.StandardCharsets;
+import java.util.function.Supplier;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
 public class MaxAccumulator implements TableAccumulator {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(MaxAccumulator.class);
   private final TSDataType seriesDataType;
+  private final Type type;
+  private final TypeServices.ColumnBatchUpdater valueUpdater;
+  private final TypeServices.StatisticsValueUpdater statisticsValueUpdater;
   private final TsPrimitiveType maxResult;
   private boolean initResult;
 
   public MaxAccumulator(TSDataType seriesDataType) {
     this.seriesDataType = seriesDataType;
-    this.maxResult = TsPrimitiveType.getByType(seriesDataType);
+    this.type = Type.fromTsDataType(seriesDataType);
+    this.maxResult = type.getTsPrimitiveType();
+    this.valueUpdater = TypeServices.MAX_COLUMN_BATCH_UPDATER_SERVICE.call(type);

Review Comment:
   MAX now selects a TypeService strategy containing the native scan, removing the shared per-value updater dispatch. NumericBatchAggregationTest verifies masked/null inputs and the existing NaN, signed-zero and integer-boundary behavior. The local mixed-type benchmark improved; fixed-DOUBLE results were smaller or approximately flat.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/ExtremeAccumulator.java:
##########
@@ -19,25 +19,36 @@
 
 package org.apache.iotdb.calc.execution.operator.source.relational.aggregation;
 
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.utils.TypeServices;
+
 import org.apache.tsfile.block.column.Column;
 import org.apache.tsfile.block.column.ColumnBuilder;
 import org.apache.tsfile.enums.TSDataType;
 import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.type.Type;
 import org.apache.tsfile.utils.RamUsageEstimator;
 import org.apache.tsfile.utils.TsPrimitiveType;
 import org.apache.tsfile.write.UnSupportedDataTypeException;
 
+import java.util.function.Supplier;
+
 public class ExtremeAccumulator implements TableAccumulator {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(ExtremeAccumulator.class);
-  private static final String UNSUPPORTED_DATA_TYPE = "Unsupported data type in EXTREME: %s";
   private final TSDataType seriesDataType;
+  private final Type type;
   private final TsPrimitiveType extremeResult;
+  private final TypeServices.ColumnBatchUpdater valueUpdater;
+  private final TypeServices.StatisticsValueUpdater statisticsValueUpdater;
   private boolean initResult;
 
   public ExtremeAccumulator(TSDataType seriesDataType) {
     this.seriesDataType = seriesDataType;
-    this.extremeResult = TsPrimitiveType.getByType(seriesDataType);
+    this.type = Type.fromTsDataType(seriesDataType);
+    this.extremeResult = type.getTsPrimitiveType();
+    this.valueUpdater = TypeServices.EXTREME_COLUMN_BATCH_UPDATER_SERVICE.call(type);

Review Comment:
   EXTREME now selects a TypeService strategy containing the native scan, removing the shared per-value updater dispatch. NumericBatchAggregationTest verifies masked/null inputs and the existing NaN, signed-zero and integer-boundary behavior. The local mixed-type benchmark improved; fixed-DOUBLE results were smaller or approximately flat.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4023233268


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/LastAccumulator.java:
##########
@@ -80,35 +90,7 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     // arguments[0] is value column, arguments[1] is time column
-    switch (seriesDataType) {
-      case INT32:
-      case DATE:
-        addIntInput(arguments[0], arguments[1], mask);
-        return;
-      case INT64:
-      case TIMESTAMP:
-        addLongInput(arguments[0], arguments[1], mask);
-        return;
-      case FLOAT:
-        addFloatInput(arguments[0], arguments[1], mask);
-        return;
-      case DOUBLE:
-        addDoubleInput(arguments[0], arguments[1], mask);
-        return;
-      case TEXT:
-      case STRING:
-      case BLOB:
-      case OBJECT:
-        addBinaryInput(arguments[0], arguments[1], mask);
-        return;
-      case BOOLEAN:
-        addBooleanInput(arguments[0], arguments[1], mask);
-        return;
-      default:
-        throw new UnSupportedDataTypeException(
-            String.format(
-                CalcMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_LAST_ARG_37F52124, seriesDataType));
-    }
+    addInput(arguments[0], arguments[1], mask);

Review Comment:
   The shared LAST/LAST_BY loops now return as soon as `hasFinalResult()` becomes true. This carries the descending subclasses' termination condition into the shared path while keeping non-finalizable inputs scanning. `LastDescendingInputTest` checks that a descending block reads only one qualifying timestamp and that non-finalizable LAST_BY still scans the block; both tests pass.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/utils/TypeServices.java:
##########
@@ -0,0 +1,3927 @@
+/*
+ * 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.iotdb.calc.utils;
+
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFillFilter;
+import org.apache.iotdb.calc.execution.operator.process.fill.ILinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.DoubleLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.FloatLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.IntLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.LongLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BinaryNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BooleanNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.DoubleNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.FloatNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.IntNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.LongNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.JoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.window.partition.Partition;
+import org.apache.iotdb.calc.execution.operator.process.window.utils.ColumnList;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AbstractApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AggregationMask;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BinaryApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BlobApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BooleanApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.DoubleApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.FloatApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.IntApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.LongApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.TableAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.approximate.HyperLogLog;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.AbstractGroupedApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BinaryGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BlobGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BooleanGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.DoubleGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.FloatGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedMaxMinByBaseAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.IntGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.LongGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BinaryBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BooleanBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.DoubleBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.FloatBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.IntBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.LongBigArray;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBlobLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBooleanLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDateLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDoubleLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToFloatLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt32LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt64LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToStringLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToTimestampLiteralVisitor;
+import org.apache.iotdb.calc.transformation.dag.column.ColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBinaryMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBooleanMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InDoubleMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InFloatMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt32MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt64MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.datastructure.SortKey;
+import org.apache.iotdb.commons.exception.IoTDBRuntimeException;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+
+import java.time.ZoneId;
+import java.time.format.DateTimeParseException;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.function.IntConsumer;
+import java.util.function.IntFunction;
+import java.util.function.IntUnaryOperator;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_ARRAY_HEADER_SIZE;
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_OBJECT_HEADER_SIZE;
+
+public class TypeServices {
+
+  /**
+   * Wraps a type service whose result is immutable/stateless and can therefore be shared for all
+   * instances of the same data type. Type objects are intentionally reduced to their enum here: all
+   * services wrapped with this helper dispatch only on {@code getTypeEnum()}.
+   */
+  private static <T> TypeService<T> cached(final TypeService<T> service) {
+    final Map<Object, T> cache = new ConcurrentHashMap<>();
+    return type -> cache.computeIfAbsent(type.getTypeEnum(), ignored -> service.call(type));
+  }
+
+  private static final IdentityLinearFill IDENTITY_LINEAR_FILL = new IdentityLinearFill();
+  private static final IdentityFill IDENTITY_FILL = new IdentityFill();
+
+  // Unsupported fill types defer their exception until the returned strategy is used so check()
+  // can still validate that every TypeEnum has a service entry.
+  public static final TypeService<Supplier<ILinearFill>> LINEAR_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE -> IntLinearFill::new;
+            case INT64, TIMESTAMP -> LongLinearFill::new;
+            case FLOAT -> FloatLinearFill::new;
+            case DOUBLE -> DoubleLinearFill::new;
+            case BOOLEAN, TEXT, STRING, BLOB, OBJECT -> () -> IDENTITY_LINEAR_FILL;
+            case ROW, UNKNOWN, VECTOR ->
+                () -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, IFill>> PREVIOUS_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                filter ->
+                    filter == null
+                        ? new BooleanPreviousFill()
+                        : new BooleanPreviousFillWithTimeDuration(filter);
+            case TEXT, STRING, BLOB, OBJECT ->
+                filter ->
+                    filter == null
+                        ? new BinaryPreviousFill()
+                        : new BinaryPreviousFillWithTimeDuration(filter);
+            case INT32, DATE ->
+                filter ->
+                    filter == null
+                        ? new IntPreviousFill()
+                        : new IntPreviousFillWithTimeDuration(filter);
+            case INT64, TIMESTAMP ->
+                filter ->
+                    filter == null
+                        ? new LongPreviousFill()
+                        : new LongPreviousFillWithTimeDuration(filter);
+            case FLOAT ->
+                filter ->
+                    filter == null
+                        ? new FloatPreviousFill()
+                        : new FloatPreviousFillWithTimeDuration(filter);
+            case DOUBLE ->
+                filter ->
+                    filter == null
+                        ? new DoublePreviousFill()
+                        : new DoublePreviousFillWithTimeDuration(filter);
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, ILinearFill>> NEXT_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> BooleanNextFill::new;
+            case TEXT, STRING, BLOB, OBJECT -> BinaryNextFill::new;
+            case INT32, DATE -> IntNextFill::new;
+            case INT64, TIMESTAMP -> LongNextFill::new;
+            case FLOAT -> FloatNextFill::new;
+            case DOUBLE -> DoubleNextFill::new;
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<BooleanFunction<JoinKeyComparator>> JOIN_KEY_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    ascending ->
+                        ascending
+                            ? AscIntTypeJoinKeyComparator.getInstance()
+                            : DescIntTypeJoinKeyComparator.getInstance();
+                case INT64, TIMESTAMP ->
+                    ascending ->
+                        ascending
+                            ? AscLongTypeJoinKeyComparator.getInstance()
+                            : DescLongTypeJoinKeyComparator.getInstance();
+                case FLOAT ->
+                    ascending ->
+                        ascending
+                            ? AscFloatTypeJoinKeyComparator.getInstance()
+                            : DescFloatTypeJoinKeyComparator.getInstance();
+                case DOUBLE ->
+                    ascending ->
+                        ascending
+                            ? AscDoubleTypeJoinKeyComparator.getInstance()
+                            : DescDoubleTypeJoinKeyComparator.getInstance();
+                case BOOLEAN ->
+                    ascending ->
+                        ascending
+                            ? AscBooleanTypeJoinKeyComparator.getInstance()
+                            : DescBooleanTypeJoinKeyComparator.getInstance();
+                case STRING, BLOB, TEXT ->
+                    ascending ->
+                        ascending
+                            ? AscBinaryTypeJoinKeyComparator.getInstance()
+                            : DescBinaryTypeJoinKeyComparator.getInstance();
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    ascending -> {
+                      throw new UnsupportedOperationException(
+                          CalcMessages.UNSUPPORTED_DATA_TYPE + type);
+                    };
+              });
+
+  public static final TypeService<IntFunction<Comparator<SortKey>>> MERGE_SORT_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    index ->
+                        Comparator.comparingInt(
+                            sortKey ->
+                                type.getInt(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case INT64, TIMESTAMP ->
+                    index ->
+                        Comparator.comparingLong(
+                            sortKey ->
+                                type.getLong(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case FLOAT ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getFloat(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case DOUBLE ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getDouble(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case TEXT, STRING, BLOB, OBJECT ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBinary(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case BOOLEAN ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBoolean(
+                                    sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                // TypeService.check() must be able to build a strategy for every enum value.
+                case ROW, UNKNOWN, VECTOR ->
+                    index -> {
+                      throw new IllegalArgumentException(
+                          String.format(CalcMessages.DATA_TYPE_CANNOT_BE_ORDERED, type));
+                    };
+              });
+
+  public static final TypeService<Integer> MEMORY_USAGE_OF_ONE_MERGE_SORT_KEY_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN -> 1;
+                case INT32, FLOAT, DATE -> 4;
+                case INT64, DOUBLE, TIMESTAMP -> 8;
+                case TEXT, STRING, BLOB, OBJECT -> 16;
+                case ROW, UNKNOWN, VECTOR ->
+                    throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                        .setChecked(true);
+              });
+
+  public static final TypeService<IntUnaryOperator>
+      MEMORY_USAGE_OF_ONE_SERIALIZABLE_ROW_FIELD_SERVICE =
+          cached(
+              type ->
+                  switch (type.getTypeEnum()) {
+                    case INT32, DATE -> ignored -> ReadWriteIOUtils.INT_LEN;
+                    case INT64, TIMESTAMP -> ignored -> ReadWriteIOUtils.LONG_LEN;
+                    case FLOAT -> ignored -> ReadWriteIOUtils.FLOAT_LEN;
+                    case DOUBLE -> ignored -> ReadWriteIOUtils.DOUBLE_LEN;
+                    case BOOLEAN -> ignored -> ReadWriteIOUtils.BOOLEAN_LEN;
+                    case TEXT, BLOB, STRING, OBJECT ->
+                        byteArrayLength ->
+                            MIN_OBJECT_HEADER_SIZE + MIN_ARRAY_HEADER_SIZE + byteArrayLength;
+                    case ROW, UNKNOWN, VECTOR ->
+                        throw new UnSupportedDataTypeException(type.toString()).setChecked(true);
+                  });
+
+  public static final TypeService<ValueFillFactory> VALUE_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (literal, zoneId) -> {
+                  Boolean value = literal.accept(new CastToBooleanLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BooleanConstantFill(value);
+                };
+            case TEXT, STRING ->
+                (literal, zoneId) -> {
+                  Binary value =
+                      literal.accept(
+                          new CastToStringLiteralVisitor(TSFileConfig.STRING_CHARSET), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case BLOB ->
+                (literal, zoneId) -> {
+                  Binary value = literal.accept(new CastToBlobLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case INT32 ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToInt32LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case DATE ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToDateLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case INT64 ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToInt64LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case TIMESTAMP ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToTimestampLiteralVisitor(zoneId), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case FLOAT ->
+                (literal, zoneId) -> {
+                  Float value = literal.accept(new CastToFloatLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new FloatConstantFill(value);
+                };
+            case DOUBLE ->
+                (literal, zoneId) -> {
+                  Double value = literal.accept(new CastToDoubleLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new DoubleConstantFill(value);
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (literal, zoneId) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads values for a cast using the source type's representation. */
+  public static final TypeService<CastInputService> CAST_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castInt(columnBuilder, type.getInt(column, position));
+            case DATE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDate(columnBuilder, type.getInt(column, position), zoneId);
+            case INT64 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castLong(columnBuilder, type.getLong(column, position));
+            case TIMESTAMP ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castTimestamp(
+                        columnBuilder, type.getLong(column, position), zoneId);
+            case FLOAT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castFloat(columnBuilder, type.getFloat(column, position));
+            case DOUBLE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDouble(columnBuilder, type.getDouble(column, position));
+            case BOOLEAN ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBoolean(columnBuilder, type.getBoolean(column, position));
+            case TEXT, STRING ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castString(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case BLOB ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBlob(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case OBJECT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castObject(columnBuilder, type.getBinary(column, position));
+            case ROW, UNKNOWN, VECTOR ->
+                (column, columnBuilder, position, castValueService, zoneId) -> {
+                  throw unsupportedCastSource(type);
+                };
+          };
+
+  /** Writes values produced by a cast into a column using the target type's representation. */
+  public static final TypeService<CastValueService> CAST_VALUE_SERVICE =
+      type ->
+          new CastValueService() {
+            @Override
+            public void castInt(ColumnBuilder columnBuilder, int value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castDate(ColumnBuilder columnBuilder, int value, ZoneId zoneId) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64 -> type.writeLong(columnBuilder, value);
+                case TIMESTAMP ->
+                    type.writeLong(
+                        columnBuilder,
+                        DateTimeUtils.correctPrecision(
+                            DateUtils.parseIntToTimestamp(value, zoneId)));
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(
+                        columnBuilder, BytesUtils.valueOf(DateUtils.formatDate(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castTimestamp(ColumnBuilder columnBuilder, long value, ZoneId zoneId) {
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      type.writeInt(columnBuilder, CastFunctionUtils.castLongToInt(value));
+                  case DATE ->
+                      type.writeInt(
+                          columnBuilder,
+                          DateUtils.parseDateExpressionToInt(
+                              DateTimeUtils.convertToLocalDate(value, zoneId)));
+                  case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                  case FLOAT -> type.writeFloat(columnBuilder, value);
+                  case DOUBLE -> type.writeDouble(columnBuilder, value);
+                  case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0L);
+                  case TEXT, STRING ->
+                      type.writeBinary(
+                          columnBuilder,
+                          BytesUtils.valueOf(DateTimeUtils.convertLongToDate(value, zoneId)));
+                  case BLOB ->
+                      type.writeBinary(columnBuilder, new Binary(BytesUtils.longToBytes(value)));
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException e) {
+                throw new IoTDBRuntimeException(
+                    "Year must be between 1000 and 9999.",
+                    org.apache.iotdb.rpc.TSStatusCode.DATE_OUT_OF_RANGE.getStatusCode(),
+                    true);
+              }
+            }
+
+            @Override
+            public void castLong(ColumnBuilder columnBuilder, long value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    type.writeInt(columnBuilder, CastFunctionUtils.castLongToInt(value));
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0L);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.longToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castFloat(ColumnBuilder columnBuilder, float value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    type.writeInt(columnBuilder, CastFunctionUtils.castFloatToInt(value));
+                case INT64, TIMESTAMP ->
+                    type.writeLong(columnBuilder, CastFunctionUtils.castFloatToLong(value));
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0.0f);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.floatToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castDouble(ColumnBuilder columnBuilder, double value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    type.writeInt(columnBuilder, CastFunctionUtils.castDoubleToInt(value));
+                case INT64, TIMESTAMP ->
+                    type.writeLong(columnBuilder, CastFunctionUtils.castDoubleToLong(value));
+                case FLOAT ->
+                    type.writeFloat(columnBuilder, CastFunctionUtils.castDoubleToFloat(value));
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0.0);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.doubleToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castBoolean(ColumnBuilder columnBuilder, boolean value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value ? 1 : 0);
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value ? 1L : 0L);
+                case FLOAT -> type.writeFloat(columnBuilder, value ? 1.0f : 0);
+                case DOUBLE -> type.writeDouble(columnBuilder, value ? 1.0 : 0);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.boolToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castString(ColumnBuilder columnBuilder, Binary value, ZoneId zoneId) {
+              String stringValue = value.getStringValue(TSFileConfig.STRING_CHARSET);
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 -> type.writeInt(columnBuilder, Integer.parseInt(stringValue));
+                  case DATE ->
+                      type.writeInt(columnBuilder, DateUtils.parseDateExpressionToInt(stringValue));
+                  case INT64 -> type.writeLong(columnBuilder, Long.parseLong(stringValue));
+                  case TIMESTAMP ->
+                      type.writeLong(
+                          columnBuilder,
+                          DateTimeUtils.convertDatetimeStrToLong(stringValue, zoneId));
+                  case FLOAT ->
+                      type.writeFloat(
+                          columnBuilder, CastFunctionUtils.castTextToFloat(stringValue));
+                  case DOUBLE ->
+                      type.writeDouble(
+                          columnBuilder, CastFunctionUtils.castTextToDouble(stringValue));
+                  case BOOLEAN ->
+                      type.writeBoolean(
+                          columnBuilder, CastFunctionUtils.castTextToBoolean(stringValue));
+                  case TEXT, STRING, BLOB, OBJECT -> type.writeBinary(columnBuilder, value);
+                  case ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException | NumberFormatException e) {
+                throw new SemanticException(
+                    String.format("Cannot cast %s to %s type", stringValue, type.getDisplayName()));
+              }
+            }
+
+            @Override
+            public void castBlob(ColumnBuilder columnBuilder, Binary value, ZoneId zoneId) {
+              String stringValue = BytesUtils.parseBlobByteArrayToString(value.getValues());
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 -> type.writeInt(columnBuilder, Integer.parseInt(stringValue));
+                  case DATE ->
+                      type.writeInt(columnBuilder, DateUtils.parseDateExpressionToInt(stringValue));
+                  case INT64 -> type.writeLong(columnBuilder, Long.parseLong(stringValue));
+                  case TIMESTAMP ->
+                      type.writeLong(
+                          columnBuilder,
+                          DateTimeUtils.convertDatetimeStrToLong(stringValue, zoneId));
+                  case FLOAT ->
+                      type.writeFloat(
+                          columnBuilder, CastFunctionUtils.castTextToFloat(stringValue));
+                  case DOUBLE ->
+                      type.writeDouble(
+                          columnBuilder, CastFunctionUtils.castTextToDouble(stringValue));
+                  case BOOLEAN ->
+                      type.writeBoolean(
+                          columnBuilder, CastFunctionUtils.castTextToBoolean(stringValue));
+                  case TEXT, STRING, BLOB -> type.writeBinary(columnBuilder, value);
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException | NumberFormatException e) {
+                throw new SemanticException(
+                    String.format("Cannot cast %s to %s type", stringValue, type.getDisplayName()));
+              }
+            }
+
+            @Override
+            public void castObject(ColumnBuilder columnBuilder, Binary value) {
+              String stringValue = BytesUtils.parseObjectByteArrayToString(value.getValues());
+              switch (type.getTypeEnum()) {
+                case STRING ->
+                    type.writeBinary(
+                        columnBuilder, BytesUtils.valueOf(String.valueOf(stringValue)));
+                case INT32,
+                    INT64,
+                    FLOAT,
+                    DOUBLE,
+                    BOOLEAN,
+                    DATE,
+                    TIMESTAMP,
+                    TEXT,
+                    BLOB,
+                    OBJECT,
+                    ROW,
+                    UNKNOWN,
+                    VECTOR ->
+                    throw unsupportedCastTarget(type);
+              }
+            }
+          };
+
+  public static final TypeService<CastObjectValueService> CAST_OBJECT_VALUE_SERVICE =
+      type ->
+          new CastObjectValueService() {
+            @Override
+            public Object castInt(int value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> value;
+                case INT64, TIMESTAMP -> (long) value;
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.intToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castDate(int value, ZoneId zoneId) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> value;
+                case INT64 -> (long) value;
+                case TIMESTAMP ->
+                    DateTimeUtils.correctPrecision(DateUtils.parseIntToTimestamp(value, zoneId));
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0;
+                case TEXT, STRING -> BytesUtils.valueOf(DateUtils.formatDate(value));
+                case BLOB -> new Binary(BytesUtils.intToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castTimestamp(long value, ZoneId zoneId) {
+              return switch (type.getTypeEnum()) {
+                case INT32 -> CastFunctionUtils.castLongToInt(value);
+                case DATE ->
+                    DateUtils.parseDateExpressionToInt(
+                        DateTimeUtils.convertToLocalDate(value, zoneId));
+                case INT64, TIMESTAMP -> value;
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0L;
+                case TEXT, STRING ->
+                    BytesUtils.valueOf(DateTimeUtils.convertLongToDate(value, zoneId));
+                case BLOB -> new Binary(BytesUtils.longToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castLong(long value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> CastFunctionUtils.castLongToInt(value);
+                case INT64, TIMESTAMP -> value;
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0L;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.longToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castFloat(float value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> CastFunctionUtils.castFloatToInt(value);
+                case INT64, TIMESTAMP -> CastFunctionUtils.castFloatToLong(value);
+                case FLOAT -> value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0.0f;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.floatToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castDouble(double value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> CastFunctionUtils.castDoubleToInt(value);
+                case INT64, TIMESTAMP -> CastFunctionUtils.castDoubleToLong(value);
+                case FLOAT -> CastFunctionUtils.castDoubleToFloat(value);
+                case DOUBLE -> value;
+                case BOOLEAN -> value != 0.0d;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.doubleToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castBoolean(boolean value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> value ? 1 : 0;
+                case INT64, TIMESTAMP -> value ? 1L : 0L;
+                case FLOAT -> value ? 1.0f : 0.0f;
+                case DOUBLE -> value ? 1.0d : 0.0d;
+                case BOOLEAN -> value;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.boolToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castBinary(Binary value, ZoneId zoneId) {
+              String stringValue = value.getStringValue(TSFileConfig.STRING_CHARSET);
+              try {
+                return switch (type.getTypeEnum()) {
+                  case INT32 -> Integer.parseInt(stringValue);
+                  case DATE -> DateUtils.parseDateExpressionToInt(stringValue);
+                  case INT64 -> Long.parseLong(stringValue);
+                  case TIMESTAMP -> DateTimeUtils.convertDatetimeStrToLong(stringValue, zoneId);
+                  case FLOAT -> CastFunctionUtils.castTextToFloat(stringValue);
+                  case DOUBLE -> CastFunctionUtils.castTextToDouble(stringValue);
+                  case BOOLEAN -> CastFunctionUtils.castTextToBoolean(stringValue);
+                  case TEXT, STRING, BLOB -> value;
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                };
+              } catch (DateTimeParseException | NumberFormatException e) {
+                throw new SemanticException(
+                    String.format("Cannot cast %s to %s type", stringValue, type.getDisplayName()));
+              }
+            }
+          };
+
+  public static final TypeService<CastObjectInputService> CAST_OBJECT_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castInt(
+                        value instanceof Integer ? (int) value : ((Long) value).intValue());
+            case DATE ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castDate(
+                        value instanceof Integer ? (int) value : ((Long) value).intValue(), zoneId);
+            case INT64 ->
+                (value, castValueService, zoneId) -> castValueService.castLong((Long) value);
+            case TIMESTAMP ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castTimestamp((Long) value, zoneId);
+            case FLOAT ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castFloat(
+                        value instanceof Float ? (float) value : ((Double) value).floatValue());
+            case DOUBLE ->
+                (value, castValueService, zoneId) -> castValueService.castDouble((Double) value);
+            case BOOLEAN ->
+                (value, castValueService, zoneId) -> castValueService.castBoolean((Boolean) value);
+            case TEXT, STRING, BLOB ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castBinary((Binary) value, zoneId);
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (value, castValueService, zoneId) -> {
+                  throw unsupportedCastSource(type);
+                };
+          };
+
+  public static final TypeService<FormatValueConverter> FORMAT_VALUE_CONVERTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case UNKNOWN -> (column, position, zoneId) -> null;
+            case INT32, INT64, FLOAT, DOUBLE, BOOLEAN, TEXT, STRING, BLOB ->
+                (column, position, zoneId) -> column.getObject(position);
+            // Java Formatter expects temporal objects for DATE and TIMESTAMP arguments.
+            case DATE ->
+                (column, position, zoneId) ->
+                    DateUtils.parseIntToLocalDate(column.getInt(position));
+            case TIMESTAMP ->
+                (column, position, zoneId) ->
+                    DateTimeUtils.convertToZonedDateTime(column.getLong(position), zoneId);
+            case OBJECT, ROW, VECTOR ->
+                (column, position, zoneId) -> {
+                  throw new UnsupportedOperationException(
+                      CalcMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                };
+          };
+
+  public static final TypeService<GroupedAccumulator>
+      GROUPED_APPROX_MOST_FREQUENT_ACCUMULATOR_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN -> new BooleanGroupedApproxMostFrequentAccumulator();
+                case INT32, DATE -> new IntGroupedApproxMostFrequentAccumulator();
+                case INT64, TIMESTAMP -> new LongGroupedApproxMostFrequentAccumulator();
+                case FLOAT -> new FloatGroupedApproxMostFrequentAccumulator();
+                case DOUBLE -> new DoubleGroupedApproxMostFrequentAccumulator();
+                case TEXT, STRING -> new BinaryGroupedApproxMostFrequentAccumulator();
+                case BLOB -> new BlobGroupedApproxMostFrequentAccumulator();
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    throw unsupportedApproxMostFrequentDataType(type);
+              };
+
+  public static final TypeService<TableAccumulator> APPROX_MOST_FREQUENT_ACCUMULATOR_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> new BooleanApproxMostFrequentAccumulator();
+            case INT32, DATE -> new IntApproxMostFrequentAccumulator();
+            case INT64, TIMESTAMP -> new LongApproxMostFrequentAccumulator();
+            case FLOAT -> new FloatApproxMostFrequentAccumulator();
+            case DOUBLE -> new DoubleApproxMostFrequentAccumulator();
+            case TEXT, STRING -> new BinaryApproxMostFrequentAccumulator();
+            case BLOB -> new BlobApproxMostFrequentAccumulator();
+            case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedApproxMostFrequentDataType(type);
+          };
+
+  public static final TypeService<Function<List<ColumnTransformer>, ColumnTransformer>>
+      GREATEST_COLUMN_TRANSFORMER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN ->
+                    columnTransformers ->
+                        new BooleanGreatestColumnTransformer(type, columnTransformers);
+                case INT32, DATE ->
+                    columnTransformers ->
+                        new Int32GreatestColumnTransformer(type, columnTransformers);
+                case INT64, TIMESTAMP ->
+                    columnTransformers ->
+                        new Int64GreatestColumnTransformer(type, columnTransformers);
+                case FLOAT ->
+                    columnTransformers ->
+                        new FloatGreatestColumnTransformer(type, columnTransformers);
+                case DOUBLE ->
+                    columnTransformers ->
+                        new DoubleGreatestColumnTransformer(type, columnTransformers);
+                case STRING, TEXT ->
+                    columnTransformers ->
+                        new BinaryGreatestColumnTransformer(type, columnTransformers);
+                case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    columnTransformers -> {
+                      throw unsupportedGreatestLeastDataType(type);
+                    };
+              };
+
+  public static final TypeService<Function<List<ColumnTransformer>, ColumnTransformer>>
+      LEAST_COLUMN_TRANSFORMER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN ->
+                    columnTransformers ->
+                        new BooleanLeastColumnTransformer(type, columnTransformers);
+                case INT32, DATE ->
+                    columnTransformers -> new Int32LeastColumnTransformer(type, columnTransformers);
+                case INT64, TIMESTAMP ->
+                    columnTransformers -> new Int64LeastColumnTransformer(type, columnTransformers);
+                case FLOAT ->
+                    columnTransformers -> new FloatLeastColumnTransformer(type, columnTransformers);
+                case DOUBLE ->
+                    columnTransformers ->
+                        new DoubleLeastColumnTransformer(type, columnTransformers);
+                case STRING, TEXT ->
+                    columnTransformers ->
+                        new BinaryLeastColumnTransformer(type, columnTransformers);
+                case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    columnTransformers -> {
+                      throw unsupportedGreatestLeastDataType(type);
+                    };
+              };
+
+  /**
+   * Creates a single-row column containing the value at the requested row. Delegating the write to
+   * {@link Type} preserves type-specific column metadata (for example, DATE) without another
+   * TsDataType dispatch.
+   */
+  public static final TypeService<ColumnRowFunction> UPDATE_LAST_ROW_SERVICE =
+      type ->
+          (column, rowIndex) -> {
+            // Use the status overload so specialized types such as DATE retain their data type.
+            ColumnBuilder columnBuilder = type.createColumnBuilder(null, 1);
+            type.write(columnBuilder, column, rowIndex);
+            return columnBuilder.build();
+          };
+
+  /** Copies a column value into a reusable primitive result without boxing. */
+  public static final TypeService<PrimitiveColumnValueSetter>
+      PRIMITIVE_COLUMN_VALUE_SETTER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (target, column, position) -> target.setInt(type.getInt(column, position));
+                case INT64, TIMESTAMP ->
+                    (target, column, position) -> target.setLong(type.getLong(column, position));
+                case FLOAT ->
+                    (target, column, position) -> target.setFloat(type.getFloat(column, position));
+                case DOUBLE ->
+                    (target, column, position) ->
+                        target.setDouble(type.getDouble(column, position));
+                case BOOLEAN ->
+                    (target, column, position) ->
+                        target.setBoolean(type.getBoolean(column, position));
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (target, column, position) ->
+                        target.setBinary(type.getBinary(column, position));
+                case ROW, UNKNOWN, VECTOR ->
+                    (target, column, position) -> {
+                      throw new UnSupportedDataTypeException(
+                              CalcMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                    };
+              };
+
+  /** Writes a statistics value into a reusable primitive result. */
+  public static final TypeService<StatisticsValueSetter> STATISTICS_VALUE_SETTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (target, value, exceptionSupplier) -> target.setInt(((Number) value).intValue());
+            case INT64, TIMESTAMP ->
+                (target, value, exceptionSupplier) -> target.setLong(((Number) value).longValue());
+            case FLOAT ->
+                (target, value, exceptionSupplier) ->
+                    target.setFloat(((Number) value).floatValue());
+            case DOUBLE ->
+                (target, value, exceptionSupplier) ->
+                    target.setDouble(((Number) value).doubleValue());
+            case BOOLEAN ->
+                (target, value, exceptionSupplier) -> target.setBoolean((boolean) value);
+            case TEXT, STRING, BLOB, OBJECT ->
+                (target, value, exceptionSupplier) -> target.setBinary(toBinary(value));
+            case ROW, UNKNOWN, VECTOR ->
+                (target, value, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  public static final TypeService<InColumnValueMatcherFactory> IN_COLUMN_VALUE_MATCHER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                values -> {
+                  Set<Integer> intSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      intSet.add(Integer.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> intSet.contains(type.getInt(column, position));
+                };
+            case INT64, TIMESTAMP ->
+                values -> {
+                  Set<Long> longSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      longSet.add(Long.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> longSet.contains(type.getLong(column, position));
+                };
+            case FLOAT ->
+                values -> {
+                  Set<Float> floatSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      floatSet.add(Float.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> floatSet.contains(type.getFloat(column, position));
+                };
+            case DOUBLE ->
+                values -> {
+                  Set<Double> doubleSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      doubleSet.add(Double.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> doubleSet.contains(type.getDouble(column, position));
+                };
+            case BOOLEAN ->
+                values -> {
+                  Set<Boolean> booleanSet = new HashSet<>();
+                  for (String value : values) {
+                    if ("true".equalsIgnoreCase(value)) {
+                      booleanSet.add(true);
+                    } else if ("false".equalsIgnoreCase(value)) {
+                      booleanSet.add(false);
+                    } else {
+                      throw new SemanticException(
+                          String.format(CalcMessages.CANNOT_CAST_TO_BOOLEAN, value));
+                    }
+                  }
+                  return (column, position) ->
+                      booleanSet.contains(type.getBoolean(column, position));
+                };
+            case TEXT, STRING ->
+                values -> {
+                  Set<Binary> stringSet =
+                      values.stream()
+                          .map(value -> new Binary(value, TSFileConfig.STRING_CHARSET))
+                          .collect(Collectors.toSet());
+                  return (column, position) -> stringSet.contains(type.getBinary(column, position));
+                };
+            case BLOB, DATE, OBJECT, ROW, UNKNOWN, VECTOR ->
+                values -> {
+                  throw new UnsupportedOperationException(
+                      CalcMessages.UNSUPPORTED_DATA_TYPE_LOWER + type.getTypeEnum());
+                };
+          };
+
+  public static final TypeService<InMultiColumnTransformerFactory>
+      IN_MULTI_COLUMN_TRANSFORMER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32 ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Integer> intSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          long v = ((LongLiteral) value).getParsedValue();
+                          if (v <= Integer.MAX_VALUE && v >= Integer.MIN_VALUE) {
+                            intSet.add((int) v);
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InInt32MultiColumnTransformer(intSet, valueColumnTransformers);
+                    };
+                case DATE ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Integer> dateSet = new HashSet<>();
+                      for (Literal value : values) {
+                        dateSet.add(Integer.parseInt(((GenericLiteral) value).getValue()));
+                      }
+                      return new InInt32MultiColumnTransformer(dateSet, valueColumnTransformers);
+                    };
+                case INT64 ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Long> longSet = new HashSet<>();
+                      for (Literal value : values) {
+                        longSet.add(((LongLiteral) value).getParsedValue());
+                      }
+                      return new InInt64MultiColumnTransformer(longSet, valueColumnTransformers);
+                    };
+                case TIMESTAMP ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Long> timestampSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          if (value instanceof LongLiteral) {
+                            timestampSet.add(((LongLiteral) value).getParsedValue());
+                          } else if (value instanceof DoubleLiteral) {
+                            timestampSet.add((long) ((DoubleLiteral) value).getValue());
+                          } else if (value instanceof FloatLiteral) {
+                            timestampSet.add((long) ((FloatLiteral) value).getValue());
+                          } else if (value instanceof GenericLiteral) {
+                            timestampSet.add(Long.parseLong(((GenericLiteral) value).getValue()));
+                          } else {
+                            throw new SemanticException(
+                                String.format(
+                                    CalcMessages.IN_LIST_LITERAL_FOR_TIMESTAMP_TYPE_RESTRICTION,
+                                    value.getClass().getSimpleName()));
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InInt64MultiColumnTransformer(
+                          timestampSet, valueColumnTransformers);
+                    };
+                case FLOAT ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Float> floatSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          if (value instanceof FloatLiteral) {
+                            floatSet.add(((FloatLiteral) value).getValue());
+                          } else {
+                            floatSet.add((float) ((DoubleLiteral) value).getValue());
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InFloatMultiColumnTransformer(floatSet, valueColumnTransformers);
+                    };
+                case DOUBLE ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Double> doubleSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          if (value instanceof FloatLiteral) {
+                            doubleSet.add((double) ((FloatLiteral) value).getValue());
+                          } else {
+                            doubleSet.add(((DoubleLiteral) value).getValue());
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InDoubleMultiColumnTransformer(doubleSet, valueColumnTransformers);
+                    };
+                case BOOLEAN ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Boolean> booleanSet = new HashSet<>();
+                      for (Literal value : values) {
+                        booleanSet.add(((BooleanLiteral) value).getValue());
+                      }
+                      return new InBooleanMultiColumnTransformer(
+                          booleanSet, valueColumnTransformers);
+                    };
+                case TEXT, STRING ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Binary> stringSet = new HashSet<>();
+                      for (Literal value : values) {
+                        stringSet.add(
+                            new Binary(
+                                ((StringLiteral) value).getValue(), TSFileConfig.STRING_CHARSET));
+                      }
+                      return new InBinaryMultiColumnTransformer(stringSet, valueColumnTransformers);
+                    };
+                case BLOB ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Binary> binarySet = new HashSet<>();
+                      for (Literal value : values) {
+                        binarySet.add(new Binary(((BinaryLiteral) value).getValue()));
+                      }
+                      return new InBinaryMultiColumnTransformer(binarySet, valueColumnTransformers);
+                    };
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    (valueColumnTransformers, values) -> {
+                      throw new UnsupportedOperationException(
+                          CalcMessages.UNSUPPORTED_DATA_TYPE_LOWER + type.getTypeEnum());
+                    };
+              };
+
+  /** Updates a result with the minimum value from statistics. */
+  public static final TypeService<StatisticsValueUpdater> MIN_STATISTICS_VALUE_UPDATER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  int candidate = ((Number) value).intValue();
+                  if (!initialized || candidate < result.getInt()) {
+                    result.setInt(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case INT64, TIMESTAMP ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  long candidate = ((Number) value).longValue();
+                  if (!initialized || candidate < result.getLong()) {
+                    result.setLong(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case FLOAT ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  float candidate = ((Number) value).floatValue();
+                  if (!initialized || candidate < result.getFloat()) {
+                    result.setFloat(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case DOUBLE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  double candidate = ((Number) value).doubleValue();
+                  if (!initialized || candidate < result.getDouble()) {
+                    result.setDouble(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case BOOLEAN ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  boolean candidate = (boolean) value;
+                  if (!initialized || !candidate) {
+                    result.setBoolean(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case TEXT, STRING, BLOB ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  Binary candidate = toBinary(value);
+                  if (!initialized || candidate.compareTo(result.getBinary()) < 0) {
+                    result.setBinary(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  /** Updates a result with the maximum value from statistics. */
+  public static final TypeService<StatisticsValueUpdater> MAX_STATISTICS_VALUE_UPDATER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  int candidate = ((Number) value).intValue();
+                  if (!initialized || candidate > result.getInt()) {
+                    result.setInt(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case INT64, TIMESTAMP ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  long candidate = ((Number) value).longValue();
+                  if (!initialized || candidate > result.getLong()) {
+                    result.setLong(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case FLOAT ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  float candidate = ((Number) value).floatValue();
+                  if (!initialized || candidate > result.getFloat()) {
+                    result.setFloat(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case DOUBLE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  double candidate = ((Number) value).doubleValue();
+                  if (!initialized || candidate > result.getDouble()) {
+                    result.setDouble(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case BOOLEAN ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  boolean candidate = (boolean) value;
+                  if (!initialized || candidate) {
+                    result.setBoolean(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case TEXT, STRING, BLOB ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  Binary candidate = toBinary(value);
+                  if (!initialized || candidate.compareTo(result.getBinary()) > 0) {
+                    result.setBinary(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  /** Updates a result with the greatest absolute numeric value from statistics. */
+  public static final TypeService<StatisticsValueUpdater> EXTREME_STATISTICS_VALUE_UPDATER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  int candidate = ((Number) value).intValue();
+                  if (!initialized || compareExtreme(candidate, result.getInt()) > 0) {
+                    result.setInt(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case INT64 ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  long candidate = ((Number) value).longValue();
+                  if (!initialized || compareExtreme(candidate, result.getLong()) > 0) {
+                    result.setLong(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case FLOAT ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  float candidate = ((Number) value).floatValue();
+                  float absCandidate = Math.abs(candidate);
+                  float absResult = Math.abs(result.getFloat());
+                  if (!initialized
+                      || absCandidate > absResult
+                      || absCandidate == absResult && candidate > result.getFloat()) {
+                    result.setFloat(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case DOUBLE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  double candidate = ((Number) value).doubleValue();
+                  double absCandidate = Math.abs(candidate);
+                  double absResult = Math.abs(result.getDouble());
+                  if (!initialized
+                      || absCandidate > absResult
+                      || absCandidate == absResult && candidate > result.getDouble()) {
+                    result.setDouble(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case BOOLEAN, DATE, TIMESTAMP, TEXT, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  /** Binds an APPROX_PERCENTILE input reader to the input column's native type. */
+  public static final TypeService<
+          Function<AbstractApproxPercentileAccumulator, BiConsumer<Column[], AggregationMask>>>
+      APPROX_PERCENTILE_INPUT_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32 -> accumulator -> accumulator::addIntInput;
+                case INT64, TIMESTAMP -> accumulator -> accumulator::addLongInput;
+                case FLOAT -> accumulator -> accumulator::addFloatInput;
+                case DOUBLE -> accumulator -> accumulator::addDoubleInput;
+                case BOOLEAN, DATE, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    accumulator ->
+                        (arguments, mask) -> {
+                          throw new UnSupportedDataTypeException(
+                              String.format(
+                                  CalcMessages
+                                      .UNSUPPORTED_DATA_TYPE_IN_APPROX_PERCENTILE_AGGREGATION,
+                                  type.getTypeEnum()));
+                        };
+              };
+
+  /** Binds a grouped APPROX_PERCENTILE input reader to the input column's native type. */
+  public static final TypeService<
+          Function<
+              AbstractGroupedApproxPercentileAccumulator,
+              TriConsumer<int[], Column[], AggregationMask>>>
+      GROUPED_APPROX_PERCENTILE_INPUT_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32 -> accumulator -> accumulator::addIntInput;
+                case INT64, TIMESTAMP -> accumulator -> accumulator::addLongInput;
+                case FLOAT -> accumulator -> accumulator::addFloatInput;
+                case DOUBLE -> accumulator -> accumulator::addDoubleInput;
+                case BOOLEAN, DATE, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    accumulator ->
+                        (groupIds, arguments, mask) -> {
+                          throw new UnSupportedDataTypeException(
+                              String.format(
+                                  CalcMessages
+                                      .UNSUPPORTED_DATA_TYPE_IN_APPROX_PERCENTILE_AGGREGATION,
+                                  type.getTypeEnum()));
+                        };
+              };
+
+  /** Provides storage operations for grouped accumulators backed by primitive big arrays. */
+  public static final TypeService<GroupedValueService> GROUPED_VALUE_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeIntValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getIntValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getIntValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getIntValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeInt(accessor.getIntValues().get(groupId));
+                  }
+                };
+            case INT64, TIMESTAMP ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeLongValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getLongValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getLongValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getLongValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeLong(accessor.getLongValues().get(groupId));
+                  }
+                };
+            case FLOAT ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeFloatValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getFloatValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getFloatValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getFloatValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeFloat(accessor.getFloatValues().get(groupId));
+                  }
+                };
+            case DOUBLE ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeDoubleValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getDoubleValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getDoubleValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getDoubleValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeDouble(accessor.getDoubleValues().get(groupId));
+                  }
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeBinaryValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getBinaryValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getBinaryValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getBinaryValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeBinary(accessor.getBinaryValues().get(groupId));
+                  }
+                };
+            case BOOLEAN ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeBooleanValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getBooleanValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getBooleanValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getBooleanValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeBoolean(accessor.getBooleanValues().get(groupId));
+                  }
+                };
+            case ROW, UNKNOWN, VECTOR -> unsupportedGroupedValueService(type);
+          };
+
+  /** Reads grouped input and intermediate columns using the native column accessor. */
+  public static final TypeService<GroupedInputReader> GROUPED_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateInt(groupIds[position], arguments[0].getInt(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateInt(groupIds[i], argument.getInt(i));
+                      }
+                    }
+                  }
+                };
+            case INT64, TIMESTAMP ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateLong(
+                                groupIds[position], arguments[0].getLong(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateLong(groupIds[i], argument.getLong(i));
+                      }
+                    }
+                  }
+                };
+            case FLOAT ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateFloat(
+                                groupIds[position], arguments[0].getFloat(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateFloat(groupIds[i], argument.getFloat(i));
+                      }
+                    }
+                  }
+                };
+            case DOUBLE ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateDouble(
+                                groupIds[position], arguments[0].getDouble(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateDouble(groupIds[i], argument.getDouble(i));
+                      }
+                    }
+                  }
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBinary(
+                                groupIds[position], arguments[0].getBinary(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateBinary(groupIds[i], argument.getBinary(i));
+                      }
+                    }
+                  }
+                };
+            case BOOLEAN ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBoolean(
+                                groupIds[position], arguments[0].getBoolean(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateBoolean(groupIds[i], argument.getBoolean(i));
+                      }
+                    }
+                  }
+                };
+            case ROW, UNKNOWN, VECTOR -> unsupportedGroupedInputReader(type);
+          };
+
+  /** Restricts grouped EXTREME to the numeric types supported by the aggregate. */
+  public static final TypeService<GroupedValueService> GROUPED_EXTREME_VALUE_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, INT64, FLOAT, DOUBLE -> GROUPED_VALUE_SERVICE.call(type);
+            case BOOLEAN, DATE, TIMESTAMP, TEXT, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                unsupportedGroupedValueService(type);
+          };
+
+  public static final TypeService<GroupedInputReader> GROUPED_EXTREME_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, INT64, FLOAT, DOUBLE -> GROUPED_INPUT_READER_SERVICE.call(type);
+            case BOOLEAN, DATE, TIMESTAMP, TEXT, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                unsupportedGroupedInputReader(type);
+          };
+
+  /** Reads a value column together with its optional ordering-time column. */
+  public static final TypeService<GroupedTimeInputReader> GROUPED_TIME_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateInt(
+                                groupIds[position],
+                                arguments[0].getInt(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case INT64, TIMESTAMP ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateLong(
+                                groupIds[position],
+                                arguments[0].getLong(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case FLOAT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateFloat(
+                                groupIds[position],
+                                arguments[0].getFloat(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case DOUBLE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateDouble(
+                                groupIds[position],
+                                arguments[0].getDouble(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBinary(
+                                groupIds[position],
+                                arguments[0].getBinary(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case BOOLEAN ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBoolean(
+                                groupIds[position],
+                                arguments[0].getBoolean(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case ROW, UNKNOWN, VECTOR ->
+                (groupIds, arguments, mask, consumer) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads x values for FIRST_BY/LAST_BY while filtering null y values. */
+  public static final TypeService<GroupedByInputReader> GROUPED_BY_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateInt(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getInt(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case INT64, TIMESTAMP ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateLong(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getLong(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case FLOAT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateFloat(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getFloat(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case DOUBLE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateDouble(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getDouble(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateBinary(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getBinary(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case BOOLEAN ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateBoolean(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getBoolean(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case ROW, UNKNOWN, VECTOR ->
+                (groupIds, arguments, mask, consumer) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Serializes/deserializes a grouped value in the native intermediate format. */
+  public static final TypeService<GroupedValueSerializer> GROUPED_VALUE_SERIALIZER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Integer.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getIntValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case INT64, TIMESTAMP ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Long.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getLongValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case FLOAT ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Float.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getFloatValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case DOUBLE ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Double.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getDoubleValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Integer.BYTES + accessor.getBinaryValues().get(index).getLength();
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getBinaryValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case BOOLEAN ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Byte.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    BytesUtils.boolToBytes(accessor.getBooleanValues().get(index), bytes, offset);
+                  }
+                };
+            case ROW, UNKNOWN, VECTOR -> unsupportedGroupedValueSerializer(type);
+          };
+
+  /** Stores a column value in the typed big array selected for a grouped accumulator. */
+  public static final TypeService<GroupedValueSetter> GROUPED_VALUE_SETTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (accessor, index, column, position) ->
+                    accessor.getIntValues().set(index, type.getInt(column, position));
+            case INT64, TIMESTAMP ->
+                (accessor, index, column, position) ->
+                    accessor.getLongValues().set(index, type.getLong(column, position));
+            case FLOAT ->
+                (accessor, index, column, position) ->
+                    accessor.getFloatValues().set(index, type.getFloat(column, position));
+            case DOUBLE ->
+                (accessor, index, column, position) ->
+                    accessor.getDoubleValues().set(index, type.getDouble(column, position));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (accessor, index, column, position) ->
+                    accessor.getBinaryValues().set(index, type.getBinary(column, position));
+            case BOOLEAN ->
+                (accessor, index, column, position) ->
+                    accessor.getBooleanValues().set(index, type.getBoolean(column, position));
+            case ROW, UNKNOWN, VECTOR ->
+                (accessor, index, column, position) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads a grouped value from bytes into a typed callback. */
+  public static final TypeService<GroupedTimeValueDeserializer>
+      GROUPED_TIME_VALUE_DESERIALIZER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateInt(
+                            groupId, BytesUtils.bytesToInt(bytes, offset), timeNull, time);
+                case INT64, TIMESTAMP ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateLong(
+                            groupId,
+                            BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                            timeNull,
+                            time);
+                case FLOAT ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateFloat(
+                            groupId, BytesUtils.bytesToFloat(bytes, offset), timeNull, time);
+                case DOUBLE ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateDouble(
+                            groupId, BytesUtils.bytesToDouble(bytes, offset), timeNull, time);
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (bytes, offset, groupId, time, timeNull, consumer) -> {
+                      int length = BytesUtils.bytesToInt(bytes, offset);
+                      consumer.updateBinary(
+                          groupId,
+                          new Binary(BytesUtils.subBytes(bytes, offset + Integer.BYTES, length)),
+                          timeNull,
+                          time);
+                    };
+                case BOOLEAN ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateBoolean(
+                            groupId, BytesUtils.bytesToBool(bytes, offset), timeNull, time);
+                case ROW, UNKNOWN, VECTOR ->
+                    (bytes, offset, groupId, time, timeNull, consumer) -> {
+                      throw unsupportedDataType(type);
+                    };
+              };
+
+  /** Reads x values from FIRST_BY/LAST_BY intermediate bytes. */
+  public static final TypeService<GroupedByValueDeserializer>
+      GROUPED_BY_VALUE_DESERIALIZER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateInt(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToInt(bytes, offset),
+                            timeNull,
+                            time);
+                case INT64, TIMESTAMP ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateLong(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                            timeNull,
+                            time);
+                case FLOAT ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateFloat(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToFloat(bytes, offset),
+                            timeNull,
+                            time);
+                case DOUBLE ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateDouble(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToDouble(bytes, offset),
+                            timeNull,
+                            time);
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) -> {
+                      Binary value = null;
+                      if (!xNull) {
+                        int length = BytesUtils.bytesToInt(bytes, offset);
+                        value =
+                            new Binary(BytesUtils.subBytes(bytes, offset + Integer.BYTES, length));
+                      }
+                      consumer.updateBinary(groupId, xNull, value, timeNull, time);
+                    };
+                case BOOLEAN ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateBoolean(
+                            groupId,
+                            xNull,
+                            xNull ? false : BytesUtils.bytesToBool(bytes, offset),
+                            timeNull,
+                            time);
+                case ROW, UNKNOWN, VECTOR ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) -> {
+                      throw unsupportedDataType(type);
+                    };
+              };
+
+  /** Selects the y-column reader used by MAX_BY and MIN_BY input processing. */
+  public static final TypeService<MaxMinByInput> MAX_MIN_BY_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateInt(
+                                arguments[1].getInt(position), arguments[0], position));
+            case INT64, TIMESTAMP ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateLong(
+                                arguments[1].getLong(position), arguments[0], position));
+            case FLOAT ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateFloat(
+                                arguments[1].getFloat(position), arguments[0], position));
+            case DOUBLE ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateDouble(
+                                arguments[1].getDouble(position), arguments[0], position));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBinary(
+                                arguments[1].getBinary(position), arguments[0], position));
+            case BOOLEAN ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBoolean(
+                                arguments[1].getBoolean(position), arguments[0], position));
+            case ROW, UNKNOWN, VECTOR ->
+                (arguments, mask, updater) -> {
+                  throw unsupportedMaxMinByDataType(type);
+                };
+          };
+
+  /** Selects the y-value decoder used by MAX_BY and MIN_BY intermediate input processing. */
+  public static final TypeService<MaxMinByIntermediateInput> MAX_MIN_BY_INTERMEDIATE_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  int value = BytesUtils.bytesToInt(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, Integer.BYTES, xType, columnBuilder);
+                  updater.updateInt(value, columnBuilder.build(), 0);
+                };
+            case INT64, TIMESTAMP ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  long value = BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, 0);
+                  readMaxMinByXFromBytes(bytes, Long.BYTES, xType, columnBuilder);
+                  updater.updateLong(value, columnBuilder.build(), 0);
+                };
+            case FLOAT ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  float value = BytesUtils.bytesToFloat(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, Float.BYTES, xType, columnBuilder);
+                  updater.updateFloat(value, columnBuilder.build(), 0);
+                };
+            case DOUBLE ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  double value = BytesUtils.bytesToDouble(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, Double.BYTES, xType, columnBuilder);
+                  updater.updateDouble(value, columnBuilder.build(), 0);
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  int length = BytesUtils.bytesToInt(bytes, 0);
+                  int xOffset = Integer.BYTES + length;
+                  Binary value = new Binary(BytesUtils.subBytes(bytes, Integer.BYTES, length));
+                  readMaxMinByXFromBytes(bytes, xOffset, xType, columnBuilder);
+                  updater.updateBinary(value, columnBuilder.build(), 0);
+                };
+            case BOOLEAN ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  boolean value = BytesUtils.bytesToBool(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, 1, xType, columnBuilder);
+                  updater.updateBoolean(value, columnBuilder.build(), 0);
+                };
+            case ROW, UNKNOWN, VECTOR ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  throw unsupportedMaxMinByDataType(type);
+                };
+          };
+
+  /** Selects the y-column reader used by grouped MAX_BY and MIN_BY input processing. */
+  public static final TypeService<GroupedMaxMinByInput> GROUPED_MAX_MIN_BY_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateInt(
+                                groupIds[position],
+                                arguments[1].getInt(position),
+                                arguments[0],
+                                position));
+            case INT64, TIMESTAMP ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateLong(
+                                groupIds[position],
+                                arguments[1].getLong(position),
+                                arguments[0],
+                                position));
+            case FLOAT ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateFloat(
+                                groupIds[position],
+                                arguments[1].getFloat(position),
+                                arguments[0],
+                                position));
+            case DOUBLE ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateDouble(
+                                groupIds[position],
+                                arguments[1].getDouble(position),
+                                arguments[0],
+                                position));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBinary(
+                                groupIds[position],
+                                arguments[1].getBinary(position),
+                                arguments[0],
+                                position));
+            case BOOLEAN ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBoolean(
+                                groupIds[position],
+                                arguments[1].getBoolean(position),
+                                arguments[0],
+                                position));
+            case ROW, UNKNOWN, VECTOR ->
+                (groupIds, arguments, mask, updater) -> {
+                  throw unsupportedMaxMinByDataType(type);
+                };
+          };
+
+  /** Selects the y-value decoder used by grouped MAX_BY and MIN_BY intermediate input. */
+  public static final TypeService<GroupedMaxMinByIntermediateInput>
+      GROUPED_MAX_MIN_BY_INTERMEDIATE_INPUT_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      int value = BytesUtils.bytesToInt(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Integer.BYTES, xType, columnBuilder);
+                      updater.updateInt(groupId, value, columnBuilder.build(), 0);
+                    };
+                case INT64, TIMESTAMP ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      long value = BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, 0);
+                      readMaxMinByXFromBytes(bytes, Long.BYTES, xType, columnBuilder);
+                      updater.updateLong(groupId, value, columnBuilder.build(), 0);
+                    };
+                case FLOAT ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      float value = BytesUtils.bytesToFloat(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Float.BYTES, xType, columnBuilder);
+                      updater.updateFloat(groupId, value, columnBuilder.build(), 0);
+                    };
+                case DOUBLE ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      double value = BytesUtils.bytesToDouble(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Double.BYTES, xType, columnBuilder);
+                      updater.updateDouble(groupId, value, columnBuilder.build(), 0);
+                    };
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      int length = BytesUtils.bytesToInt(bytes, 0);
+                      int xOffset = Integer.BYTES + length;
+                      Binary value = new Binary(BytesUtils.subBytes(bytes, Integer.BYTES, length));
+                      readMaxMinByXFromBytes(bytes, xOffset, xType, columnBuilder);
+                      updater.updateBinary(groupId, value, columnBuilder.build(), 0);
+                    };
+                case BOOLEAN ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      boolean value = BytesUtils.bytesToBool(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Byte.BYTES, xType, columnBuilder);
+                      updater.updateBoolean(groupId, value, columnBuilder.build(), 0);
+                    };
+                case ROW, UNKNOWN, VECTOR ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      throw unsupportedMaxMinByDataType(type);
+                    };
+              };
+
+  /** Selects the type-specific decoder for a LAST intermediate value. */
+  public static final TypeService<LastValueDeserializer> LAST_VALUE_DESERIALIZER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  int value = BytesUtils.bytesToInt(bytes, offset);
+                  updater.updateInt(value, time, isOrderTimeNull);
+                };
+            case INT64, TIMESTAMP ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  long value = BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset);
+                  updater.updateLong(value, time, isOrderTimeNull);
+                };
+            case FLOAT ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  float value = BytesUtils.bytesToFloat(bytes, offset);
+                  updater.updateFloat(value, time, isOrderTimeNull);
+                };
+            case DOUBLE ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  double value = BytesUtils.bytesToDouble(bytes, offset);
+                  updater.updateDouble(value, time, isOrderTimeNull);
+                };
+            case TEXT, BLOB, OBJECT, STRING ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  int length = BytesUtils.bytesToInt(bytes, offset);
+                  Binary value =
+                      new Binary(BytesUtils.subBytes(bytes, offset + Integer.BYTES, length));
+                  updater.updateBinary(value, time, isOrderTimeNull);
+                };
+            case BOOLEAN ->
+                (bytes, offset, time, isOrderTimeNull, updater) ->
+                    updater.updateBoolean(
+                        BytesUtils.bytesToBool(bytes, offset), time, isOrderTimeNull);
+            case ROW, UNKNOWN, VECTOR ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  throw new UnSupportedDataTypeException(
+                      CalcMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                };
+          };
+
+  public static final TypeService<Function<TsPrimitiveType, Object>>
+      PRIMITIVE_TYPE_VALUE_EXTRACTOR_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> TsPrimitiveType::getValue;
+                case DATE -> primitiveType -> DateUtils.parseIntToLocalDate(primitiveType.getInt());
+                case TEXT, BLOB, STRING ->
+                    primitiveType -> {
+                      final Binary binary = primitiveType.getBinary();
+                      return binary == null || binary.getValues() == null
+                          ? Binary.EMPTY_VALUE
+                          : binary;
+                    };
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    primitiveType -> {
+                      throw new UnSupportedDataTypeException(
+                              CalcMessages.UNSUPPORTED_DATA_TYPE + primitiveType.getDataType())
+                          .setChecked(true);
+                    };
+              };
+
+  /** Reads, serializes, deserializes, and writes Mode values without TsPrimitiveType conversion. */
+  public static final TypeService<ModeValueService> MODE_VALUE_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                modeValueService(
+                    type,
+                    type::getBoolean,
+                    BytesUtils::bytesToBool,
+                    (value, bytes, offset) -> {
+                      BytesUtils.boolToBytes((boolean) value, bytes, offset);
+                      return Byte.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeBoolean(columnBuilder, (boolean) value));
+            case INT32, DATE ->
+                modeValueService(
+                    type,
+                    type::getInt,
+                    BytesUtils::bytesToInt,
+                    (value, bytes, offset) -> {
+                      BytesUtils.intToBytes((int) value, bytes, offset);
+                      return Integer.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeInt(columnBuilder, (int) value));
+            case INT64, TIMESTAMP ->
+                modeValueService(
+                    type,
+                    type::getLong,
+                    (bytes, offset) -> BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                    (value, bytes, offset) -> {
+                      BytesUtils.longToBytes((long) value, bytes, offset);
+                      return Long.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeLong(columnBuilder, (long) value));
+            case FLOAT ->
+                modeValueService(
+                    type,
+                    type::getFloat,
+                    BytesUtils::bytesToFloat,
+                    (value, bytes, offset) -> {
+                      BytesUtils.floatToBytes((float) value, bytes, offset);
+                      return Float.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeFloat(columnBuilder, (float) value));
+            case DOUBLE ->
+                modeValueService(
+                    type,
+                    type::getDouble,
+                    BytesUtils::bytesToDouble,
+                    (value, bytes, offset) -> {
+                      BytesUtils.doubleToBytes((double) value, bytes, offset);
+                      return Double.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeDouble(columnBuilder, (double) value));
+            case TEXT, STRING, BLOB ->
+                modeValueService(
+                    type,
+                    type::getBinary,
+                    TypeServices::deserializeModeBinary,
+                    TypeServices::serializeModeBinary,
+                    (columnBuilder, value) -> type.writeBinary(columnBuilder, (Binary) value));
+            case OBJECT, ROW, UNKNOWN, VECTOR -> unsupportedModeValueService(type);
+          };
+
+  // The caller supplies the exception so shared conversion keeps each aggregation API's contract.
+  public static final TypeService<ColumnToDoubleConverterFactory>
+      NUMERIC_COLUMN_TO_DOUBLE_CONVERTER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> ignored -> type::getDouble;
+                case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    exceptionSupplier ->
+                        (column, position) -> {
+                          throw exceptionSupplier.get();
+                        };
+              };
+
+  /** Numeric inputs supported by SUM, AVG and percentile aggregations. */
+  public static final TypeService<ColumnToDoubleConverterFactory>
+      AGGREGATION_NUMERIC_COLUMN_TO_DOUBLE_CONVERTER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, INT64, FLOAT, DOUBLE -> ignored -> type::getDouble;

Review Comment:
   Moved SUM's add/remove loops into the strategies returned by `AGGREGATION_NUMERIC_COLUMN_TO_DOUBLE_CONVERTER_SERVICE`. The accumulator selects its strategy once, and each batch uses a native getter loop rather than the shared per-value converter. The loop starts with the existing sum so floating-point additions are not regrouped across batches; empty/all-null unsupported inputs retain deferred rejection. `SumAccumulatorTest` covers mixed types, masks/nulls, removal and reset. A warmed local Windows/JBR 21 microbenchmark with four numeric types alternating every 1,024 rows improved from 3.738 to 0.440 ns/value against `6ac266b065`, with matching checksums. This is an aggregation-kernel result, not SQL throughput. I also benchmarked analogous AVG/grouped aggregates, extrema, rate, moment and cast loops separately and retained 23 of 30 additional candidates; the seven rejected candidates were restored.



##########
iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java:
##########
@@ -3875,6 +3804,52 @@ private BitMap sortBitMap(BitMap bitMap, Integer[] index) {
     return sortedBitMap;
   }
 
+  private static int[] sortedIndex(List<Long> values) {
+    return sortedIndex(values.size(), index -> values.get(index));
+  }
+
+  private static int[] sortedIndex(long[] values, int size) {
+    return sortedIndex(size, index -> values[index]);
+  }
+
+  private static int[] sortedIndex(int size, IntToLongFunction valueProvider) {
+    int[] index = new int[size];
+    int[] scratch = new int[size];
+    for (int i = 0; i < size; i++) {
+      index[i] = i;
+    }
+    sortIndexes(index, scratch, 0, size, valueProvider);
+    return index;
+  }
+
+  private static void sortIndexes(
+      int[] index, int[] scratch, int from, int to, IntToLongFunction valueProvider) {
+    if (to - from < 2) {
+      return;
+    }
+    int middle = (from + to) >>> 1;
+    sortIndexes(index, scratch, from, middle, valueProvider);

Review Comment:
   Kept primitive indexes and added ordered-run detection before recursion, skipped already ordered merges, and used direct reversal only for strictly descending inputs so duplicate timestamp order remains stable. Session regression tests cover ordering and duplicate stability. On the local Windows/JBR 21 benchmark (262,144 rows, one INT32 column, 60 warm-ups and 21 samples; construction outside timing), almost-sorted input improved from 27.271 to 6.378 ns/row and descending input from 34.324 to 3.748; random input was effectively unchanged at 168.075 vs 168.481. These compare `6ac266b065` with the fix and measure local sorting, not RPC throughput.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java:
##########
@@ -1408,44 +1202,8 @@ private boolean equals(Object[] columns) {
     for (int i = 0; i < columns.length; i++) {
       final TSDataType dataType = getDataType(i);
       if (dataType != null) {
-        switch (dataType) {
-          case INT32:
-          case DATE:
-            if (!Arrays.equals((int[]) this.columns[i], (int[]) columns[i])) {
-              return false;
-            }
-            break;
-          case INT64:
-          case TIMESTAMP:
-            if (!Arrays.equals((long[]) this.columns[i], (long[]) columns[i])) {
-              return false;
-            }
-            break;
-          case FLOAT:
-            if (!Arrays.equals((float[]) this.columns[i], (float[]) columns[i])) {
-              return false;
-            }
-            break;
-          case DOUBLE:
-            if (!Arrays.equals((double[]) this.columns[i], (double[]) columns[i])) {
-              return false;
-            }
-            break;
-          case BOOLEAN:
-            if (!Arrays.equals((boolean[]) this.columns[i], (boolean[]) columns[i])) {
-              return false;
-            }
-            break;
-          case TEXT:
-          case BLOB:
-          case STRING:
-          case OBJECT:
-            if (!Arrays.equals((Binary[]) this.columns[i], (Binary[]) columns[i])) {
-              return false;
-            }
-            break;
-          default:
-            throw new UnSupportedDataTypeException(String.format(DATATYPE_UNSUPPORTED, dataType));
+        if (!Type.fromTsDataType(dataType).arrayEquals(this.columns[i], columns[i], rowCount)) {

Review Comment:
   Changed the column hash to consume exactly the first `rowCount` values from each original backing array, without copying. The native loops are selected through `StorageEngine.ARRAY_PREFIX_HASHER_SERVICE`, keeping the TSDataType switch inside TypeService as required by this PR's architecture rule. DATE hashes normalize LocalDate and integer representations consistently with equality. Regression tests cover equal active rows with different spare values/capacities and HashSet lookup, alongside the existing serialization tests.



##########
library-udf/src/main/java/org/apache/iotdb/library/frequency/UDFEnvelopeAnalysis.java:
##########
@@ -213,32 +220,14 @@ public long calculateMode(LongArrayList timestamps) {
   }
 
   public double getValueAsDouble(Row row, int index) throws IOException {
-    double ans;
-    switch (row.getDataType(index)) {
-      case INT32:
-        ans = row.getInt(index);
-        break;
-      case INT64:
-        ans = row.getLong(index);
-        break;
-      case FLOAT:
-        ans = row.getFloat(index);
-        break;
-      case DOUBLE:
-        ans = row.getDouble(index);
-        break;
-      case TEXT:
-      case STRING:
-      case BOOLEAN:
-      case BLOB:
-      case DATE:
-      case TIMESTAMP:
-      default:
-        throw new UDFOutputSeriesDataTypeNotValidException(
-            index,
-            LibraryUdfMessages.EXCEPTION_FAIL_TO_GET_DATA_TYPE_IN_ROW_8CD82629 + row.getTime());
+    try {
+      return TypeServices.NUMERIC_ROW_READER_SERVICE
+          .call(TypeServices.toReadType(row.getDataType(index)))
+          .read(row);

Review Comment:
   Switched this helper to `INDEXED_NUMERIC_ROW_READER_SERVICE` and passed `index` to `read(row, index)`. The regression test supplies two INT32 values `[11, 22]` and verifies that column 1 returns `22.0`; the Envelope test suite passes. This fixes the public helper contract without claiming an ordinary Envelope SQL failure.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4059271190


##########
iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/plugin/builtin/BuiltinPipePlugin.java:
##########
@@ -157,7 +157,6 @@ public String getClassName() {
                   IOT_CONSENSUS_V2_ASYNC_CONNECTOR.getPipePluginName().toLowerCase(),
                   PIPE_CONSENSUS_ASYNC_CONNECTOR.getPipePluginName().toLowerCase(),
                   WEBSOCKET_CONNECTOR.getPipePluginName().toLowerCase(),
-                  OPC_UA_CONNECTOR.getPipePluginName().toLowerCase(),

Review Comment:
   Remove the stale OPC_UA_CONNECTOR and OPC_UA_SINK entries from BUILTIN_SINKS. Master moved OPC UA to library-pipe and removed those enum constants, but these two references remained, causing node-commons compilation to fail. Removing both entries also correctly classifies the separately registered OPC UA plugin as external. The compatibility names in PipeSinkConstant remain available for configuration and the single-thread policy. Both locale builds passed after this cleanup.



##########
library-pipe/opc-ua-sink/src/test/java/org/apache/iotdb/pipe/plugin/sink/opcua/server/OpcUaTypeServicesTest.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.iotdb.pipe.plugin.sink.opcua.server;
+
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.read.common.type.Type;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.junit.Test;
+
+import java.time.LocalDate;
+import java.time.ZoneId;
+
+import static org.junit.Assert.assertEquals;
+
+public class OpcUaTypeServicesTest {
+
+  @Test

Review Comment:
   Move the existing DATE regression from datanode's TypeServicesTest alongside the relocated OPC UA services. The same assertion still checks Milo's DateTime against the LocalDate at the system zone's start of day, guarding against reintroducing java.sql.Date.toInstant(), which throws UnsupportedOperationException. This keeps regression coverage while allowing datanode tests to compile without Milo. The relocated test passed, together with five OPC UA metadata tests and the remaining 60 targeted tests.



##########
library-pipe/opc-ua-sink/src/main/java/org/apache/iotdb/pipe/plugin/sink/opcua/server/OpcUaTypeServices.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.iotdb.pipe.plugin.sink.opcua.server;
+
+import org.apache.iotdb.commons.exception.pipe.PipeRuntimeNonCriticalException;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.util.Date;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+// Keep Milo-dependent type services in the external plugin so core can load without Milo.
+final class OpcUaTypeServices {

Review Comment:
   Relocate the four OPC UA TypeServices from datanode's TypeServices.Pipe into the external plugin, and update all four OpcUaNameSpace call sites to use this class. Master removed Milo from datanode's dependencies; retaining DateTime/NodeId/Identifiers references there prevented compilation. Keeping the services with the plugin preserves the existing conversions, service checks, and Pub/Sub type selection outside the row loop without reintroducing Milo into core. The java.util.Date conversion fix is retained. Both locale reactor builds and the targeted OPC UA metadata/conversion tests passed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "Caideyipi (via GitHub)" <gi...@apache.org>.
Caideyipi commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r3964636195


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java:
##########
@@ -792,108 +749,12 @@ private void writeValues(DataOutputStream stream) throws IOException {
   }
 
   private void serializeColumn(TSDataType dataType, Object column, ByteBuffer buffer) {
-    switch (dataType) {
-      case INT32:
-      case DATE:
-        int[] intValues = (int[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(intValues[j], buffer);
-        }
-        break;
-      case INT64:
-      case TIMESTAMP:
-        long[] longValues = (long[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(longValues[j], buffer);
-        }
-        break;
-      case FLOAT:
-        float[] floatValues = (float[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(floatValues[j], buffer);
-        }
-        break;
-      case DOUBLE:
-        double[] doubleValues = (double[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(doubleValues[j], buffer);
-        }
-        break;
-      case BOOLEAN:
-        boolean[] boolValues = (boolean[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(BytesUtils.boolToByte(boolValues[j]), buffer);
-        }
-        break;
-      case TEXT:
-      case BLOB:
-      case STRING:
-      case OBJECT:
-        Binary[] binaryValues = (Binary[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          if (binaryValues[j] != null && binaryValues[j].getValues() != null) {
-            ReadWriteIOUtils.write(binaryValues[j], buffer);
-          } else {
-            ReadWriteIOUtils.write(0, buffer);
-          }
-        }
-        break;
-      default:
-        throw new UnSupportedDataTypeException(String.format(DATATYPE_UNSUPPORTED, dataType));
-    }
+    Type.fromTsDataType(dataType).serializeArray(column, rowCount, buffer);

Review Comment:
   `Type.serializeArray` uses TsFile's binary-array format, which writes a presence byte before each binary value. The Tablet reader in `RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE` still reads the legacy Tablet format (length + payload only, with nulls represented by the separate bitmap), so the first presence byte is interpreted as part of the length and the stream becomes misaligned. CI fails with `BufferUnderflowException` in `InsertMultiTabletsNodeSerdeTest`. Please preserve the existing Tablet wire format or update both serialization, size calculation, and all readers together.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java:
##########
@@ -1032,36 +893,7 @@ private int getRowNumInRange(List<int[]> rangeList) {
   }
 
   private int getColumnSize(TSDataType dataType, Object column, int start, int end) {
-    int size = 0;
-    switch (dataType) {
-      case INT32:
-      case DATE:
-        size += Integer.BYTES * (end - start);
-        break;
-      case INT64:
-      case TIMESTAMP:
-        size += Long.BYTES * (end - start);
-        break;
-      case FLOAT:
-        size += Float.BYTES * (end - start);
-        break;
-      case DOUBLE:
-        size += Double.BYTES * (end - start);
-        break;
-      case BOOLEAN:
-        size += Byte.BYTES * (end - start);
-        break;
-      case TEXT:
-      case BLOB:
-      case STRING:
-      case OBJECT:
-        Binary[] binaryValues = (Binary[]) column;
-        for (int j = start; j < end; j++) {
-          size += ReadWriteIOUtils.sizeToWrite(binaryValues[j]);
-        }
-        break;
-    }
-    return size;
+    return Type.fromTsDataType(dataType).serializedSize(column, start, end);

Review Comment:
   The WAL size calculation now uses `Type.serializedSize`, whose binary-array size includes a presence byte, but `WAL_ARRAY_WRITER_SERVICE` still writes only the length and payload. The calculated WAL entry size therefore disagrees with the bytes actually written, which breaks WAL offsets/search indexes. The three `WALFileTest` failures in CI reproduce this. Please use a size calculation matching the WAL writer's wire format.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedMaxAccumulator.java:
##########
@@ -519,4 +287,100 @@ protected void updateBooleanValue(int groupId, boolean value) {
       booleanValues.set(groupId, value);
     }
   }
+
+  @Override
+  public RuntimeException unsupportedException() {
+    return new UnSupportedDataTypeException(
+        String.format(CalcMessages.UNSUPPORTED_DATA_TYPE_IN_MAX_AGGREGATION, seriesDataType));
+  }
+
+  @Override
+  public void initializeIntValues() {
+    intValues = new IntBigArray(Integer.MIN_VALUE);
+  }
+
+  @Override
+  public void initializeLongValues() {
+    longValues = new LongBigArray(Long.MIN_VALUE);
+  }
+
+  @Override
+  public void initializeFloatValues() {
+    floatValues = new FloatBigArray(Float.MIN_VALUE);

Review Comment:
   `Float.MIN_VALUE` and `Double.MIN_VALUE` are the smallest positive values, not lower bounds. With this initialization, `MAX` ignores zero and all negative FLOAT/DOUBLE inputs, leaving `inits` false and returning NULL. The existing CI tests `testFloatMaxWithNonPositiveInput`, `testDoubleMaxWithNonPositiveInput`, and `testDoubleMaxWithNonPositiveIntermediateInput` reproduce this regression. Please keep the previous `NEGATIVE_INFINITY` initialization or use another true lower bound.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/TypeServices.java:
##########
@@ -0,0 +1,4012 @@
+/*
+ * 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.iotdb.db.utils;
+
+import org.apache.iotdb.calc.exception.QueryProcessException;
+import org.apache.iotdb.calc.execution.aggregation.Accumulator;
+import org.apache.iotdb.calc.execution.aggregation.BinaryModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.BooleanModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.DoubleModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.FloatModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.IntModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.LongModeAccumulator;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.constant.SqlConstant;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.exception.pipe.PipeRuntimeNonCriticalException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
+import org.apache.iotdb.db.pipe.processor.aggregate.TimeSeriesRuntimeState;
+import org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.AbstractSameTypeNumericOperator;
+import org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.WindowOutput;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBinaryWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBooleanWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowParameter;
+import org.apache.iotdb.db.queryengine.statistics.StatisticsManager;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.ArithmeticNegationTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.InTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.DiffFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.RoundFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.datastructure.util.ValueRecorder;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.IWALByteBufferView;
+import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALWriteUtils;
+import org.apache.iotdb.db.utils.datastructure.AlignedTVList;
+import org.apache.iotdb.db.utils.datastructure.BinaryTVList;
+import org.apache.iotdb.db.utils.datastructure.BooleanTVList;
+import org.apache.iotdb.db.utils.datastructure.DoubleTVList;
+import org.apache.iotdb.db.utils.datastructure.FloatTVList;
+import org.apache.iotdb.db.utils.datastructure.IntTVList;
+import org.apache.iotdb.db.utils.datastructure.LongTVList;
+import org.apache.iotdb.db.utils.datastructure.TVList;
+import org.apache.iotdb.db.utils.windowing.window.EvictableBatchList;
+import org.apache.iotdb.db.utils.windowing.window.WindowImpl;
+import org.apache.iotdb.pipe.api.access.Row;
+import org.apache.iotdb.rpc.RpcUtils;
+
+import com.google.common.io.BaseEncoding;
+import com.sun.jna.platform.win32.OaIdl;
+import com.sun.jna.platform.win32.OleAuto;
+import com.sun.jna.platform.win32.Variant;
+import com.sun.jna.platform.win32.WTypes;
+import com.sun.jna.platform.win32.WinDef;
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.encoding.decoder.Decoder;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.external.commons.lang3.StringUtils;
+import org.apache.tsfile.file.metadata.IChunkMetadata;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.file.metadata.statistics.DateStatistics;
+import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.BatchData;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.read.common.block.column.BinaryColumnBuilder;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.read.filter.basic.Filter;
+import org.apache.tsfile.read.reader.series.PaginationController;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.RamUsageEstimator;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ValueChunkWriter;
+import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.sql.Date;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import java.util.function.ToDoubleFunction;
+import java.util.function.ToIntFunction;
+import java.util.function.ToLongFunction;
+
+public class TypeServices {
+
+  public static final int DEFAULT_DATE =
+      DateUtils.parseDateExpressionToInt(LocalDate.of(1970, 1, 1));
+  private static final LocalDate EMPTY_LOCAL_DATE = LocalDate.of(1000, 1, 1);
+
+  public static final class Memory {
+
+    public static final TypeService<LongSupplier> STATEMENT_VALUE_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::estimateValueSize;
+              case TEXT, BLOB, STRING ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        CalcMessages.UNKNOWN_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToLongFunction<Object>> INSERT_NODE_VALUE_SIZE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  value ->
+                      RamUsageEstimator.alignObjectSize(
+                          type.estimateValueSize() + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER);
+              case TEXT, BLOB, STRING ->
+                  value -> Objects.nonNull(value) ? ((Binary) value).ramBytesUsed() : 0L;
+              case OBJECT, ROW, UNKNOWN, VECTOR -> value -> 0L;
+            };
+
+    static {
+      STATEMENT_VALUE_SIZE_PER_LINE_SERVICE.check();
+      INSERT_NODE_VALUE_SIZE_SERVICE.check();
+    }
+
+    private Memory() {
+      // Utility class
+    }
+  }
+
+  public static final class Transformation {
+
+    public static final TypeService<Function<Object, Column>> CONSTANT_COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT ->
+                  value -> {
+                    final ColumnBuilder builder = type.createColumnBuilder(1);
+                    type.writeObject(builder, value);
+                    return builder.build();
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<
+            Function<org.apache.iotdb.db.queryengine.plan.statement.literal.Literal, IFill>>
+        CONSTANT_FILL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> literal -> new BooleanConstantFill(literal.getBoolean());
+                  case INT32 -> literal -> new IntConstantFill(literal.getInt());
+                  case DATE -> literal -> new IntConstantFill(literal.getDate());
+                  case INT64, TIMESTAMP -> literal -> new LongConstantFill(literal.getLong());
+                  case FLOAT -> literal -> new FloatConstantFill(literal.getFloat());
+                  case DOUBLE -> literal -> new DoubleConstantFill(literal.getDouble());
+                  case TEXT, BLOB, STRING -> literal -> new BinaryConstantFill(literal.getBinary());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      literal -> {
+                        throw new IllegalArgumentException(
+                            CommonOperatorUtils.UNKNOWN_DATATYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<ColumnBuilder>> COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createColumnBuilder;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          String.format(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_FMT, type.getTypeEnum()))
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ColumnToDoubleConverter> VALUE_TO_DOUBLE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> type::getInt;
+              case INT64, TIMESTAMP -> type::getLong;
+              case FLOAT -> type::getFloat;
+              case DOUBLE -> type::getDouble;
+              case BOOLEAN -> (column, index) -> type.getBoolean(column, index) ? 1 : 0;
+              case TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (column, index) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ColumnValueWriter> TRANSFORM_COLUMN_VALUE_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::write;
+              case ROW, UNKNOWN, VECTOR ->
+                  (builder, column, index) -> {
+                    throw new UnSupportedDataTypeException(
+                        String.format(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_FMT, type.getTypeEnum()));
+                  };
+            };
+
+    // Schema evolution keeps physically compatible columns, widens supported values, and exposes
+    // incompatible historical values as nulls instead of interpreting their raw storage.
+    public static final TypeService<AlteredDataTypeColumnTransformer>
+        ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      INT64,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      STRING,
+                      TIMESTAMP,
+                      DATE,
+                      BLOB -> {
+                    final TSDataType targetType = TSDataType.valueOf(type.getTypeEnum().name());
+                    yield (source, positionCount) -> {
+                      final TSDataType sourceType = source.getDataType();
+                      // DATE shares INT32's physical column but was historically incompatible with
+                      // a schema change to INT32, while the other shared-column pairs are reusable.
+                      if (sourceType == targetType
+                          || (targetType != TSDataType.INT32
+                              && SchemaUtils.isUsingSameColumn(sourceType, targetType))) {
+                        return source;
+                      }
+                      return targetType.isCompatible(sourceType)
+                          ? source.convertTo(targetType)
+                          : type.createNullColumn(positionCount);
+                    };
+                  }
+                  case OBJECT -> (source, positionCount) -> source;
+                  case ROW, UNKNOWN, VECTOR -> (source, positionCount) -> null;
+                };
+
+    public static final TypeService<RoundTransformer> ROUND_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> RoundFunctionTransformer::transformInt;
+              case INT64 -> RoundFunctionTransformer::transformLong;
+              case FLOAT -> RoundFunctionTransformer::transformFloat;
+              case DOUBLE -> RoundFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new UnsupportedOperationException(
+                        String.format("Unsupported source dataType: %s", type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<DiffTransformer> DIFF_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> DiffFunctionTransformer::transformInt;
+              case INT64 -> DiffFunctionTransformer::transformLong;
+              case FLOAT -> DiffFunctionTransformer::transformFloat;
+              case DOUBLE -> DiffFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<NegationTransformer> NEGATION_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> ArithmeticNegationTransformer::transformInt;
+              case INT64 -> ArithmeticNegationTransformer::transformLong;
+              case FLOAT -> ArithmeticNegationTransformer::transformFloat;
+              case DOUBLE -> ArithmeticNegationTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<StateWindowSplitter> STATE_WINDOW_SPLITTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordInt(type.getInt(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getInt(values, index) - valueRecorder.getInt()) > delta;
+                    if (split) {
+                      valueRecorder.recordInt(type.getInt(values, index));
+                    }
+                    return split;
+                  };
+              case INT64 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordLong(type.getLong(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getLong(values, index) - valueRecorder.getLong()) > delta;
+                    if (split) {
+                      valueRecorder.recordLong(type.getLong(values, index));
+                    }
+                    return split;
+                  };
+              case FLOAT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordFloat(type.getFloat(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getFloat(values, index) - valueRecorder.getFloat()) > delta;
+                    if (split) {
+                      valueRecorder.recordFloat(type.getFloat(values, index));
+                    }
+                    return split;
+                  };
+              case DOUBLE ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordDouble(type.getDouble(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getDouble(values, index) - valueRecorder.getDouble()) > delta;
+                    if (split) {
+                      valueRecorder.recordDouble(type.getDouble(values, index));
+                    }
+                    return split;
+                  };
+              case BOOLEAN ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        type.getBoolean(values, index) != valueRecorder.getBoolean();
+                    if (split) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index));
+                    }
+                    return split;
+                  };
+              case TEXT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordString(type.getBinary(values, index - 1).toString());
+                      valueRecorder.setRecorded(true);
+                    }
+                    final String value = type.getBinary(values, index).toString();
+                    final boolean split = !value.equals(valueRecorder.getString());
+                    if (split) {
+                      valueRecorder.recordString(value);
+                    }
+                    return split;
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (valueRecorder, delta, values, index) -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages.INVALID_DATA_TYPE_FOR_STATE_WINDOW_STRATEGY);
+                  };
+            };
+
+    public static final TypeService<InTransformerSetInitializer>
+        IN_TRANSFORMER_SET_INITIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::initIntSet;
+                  case INT64, TIMESTAMP -> InTransformer::initLongSet;
+                  case FLOAT -> InTransformer::initFloatSet;
+                  case DOUBLE -> InTransformer::initDoubleSet;
+                  case BOOLEAN -> InTransformer::initBooleanSet;
+                  case TEXT, STRING -> InTransformer::initStringSet;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, values) -> {
+                        throw new UnsupportedOperationException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<InTransformerColumnTransformer>
+        IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::transformInt;
+                  case INT64, TIMESTAMP -> InTransformer::transformLong;
+                  case FLOAT -> InTransformer::transformFloat;
+                  case DOUBLE -> InTransformer::transformDouble;
+                  case BOOLEAN -> InTransformer::transformBoolean;
+                  case TEXT, STRING -> InTransformer::transformBinary;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, columns, builder) -> {
+                        throw new QueryProcessException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<TypeService<CastColumnStrategy>> CAST_COLUMN_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(builder, type.getInt(column, index)));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getInt(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getInt(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getInt(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getInt(column, index) != 0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getInt(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case INT64 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castLongToInt(
+                                            type.getLong(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getLong(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getLong(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getLong(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getLong(column, index) != 0L));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getLong(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case FLOAT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castFloatToInt(
+                                            type.getFloat(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castFloatToLong(
+                                            type.getFloat(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getFloat(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getFloat(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getFloat(column, index) != 0.0f));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getFloat(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DOUBLE ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToInt(
+                                            type.getDouble(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToLong(
+                                            type.getDouble(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToFloat(
+                                            type.getDouble(column, index))));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getDouble(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getDouble(column, index) != 0.0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getDouble(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case BOOLEAN ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder, type.getBoolean(column, index) ? 1 : 0));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder, type.getBoolean(column, index) ? 1L : 0L));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder, type.getBoolean(column, index) ? 1.0f : 0.0f));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(
+                                        builder, type.getBoolean(column, index) ? 1.0 : 0.0));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getBoolean(column, index)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getBoolean(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case TEXT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeInt(builder, Integer.parseInt(value)));
+                        case INT64 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeLong(builder, Long.parseLong(value)));
+                        case FLOAT ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeFloat(
+                                        builder, CastFunctionUtils.castTextToFloat(value)));
+                        case DOUBLE ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeDouble(
+                                        builder, CastFunctionUtils.castTextToDouble(value)));
+                        case BOOLEAN ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, CastFunctionUtils.castTextToBoolean(value)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(builder, type.getBinary(column, index)));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  targetType -> unsupportedSourceCastStrategy(type);
+            };
+
+    private static CastColumnStrategy castColumnStrategy(
+        final Type targetType, final CastColumnWriter writer) {
+      return new CastColumnStrategy(() -> {}, targetType::createColumnBuilder, writer);
+    }
+
+    private static CastColumnStrategy castBinaryColumnStrategy(
+        final Type sourceType, final Type targetType, final BinaryStringCastWriter writer) {
+      return castColumnStrategy(
+          targetType,
+          (column, index, builder) ->
+              writer.write(
+                  sourceType.getBinary(column, index).getStringValue(TSFileConfig.STRING_CHARSET),
+                  builder));
+    }
+
+    private static CastColumnStrategy unsupportedSourceCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported source dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedTargetCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported target dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedCastStrategy(final String message) {
+      return new CastColumnStrategy(
+          () -> {
+            throw new UnsupportedOperationException(message);
+          },
+          ignored -> {
+            throw new UnsupportedOperationException(message);
+          },
+          (column, index, builder) -> {
+            throw new UnsupportedOperationException(message);
+          });
+    }
+
+    public static final class CastColumnStrategy {
+      private final Runnable validator;
+      private final IntFunction<ColumnBuilder> builderFactory;
+      private final CastColumnWriter writer;
+
+      private CastColumnStrategy(
+          final Runnable validator,
+          final IntFunction<ColumnBuilder> builderFactory,
+          final CastColumnWriter writer) {
+        this.validator = validator;
+        this.builderFactory = builderFactory;
+        this.writer = writer;
+      }
+
+      public void validate() {
+        validator.run();
+      }
+
+      public ColumnBuilder createBuilder(final int expectedEntries) {
+        return builderFactory.apply(expectedEntries);
+      }
+
+      public void cast(final Column column, final int index, final ColumnBuilder builder) {
+        writer.write(column, index, builder);
+      }
+    }
+
+    @FunctionalInterface
+    private interface CastColumnWriter {
+      void write(Column column, int index, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    private interface BinaryStringCastWriter {
+      void write(String value, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    public interface ColumnToDoubleConverter {
+      double convert(Column column, int index) throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface ColumnValueWriter {
+      void write(ColumnBuilder builder, Column column, int index);
+    }
+
+    @FunctionalInterface
+    public interface AlteredDataTypeColumnTransformer {
+      Column transform(Column source, int positionCount);
+    }
+
+    @FunctionalInterface
+    public interface RoundTransformer {
+      void transform(RoundFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface DiffTransformer {
+      void transform(DiffFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface NegationTransformer {
+      void transform(
+          ArithmeticNegationTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface StateWindowSplitter {
+      boolean split(ValueRecorder valueRecorder, double delta, Column values, int index);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerSetInitializer {
+      void initialize(InTransformer transformer, Set<String> values);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerColumnTransformer {
+      void transform(InTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    static {
+      CONSTANT_COLUMN_BUILDER_SERVICE.check();
+      CONSTANT_FILL_SERVICE.check();
+      COLUMN_BUILDER_SERVICE.check();
+      VALUE_TO_DOUBLE_SERVICE.check();
+      TRANSFORM_COLUMN_VALUE_WRITER_SERVICE.check();
+      ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE.check();
+      ROUND_TRANSFORMER_SERVICE.check();
+      DIFF_TRANSFORMER_SERVICE.check();
+      NEGATION_TRANSFORMER_SERVICE.check();
+      STATE_WINDOW_SPLITTER_SERVICE.check();
+      IN_TRANSFORMER_SET_INITIALIZER_SERVICE.check();
+      IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE.check();
+      CAST_COLUMN_SERVICE.check();
+    }
+
+    private Transformation() {
+      // Utility class
+    }
+  }
+
+  public static final class Aggregation {
+
+    public static final TypeService<ExtremeValueAccumulatorStrategy>
+        EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateIntResult(column.getInt(index)),
+                          (accumulator, value) ->
+                              accumulator.updateIntResult(((Number) value).intValue()),
+                          (accumulator, column) -> accumulator.getResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateLongResult(column.getLong(index)),
+                          (accumulator, value) ->
+                              accumulator.updateLongResult(((Number) value).longValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateFloatResult(column.getFloat(index)),
+                          (accumulator, value) ->
+                              accumulator.updateFloatResult(((Number) value).floatValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateDoubleResult(column.getDouble(index)),
+                          (accumulator, value) ->
+                              accumulator.updateDoubleResult(((Number) value).doubleValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case STRING ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateBinaryResult(column.getBinary(index)),
+                          (accumulator, value) -> accumulator.updateBinaryResult((Binary) value),
+                          (accumulator, column) ->
+                              accumulator.getResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN, TEXT, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      ExtremeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<TimeValueAccumulatorStrategy>
+        TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateIntResult(column.getInt(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateIntResult(
+                                  ((Number) getStatisticsValue(statistics, first)).intValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateLongResult(column.getLong(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateLongResult(
+                                  ((Number) getStatisticsValue(statistics, first)).longValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateFloatResult(column.getFloat(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateFloatResult(
+                                  ((Number) getStatisticsValue(statistics, first)).floatValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateDoubleResult(column.getDouble(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateDoubleResult(
+                                  ((Number) getStatisticsValue(statistics, first)).doubleValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBinaryResult(column.getBinary(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBinaryResult(
+                                  getBinaryStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBooleanResult(column.getBoolean(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBooleanResult(
+                                  (boolean) getStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBoolean(column.getBoolean(0)),
+                          (builder, result) -> builder.writeBoolean(result.getBoolean()));
+                  case ROW, UNKNOWN, VECTOR -> TimeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<MaxMinByAccumulatorStrategy>
+        MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateIntResult(
+                                  time, yColumn.getInt(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateIntResult(
+                                  time,
+                                  BytesUtils.bytesToInt(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Integer.BYTES),
+                                  0));
+                  case INT64, TIMESTAMP ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateLongResult(
+                                  time, yColumn.getLong(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateLongResult(
+                                  time,
+                                  BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Long.BYTES),
+                                  0));
+                  case FLOAT ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateFloatResult(
+                                  time, yColumn.getFloat(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateFloatResult(
+                                  time,
+                                  BytesUtils.bytesToFloat(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Float.BYTES),
+                                  0));
+                  case DOUBLE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateDoubleResult(
+                                  time, yColumn.getDouble(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateDoubleResult(
+                                  time,
+                                  BytesUtils.bytesToDouble(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Double.BYTES),
+                                  0));
+                  case STRING ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateBinaryResult(
+                                  time, yColumn.getBinary(yIndex), xColumn, xIndex),
+                          TypeServices.Aggregation::updateBinaryIntermediate);
+                  case TEXT, BLOB, OBJECT -> maxMinByAccumulatorStrategy(type, null, null);
+                  case BOOLEAN -> maxMinByAccumulatorStrategy(type, null, null);
+                  case ROW, UNKNOWN, VECTOR -> MaxMinByAccumulatorStrategy.unsupported(type);
+                };
+
+    public static final TypeService<EventWindowManagerProvider>
+        EVENT_WINDOW_MANAGER_PROVIDER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      eventWindowManagerProvider(
+                          EqualIntWindowManager::new, VariationIntWindowManager::new);
+                  case INT64 ->
+                      eventWindowManagerProvider(
+                          EqualLongWindowManager::new, VariationLongWindowManager::new);
+                  case FLOAT ->
+                      eventWindowManagerProvider(
+                          EqualFloatWindowManager::new, VariationFloatWindowManager::new);
+                  case DOUBLE ->
+                      eventWindowManagerProvider(
+                          EqualDoubleWindowManager::new, VariationDoubleWindowManager::new);
+                  case TEXT -> eventWindowManagerProvider(EqualBinaryWindowManager::new, null);
+                  case BOOLEAN -> eventWindowManagerProvider(EqualBooleanWindowManager::new, null);
+                  case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      EventWindowManagerProvider.unsupported();
+                };
+
+    private static EventWindowManagerProvider eventWindowManagerProvider(
+        final EventWindowManagerFactory equalFactory,
+        final EventWindowManagerFactory variationFactory) {
+      return new EventWindowManagerProvider(equalFactory, variationFactory);
+    }
+
+    private static void updateBinaryIntermediate(
+        final MaxMinByAccumulator accumulator,
+        final long time,
+        final byte[] bytes,
+        final int offset) {
+      final int length = BytesUtils.bytesToInt(bytes, offset);
+      final int valueOffset = offset + Integer.BYTES;
+      accumulator.updateBinaryResult(
+          time,
+          new Binary(BytesUtils.subBytes(bytes, valueOffset, length)),
+          accumulator.readXFromBytesIntermediateInput(bytes, valueOffset + length),
+          0);
+    }
+
+    private static MaxMinByAccumulatorStrategy maxMinByAccumulatorStrategy(
+        final Type type,
+        final MaxMinByYColumnUpdater yColumnUpdater,
+        final MaxMinByYBytesUpdater yBytesUpdater) {
+      return new MaxMinByAccumulatorStrategy(type, true, yColumnUpdater, yBytesUpdater);
+    }
+
+    private static TimeValueAccumulatorStrategy timeValueAccumulatorStrategy(
+        final TimeValueColumnUpdater columnUpdater,
+        final TimeValueStatisticsUpdater statisticsUpdater,
+        final TimeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new TimeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    private static Object getStatisticsValue(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getFirstValue() : statistics.getLastValue();
+    }
+
+    private static long getStatisticsTime(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getStartTime() : statistics.getEndTime();
+    }
+
+    private static Binary getBinaryStatisticsValue(
+        final Statistics<?> statistics, final boolean first) {
+      final Object value = getStatisticsValue(statistics, first);
+      if (statistics instanceof DateStatistics) {
+        return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+      }
+      return value instanceof Binary
+          ? (Binary) value
+          : new Binary(String.valueOf(value), StandardCharsets.UTF_8);
+    }
+
+    public static final class TimeValueAccumulatorStrategy {
+      private final TimeValueColumnUpdater columnUpdater;
+      private final TimeValueStatisticsUpdater statisticsUpdater;
+      private final TimeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private TimeValueAccumulatorStrategy(
+          final TimeValueColumnUpdater columnUpdater,
+          final TimeValueStatisticsUpdater statisticsUpdater,
+          final TimeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static TimeValueAccumulatorStrategy unsupported() {
+        return new TimeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final TimeValueAccumulator accumulator,
+          final Column[] columns,
+          final BitMap bitMap,
+          final boolean stopAfterFirstValue,
+          final boolean bitmapMarksSelected) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && bitmapMarksSelected != bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i, columns[0].getLong(i));
+            if (stopAfterFirstValue) {
+              return;
+            }
+          }
+        }
+      }
+
+      public void addIntermediate(
+          final TimeValueAccumulator accumulator,
+          final Column valueColumn,
+          final Column timeColumn) {
+        columnUpdater.update(accumulator, valueColumn, 0, timeColumn.getLong(0));
+      }
+
+      public void addStatistics(
+          final TimeValueAccumulator accumulator,
+          final Statistics<?> statistics,
+          final boolean first) {
+        statisticsUpdater.update(accumulator, statistics, first);
+      }
+
+      public void setFinal(final TimeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final class MaxMinByAccumulatorStrategy {
+      private final Type type;
+      private final boolean xSupported;
+      private final MaxMinByYColumnUpdater yColumnUpdater;
+      private final MaxMinByYBytesUpdater yBytesUpdater;
+
+      private MaxMinByAccumulatorStrategy(
+          final Type type,
+          final boolean xSupported,
+          final MaxMinByYColumnUpdater yColumnUpdater,
+          final MaxMinByYBytesUpdater yBytesUpdater) {
+        this.type = type;
+        this.xSupported = xSupported;
+        this.yColumnUpdater = yColumnUpdater;
+        this.yBytesUpdater = yBytesUpdater;
+      }
+
+      private static MaxMinByAccumulatorStrategy unsupported(final Type type) {
+        return new MaxMinByAccumulatorStrategy(type, false, null, null);
+      }
+
+      public boolean isXSupported() {
+        return xSupported;
+      }
+
+      public boolean isYSupported() {
+        return yColumnUpdater != null;
+      }
+
+      public void addInput(
+          final MaxMinByAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[2].isNull(i)) {
+            yColumnUpdater.update(accumulator, columns[0].getLong(i), columns[2], i, columns[1], i);
+          }
+        }
+      }
+
+      public void setXResult(final TsPrimitiveType result, final Column column, final int index) {
+        type.setTo(result, column, index);

Review Comment:
   `Type.setTo(TsPrimitiveType, Column, int)` copies the primitive into the column; it does not copy the column value into the primitive. This call therefore leaves `xResult` at its default value and can overwrite the input column. CI reproduces this in `AccumulatorTest.maxByAccumulatorTest` (`-99` expected, `0` returned). Please use the correct column-to-primitive copy operation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r3977856338


##########
example/session/src/main/java/org/apache/iotdb/DataMigrationExample.java:
##########
@@ -60,6 +64,21 @@ public class DataMigrationExample {
   // concurrent thread of loading timeseries data
   private static final int CONCURRENCY = 5;
 
+  private static final TypeService<ColumnValueGetter> COLUMN_VALUE_GETTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> DataIterator::getBoolean;
+            case INT32 -> DataIterator::getInt;
+            case INT64, TIMESTAMP -> DataIterator::getLong;
+            case FLOAT -> DataIterator::getFloat;
+            case DOUBLE -> DataIterator::getDouble;
+            case TEXT, STRING -> DataIterator::getString;
+            case DATE, BLOB, OBJECT -> DataIterator::getObject;
+            case ROW, UNKNOWN, VECTOR ->

Review Comment:
   Migration column readers now use TypeService with explicit rejection of ROW, UNKNOWN and VECTOR. An unsupported type raises a localized UnSupportedDataTypeException and reaches the existing device-failure handler; the previous null-result/log-and-continue fallback is removed. The example and its reactor dependencies compile successfully.



##########
iotdb-client/cli/src/main/java/org/apache/iotdb/cli/AbstractCli.java:
##########
@@ -56,6 +59,38 @@
 
 public abstract class AbstractCli {
 
+  static String timestampPrecision = "ms";
+  static String timeFormat = RpcUtils.DEFAULT_TIME_FORMAT;
+
+  private static final TypeService<SqlValueGetter> SQL_VALUE_GETTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT, STRING, OBJECT ->
+                (resultSet, columnIndex, zoneId) -> resultSet.getString(columnIndex);
+            case BLOB ->
+                (resultSet, columnIndex, zoneId) -> {
+                  byte[] value = resultSet.getBytes(columnIndex);
+                  return value == null ? null : BytesUtils.parseBlobByteArrayToString(value);
+                };
+            case DATE ->
+                (resultSet, columnIndex, zoneId) -> {
+                  int value = resultSet.getInt(columnIndex);
+                  return resultSet.wasNull() ? null : DateUtils.formatDate(value);
+                };
+            case TIMESTAMP ->
+                (resultSet, columnIndex, zoneId) -> {
+                  long value = resultSet.getLong(columnIndex);
+                  return resultSet.wasNull()
+                      ? null
+                      : RpcUtils.formatDatetime(timeFormat, timestampPrecision, value, zoneId);
+                };
+            case ROW, UNKNOWN, VECTOR ->

Review Comment:
   CLI value formatting now dispatches through TypeService with an exhaustive enum switch. ROW, UNKNOWN and VECTOR explicitly throw UnSupportedDataTypeException using the English/Chinese CLI message, so unsupported output types cannot silently become null. Supported DATE/TIMESTAMP/BLOB null handling and formatting are preserved. AbstractCliTest passes (6 tests).



##########
iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/AbstractDataTool.java:
##########
@@ -88,6 +91,35 @@
 
 public abstract class AbstractDataTool {
 
+  private static final TypeService<ValueParser> VALUE_PARSER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case TEXT, STRING ->
+                value -> {
+                  if (value.startsWith("\"") && value.endsWith("\"")) {
+                    return value.substring(1, value.length() - 1);
+                  }
+                  return value;
+                };
+            case BOOLEAN ->
+                value ->
+                    !"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)
+                        ? null
+                        : Boolean.parseBoolean(value);
+            case INT32 -> value -> Integer.parseInt(value);
+            case INT64, TIMESTAMP -> value -> Long.parseLong(value);
+            case FLOAT -> value -> Float.parseFloat(value);
+            case DOUBLE -> value -> Double.parseDouble(value);
+            case DATE -> value -> LocalDate.parse(value);
+            case BLOB ->
+                value -> new Binary(parseHexStringToByteArray(value.replaceFirst("0x", "")));
+            case OBJECT, ROW, UNKNOWN, VECTOR ->

Review Comment:
   Import value parsing now dispatches through TypeService. OBJECT, ROW, UNKNOWN and VECTOR are explicitly rejected using the localized unsupported-type exception; the default null-producing parser is removed. NumberFormatException handling still returns null for invalid numeric input. The CLI/tool test run passes all 9 tests.



##########
iotdb-client/jdbc/src/main/java/org/apache/iotdb/jdbc/IoTDBAbstractDatabaseMetadata.java:
##########
@@ -52,6 +56,25 @@
 public abstract class IoTDBAbstractDatabaseMetadata implements DatabaseMetaData {
 
   private static final Logger LOGGER = LoggerFactory.getLogger(IoTDBAbstractDatabaseMetadata.class);
+
+  private static final TypeService<ColumnValueWriter> COLUMN_VALUE_WRITER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case TEXT, STRING, BLOB, OBJECT ->
+                (builder, value) ->
+                    builder.writeBinary(new Binary(value.toString(), TSFileConfig.STRING_CHARSET));
+            case FLOAT -> (builder, value) -> builder.writeFloat((float) value);
+            case INT32, DATE -> (builder, value) -> builder.writeInt((int) value);
+            case INT64, TIMESTAMP -> (builder, value) -> builder.writeLong((long) value);
+            case DOUBLE -> (builder, value) -> builder.writeDouble((double) value);
+            case BOOLEAN -> (builder, value) -> builder.writeBoolean((boolean) value);
+            case ROW, UNKNOWN, VECTOR ->

Review Comment:
   JDBC metadata column writing now dispatches through TypeService. ROW, UNKNOWN and VECTOR explicitly throw UnSupportedDataTypeException using matching English/Chinese message keys, replacing the logging-only default branch. IoTDBDatabaseMetadataTest passes all 5 tests, and both locale source reactor builds succeed.



##########
external-service-impl/rest/src/main/java/org/apache/iotdb/rest/protocol/utils/InsertRowDataUtils.java:
##########
@@ -31,6 +33,58 @@
 
 public class InsertRowDataUtils {
 
+  private static final TypeService<ValueConverter> VALUE_CONVERTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (value, index, mismatchedInfo) -> {
+                  if (!(value instanceof Boolean)) {
+                    mismatchedInfo.put(index, value);
+                  }
+                  return value;
+                };
+            case INT32, DATE ->
+                (value, index, mismatchedInfo) -> {
+                  if (value instanceof Number number) {
+                    return number.intValue();
+                  }
+                  mismatchedInfo.put(index, value);
+                  return value;
+                };
+            case INT64, TIMESTAMP ->
+                (value, index, mismatchedInfo) -> {
+                  if (value instanceof Number number) {
+                    return number.longValue();
+                  }
+                  mismatchedInfo.put(index, value);
+                  return value;
+                };
+            case FLOAT ->
+                (value, index, mismatchedInfo) -> {
+                  if (value instanceof Number number) {
+                    return number.floatValue();
+                  }
+                  mismatchedInfo.put(index, value);
+                  return value;
+                };
+            case DOUBLE ->
+                (value, index, mismatchedInfo) -> {
+                  if (value instanceof Number number) {
+                    return number.doubleValue();
+                  }
+                  mismatchedInfo.put(index, value);
+                  return value;
+                };
+            case TEXT, BLOB, STRING ->
+                (value, index, mismatchedInfo) ->
+                    new Binary(value.toString().getBytes(StandardCharsets.UTF_8));
+            case OBJECT, ROW, UNKNOWN, VECTOR ->

Review Comment:
   REST row conversion now uses an exhaustive TypeService switch. OBJECT, ROW, UNKNOWN and VECTOR explicitly retain the existing IoTDBConnectionException behavior, and numeric converters use instanceof pattern variables while preserving mismatch reporting. All 19 REST tests pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "JackieTien97 (via GitHub)" <gi...@apache.org>.
JackieTien97 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4012011471


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/TableCorrelationAccumulator.java:
##########
@@ -82,31 +81,15 @@ public void addInput(Column[] arguments, AggregationMask mask) {
         if (arguments[0].isNull(position) || arguments[1].isNull(position)) {
           continue;
         }
-        double x = getDoubleValue(arguments[0], position, xDataType);
-        double y = getDoubleValue(arguments[1], position, yDataType);
+        double x = getDoubleValue(arguments[0], position);
+        double y = getDoubleValue(arguments[1], position);
         update(x, y);
       }
     }
   }
 
-  private double getDoubleValue(Column column, int position, TSDataType dataType) {
-    switch (dataType) {
-      case INT32:
-      case DATE:
-        return column.getInt(position);
-      case INT64:
-      case TIMESTAMP:
-        return column.getLong(position);
-      case FLOAT:
-        return column.getFloat(position);
-      case DOUBLE:
-        return column.getDouble(position);
-      default:
-        throw new UnSupportedDataTypeException(
-            String.format(
-                CalcMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_CORRELATION_AGGREGATION_ARG_2FF29597,
-                dataType));
-    }
+  private double getDoubleValue(Column column, int position) {
+    return column.getDouble(position);

Review Comment:
   [P1] Preserve native timestamp reads for TimeColumn inputs
   
   The previous implementation read INT64/TIMESTAMP using `column.getLong(position)` and widened the result to double. `column.getDouble(position)` is not equivalent for the actual `TimeColumn` implementation in the pinned TsFile snapshot: it inherits the default method that throws `UnsupportedOperationException`.
   
   This is reachable in table SQL. [AbstractAggTableScanOperator.buildValueColumn](https://github.com/apache/iotdb/blob/6ac266b065f06b9bc6b16d31a4b58c66e08b90fb/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractAggTableScanOperator.java#L393) returns `inputRegion.getTimeColumn()` for a TIME argument and places that same object in the aggregation block's `valueColumns`. Replacing the block's dedicated time slot with a placeholder does not convert this value-column object into a LongColumn. Table metadata accepts TIMESTAMP arguments for these functions.
   
   Table-model reproducer using the values from the real-instance comparison:
   
   ```sql
   CREATE DATABASE review18606_corr;
   USE review18606_corr;
   CREATE TABLE readings(device_id STRING TAG, d DOUBLE FIELD);
   INSERT INTO readings(time,device_id,d)
   VALUES (1,'neg',-8.5),(2,'neg',-2.75);
   FLUSH;
   SELECT corr(time,d),covar_pop(time,d),regr_slope(time,d)
   FROM readings WHERE device_id='neg';
   ```
   
   The earlier BASE `25ab7941ce` vs PR `9f4c0f0404` real-instance run returned `[1.0, 1.4375, 0.17391304347826086]` on BASE and `301: org.apache.tsfile.read.common.block.column.TimeColumn` on the PR. Tree SQL and grouped variants reproduced the same failure. This getter and the relevant dependency remain unchanged at `6ac266b065`; the TsFile artifact still resolves to `2.4.1-260909-20260909.035234-2`.
   
   Please preserve declared-type/native reads, or complete the concrete Column contracts before relying on the generic accessor. The equivalent correlation/covariance/regression changes in the tree, table and grouped implementations need the same treatment.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/TimeSeriesRuntimeState.java:
##########
@@ -74,6 +79,22 @@ public TimeSeriesRuntimeState(
     this.windowingProcessor = windowingProcessor;
   }
 
+  public Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> updateWindows(
+      final long timestamp,
+      final Row row,
+      final int columnIndex,
+      final long outputMinReportIntervalMilliseconds)
+      throws IOException {
+    if (rowValueUpdater == null) {

Review Comment:
   [P2] Refresh the cached row updater when a series changes type
   
   `AggregateProcessor` retains this state by timeseries path, but `rowValueUpdater` is selected only for the first row's type. If the same path is recreated with a different type, later rows continue through the original getter. For example, an INT32 row followed by a DOUBLE row still calls `PipeRow.getInt`, which casts the DOUBLE column's `double[]` to `int[]` and fails before the window can handle the type transition.
   
   Previously, `AggregateProcessor` dispatched on each row's actual type. `TimeSeriesWindow` explicitly handles a changed input type by purging the old window. Caching the getter indefinitely prevents reaching that existing behavior.
   
   Executed dispatch-level reproduction with real PipeRow instances and the real `TimeSeriesRuntimeState.updateWindows(..., Row, ...)` entry point:
   
   ```text
   First row:  INT32 [42]   -> INT32 updater
   Next row:   DOUBLE [2.5] -> ClassCastException: [D cannot be cast to [I
   Direct DOUBLE overload  -> receives 2.5 normally
   ```
   
   The typed overloads were instrumented to record dispatch; this test did not run the complete Pipe lifecycle. The state key, one-time initialization and primitive-array getters establish the failure path, and remain unchanged in this HEAD.
   
   Please cache the associated data type together with the updater and refresh it on a type change, or dispatch using each row's actual type.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedModeAccumulator.java:
##########
@@ -188,121 +135,52 @@ public void reset() {
     nullCounts.reset();
   }
 
+  private void addInput(int[] groupIds, Column column, AggregationMask mask) {
+    int positionCount = mask.getSelectedPositionCount();
+    if (mask.isSelectAll()) {
+      for (int i = 0; i < positionCount; i++) {
+        addValue(groupIds[i], column, i);
+      }
+    } else {
+      int[] selectedPositions = mask.getSelectedPositions();
+      for (int i = 0; i < positionCount; i++) {
+        int position = selectedPositions[i];
+        addValue(groupIds[position], column, position);
+      }
+    }
+  }
+
+  private void addValue(int groupId, Column column, int position) {
+    HashMap<TsPrimitiveType, Long> countMap = countMaps.get(groupId);
+    if (column.isNull(position)) {
+      nullCounts.increment(groupId);
+    } else {
+      countMap.compute(
+          column.getTsPrimitiveType(position), (key, count) -> count == null ? 1L : count + 1);

Review Comment:
   [P1] Preserve logical row access when constructing MODE keys
   
   The old typed getters are not equivalent to `getTsPrimitiveType(position)` for two Column implementations used by this code:
   
   - `TimeColumn` does not implement this method and throws.
   - `DictionaryColumn.getTsPrimitiveType` currently passes the logical position straight to its dictionary, without applying `getId(position)` as its typed getters do. MODE can therefore count values that are not present in its logical input.
   
   Table-model time-column reproducer:
   
   ```sql
   CREATE DATABASE review18606_mode;
   USE review18606_mode;
   CREATE TABLE readings(device_id STRING TAG, d DOUBLE FIELD);
   INSERT INTO readings(time,device_id,d)
   VALUES (1,'neg',-8.5),(2,'neg',-2.75);
   FLUSH;
   SELECT substring(device_id,1,1),mode(time)
   FROM readings
   GROUP BY substring(device_id,1,1)
   ORDER BY 1;
   ```
   
   In the earlier real-instance comparison (BASE `25ab7941ce`, PR `9f4c0f0404`), the matching group returned time=1 on BASE, while the PR threw the TimeColumn exception.
   
   A separate executed class-level test covers the dictionary mapping:
   
   ```text
   Underlying values: [10, 11, 12, 100, 100, 100]
   Selected positions: [3, 4, 5]
   Logical input:      [100, 100, 100]
   BASE MODE: 100
   PR MODE:   10
   ```
   
   The real `DistinctGroupedAccumulator` wrapper also reproduces the dictionary result with the corresponding selected mask. This is evidence for that concrete class-level path, not a claim that every MODE(DISTINCT ...) SQL plan fails. The call and relevant TsFile implementations remain unchanged at the current HEAD.
   
   Please construct keys through declared-type native getters, or fix and validate both concrete Column implementations, including non-identity/repeated dictionary mappings.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/LastAccumulator.java:
##########
@@ -80,35 +90,7 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     // arguments[0] is value column, arguments[1] is time column
-    switch (seriesDataType) {
-      case INT32:
-      case DATE:
-        addIntInput(arguments[0], arguments[1], mask);
-        return;
-      case INT64:
-      case TIMESTAMP:
-        addLongInput(arguments[0], arguments[1], mask);
-        return;
-      case FLOAT:
-        addFloatInput(arguments[0], arguments[1], mask);
-        return;
-      case DOUBLE:
-        addDoubleInput(arguments[0], arguments[1], mask);
-        return;
-      case TEXT:
-      case STRING:
-      case BLOB:
-      case OBJECT:
-        addBinaryInput(arguments[0], arguments[1], mask);
-        return;
-      case BOOLEAN:
-        addBooleanInput(arguments[0], arguments[1], mask);
-        return;
-      default:
-        throw new UnSupportedDataTypeException(
-            String.format(
-                CalcMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_LAST_ARG_37F52124, seriesDataType));
-    }
+    addInput(arguments[0], arguments[1], mask);

Review Comment:
   [P2] Keep the descending LAST/LAST_BY early-return path
   
   The old switch invoked protected `addIntInput`/`addLongInput`/etc., so a `LastDescAccumulator` executed its overridden loop and returned after the first qualifying row. The factory still creates the descending subclass, but this new call enters a private superclass loop and bypasses those overrides. The equivalent `LastByAccumulator` change bypasses the `LastByDescAccumulator` optimization when `canFinishAfterInit` is true.
   
   An executed BASE `25ab7941ce` vs PR `9f4c0f0404` comparison instrumented the time Column on the same 1,024-row, descending, non-null block:
   
   | Accumulator | BASE time.getLong calls | PR calls | Result |
   |---|---:|---:|---|
   | LastDescAccumulator | 1 | 1,024 | unchanged |
   | LastByDescAccumulator | 1 | 1,024 | unchanged |
   
   These are measured getter counts, not latency ratios. The outer scan can still inspect `hasFinalResult()` after the call and skip subsequent blocks; it cannot recover the work already done inside this block. The private loops remain unchanged at the current HEAD.
   
   Please preserve the type-specific/overridable batch entry point or explicitly carry the descending early-return condition into the shared loop. Ascending or otherwise non-finalizable inputs must continue scanning.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java:
##########
@@ -1408,44 +1202,8 @@ private boolean equals(Object[] columns) {
     for (int i = 0; i < columns.length; i++) {
       final TSDataType dataType = getDataType(i);
       if (dataType != null) {
-        switch (dataType) {
-          case INT32:
-          case DATE:
-            if (!Arrays.equals((int[]) this.columns[i], (int[]) columns[i])) {
-              return false;
-            }
-            break;
-          case INT64:
-          case TIMESTAMP:
-            if (!Arrays.equals((long[]) this.columns[i], (long[]) columns[i])) {
-              return false;
-            }
-            break;
-          case FLOAT:
-            if (!Arrays.equals((float[]) this.columns[i], (float[]) columns[i])) {
-              return false;
-            }
-            break;
-          case DOUBLE:
-            if (!Arrays.equals((double[]) this.columns[i], (double[]) columns[i])) {
-              return false;
-            }
-            break;
-          case BOOLEAN:
-            if (!Arrays.equals((boolean[]) this.columns[i], (boolean[]) columns[i])) {
-              return false;
-            }
-            break;
-          case TEXT:
-          case BLOB:
-          case STRING:
-          case OBJECT:
-            if (!Arrays.equals((Binary[]) this.columns[i], (Binary[]) columns[i])) {
-              return false;
-            }
-            break;
-          default:
-            throw new UnSupportedDataTypeException(String.format(DATATYPE_UNSUPPORTED, dataType));
+        if (!Type.fromTsDataType(dataType).arrayEquals(this.columns[i], columns[i], rowCount)) {

Review Comment:
   [P3] Keep hashCode consistent with active-row equality
   
   `equals` now compares column values only through `rowCount`, but `hashCode` still uses `Arrays.deepHashCode(columns)` over the complete backing arrays. Two otherwise identical nodes with the same active rows and different spare-capacity values can therefore be equal while having different hashes.
   
   The earlier real-node comparison reproduced `equals == true`, different hash codes, and `HashSet.contains == false` for such a pair. BASE considered the nodes unequal because it compared the complete arrays.
   
   Please make the hash cover the same active values as equality, or retain consistent full-array semantics in both methods. This is a Java equality/hash contract issue; I have not identified a production caller using these nodes as hash keys, so I am not claiming an observed write/deduplication failure.



##########
library-udf/src/main/java/org/apache/iotdb/library/frequency/UDFEnvelopeAnalysis.java:
##########
@@ -213,32 +220,14 @@ public long calculateMode(LongArrayList timestamps) {
   }
 
   public double getValueAsDouble(Row row, int index) throws IOException {
-    double ans;
-    switch (row.getDataType(index)) {
-      case INT32:
-        ans = row.getInt(index);
-        break;
-      case INT64:
-        ans = row.getLong(index);
-        break;
-      case FLOAT:
-        ans = row.getFloat(index);
-        break;
-      case DOUBLE:
-        ans = row.getDouble(index);
-        break;
-      case TEXT:
-      case STRING:
-      case BOOLEAN:
-      case BLOB:
-      case DATE:
-      case TIMESTAMP:
-      default:
-        throw new UDFOutputSeriesDataTypeNotValidException(
-            index,
-            LibraryUdfMessages.EXCEPTION_FAIL_TO_GET_DATA_TYPE_IN_ROW_8CD82629 + row.getTime());
+    try {
+      return TypeServices.NUMERIC_ROW_READER_SERVICE
+          .call(TypeServices.toReadType(row.getDataType(index)))
+          .read(row);

Review Comment:
   [P3] Pass the requested column index to the numeric reader
   
   This public helper selects the type from `row.getDataType(index)`, but `NUMERIC_ROW_READER_SERVICE` always reads column 0. The previous switch read `row.getInt(index)` / `getLong(index)` / etc. For a real RowImpl with two INT32 values `[11, 22]`, the executed BASE/PR comparison of `getValueAsDouble(row, 1)` returned 22.0 before the refactor and 11.0 afterwards.
   
   Please use the indexed numeric reader and pass `index` through. The current single-input Envelope transform no longer calls this helper, and I did not find another in-repository production caller, so this is a low-priority helper-contract regression rather than a demonstrated ordinary Envelope SQL failure.



##########
iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java:
##########
@@ -3875,6 +3804,52 @@ private BitMap sortBitMap(BitMap bitMap, Integer[] index) {
     return sortedBitMap;
   }
 
+  private static int[] sortedIndex(List<Long> values) {
+    return sortedIndex(values.size(), index -> values.get(index));
+  }
+
+  private static int[] sortedIndex(long[] values, int size) {
+    return sortedIndex(size, index -> values[index]);
+  }
+
+  private static int[] sortedIndex(int size, IntToLongFunction valueProvider) {
+    int[] index = new int[size];
+    int[] scratch = new int[size];
+    for (int i = 0; i < size; i++) {
+      index[i] = i;
+    }
+    sortIndexes(index, scratch, 0, size, valueProvider);
+    return index;
+  }
+
+  private static void sortIndexes(
+      int[] index, int[] scratch, int from, int to, IntToLongFunction valueProvider) {
+    if (to - from < 2) {
+      return;
+    }
+    int middle = (from + to) >>> 1;
+    sortIndexes(index, scratch, from, middle, valueProvider);

Review Comment:
   [P2] Preserve the fast path for long ordered runs in large tablets
   
   Previously the index array was `Integer[]` sorted with `Arrays.sort(..., Comparator.comparingLong(...))`, whose TimSort implementation recognizes existing ordered runs. This primitive merge sort reduces boxing, but unconditionally recurses, merges and copies at every level, even when the input is almost sorted. The normal insert path calls `checkSorted` first, so a fully sorted tablet skips sorting on both versions; a single inversion is enough to enter this more expensive path.
   
   Executed benchmark of the real `Session.sortTablet`: 262,144 rows, one INT32 value column, 60 warm-up sorts followed by 21 samples (median shown). Tablet construction/cloning was outside the timing region; sorting timestamps/indices and reordering the value column were inside. Results were consumed through a volatile sink. BASE and PR ran in separate JVMs.
   
   | Input / runtime | BASE ns/row | PR ns/row | PR / BASE |
   |---|---:|---:|---:|
   | One inversion, Corretto 17.0.5 arm64 | 5.644 | 34.935 | 6.19x |
   | One inversion, OpenJDK 24.0.2 arm64 | 5.628 | 29.466 | 5.24x |
   | Reverse ordered, OpenJDK 24.0.2 arm64 | 5.745 | 28.368 | 4.94x |
   | Random, OpenJDK 24.0.2 arm64 | 244.440 | 151.547 | 0.62x (improves) |
   
   For the one-inversion JDK 24 case, this is approximately 1.48 ms -> 7.72 ms per sort. The input was an increasing timestamp sequence with only its final pair out of order. Smaller 1,024-row cases did not show a stable regression.
   
   The measurements compare BASE `25ab7941ce` with PR `9f4c0f0404`; Session.java and this sorting path are unchanged at the current HEAD. They measure local sort latency, not complete RPC write throughput.
   
   Please keep the primitive-array benefit while restoring ordered-run handling or skipping unnecessary merges, with equal-timestamp stability preserved. Random inputs improve, so simply reverting every part of the primitive-array change would lose that benefit.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/utils/TypeServices.java:
##########
@@ -0,0 +1,3927 @@
+/*
+ * 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.iotdb.calc.utils;
+
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFillFilter;
+import org.apache.iotdb.calc.execution.operator.process.fill.ILinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.DoubleLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.FloatLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.IntLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.LongLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BinaryNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BooleanNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.DoubleNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.FloatNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.IntNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.LongNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.JoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.window.partition.Partition;
+import org.apache.iotdb.calc.execution.operator.process.window.utils.ColumnList;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AbstractApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AggregationMask;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BinaryApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BlobApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BooleanApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.DoubleApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.FloatApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.IntApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.LongApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.TableAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.approximate.HyperLogLog;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.AbstractGroupedApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BinaryGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BlobGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BooleanGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.DoubleGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.FloatGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedMaxMinByBaseAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.IntGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.LongGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BinaryBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BooleanBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.DoubleBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.FloatBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.IntBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.LongBigArray;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBlobLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBooleanLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDateLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDoubleLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToFloatLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt32LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt64LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToStringLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToTimestampLiteralVisitor;
+import org.apache.iotdb.calc.transformation.dag.column.ColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBinaryMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBooleanMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InDoubleMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InFloatMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt32MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt64MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.datastructure.SortKey;
+import org.apache.iotdb.commons.exception.IoTDBRuntimeException;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+
+import java.time.ZoneId;
+import java.time.format.DateTimeParseException;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.function.IntConsumer;
+import java.util.function.IntFunction;
+import java.util.function.IntUnaryOperator;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_ARRAY_HEADER_SIZE;
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_OBJECT_HEADER_SIZE;
+
+public class TypeServices {
+
+  /**
+   * Wraps a type service whose result is immutable/stateless and can therefore be shared for all
+   * instances of the same data type. Type objects are intentionally reduced to their enum here: all
+   * services wrapped with this helper dispatch only on {@code getTypeEnum()}.
+   */
+  private static <T> TypeService<T> cached(final TypeService<T> service) {
+    final Map<Object, T> cache = new ConcurrentHashMap<>();
+    return type -> cache.computeIfAbsent(type.getTypeEnum(), ignored -> service.call(type));
+  }
+
+  private static final IdentityLinearFill IDENTITY_LINEAR_FILL = new IdentityLinearFill();
+  private static final IdentityFill IDENTITY_FILL = new IdentityFill();
+
+  // Unsupported fill types defer their exception until the returned strategy is used so check()
+  // can still validate that every TypeEnum has a service entry.
+  public static final TypeService<Supplier<ILinearFill>> LINEAR_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE -> IntLinearFill::new;
+            case INT64, TIMESTAMP -> LongLinearFill::new;
+            case FLOAT -> FloatLinearFill::new;
+            case DOUBLE -> DoubleLinearFill::new;
+            case BOOLEAN, TEXT, STRING, BLOB, OBJECT -> () -> IDENTITY_LINEAR_FILL;
+            case ROW, UNKNOWN, VECTOR ->
+                () -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, IFill>> PREVIOUS_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                filter ->
+                    filter == null
+                        ? new BooleanPreviousFill()
+                        : new BooleanPreviousFillWithTimeDuration(filter);
+            case TEXT, STRING, BLOB, OBJECT ->
+                filter ->
+                    filter == null
+                        ? new BinaryPreviousFill()
+                        : new BinaryPreviousFillWithTimeDuration(filter);
+            case INT32, DATE ->
+                filter ->
+                    filter == null
+                        ? new IntPreviousFill()
+                        : new IntPreviousFillWithTimeDuration(filter);
+            case INT64, TIMESTAMP ->
+                filter ->
+                    filter == null
+                        ? new LongPreviousFill()
+                        : new LongPreviousFillWithTimeDuration(filter);
+            case FLOAT ->
+                filter ->
+                    filter == null
+                        ? new FloatPreviousFill()
+                        : new FloatPreviousFillWithTimeDuration(filter);
+            case DOUBLE ->
+                filter ->
+                    filter == null
+                        ? new DoublePreviousFill()
+                        : new DoublePreviousFillWithTimeDuration(filter);
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, ILinearFill>> NEXT_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> BooleanNextFill::new;
+            case TEXT, STRING, BLOB, OBJECT -> BinaryNextFill::new;
+            case INT32, DATE -> IntNextFill::new;
+            case INT64, TIMESTAMP -> LongNextFill::new;
+            case FLOAT -> FloatNextFill::new;
+            case DOUBLE -> DoubleNextFill::new;
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<BooleanFunction<JoinKeyComparator>> JOIN_KEY_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    ascending ->
+                        ascending
+                            ? AscIntTypeJoinKeyComparator.getInstance()
+                            : DescIntTypeJoinKeyComparator.getInstance();
+                case INT64, TIMESTAMP ->
+                    ascending ->
+                        ascending
+                            ? AscLongTypeJoinKeyComparator.getInstance()
+                            : DescLongTypeJoinKeyComparator.getInstance();
+                case FLOAT ->
+                    ascending ->
+                        ascending
+                            ? AscFloatTypeJoinKeyComparator.getInstance()
+                            : DescFloatTypeJoinKeyComparator.getInstance();
+                case DOUBLE ->
+                    ascending ->
+                        ascending
+                            ? AscDoubleTypeJoinKeyComparator.getInstance()
+                            : DescDoubleTypeJoinKeyComparator.getInstance();
+                case BOOLEAN ->
+                    ascending ->
+                        ascending
+                            ? AscBooleanTypeJoinKeyComparator.getInstance()
+                            : DescBooleanTypeJoinKeyComparator.getInstance();
+                case STRING, BLOB, TEXT ->
+                    ascending ->
+                        ascending
+                            ? AscBinaryTypeJoinKeyComparator.getInstance()
+                            : DescBinaryTypeJoinKeyComparator.getInstance();
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    ascending -> {
+                      throw new UnsupportedOperationException(
+                          CalcMessages.UNSUPPORTED_DATA_TYPE + type);
+                    };
+              });
+
+  public static final TypeService<IntFunction<Comparator<SortKey>>> MERGE_SORT_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    index ->
+                        Comparator.comparingInt(
+                            sortKey ->
+                                type.getInt(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case INT64, TIMESTAMP ->
+                    index ->
+                        Comparator.comparingLong(
+                            sortKey ->
+                                type.getLong(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case FLOAT ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getFloat(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case DOUBLE ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getDouble(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case TEXT, STRING, BLOB, OBJECT ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBinary(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case BOOLEAN ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBoolean(
+                                    sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                // TypeService.check() must be able to build a strategy for every enum value.
+                case ROW, UNKNOWN, VECTOR ->
+                    index -> {
+                      throw new IllegalArgumentException(
+                          String.format(CalcMessages.DATA_TYPE_CANNOT_BE_ORDERED, type));
+                    };
+              });
+
+  public static final TypeService<Integer> MEMORY_USAGE_OF_ONE_MERGE_SORT_KEY_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN -> 1;
+                case INT32, FLOAT, DATE -> 4;
+                case INT64, DOUBLE, TIMESTAMP -> 8;
+                case TEXT, STRING, BLOB, OBJECT -> 16;
+                case ROW, UNKNOWN, VECTOR ->
+                    throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                        .setChecked(true);
+              });
+
+  public static final TypeService<IntUnaryOperator>
+      MEMORY_USAGE_OF_ONE_SERIALIZABLE_ROW_FIELD_SERVICE =
+          cached(
+              type ->
+                  switch (type.getTypeEnum()) {
+                    case INT32, DATE -> ignored -> ReadWriteIOUtils.INT_LEN;
+                    case INT64, TIMESTAMP -> ignored -> ReadWriteIOUtils.LONG_LEN;
+                    case FLOAT -> ignored -> ReadWriteIOUtils.FLOAT_LEN;
+                    case DOUBLE -> ignored -> ReadWriteIOUtils.DOUBLE_LEN;
+                    case BOOLEAN -> ignored -> ReadWriteIOUtils.BOOLEAN_LEN;
+                    case TEXT, BLOB, STRING, OBJECT ->
+                        byteArrayLength ->
+                            MIN_OBJECT_HEADER_SIZE + MIN_ARRAY_HEADER_SIZE + byteArrayLength;
+                    case ROW, UNKNOWN, VECTOR ->
+                        throw new UnSupportedDataTypeException(type.toString()).setChecked(true);
+                  });
+
+  public static final TypeService<ValueFillFactory> VALUE_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (literal, zoneId) -> {
+                  Boolean value = literal.accept(new CastToBooleanLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BooleanConstantFill(value);
+                };
+            case TEXT, STRING ->
+                (literal, zoneId) -> {
+                  Binary value =
+                      literal.accept(
+                          new CastToStringLiteralVisitor(TSFileConfig.STRING_CHARSET), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case BLOB ->
+                (literal, zoneId) -> {
+                  Binary value = literal.accept(new CastToBlobLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case INT32 ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToInt32LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case DATE ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToDateLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case INT64 ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToInt64LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case TIMESTAMP ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToTimestampLiteralVisitor(zoneId), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case FLOAT ->
+                (literal, zoneId) -> {
+                  Float value = literal.accept(new CastToFloatLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new FloatConstantFill(value);
+                };
+            case DOUBLE ->
+                (literal, zoneId) -> {
+                  Double value = literal.accept(new CastToDoubleLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new DoubleConstantFill(value);
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (literal, zoneId) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads values for a cast using the source type's representation. */
+  public static final TypeService<CastInputService> CAST_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castInt(columnBuilder, type.getInt(column, position));
+            case DATE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDate(columnBuilder, type.getInt(column, position), zoneId);
+            case INT64 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castLong(columnBuilder, type.getLong(column, position));
+            case TIMESTAMP ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castTimestamp(
+                        columnBuilder, type.getLong(column, position), zoneId);
+            case FLOAT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castFloat(columnBuilder, type.getFloat(column, position));
+            case DOUBLE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDouble(columnBuilder, type.getDouble(column, position));
+            case BOOLEAN ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBoolean(columnBuilder, type.getBoolean(column, position));
+            case TEXT, STRING ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castString(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case BLOB ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBlob(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case OBJECT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castObject(columnBuilder, type.getBinary(column, position));
+            case ROW, UNKNOWN, VECTOR ->
+                (column, columnBuilder, position, castValueService, zoneId) -> {
+                  throw unsupportedCastSource(type);
+                };
+          };
+
+  /** Writes values produced by a cast into a column using the target type's representation. */
+  public static final TypeService<CastValueService> CAST_VALUE_SERVICE =
+      type ->
+          new CastValueService() {
+            @Override
+            public void castInt(ColumnBuilder columnBuilder, int value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castDate(ColumnBuilder columnBuilder, int value, ZoneId zoneId) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64 -> type.writeLong(columnBuilder, value);
+                case TIMESTAMP ->
+                    type.writeLong(
+                        columnBuilder,
+                        DateTimeUtils.correctPrecision(
+                            DateUtils.parseIntToTimestamp(value, zoneId)));
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(
+                        columnBuilder, BytesUtils.valueOf(DateUtils.formatDate(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castTimestamp(ColumnBuilder columnBuilder, long value, ZoneId zoneId) {
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      type.writeInt(columnBuilder, CastFunctionUtils.castLongToInt(value));
+                  case DATE ->
+                      type.writeInt(
+                          columnBuilder,
+                          DateUtils.parseDateExpressionToInt(
+                              DateTimeUtils.convertToLocalDate(value, zoneId)));
+                  case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                  case FLOAT -> type.writeFloat(columnBuilder, value);
+                  case DOUBLE -> type.writeDouble(columnBuilder, value);
+                  case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0L);
+                  case TEXT, STRING ->
+                      type.writeBinary(
+                          columnBuilder,
+                          BytesUtils.valueOf(DateTimeUtils.convertLongToDate(value, zoneId)));
+                  case BLOB ->
+                      type.writeBinary(columnBuilder, new Binary(BytesUtils.longToBytes(value)));
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException e) {
+                throw new IoTDBRuntimeException(
+                    "Year must be between 1000 and 9999.",

Review Comment:
   [P2] Retain the localized messages when moving the implementation
   
   This catch previously used `CalcMessages.EXCEPTION_YEAR_MUST_BETWEEN_1000_9999_8FBB94AA`, but now emits a raw English literal. The same regression remains in the `Cannot cast %s to %s type` branches in this file and several SUM/AVG argument checks. These strings stay English in a Chinese-locale build even when `zh-locale-compile` passes.
   
   Some of the earlier message-key feedback has been fixed, but these call sites still bypass the existing English/Chinese constants. Please restore the corresponding localized constants and keep any new messages in both locale files.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/TypeServices.java:
##########
@@ -0,0 +1,4276 @@
+/*
+ * 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.iotdb.db.utils;
+
+import org.apache.iotdb.calc.exception.QueryProcessException;
+import org.apache.iotdb.calc.execution.aggregation.Accumulator;
+import org.apache.iotdb.calc.execution.aggregation.BinaryModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.BooleanModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.DoubleModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.FloatModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.IntModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.LongModeAccumulator;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.TypeServices.PrimitiveColumnValueSetter;
+import org.apache.iotdb.calc.utils.constant.SqlConstant;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.exception.pipe.PipeRuntimeNonCriticalException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
+import org.apache.iotdb.db.pipe.processor.aggregate.TimeSeriesRuntimeState;
+import org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.AbstractSameTypeNumericOperator;
+import org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.WindowOutput;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBinaryWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBooleanWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowParameter;
+import org.apache.iotdb.db.queryengine.statistics.StatisticsManager;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.ArithmeticNegationTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.InTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.DiffFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.RoundFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.datastructure.util.ValueRecorder;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.IWALByteBufferView;
+import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALWriteUtils;
+import org.apache.iotdb.db.utils.datastructure.AlignedTVList;
+import org.apache.iotdb.db.utils.datastructure.BinaryTVList;
+import org.apache.iotdb.db.utils.datastructure.BooleanTVList;
+import org.apache.iotdb.db.utils.datastructure.DoubleTVList;
+import org.apache.iotdb.db.utils.datastructure.FloatTVList;
+import org.apache.iotdb.db.utils.datastructure.IntTVList;
+import org.apache.iotdb.db.utils.datastructure.LongTVList;
+import org.apache.iotdb.db.utils.datastructure.TVList;
+import org.apache.iotdb.db.utils.windowing.window.EvictableBatchList;
+import org.apache.iotdb.db.utils.windowing.window.WindowImpl;
+import org.apache.iotdb.pipe.api.access.Row;
+import org.apache.iotdb.rpc.RpcUtils;
+
+import com.google.common.io.BaseEncoding;
+import com.sun.jna.platform.win32.OaIdl;
+import com.sun.jna.platform.win32.OleAuto;
+import com.sun.jna.platform.win32.Variant;
+import com.sun.jna.platform.win32.WTypes;
+import com.sun.jna.platform.win32.WinDef;
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.encoding.decoder.Decoder;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.external.commons.lang3.StringUtils;
+import org.apache.tsfile.file.metadata.IChunkMetadata;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.file.metadata.statistics.DateStatistics;
+import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.BatchData;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.read.common.block.column.BinaryColumnBuilder;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.read.filter.basic.Filter;
+import org.apache.tsfile.read.reader.series.PaginationController;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.RamUsageEstimator;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ValueChunkWriter;
+import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.sql.Date;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import java.util.function.ToDoubleFunction;
+import java.util.function.ToIntFunction;
+import java.util.function.ToLongFunction;
+
+public class TypeServices {
+
+  public static final int DEFAULT_DATE =
+      DateUtils.parseDateExpressionToInt(LocalDate.of(1970, 1, 1));
+  private static final LocalDate EMPTY_LOCAL_DATE = LocalDate.of(1000, 1, 1);
+
+  public static final class Memory {
+
+    public static final TypeService<LongSupplier> STATEMENT_VALUE_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::estimateValueSize;
+              case TEXT, BLOB, STRING ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        CalcMessages.UNKNOWN_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToLongFunction<Object>> INSERT_NODE_VALUE_SIZE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  value ->
+                      RamUsageEstimator.alignObjectSize(
+                          type.estimateValueSize() + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER);
+              case TEXT, BLOB, STRING ->
+                  value -> Objects.nonNull(value) ? ((Binary) value).ramBytesUsed() : 0L;
+              case OBJECT, ROW, UNKNOWN, VECTOR -> value -> 0L;
+            };
+
+    static {
+      STATEMENT_VALUE_SIZE_PER_LINE_SERVICE.check();
+      INSERT_NODE_VALUE_SIZE_SERVICE.check();
+    }
+
+    private Memory() {
+      // Utility class
+    }
+  }
+
+  public static final class Transformation {
+
+    public static final TypeService<Function<Object, Column>> CONSTANT_COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT ->
+                  value -> {
+                    final ColumnBuilder builder = type.createColumnBuilder(1);
+                    type.writeObject(builder, value);
+                    return builder.build();
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<
+            Function<org.apache.iotdb.db.queryengine.plan.statement.literal.Literal, IFill>>
+        CONSTANT_FILL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> literal -> new BooleanConstantFill(literal.getBoolean());
+                  case INT32 -> literal -> new IntConstantFill(literal.getInt());
+                  case DATE -> literal -> new IntConstantFill(literal.getDate());
+                  case INT64, TIMESTAMP -> literal -> new LongConstantFill(literal.getLong());
+                  case FLOAT -> literal -> new FloatConstantFill(literal.getFloat());
+                  case DOUBLE -> literal -> new DoubleConstantFill(literal.getDouble());
+                  case TEXT, BLOB, STRING -> literal -> new BinaryConstantFill(literal.getBinary());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      literal -> {
+                        throw new IllegalArgumentException(
+                            CommonOperatorUtils.UNKNOWN_DATATYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<ColumnBuilder>> COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createColumnBuilder;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()))
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ColumnToDoubleConverter> VALUE_TO_DOUBLE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> type::getInt;
+              case INT64, TIMESTAMP -> type::getLong;
+              case FLOAT -> type::getFloat;
+              case DOUBLE -> type::getDouble;
+              case BOOLEAN -> (column, index) -> type.getBoolean(column, index) ? 1 : 0;
+              case TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (column, index) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ColumnValueWriter> TRANSFORM_COLUMN_VALUE_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::write;
+              case ROW, UNKNOWN, VECTOR ->
+                  (builder, column, index) -> {
+                    throw new UnSupportedDataTypeException(
+                        String.format(
+                            DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                            type.getTypeEnum()));
+                  };
+            };
+
+    // Schema evolution keeps physically compatible columns, widens supported values, and exposes
+    // incompatible historical values as nulls instead of interpreting their raw storage.
+    public static final TypeService<AlteredDataTypeColumnTransformer>
+        ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      INT64,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      STRING,
+                      TIMESTAMP,
+                      DATE,
+                      BLOB -> {
+                    final TSDataType targetType = TSDataType.valueOf(type.getTypeEnum().name());
+                    yield (source, positionCount) -> {
+                      final TSDataType sourceType = source.getDataType();
+                      // DATE shares INT32's physical column but was historically incompatible with
+                      // a schema change to INT32, while the other shared-column pairs are reusable.
+                      if (sourceType == targetType
+                          || (targetType != TSDataType.INT32
+                              && SchemaUtils.isUsingSameColumn(sourceType, targetType))) {
+                        return source;
+                      }
+                      return targetType.isCompatible(sourceType)
+                          ? source.convertTo(targetType)
+                          : type.createNullColumn(positionCount);
+                    };
+                  }
+                  case OBJECT -> (source, positionCount) -> source;
+                  case ROW, UNKNOWN, VECTOR -> (source, positionCount) -> null;
+                };
+
+    public static final TypeService<RoundTransformer> ROUND_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> RoundFunctionTransformer::transformInt;
+              case INT64 -> RoundFunctionTransformer::transformLong;
+              case FLOAT -> RoundFunctionTransformer::transformFloat;
+              case DOUBLE -> RoundFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new UnsupportedOperationException(
+                        String.format("Unsupported source dataType: %s", type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<DiffTransformer> DIFF_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> DiffFunctionTransformer::transformInt;
+              case INT64 -> DiffFunctionTransformer::transformLong;
+              case FLOAT -> DiffFunctionTransformer::transformFloat;
+              case DOUBLE -> DiffFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<NegationTransformer> NEGATION_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> ArithmeticNegationTransformer::transformInt;
+              case INT64 -> ArithmeticNegationTransformer::transformLong;
+              case FLOAT -> ArithmeticNegationTransformer::transformFloat;
+              case DOUBLE -> ArithmeticNegationTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<StateWindowSplitter> STATE_WINDOW_SPLITTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordInt(type.getInt(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getInt(values, index) - valueRecorder.getInt()) > delta;
+                    if (split) {
+                      valueRecorder.recordInt(type.getInt(values, index));
+                    }
+                    return split;
+                  };
+              case INT64 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordLong(type.getLong(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getLong(values, index) - valueRecorder.getLong()) > delta;
+                    if (split) {
+                      valueRecorder.recordLong(type.getLong(values, index));
+                    }
+                    return split;
+                  };
+              case FLOAT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordFloat(type.getFloat(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getFloat(values, index) - valueRecorder.getFloat()) > delta;
+                    if (split) {
+                      valueRecorder.recordFloat(type.getFloat(values, index));
+                    }
+                    return split;
+                  };
+              case DOUBLE ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordDouble(type.getDouble(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getDouble(values, index) - valueRecorder.getDouble()) > delta;
+                    if (split) {
+                      valueRecorder.recordDouble(type.getDouble(values, index));
+                    }
+                    return split;
+                  };
+              case BOOLEAN ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        type.getBoolean(values, index) != valueRecorder.getBoolean();
+                    if (split) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index));
+                    }
+                    return split;
+                  };
+              case TEXT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordString(type.getBinary(values, index - 1).toString());
+                      valueRecorder.setRecorded(true);
+                    }
+                    final String value = type.getBinary(values, index).toString();
+                    final boolean split = !value.equals(valueRecorder.getString());
+                    if (split) {
+                      valueRecorder.recordString(value);
+                    }
+                    return split;
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (valueRecorder, delta, values, index) -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages
+                            .EXCEPTION_THE_DATA_TYPE_OF_THE_STATE_WINDOW_STRATEGY_IS_NOT_VALID_61F4E273);
+                  };
+            };
+
+    public static final TypeService<InTransformerSetInitializer>
+        IN_TRANSFORMER_SET_INITIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::initIntSet;
+                  case INT64, TIMESTAMP -> InTransformer::initLongSet;
+                  case FLOAT -> InTransformer::initFloatSet;
+                  case DOUBLE -> InTransformer::initDoubleSet;
+                  case BOOLEAN -> InTransformer::initBooleanSet;
+                  case TEXT, STRING -> InTransformer::initStringSet;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, values) -> {
+                        throw new UnsupportedOperationException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<InTransformerColumnTransformer>
+        IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::transformInt;
+                  case INT64, TIMESTAMP -> InTransformer::transformLong;
+                  case FLOAT -> InTransformer::transformFloat;
+                  case DOUBLE -> InTransformer::transformDouble;
+                  case BOOLEAN -> InTransformer::transformBoolean;
+                  case TEXT, STRING -> InTransformer::transformBinary;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, columns, builder) -> {
+                        throw new QueryProcessException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<TypeService<CastColumnStrategy>> CAST_COLUMN_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(builder, type.getInt(column, index)));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getInt(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getInt(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getInt(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getInt(column, index) != 0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getInt(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case INT64 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castLongToInt(
+                                            type.getLong(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getLong(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getLong(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getLong(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getLong(column, index) != 0L));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getLong(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case FLOAT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castFloatToInt(
+                                            type.getFloat(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castFloatToLong(
+                                            type.getFloat(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getFloat(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getFloat(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getFloat(column, index) != 0.0f));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getFloat(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DOUBLE ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToInt(
+                                            type.getDouble(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToLong(
+                                            type.getDouble(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToFloat(
+                                            type.getDouble(column, index))));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getDouble(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getDouble(column, index) != 0.0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getDouble(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case BOOLEAN ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder, type.getBoolean(column, index) ? 1 : 0));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder, type.getBoolean(column, index) ? 1L : 0L));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder, type.getBoolean(column, index) ? 1.0f : 0.0f));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(
+                                        builder, type.getBoolean(column, index) ? 1.0 : 0.0));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getBoolean(column, index)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getBoolean(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case TEXT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeInt(builder, Integer.parseInt(value)));
+                        case INT64 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeLong(builder, Long.parseLong(value)));
+                        case FLOAT ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeFloat(
+                                        builder, CastFunctionUtils.castTextToFloat(value)));
+                        case DOUBLE ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeDouble(
+                                        builder, CastFunctionUtils.castTextToDouble(value)));
+                        case BOOLEAN ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, CastFunctionUtils.castTextToBoolean(value)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(builder, type.getBinary(column, index)));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  targetType -> unsupportedSourceCastStrategy(type);
+            };
+
+    private static CastColumnStrategy castColumnStrategy(
+        final Type targetType, final CastColumnWriter writer) {
+      return new CastColumnStrategy(() -> {}, targetType::createColumnBuilder, writer);
+    }
+
+    private static CastColumnStrategy castBinaryColumnStrategy(
+        final Type sourceType, final Type targetType, final BinaryStringCastWriter writer) {
+      return castColumnStrategy(
+          targetType,
+          (column, index, builder) ->
+              writer.write(
+                  sourceType.getBinary(column, index).getStringValue(TSFileConfig.STRING_CHARSET),
+                  builder));
+    }
+
+    private static CastColumnStrategy unsupportedSourceCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported source dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedTargetCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported target dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedCastStrategy(final String message) {
+      return new CastColumnStrategy(
+          () -> {
+            throw new UnsupportedOperationException(message);
+          },
+          ignored -> {
+            throw new UnsupportedOperationException(message);
+          },
+          (column, index, builder) -> {
+            throw new UnsupportedOperationException(message);
+          });
+    }
+
+    public static final class CastColumnStrategy {
+      private final Runnable validator;
+      private final IntFunction<ColumnBuilder> builderFactory;
+      private final CastColumnWriter writer;
+
+      private CastColumnStrategy(
+          final Runnable validator,
+          final IntFunction<ColumnBuilder> builderFactory,
+          final CastColumnWriter writer) {
+        this.validator = validator;
+        this.builderFactory = builderFactory;
+        this.writer = writer;
+      }
+
+      public void validate() {
+        validator.run();
+      }
+
+      public ColumnBuilder createBuilder(final int expectedEntries) {
+        return builderFactory.apply(expectedEntries);
+      }
+
+      public void cast(final Column column, final int index, final ColumnBuilder builder) {
+        writer.write(column, index, builder);
+      }
+    }
+
+    @FunctionalInterface
+    private interface CastColumnWriter {
+      void write(Column column, int index, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    private interface BinaryStringCastWriter {
+      void write(String value, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    public interface ColumnToDoubleConverter {
+      double convert(Column column, int index) throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface ColumnValueWriter {
+      void write(ColumnBuilder builder, Column column, int index);
+    }
+
+    @FunctionalInterface
+    public interface AlteredDataTypeColumnTransformer {
+      Column transform(Column source, int positionCount);
+    }
+
+    @FunctionalInterface
+    public interface RoundTransformer {
+      void transform(RoundFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface DiffTransformer {
+      void transform(DiffFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface NegationTransformer {
+      void transform(
+          ArithmeticNegationTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface StateWindowSplitter {
+      boolean split(ValueRecorder valueRecorder, double delta, Column values, int index);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerSetInitializer {
+      void initialize(InTransformer transformer, Set<String> values);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerColumnTransformer {
+      void transform(InTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    static {
+      CONSTANT_COLUMN_BUILDER_SERVICE.check();
+      CONSTANT_FILL_SERVICE.check();
+      COLUMN_BUILDER_SERVICE.check();
+      VALUE_TO_DOUBLE_SERVICE.check();
+      TRANSFORM_COLUMN_VALUE_WRITER_SERVICE.check();
+      ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE.check();
+      ROUND_TRANSFORMER_SERVICE.check();
+      DIFF_TRANSFORMER_SERVICE.check();
+      NEGATION_TRANSFORMER_SERVICE.check();
+      STATE_WINDOW_SPLITTER_SERVICE.check();
+      IN_TRANSFORMER_SET_INITIALIZER_SERVICE.check();
+      IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE.check();
+      CAST_COLUMN_SERVICE.check();
+    }
+
+    private Transformation() {
+      // Utility class
+    }
+  }
+
+  public static final class Aggregation {
+
+    public static final TypeService<ExtremeValueAccumulatorStrategy>
+        EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateIntResult(column.getInt(index)),
+                          (accumulator, value) ->
+                              accumulator.updateIntResult(((Number) value).intValue()),
+                          (accumulator, column) -> accumulator.getResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateLongResult(column.getLong(index)),
+                          (accumulator, value) ->
+                              accumulator.updateLongResult(((Number) value).longValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateFloatResult(column.getFloat(index)),
+                          (accumulator, value) ->
+                              accumulator.updateFloatResult(((Number) value).floatValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateDoubleResult(column.getDouble(index)),
+                          (accumulator, value) ->
+                              accumulator.updateDoubleResult(((Number) value).doubleValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case STRING ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateBinaryResult(column.getBinary(index)),
+                          (accumulator, value) -> accumulator.updateBinaryResult((Binary) value),
+                          (accumulator, column) ->
+                              accumulator.getResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN, TEXT, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      ExtremeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<TimeValueAccumulatorStrategy>
+        TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateIntResult(column.getInt(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateIntResult(
+                                  ((Number) getStatisticsValue(statistics, first)).intValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateLongResult(column.getLong(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateLongResult(
+                                  ((Number) getStatisticsValue(statistics, first)).longValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateFloatResult(column.getFloat(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateFloatResult(
+                                  ((Number) getStatisticsValue(statistics, first)).floatValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateDoubleResult(column.getDouble(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateDoubleResult(
+                                  ((Number) getStatisticsValue(statistics, first)).doubleValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBinaryResult(column.getBinary(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBinaryResult(
+                                  getBinaryStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBooleanResult(column.getBoolean(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBooleanResult(
+                                  (boolean) getStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBoolean(column.getBoolean(0)),
+                          (builder, result) -> builder.writeBoolean(result.getBoolean()));
+                  case ROW, UNKNOWN, VECTOR -> TimeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<MaxMinByAccumulatorStrategy>
+        MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateIntResult(
+                                  time, yColumn.getInt(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateIntResult(
+                                  time,
+                                  BytesUtils.bytesToInt(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Integer.BYTES),
+                                  0));
+                  case INT64, TIMESTAMP ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateLongResult(
+                                  time, yColumn.getLong(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateLongResult(
+                                  time,
+                                  BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Long.BYTES),
+                                  0));
+                  case FLOAT ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateFloatResult(
+                                  time, yColumn.getFloat(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateFloatResult(
+                                  time,
+                                  BytesUtils.bytesToFloat(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Float.BYTES),
+                                  0));
+                  case DOUBLE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateDoubleResult(
+                                  time, yColumn.getDouble(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateDoubleResult(
+                                  time,
+                                  BytesUtils.bytesToDouble(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Double.BYTES),
+                                  0));
+                  case STRING ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateBinaryResult(
+                                  time, yColumn.getBinary(yIndex), xColumn, xIndex),
+                          TypeServices.Aggregation::updateBinaryIntermediate);
+                  case TEXT, BLOB, OBJECT -> maxMinByAccumulatorStrategy(type, null, null);
+                  case BOOLEAN -> maxMinByAccumulatorStrategy(type, null, null);
+                  case ROW, UNKNOWN, VECTOR -> MaxMinByAccumulatorStrategy.unsupported(type);
+                };
+
+    public static final TypeService<EventWindowManagerProvider>
+        EVENT_WINDOW_MANAGER_PROVIDER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      eventWindowManagerProvider(
+                          EqualIntWindowManager::new, VariationIntWindowManager::new);
+                  case INT64 ->
+                      eventWindowManagerProvider(
+                          EqualLongWindowManager::new, VariationLongWindowManager::new);
+                  case FLOAT ->
+                      eventWindowManagerProvider(
+                          EqualFloatWindowManager::new, VariationFloatWindowManager::new);
+                  case DOUBLE ->
+                      eventWindowManagerProvider(
+                          EqualDoubleWindowManager::new, VariationDoubleWindowManager::new);
+                  case TEXT -> eventWindowManagerProvider(EqualBinaryWindowManager::new, null);
+                  case BOOLEAN -> eventWindowManagerProvider(EqualBooleanWindowManager::new, null);
+                  case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      EventWindowManagerProvider.unsupported();
+                };
+
+    private static EventWindowManagerProvider eventWindowManagerProvider(
+        final EventWindowManagerFactory equalFactory,
+        final EventWindowManagerFactory variationFactory) {
+      return new EventWindowManagerProvider(equalFactory, variationFactory);
+    }
+
+    private static void updateBinaryIntermediate(
+        final MaxMinByAccumulator accumulator,
+        final long time,
+        final byte[] bytes,
+        final int offset) {
+      final int length = BytesUtils.bytesToInt(bytes, offset);
+      final int valueOffset = offset + Integer.BYTES;
+      accumulator.updateBinaryResult(
+          time,
+          new Binary(BytesUtils.subBytes(bytes, valueOffset, length)),
+          accumulator.readXFromBytesIntermediateInput(bytes, valueOffset + length),
+          0);
+    }
+
+    private static MaxMinByAccumulatorStrategy maxMinByAccumulatorStrategy(
+        final Type type,
+        final MaxMinByYColumnUpdater yColumnUpdater,
+        final MaxMinByYBytesUpdater yBytesUpdater) {
+      return new MaxMinByAccumulatorStrategy(type, true, yColumnUpdater, yBytesUpdater);
+    }
+
+    private static TimeValueAccumulatorStrategy timeValueAccumulatorStrategy(
+        final TimeValueColumnUpdater columnUpdater,
+        final TimeValueStatisticsUpdater statisticsUpdater,
+        final TimeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new TimeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    private static Object getStatisticsValue(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getFirstValue() : statistics.getLastValue();
+    }
+
+    private static long getStatisticsTime(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getStartTime() : statistics.getEndTime();
+    }
+
+    private static Binary getBinaryStatisticsValue(
+        final Statistics<?> statistics, final boolean first) {
+      final Object value = getStatisticsValue(statistics, first);
+      if (statistics instanceof DateStatistics) {
+        return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+      }
+      return value instanceof Binary
+          ? (Binary) value
+          : new Binary(String.valueOf(value), StandardCharsets.UTF_8);
+    }
+
+    public static final class TimeValueAccumulatorStrategy {
+      private final TimeValueColumnUpdater columnUpdater;
+      private final TimeValueStatisticsUpdater statisticsUpdater;
+      private final TimeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private TimeValueAccumulatorStrategy(
+          final TimeValueColumnUpdater columnUpdater,
+          final TimeValueStatisticsUpdater statisticsUpdater,
+          final TimeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static TimeValueAccumulatorStrategy unsupported() {
+        return new TimeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final TimeValueAccumulator accumulator,
+          final Column[] columns,
+          final BitMap bitMap,
+          final boolean stopAfterFirstValue,
+          final boolean bitmapMarksSelected) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && bitmapMarksSelected != bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i, columns[0].getLong(i));
+            if (stopAfterFirstValue) {
+              return;
+            }
+          }
+        }
+      }
+
+      public void addIntermediate(
+          final TimeValueAccumulator accumulator,
+          final Column valueColumn,
+          final Column timeColumn) {
+        columnUpdater.update(accumulator, valueColumn, 0, timeColumn.getLong(0));
+      }
+
+      public void addStatistics(
+          final TimeValueAccumulator accumulator,
+          final Statistics<?> statistics,
+          final boolean first) {
+        statisticsUpdater.update(accumulator, statistics, first);
+      }
+
+      public void setFinal(final TimeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final class MaxMinByAccumulatorStrategy {
+      private final Type type;
+      private final PrimitiveColumnValueSetter xValueSetter;
+      private final boolean xSupported;
+      private final MaxMinByYColumnUpdater yColumnUpdater;
+      private final MaxMinByYBytesUpdater yBytesUpdater;
+
+      private MaxMinByAccumulatorStrategy(
+          final Type type,
+          final boolean xSupported,
+          final MaxMinByYColumnUpdater yColumnUpdater,
+          final MaxMinByYBytesUpdater yBytesUpdater) {
+        this.type = type;
+        this.xValueSetter =
+            org.apache.iotdb.calc.utils.TypeServices.PRIMITIVE_COLUMN_VALUE_SETTER_SERVICE.call(
+                type);
+        this.xSupported = xSupported;
+        this.yColumnUpdater = yColumnUpdater;
+        this.yBytesUpdater = yBytesUpdater;
+      }
+
+      private static MaxMinByAccumulatorStrategy unsupported(final Type type) {
+        return new MaxMinByAccumulatorStrategy(type, false, null, null);
+      }
+
+      public boolean isXSupported() {
+        return xSupported;
+      }
+
+      public boolean isYSupported() {
+        return yColumnUpdater != null;
+      }
+
+      public void addInput(
+          final MaxMinByAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[2].isNull(i)) {
+            yColumnUpdater.update(accumulator, columns[0].getLong(i), columns[2], i, columns[1], i);
+          }
+        }
+      }
+
+      public void setXResult(final TsPrimitiveType result, final Column column, final int index) {
+        // Type.setTo copies the primitive into the column; aggregation must read the input instead.
+        xValueSetter.set(result, column, index);
+      }
+
+      public void writeXResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        type.write(builder, result);
+      }
+
+      public void writeSerializedValue(
+          final byte[] bytes, final int offset, final ColumnBuilder builder) {
+        type.write(builder, bytes, offset);
+      }
+
+      public void updateIntermediate(
+          final MaxMinByAccumulator accumulator,
+          final long time,
+          final byte[] bytes,
+          final int offset) {
+        yBytesUpdater.update(accumulator, time, bytes, offset);
+      }
+    }
+
+    public static final class EventWindowManagerProvider {
+      private static final EventWindowManagerProvider UNSUPPORTED =
+          new EventWindowManagerProvider(null, null);
+
+      private final EventWindowManagerFactory equalFactory;
+      private final EventWindowManagerFactory variationFactory;
+
+      private EventWindowManagerProvider(
+          final EventWindowManagerFactory equalFactory,
+          final EventWindowManagerFactory variationFactory) {
+        this.equalFactory = equalFactory;
+        this.variationFactory = variationFactory;
+      }
+
+      private static EventWindowManagerProvider unsupported() {
+        return UNSUPPORTED;
+      }
+
+      public VariationWindowManager createEqual(
+          final VariationWindowParameter parameter, final boolean ascending) {
+        if (equalFactory == null) {
+          throw new UnSupportedDataTypeException(
+              String.format(
+                  DataNodeQueryMessages
+                      .EXCEPTION_UNSUPPORTED_DATA_TYPE_IN_EQUAL_EVENT_AGGREGATION_ARG_77E085EB,
+                  parameter.getDataType()));
+        }
+        return equalFactory.create(parameter, ascending);
+      }
+
+      public VariationWindowManager createVariation(
+          final VariationWindowParameter parameter, final boolean ascending) {
+        if (variationFactory == null) {
+          throw new UnSupportedDataTypeException(
+              String.format(
+                  DataNodeQueryMessages
+                      .EXCEPTION_UNSUPPORTED_DATA_TYPE_IN_VARIATION_EVENT_AGGREGATION_ARG_3D0F0388,
+                  parameter.getDataType()));
+        }
+        return variationFactory.create(parameter, ascending);
+      }
+    }
+
+    private static ExtremeValueAccumulatorStrategy extremeValueAccumulatorStrategy(
+        final ExtremeValueColumnUpdater columnUpdater,
+        final ExtremeValueStatisticsUpdater statisticsUpdater,
+        final ExtremeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new ExtremeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    public static final class ExtremeValueAccumulatorStrategy {
+      private final ExtremeValueColumnUpdater columnUpdater;
+      private final ExtremeValueStatisticsUpdater statisticsUpdater;
+      private final ExtremeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private ExtremeValueAccumulatorStrategy(
+          final ExtremeValueColumnUpdater columnUpdater,
+          final ExtremeValueStatisticsUpdater statisticsUpdater,
+          final ExtremeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static ExtremeValueAccumulatorStrategy unsupported() {
+        return new ExtremeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final ExtremeValueAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i);
+          }
+        }
+      }
+
+      public void addIntermediate(final ExtremeValueAccumulator accumulator, final Column column) {
+        columnUpdater.update(accumulator, column, 0);
+      }
+
+      public void addStatistics(
+          final ExtremeValueAccumulator accumulator, final Object statisticsValue) {
+        statisticsUpdater.update(accumulator, statisticsValue);
+      }
+
+      public void setFinal(final ExtremeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final TypeService<LongSupplier> OUTPUT_COLUMN_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  () -> type.estimateValueSize() + Byte.BYTES;
+              case TEXT, BLOB, STRING, OBJECT ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages.UNKNOWN_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Supplier<Accumulator>> MODE_ACCUMULATOR_PROVIDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> BooleanModeAccumulator::new;
+              case TEXT, BLOB, STRING -> BinaryModeAccumulator::new;
+              case INT32, DATE -> IntModeAccumulator::new;
+              case INT64, TIMESTAMP -> LongModeAccumulator::new;
+              case FLOAT -> FloatModeAccumulator::new;
+              case DOUBLE -> DoubleModeAccumulator::new;
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new IllegalArgumentException(
+                        DataNodeQueryMessages.UNKNOWN_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    static {
+      EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE.check();
+      TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE.check();
+      MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE.check();
+      EVENT_WINDOW_MANAGER_PROVIDER_SERVICE.check();
+      OUTPUT_COLUMN_SIZE_PER_LINE_SERVICE.check();
+      MODE_ACCUMULATOR_PROVIDER_SERVICE.check();
+    }
+
+    private Aggregation() {
+      // Utility class
+    }
+
+    public interface ExtremeValueAccumulator {
+      TsPrimitiveType getResult();
+
+      void updateIntResult(int value);
+
+      void updateLongResult(long value);
+
+      void updateFloatResult(float value);
+
+      void updateDoubleResult(double value);
+
+      void updateBinaryResult(Binary value);
+    }
+
+    public interface TimeValueAccumulator {
+      TsPrimitiveType getTimeValueResult();
+
+      void updateIntResult(int value, long time);
+
+      void updateLongResult(long value, long time);
+
+      void updateFloatResult(float value, long time);
+
+      void updateDoubleResult(double value, long time);
+
+      void updateBinaryResult(Binary value, long time);
+
+      void updateBooleanResult(boolean value, long time);
+    }
+
+    public interface MaxMinByAccumulator {
+      Column readXFromBytesIntermediateInput(byte[] bytes, int offset);
+
+      void updateIntResult(long time, int yValue, Column xColumn, int xIndex);
+
+      void updateLongResult(long time, long yValue, Column xColumn, int xIndex);
+
+      void updateFloatResult(long time, float yValue, Column xColumn, int xIndex);
+
+      void updateDoubleResult(long time, double yValue, Column xColumn, int xIndex);
+
+      void updateBinaryResult(long time, Binary yValue, Column xColumn, int xIndex);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueColumnUpdater {
+      void update(ExtremeValueAccumulator accumulator, Column column, int index);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueStatisticsUpdater {
+      void update(ExtremeValueAccumulator accumulator, Object value);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueFinalSetter {
+      void set(ExtremeValueAccumulator accumulator, Column column);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueColumnUpdater {
+      void update(TimeValueAccumulator accumulator, Column column, int index, long time);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueStatisticsUpdater {
+      void update(TimeValueAccumulator accumulator, Statistics<?> statistics, boolean first);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueFinalSetter {
+      void set(TimeValueAccumulator accumulator, Column column);
+    }
+
+    @FunctionalInterface
+    private interface MaxMinByYColumnUpdater {
+      void update(
+          MaxMinByAccumulator accumulator,
+          long time,
+          Column yColumn,
+          int yIndex,
+          Column xColumn,
+          int xIndex);
+    }
+
+    @FunctionalInterface
+    private interface MaxMinByYBytesUpdater {
+      void update(MaxMinByAccumulator accumulator, long time, byte[] bytes, int offset);
+    }
+
+    @FunctionalInterface
+    private interface EventWindowManagerFactory {
+      VariationWindowManager create(VariationWindowParameter parameter, boolean ascending);
+    }
+  }
+
+  public static final class ValueConversion {
+
+    public static final TypeService<Function<String, Object>> VALUE_PARSER_NO_EXCEPTION_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> Boolean::parseBoolean;
+              case INT32 -> TypeServices::parseInteger;
+              case INT64 -> TypeServices::parseLong;
+              case FLOAT -> TypeServices::parseFloat;
+              case DOUBLE -> TypeServices::parseDouble;
+              case TEXT -> TypeServices::parseText;
+              case TIMESTAMP -> TypeServices::parseTimestamp;
+              case DATE -> TypeServices::parseDate;
+              case BLOB -> TypeServices::parseBlob;
+              case STRING -> TypeServices::parseString;
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ContextualValueParser> VALUE_PARSER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (value, zoneId) -> CommonUtils.parseBoolean(value);
+              case INT32 ->
+                  (value, zoneId) -> {
+                    try {
+                      return Integer.parseInt(StringUtils.trim(value));
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                  };
+              case INT64 ->
+                  (value, zoneId) -> {
+                    try {
+                      return Long.parseLong(StringUtils.trim(value));
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                  };
+              case TIMESTAMP ->
+                  (value, zoneId) -> {
+                    try {
+                      return TypeInferenceUtils.isNumber(value)
+                          ? Long.parseLong(value)
+                          : DataNodeDateTimeUtils.parseDateTimeExpressionToLong(
+                              StringUtils.trim(value), zoneId);
+                    } catch (final Throwable e) {
+                      throw new NumberFormatException(
+                          String.format(
+                              DataNodeMiscMessages
+                                  .EXCEPTION_DATA_TYPE_IS_NOT_CONSISTENT_INPUT_ARG_REGISTERED_ARG_BECAUSE_ARG_C8637858,
+                              value,
+                              type.getTypeEnum(),
+                              e.getMessage()));
+                    }
+                  };
+              case DATE -> (value, zoneId) -> CommonUtils.parseIntFromString(value);
+              case FLOAT ->
+                  (value, zoneId) -> {
+                    final float result;
+                    try {
+                      result = Float.parseFloat(value);
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                    if (Float.isInfinite(result)) {
+                      throw new NumberFormatException(DataNodeMiscMessages.INPUT_FLOAT_INFINITY);
+                    }
+                    return result;
+                  };
+              case DOUBLE ->
+                  (value, zoneId) -> {
+                    final double result;
+                    try {
+                      result = Double.parseDouble(value);
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                    if (Double.isInfinite(result)) {
+                      throw new NumberFormatException(DataNodeMiscMessages.INPUT_DOUBLE_INFINITY);
+                    }
+                    return result;
+                  };
+              case TEXT, STRING ->
+                  (value, zoneId) ->
+                      new Binary(stripQuotesIfPresent(value), TSFileConfig.STRING_CHARSET);
+              case BLOB ->
+                  (value, zoneId) ->
+                      new Binary(
+                          CommonUtils.parseBlobStringToByteArray(stripQuotesIfPresent(value)));
+              case OBJECT ->
+                  (value, zoneId) -> {
+                    throw inconsistentValueException(value, type);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  (value, zoneId) -> {
+                    throw new QueryProcessException(
+                        DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<java.util.function.Predicate<TSDataType>> AUTO_CAST_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      targetType == TSDataType.INT64
+                          || targetType == TSDataType.FLOAT
+                          || targetType == TSDataType.DOUBLE;
+              case INT64, FLOAT -> targetType -> targetType == TSDataType.DOUBLE;
+              case BOOLEAN, DATE, TIMESTAMP, DOUBLE, TEXT, BLOB, STRING, OBJECT ->
+                  targetType -> false;
+              case ROW, UNKNOWN, VECTOR ->
+                  targetType -> {
+                    throw new IllegalArgumentException(
+                        DataNodeMiscMessages.UNKNOWN_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Function<Object, Pair<Literal, String>>>
+        PREPARED_PARAMETER_LITERAL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      value -> {
+                        final String text = Boolean.toString((Boolean) value);
+                        return new Pair<>(new BooleanLiteral(text), text);
+                      };
+                  case INT32, INT64 ->
+                      value -> {
+                        final String text = String.valueOf(value);
+                        return new Pair<>(new LongLiteral(text), text);
+                      };
+                  case FLOAT ->
+                      value -> new Pair<>(new DoubleLiteral((Float) value), String.valueOf(value));
+                  case DOUBLE ->
+                      value -> new Pair<>(new DoubleLiteral((Double) value), String.valueOf(value));
+                  case TEXT, STRING ->
+                      value -> {
+                        final String text = (String) value;
+                        return new Pair<>(
+                            new StringLiteral(text), "'" + text.replace("'", "''") + "'");
+                      };
+                  case BLOB ->
+                      value -> {
+                        final BinaryLiteral literal = new BinaryLiteral((byte[]) value);
+                        return new Pair<>(literal, "X'" + literal.toHexString() + "'");
+                      };
+                  case DATE, TIMESTAMP, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new IllegalArgumentException(
+                            DataNodeMiscMessages.UNKNOWN_PARAMETER_TYPE + type.getTypeEnum());
+                      };
+                };
+
+    static {
+      VALUE_PARSER_NO_EXCEPTION_SERVICE.check();
+      VALUE_PARSER_SERVICE.check();
+      AUTO_CAST_SERVICE.check();
+      PREPARED_PARAMETER_LITERAL_SERVICE.check();
+    }
+
+    private static NumberFormatException inconsistentValueException(
+        final String value, final Type type) {
+      return new NumberFormatException(
+          String.format(
+              DataNodeMiscMessages
+                  .EXCEPTION_DATA_TYPE_IS_NOT_CONSISTENT_INPUT_ARG_REGISTERED_ARG_0EF32FD3,
+              value,
+              type.getTypeEnum()));
+    }
+
+    private static String stripQuotesIfPresent(final String value) {
+      if ((value.startsWith(SqlConstant.QUOTE) && value.endsWith(SqlConstant.QUOTE))
+          || (value.startsWith(SqlConstant.DQUOTE) && value.endsWith(SqlConstant.DQUOTE))) {
+        return value.length() == 1 ? value : value.substring(1, value.length() - 1);
+      }
+      return value;
+    }
+
+    @FunctionalInterface
+    public interface ContextualValueParser {
+      Object parse(String value, ZoneId zoneId) throws QueryProcessException;
+    }
+
+    private ValueConversion() {
+      // Utility class
+    }
+  }
+
+  public static final class StorageEngine {
+
+    public static final TypeService<ToIntFunction<Object>>
+        INSERT_ROW_SERIALIZED_VALUE_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> value -> Byte.BYTES;
+                  case INT32, DATE, FLOAT -> value -> Integer.BYTES;
+                  case INT64, TIMESTAMP, DOUBLE -> value -> Long.BYTES;
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      value -> ReadWriteIOUtils.sizeToWrite((Binary) value);
+                  case ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnSupportedDataTypeException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<SerializedColumnSizeCalculator>
+        INSERT_TABLET_SERIALIZED_COLUMN_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (column, start, end) -> (end - start) * Byte.BYTES;
+                  case INT32, DATE, FLOAT -> (column, start, end) -> (end - start) * Integer.BYTES;
+                  case INT64, TIMESTAMP, DOUBLE ->
+                      (column, start, end) -> (end - start) * Long.BYTES;
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (column, start, end) -> {
+                        int size = 0;
+                        Binary[] values = (Binary[]) column;
+                        // Tablet and WAL use a length prefix without TsFile's presence byte.
+                        // Count only the selected range, including placeholders for null values.
+                        for (int i = start; i < end; i++) {
+                          byte[] bytes =
+                              values == null || values[i] == null ? null : values[i].getValues();
+                          size += Integer.BYTES + (bytes == null ? 0 : bytes.length);
+                        }
+                        return size;
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      (column, start, end) -> {
+                        throw new UnSupportedDataTypeException(
+                            String.format(
+                                DataNodeQueryMessages
+                                    .QUERY_EXCEPTION_DATA_TYPE_S_IS_NOT_SUPPORTED_5D5C02E4,
+                                type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<RawArrayByteBufferSerializer>
+        RAW_ARRAY_BYTE_BUFFER_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                      type::serializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (column, rows, buffer) -> {
+                        Binary[] values = (Binary[]) column;
+                        // Preserve the Tablet wire format: nullness lives in the separate bitmap.
+                        for (int i = 0; i < rows; i++) {
+                          if (values[i] != null && values[i].getValues() != null) {
+                            ReadWriteIOUtils.write(values[i], buffer);
+                          } else {
+                            buffer.putInt(0);
+                          }
+                        }
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<RawArrayOutputStreamSerializer>
+        RAW_ARRAY_OUTPUT_STREAM_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                      type::serializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (column, rows, stream) -> {
+                        Binary[] values = (Binary[]) column;
+                        // Match the ByteBuffer writer, including zero-length null placeholders.
+                        for (int i = 0; i < rows; i++) {
+                          if (values[i] != null && values[i].getValues() != null) {
+                            ReadWriteIOUtils.write(values[i], stream);
+                          } else {
+                            stream.writeInt(0);
+                          }
+                        }
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Boolean> TABLET_PLAIN_FAST_PATH_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, DATE, INT32, TIMESTAMP, INT64, FLOAT, DOUBLE, STRING, BLOB, TEXT ->
+                  true;
+              case ROW, VECTOR, UNKNOWN, OBJECT -> false;
+            };
+
+    public static final TypeService<AlignedTVListColumnWriter>
+        ALIGNED_TV_LIST_COLUMN_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, !isNull && list.getBooleanByValueIndex(row, column), isNull);
+                  case INT32, DATE ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0 : list.getIntByValueIndex(row, column), isNull);
+                  case INT64, TIMESTAMP ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0L : list.getLongByValueIndex(row, column), isNull);
+                  case FLOAT ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0F : list.getFloatByValueIndex(row, column), isNull);
+                  case DOUBLE ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0D : list.getDoubleByValueIndex(row, column), isNull);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time,
+                              isNull ? null : list.getBinaryByValueIndex(row, column),
+                              isNull);
+                  // Preserve the flush path's no-op behavior for non-value types.
+                  case ROW, UNKNOWN, VECTOR -> (writer, time, list, row, column, isNull) -> {};
+                };
+
+    private static final Binary EMPTY_BINARY = new Binary("", StandardCharsets.UTF_8);
+
+    public static final TypeService<ChunkMetadataStatisticsConverter>
+        CHUNK_METADATA_STATISTICS_CONVERTER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, INT64, TIMESTAMP, FLOAT, DOUBLE, BOOLEAN ->
+                      StorageEngine::convertNumericOrBooleanStatistics;
+                  case DATE -> StorageEngine::convertDateStatistics;
+                  case STRING -> StorageEngine::convertStringStatistics;
+                  case TEXT -> StorageEngine::convertTextStatistics;
+                  case BLOB -> StorageEngine::convertBlobStatistics;
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (chunkMetadata, targetDataType, statistics) -> statistics;
+                };
+
+    public static final TypeService<BiConsumer<Object, IWALByteBufferView>>
+        WAL_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (value, buffer) -> WALWriteUtils.write((Boolean) value, buffer);
+                  case INT32, DATE ->
+                      (value, buffer) -> WALWriteUtils.write((Integer) value, buffer);
+                  case INT64, TIMESTAMP ->
+                      (value, buffer) -> WALWriteUtils.write((Long) value, buffer);
+                  case FLOAT -> (value, buffer) -> WALWriteUtils.write((Float) value, buffer);
+                  case DOUBLE -> (value, buffer) -> WALWriteUtils.write((Double) value, buffer);
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (value, buffer) -> WALWriteUtils.write((Binary) value, buffer);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    // Unmaterialized blocks still write zero placeholders; the bitmap carries nullness in WAL.
+    public static final TypeService<WALColumnWriter> WAL_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (column, buffer, start, end) -> {
+                    int[] values = (int[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putInt(values == null ? 0 : values[i]);
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (column, buffer, start, end) -> {
+                    long[] values = (long[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putLong(values == null ? 0L : values[i]);
+                    }
+                  };
+              case FLOAT ->
+                  (column, buffer, start, end) -> {
+                    float[] values = (float[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putFloat(values == null ? 0F : values[i]);
+                    }
+                  };
+              case DOUBLE ->
+                  (column, buffer, start, end) -> {
+                    double[] values = (double[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putDouble(values == null ? 0D : values[i]);
+                    }
+                  };
+              case BOOLEAN ->
+                  (column, buffer, start, end) -> {
+                    boolean[] values = (boolean[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.put((byte) (values != null && values[i] ? 1 : 0));
+                    }
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (column, buffer, start, end) -> {
+                    Binary[] values = (Binary[]) column;
+                    for (int i = start; i < end; i++) {
+                      if (values != null && values[i] != null && values[i].getValues() != null) {
+                        WALWriteUtils.write(values[i], buffer);
+                      } else {
+                        buffer.putInt(0);
+                      }
+                    }
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedValueChunkWriter> DECODED_VALUE_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0 : ReadWriteIOUtils.readInt(stream), isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0L : ReadWriteIOUtils.readLong(stream), isNull);
+              case FLOAT ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0F : ReadWriteIOUtils.readFloat(stream), isNull);
+              case DOUBLE ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0D : ReadWriteIOUtils.readDouble(stream), isNull);
+              case BOOLEAN ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, !isNull && ReadWriteIOUtils.readBool(stream), isNull);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(
+                          time, isNull ? null : ReadWriteIOUtils.readBinary(stream), isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<SegmentedArraySerializedSizeCalculator>
+        SEGMENTED_ARRAY_SERIALIZED_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (valueArrays, rowCount, arraySize) -> rowCount * Byte.BYTES;
+                  case INT32, DATE ->
+                      (valueArrays, rowCount, arraySize) -> rowCount * Integer.BYTES;
+                  case INT64, TIMESTAMP ->
+                      (valueArrays, rowCount, arraySize) -> rowCount * Long.BYTES;
+                  case FLOAT -> (valueArrays, rowCount, arraySize) -> rowCount * Float.BYTES;
+                  case DOUBLE -> (valueArrays, rowCount, arraySize) -> rowCount * Double.BYTES;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (valueArrays, rowCount, arraySize) -> {
+                        int size = 0;
+                        int remaining = rowCount;
+                        for (Object valueArray : valueArrays) {
+                          int length = Math.min(remaining, arraySize);
+                          // WAL uses length-prefixed binaries, without TsFile array presence bytes.
+                          Binary[] binaryValues = (Binary[]) valueArray;
+                          for (int i = 0; i < length; i++) {
+                            Binary value = binaryValues == null ? null : binaryValues[i];
+                            size += Integer.BYTES;
+                            if (value != null && value.getValues() != null) {
+                              size += value.getLength();
+                            }
+                          }
+                          remaining -= length;
+                          if (remaining == 0) {
+                            break;
+                          }
+                        }
+                        return size;
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<ArrayValueColumnWriter> ARRAY_VALUE_COLUMN_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeBoolean(((boolean[]) values)[index]);
+              case INT32 ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeInt(((int[]) values)[index]);
+              case DATE ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    int value = ((int[]) values)[index];
+                    if (builder instanceof BinaryColumnBuilder) {
+                      ((BinaryColumnBuilder) builder).writeDate(value);
+                    } else {
+                      builder.writeInt(value);
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeLong(((long[]) values)[index]);
+              case FLOAT ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    float value = ((float[]) values)[index];
+                    if (encoding != null
+                        && !Float.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    builder.writeFloat(value);
+                  };
+              case DOUBLE ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    double value = ((double[]) values)[index];
+                    if (encoding != null
+                        && !Double.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    builder.writeDouble(value);
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeBinary(((Binary[]) values)[index]);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<BatchDataColumnWriter> BATCH_DATA_COLUMN_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (batchData, time, column, index) ->
+                      batchData.putBoolean(time, type.getBoolean(column, index));
+              case INT32, DATE ->
+                  (batchData, time, column, index) ->
+                      batchData.putInt(time, type.getInt(column, index));
+              case INT64, TIMESTAMP ->
+                  (batchData, time, column, index) ->
+                      batchData.putLong(time, type.getLong(column, index));
+              case FLOAT ->
+                  (batchData, time, column, index) ->
+                      batchData.putFloat(time, type.getFloat(column, index));
+              case DOUBLE ->
+                  (batchData, time, column, index) ->
+                      batchData.putDouble(time, type.getDouble(column, index));
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (batchData, time, column, index) ->
+                      batchData.putBinary(time, type.getBinary(column, index));
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueSerializer<Object>> OBJECT_VALUE_SERIALIZER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> (value, stream) -> ReadWriteIOUtils.write((int) value, stream);
+              case INT64, TIMESTAMP ->
+                  (value, stream) -> ReadWriteIOUtils.write((long) value, stream);
+              case FLOAT -> (value, stream) -> ReadWriteIOUtils.write((float) value, stream);
+              case DOUBLE -> (value, stream) -> ReadWriteIOUtils.write((double) value, stream);
+              case BOOLEAN -> (value, stream) -> ReadWriteIOUtils.write((boolean) value, stream);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (value, stream) -> ReadWriteIOUtils.write((Binary) value, stream);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueSerializer<TsPrimitiveType>>
+        TS_PRIMITIVE_VALUE_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getInt(), stream);
+                  case INT64, TIMESTAMP ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getLong(), stream);
+                  case FLOAT -> (value, stream) -> ReadWriteIOUtils.write(value.getFloat(), stream);
+                  case DOUBLE ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getDouble(), stream);
+                  case BOOLEAN ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getBoolean(), stream);
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getBinary(), stream);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Supplier<TsPrimitiveType>>
+        EMPTY_TS_PRIMITIVE_TYPE_FACTORY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, FLOAT, DOUBLE -> type::getTsPrimitiveType;
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::getTsPrimitiveType;
+                  case TIMESTAMP -> Type.fromTsDataType(TSDataType.INT64)::getTsPrimitiveType;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      () ->
+                          Type.fromTsDataType(TSDataType.TEXT)
+                              .getTsPrimitiveType(new Binary("", TSFileConfig.STRING_CHARSET));
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Function<IoTDBConfig, TSEncoding>> DEFAULT_ENCODING_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> IoTDBConfig::getDefaultBooleanEncoding;
+              case INT32, DATE -> IoTDBConfig::getDefaultInt32Encoding;
+              case INT64, TIMESTAMP -> IoTDBConfig::getDefaultInt64Encoding;
+              case FLOAT -> IoTDBConfig::getDefaultFloatEncoding;
+              case DOUBLE -> IoTDBConfig::getDefaultDoubleEncoding;
+              case TEXT, BLOB, STRING, OBJECT -> IoTDBConfig::getDefaultTextEncoding;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TabletColumnDecoder> TABLET_COLUMN_DECODER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    int[] values = new int[rowCount];
+                    // PlainEncoder uses var int, which may cause compatibility problems.
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] =
+                          encoding == TSEncoding.PLAIN
+                              ? ReadWriteIOUtils.readInt(buffer)
+                              : decoder.readInt(buffer);
+                    }
+                    return values;
+                  };
+              case INT64, TIMESTAMP ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    long[] values = new long[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readLong(buffer);
+                    }
+                    return values;
+                  };
+              case FLOAT ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    float[] values = new float[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readFloat(buffer);
+                    }
+                    return values;
+                  };
+              case DOUBLE ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    double[] values = new double[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readDouble(buffer);
+                    }
+                    return values;
+                  };
+              case BOOLEAN ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    boolean[] values = new boolean[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readBoolean(buffer);
+                    }
+                    return values;
+                  };
+              case TEXT, BLOB, STRING ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    Binary[] values = new Binary[rowCount];
+                    // PlainEncoder uses var int, which may cause compatibility problems.
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] =
+                          encoding == TSEncoding.PLAIN
+                              ? ReadWriteIOUtils.readBinary(buffer)
+                              : decoder.readBinary(buffer);
+                    }
+                    return values;
+                  };
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedArrayValueReader> DECODED_ARRAY_VALUE_READER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (values, index, stream) ->
+                      ((int[]) values)[index] = ReadWriteIOUtils.readInt(stream);
+              case INT64, TIMESTAMP ->
+                  (values, index, stream) ->
+                      ((long[]) values)[index] = ReadWriteIOUtils.readLong(stream);
+              case FLOAT ->
+                  (values, index, stream) ->
+                      ((float[]) values)[index] = ReadWriteIOUtils.readFloat(stream);
+              case DOUBLE ->
+                  (values, index, stream) ->
+                      ((double[]) values)[index] = ReadWriteIOUtils.readDouble(stream);
+              case BOOLEAN ->
+                  (values, index, stream) ->
+                      ((boolean[]) values)[index] = ReadWriteIOUtils.readBool(stream);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (values, index, stream) ->
+                      ((Binary[]) values)[index] = ReadWriteIOUtils.readBinary(stream);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedChunkWriter> DECODED_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readInt(stream));
+              case INT64, TIMESTAMP ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readLong(stream));
+              case FLOAT ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readFloat(stream));
+              case DOUBLE ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readDouble(stream));
+              case BOOLEAN ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readBool(stream));
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readBinary(stream));
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListArrayWriter> TV_LIST_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putBooleans(times, (boolean[]) values, bitMap, start, end);
+              case INT32, DATE ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putInts(times, (int[]) values, bitMap, start, end);
+              case INT64, TIMESTAMP ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putLongs(times, (long[]) values, bitMap, start, end);
+              case FLOAT ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putFloats(times, (float[]) values, bitMap, start, end);
+              case DOUBLE ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putDoubles(times, (double[]) values, bitMap, start, end);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putBinaries(times, (Binary[]) values, bitMap, start, end);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListObjectWriter> TV_LIST_OBJECT_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (tvList, time, value) -> tvList.putBoolean(time, (boolean) value);
+              case INT32, DATE -> (tvList, time, value) -> tvList.putInt(time, (int) value);
+              case INT64, TIMESTAMP -> (tvList, time, value) -> tvList.putLong(time, (long) value);
+              case FLOAT -> (tvList, time, value) -> tvList.putFloat(time, (float) value);
+              case DOUBLE -> (tvList, time, value) -> tvList.putDouble(time, (double) value);
+              case TEXT, BLOB, STRING ->
+                  (tvList, time, value) -> tvList.putBinary(time, (Binary) value);
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    private static final TVListProvider UNSUPPORTED_TV_LIST_PROVIDER =
+        new TVListProvider(() -> null, stream -> null, stream -> null);
+
+    public static final TypeService<TVListProvider> TV_LIST_PROVIDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  new TVListProvider(
+                      BooleanTVList::newList,
+                      BooleanTVList::deserialize,
+                      BooleanTVList::deserializeWithoutBitMap);
+              case INT32 ->
+                  new TVListProvider(
+                      () -> IntTVList.newList(TSDataType.INT32),
+                      stream -> IntTVList.deserialize(stream, TSDataType.INT32),
+                      stream -> IntTVList.deserializeWithoutBitMap(stream, TSDataType.INT32));
+              case DATE ->
+                  new TVListProvider(
+                      () -> IntTVList.newList(TSDataType.DATE),
+                      stream -> IntTVList.deserialize(stream, TSDataType.DATE),
+                      stream -> IntTVList.deserializeWithoutBitMap(stream, TSDataType.DATE));
+              case INT64, TIMESTAMP ->
+                  new TVListProvider(
+                      LongTVList::newList,
+                      LongTVList::deserialize,
+                      LongTVList::deserializeWithoutBitMap);
+              case FLOAT ->
+                  new TVListProvider(
+                      FloatTVList::newList,
+                      FloatTVList::deserialize,
+                      FloatTVList::deserializeWithoutBitMap);
+              case DOUBLE ->
+                  new TVListProvider(
+                      DoubleTVList::newList,
+                      DoubleTVList::deserialize,
+                      DoubleTVList::deserializeWithoutBitMap);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  new TVListProvider(
+                      BinaryTVList::newList,
+                      BinaryTVList::deserialize,
+                      BinaryTVList::deserializeWithoutBitMap);
+              case ROW, UNKNOWN, VECTOR -> UNSUPPORTED_TV_LIST_PROVIDER;
+            };
+
+    public static final TypeService<TVListChunkWriter> TV_LIST_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getBoolean(index));
+                    return 8L + 1L;
+                  };
+              case INT32, DATE ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getInt(index));
+                    return 8L + 4L;
+                  };
+              case INT64, TIMESTAMP ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getLong(index));
+                    return 8L + 8L;
+                  };
+              case FLOAT ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getFloat(index));
+                    return 8L + 4L;
+                  };
+              case DOUBLE ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getDouble(index));
+                    return 8L + 8L;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, tvList, index) -> {
+                    Binary value = tvList.getBinary(index);
+                    writer.write(time, value);
+                    return 8L + MemUtils.getBinarySize(value);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListBatchWriter> TV_LIST_BATCH_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    boolean value = tvList.getBoolean(index);
+                    if (filter != null && !filter.satisfyBoolean(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeBoolean(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case INT32, DATE ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    int value = tvList.getInt(index);
+                    if (filter != null && !filter.satisfyInteger(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeInt(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case INT64, TIMESTAMP ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    long value = tvList.getLong(index);
+                    if (filter != null && !filter.satisfyLong(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeLong(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case FLOAT ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    float value = tvList.getFloat(index);
+                    if (!Float.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    if (filter != null && !filter.satisfyFloat(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeFloat(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case DOUBLE ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    double value = tvList.getDouble(index);
+                    if (!Double.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    if (filter != null && !filter.satisfyDouble(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeDouble(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    Binary value = tvList.getBinary(index);
+                    if (filter != null && !filter.satisfyBinary(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeBinary(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    private static boolean consumeOffset(PaginationController paginationController) {
+      if (paginationController != null && paginationController.hasCurOffset()) {
+        paginationController.consumeOffset();
+        return true;
+      }
+      return false;
+    }
+
+    private static void consumeLimit(PaginationController paginationController) {
+      if (paginationController != null) {
+        paginationController.consumeLimit();
+      }
+    }
+
+    public static final TypeService<AlignedTVListChunkWriter> ALIGNED_TV_LIST_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? false : tvList.getBooleanByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case INT32, DATE ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0 : tvList.getIntByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0L : tvList.getLongByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case FLOAT ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0F : tvList.getFloatByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case DOUBLE ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0D : tvList.getDoubleByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? null : tvList.getBinaryByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueChunkArrayWriter> VALUE_CHUNK_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, !isNull && values != null && ((boolean[]) values)[index], isNull);
+              case INT32, DATE ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0 : ((int[]) values)[index], isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0L : ((long[]) values)[index], isNull);
+              case FLOAT ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0F : ((float[]) values)[index], isNull);
+              case DOUBLE ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0D : ((double[]) values)[index], isNull);
+              case TEXT, STRING, BLOB, OBJECT ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time,
+                          isNull || values == null ? null : ((Binary[]) values)[index],
+                          isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueChunkArrayBatchWriter>
+        VALUE_CHUNK_ARRAY_BATCH_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (boolean[]) values, nulls, count, offset);
+                  case INT32, DATE ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (int[]) values, nulls, count, offset);
+                  case INT64, TIMESTAMP ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (long[]) values, nulls, count, offset);
+                  case FLOAT ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (float[]) values, nulls, count, offset);
+                  case DOUBLE ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (double[]) values, nulls, count, offset);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (Binary[]) values, nulls, count, offset);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    // Preserve the bitmap path so nulls do not require a temporary boolean array or value encoding.
+    public static final TypeService<ValueChunkArrayBitmapWriter>
+        VALUE_CHUNK_ARRAY_BITMAP_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (boolean[]) values, bitMap, offset, count, offset);
+                  case INT32, DATE ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (int[]) values, bitMap, offset, count, offset);
+                  case INT64, TIMESTAMP ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (long[]) values, bitMap, offset, count, offset);
+                  case FLOAT ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (float[]) values, bitMap, offset, count, offset);
+                  case DOUBLE ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (double[]) values, bitMap, offset, count, offset);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (Binary[]) values, bitMap, offset, count, offset);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<IntFunction<Object>> PRIMITIVE_ARRAY_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE, TEXT, BLOB, STRING, OBJECT ->
+                  type::createArray;
+              case DATE -> Type.fromTsDataType(TSDataType.INT32)::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<SourceColumnToTabletValueWriter>
+        SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((boolean[]) targetColumn)[targetIndex] =
+                              sourceType.getBoolean(sourceColumn, sourceIndex);
+                  case INT32, DATE ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((int[]) targetColumn)[targetIndex] =
+                              sourceType.getInt(sourceColumn, sourceIndex);
+                  case INT64, TIMESTAMP ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((long[]) targetColumn)[targetIndex] =
+                              sourceType.getLong(sourceColumn, sourceIndex);
+                  case FLOAT ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((float[]) targetColumn)[targetIndex] =
+                              sourceType.getFloat(sourceColumn, sourceIndex);
+                  case DOUBLE ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((double[]) targetColumn)[targetIndex] =
+                              sourceType.getDouble(sourceColumn, sourceIndex);
+                  case TEXT, BLOB, STRING ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((Binary[]) targetColumn)[targetIndex] =
+                              sourceType.getBinary(sourceColumn, sourceIndex);
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) -> {
+                        throw new UnSupportedDataTypeException(
+                            DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<Object>> TABLET_COLUMN_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<IntFunction<Object>> EMPTY_TABLET_COLUMN_FACTORY_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::createArray;
+              case DATE ->
+                  size -> {
+                    LocalDate[] values = (LocalDate[]) type.createArray(size);
+                    Arrays.fill(values, LocalDate.of(1000, 1, 1));
+                    return values;
+                  };
+              case TEXT, BLOB, STRING ->
+                  size -> {
+                    Binary[] values = (Binary[]) type.createArray(size);
+                    Arrays.fill(values, Binary.EMPTY_VALUE);
+                    return values;
+                  };
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<WindowValueArrayBuilder> WINDOW_VALUE_ARRAY_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (window, list, begin, size) -> {
+                    int[] values = new int[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getIntByIndex(begin + i);
+                    }
+                    window.setIntValues(values);
+                  };
+              case INT64, TIMESTAMP ->
+                  (window, list, begin, size) -> {
+                    long[] values = new long[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getLongByIndex(begin + i);
+                    }
+                    window.setLongValues(values);
+                  };
+              case FLOAT ->
+                  (window, list, begin, size) -> {
+                    float[] values = new float[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getFloatByIndex(begin + i);
+                    }
+                    window.setFloatValues(values);
+                  };
+              case DOUBLE ->
+                  (window, list, begin, size) -> {
+                    double[] values = new double[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getDoubleByIndex(begin + i);
+                    }
+                    window.setDoubleValues(values);
+                  };
+              case BOOLEAN ->
+                  (window, list, begin, size) -> {
+                    boolean[] values = new boolean[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getBooleanByIndex(begin + i);
+                    }
+                    window.setBooleanValues(values);
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (window, list, begin, size) -> {
+                    Binary[] values = new Binary[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getBinaryByIndex(begin + i);
+                    }
+                    window.setBinaryValues(values);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<BiFunction<ByteBuffer, Integer, Object>>
+        RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::deserializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (buffer, size) -> {
+                        // Tablet RPC has no per-value presence byte; nulls use a separate bitmap.
+                        Binary[] values = new Binary[size];
+                        for (int i = 0; i < size; i++) {
+                          values[i] = ReadWriteIOUtils.readBinary(buffer);
+                        }
+                        return values;
+                      };
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::deserializeArray;
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<RawArrayInputStreamDeserializer>
+        RAW_ARRAY_INPUT_STREAM_DESERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::deserializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (stream, size) -> {
+                        // Match the ByteBuffer tablet reader, not TsFile's array wire format.
+                        Binary[] values = new Binary[size];
+                        for (int i = 0; i < size; i++) {
+                          values[i] = ReadWriteIOUtils.readBinary(stream);
+                        }
+                        return values;
+                      };
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::deserializeArray;
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<ArrayValueGetter> ARRAY_VALUE_GETTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (array, index) -> ((boolean[]) array)[index];
+              case INT32, DATE -> (array, index) -> ((int[]) array)[index];
+              case INT64, TIMESTAMP -> (array, index) -> ((long[]) array)[index];
+              case FLOAT -> (array, index) -> ((float[]) array)[index];
+              case DOUBLE -> (array, index) -> ((double[]) array)[index];
+              case TEXT, BLOB, STRING, OBJECT -> (array, index) -> ((Binary[]) array)[index];
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    static {
+      CHUNK_METADATA_STATISTICS_CONVERTER_SERVICE.check();
+      INSERT_ROW_SERIALIZED_VALUE_SIZE_SERVICE.check();
+      INSERT_TABLET_SERIALIZED_COLUMN_SIZE_SERVICE.check();
+      RAW_ARRAY_BYTE_BUFFER_SERIALIZER_SERVICE.check();
+      RAW_ARRAY_OUTPUT_STREAM_SERIALIZER_SERVICE.check();
+      TABLET_PLAIN_FAST_PATH_SERVICE.check();
+      ALIGNED_TV_LIST_COLUMN_WRITER_SERVICE.check();
+      TV_LIST_ARRAY_WRITER_SERVICE.check();
+      TV_LIST_OBJECT_WRITER_SERVICE.check();
+      TV_LIST_PROVIDER_SERVICE.check();
+      TV_LIST_CHUNK_WRITER_SERVICE.check();
+      TV_LIST_BATCH_WRITER_SERVICE.check();
+      ALIGNED_TV_LIST_CHUNK_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_BATCH_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_BITMAP_WRITER_SERVICE.check();
+      PRIMITIVE_ARRAY_ALLOCATOR_SERVICE.check();
+      SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE.check();
+      TABLET_COLUMN_ALLOCATOR_SERVICE.check();
+      EMPTY_TABLET_COLUMN_FACTORY_SERVICE.check();
+      WINDOW_VALUE_ARRAY_BUILDER_SERVICE.check();
+      RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE.check();
+      RAW_ARRAY_INPUT_STREAM_DESERIALIZER_SERVICE.check();
+      ARRAY_VALUE_GETTER_SERVICE.check();
+      DECODED_VALUE_CHUNK_WRITER_SERVICE.check();
+      SEGMENTED_ARRAY_SERIALIZED_SIZE_SERVICE.check();
+      ARRAY_VALUE_COLUMN_WRITER_SERVICE.check();
+      BATCH_DATA_COLUMN_WRITER_SERVICE.check();
+      OBJECT_VALUE_SERIALIZER_SERVICE.check();
+      TS_PRIMITIVE_VALUE_SERIALIZER_SERVICE.check();
+      EMPTY_TS_PRIMITIVE_TYPE_FACTORY_SERVICE.check();
+      DEFAULT_ENCODING_SERVICE.check();
+      TABLET_COLUMN_DECODER_SERVICE.check();
+      DECODED_ARRAY_VALUE_READER_SERVICE.check();
+      DECODED_CHUNK_WRITER_SERVICE.check();
+    }
+
+    private static Statistics<?> convertNumericOrBooleanStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING) {
+        Binary[] binaryValues = new Binary[4];
+        binaryValues[0] =
+            new Binary(
+                chunkMetadata.getStatistics().getFirstValue().toString(), StandardCharsets.UTF_8);
+        binaryValues[1] =
+            new Binary(
+                chunkMetadata.getStatistics().getLastValue().toString(), StandardCharsets.UTF_8);
+        if (chunkMetadata.getDataType() == TSDataType.BOOLEAN) {
+          binaryValues[2] = new Binary(Boolean.FALSE.toString(), StandardCharsets.UTF_8);
+          binaryValues[3] = new Binary(Boolean.TRUE.toString(), StandardCharsets.UTF_8);
+        } else {
+          binaryValues[2] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8);
+          binaryValues[3] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8);
+        }
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.TEXT) {
+        Binary[] binaryValues = new Binary[2];
+        if (chunkMetadata.getDataType() == TSDataType.BOOLEAN) {
+          binaryValues[0] = new Binary(Boolean.FALSE.toString(), StandardCharsets.UTF_8);
+          binaryValues[1] = new Binary(Boolean.TRUE.toString(), StandardCharsets.UTF_8);
+        } else {
+          binaryValues[0] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8);
+          binaryValues[1] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8);
+        }
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertDateStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType != TSDataType.STRING && targetDataType != TSDataType.TEXT) {
+        return statistics;
+      }
+      int valueCount = targetDataType == TSDataType.STRING ? 4 : 2;
+      Binary[] binaryValues = new Binary[valueCount];
+      binaryValues[0] = toDateBinary(chunkMetadata.getStatistics().getFirstValue());
+      binaryValues[1] = toDateBinary(chunkMetadata.getStatistics().getLastValue());
+      if (targetDataType == TSDataType.STRING) {
+        binaryValues[2] = toDateBinary(chunkMetadata.getStatistics().getMinValue());
+        binaryValues[3] = toDateBinary(chunkMetadata.getStatistics().getMaxValue());
+      }
+      updateStatistics(statistics, chunkMetadata, binaryValues);
+      return statistics;
+    }
+
+    private static Statistics<?> convertStringStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.TEXT) {
+        Binary[] binaryValues = {
+          new Binary(
+              chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8),
+          new Binary(chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8)
+        };
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.BLOB) {
+        statistics.update(
+            chunkMetadata.getStatistics().getStartTime(),
+            new Binary(
+                chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8));
+        statistics.update(
+            chunkMetadata.getStatistics().getEndTime(),
+            new Binary(
+                chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8));
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertTextStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING) {
+        Binary[] binaryValues = {
+          (Binary) chunkMetadata.getStatistics().getFirstValue(),
+          (Binary) chunkMetadata.getStatistics().getLastValue()
+        };
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.BLOB) {
+        statistics.update(chunkMetadata.getStatistics().getStartTime(), EMPTY_BINARY);
+        statistics.update(chunkMetadata.getStatistics().getEndTime(), EMPTY_BINARY);
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertBlobStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING || targetDataType == TSDataType.TEXT) {
+        updateStatistics(statistics, chunkMetadata, new Binary[] {EMPTY_BINARY, EMPTY_BINARY});
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Binary toDateBinary(Object value) {
+      return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+    }
+
+    private static void updateStatistics(
+        Statistics<?> statistics, IChunkMetadata chunkMetadata, Binary[] binaryValues) {
+      long[] longValues = new long[binaryValues.length];
+      longValues[0] = chunkMetadata.getStatistics().getStartTime();
+      longValues[1] = chunkMetadata.getStatistics().getEndTime();
+      Arrays.fill(longValues, 2, longValues.length, longValues[1]);
+      statistics.update(longValues, binaryValues, binaryValues.length);
+    }
+
+    private StorageEngine() {
+      // Utility class
+    }
+  }
+
+  public static final class Predicate {
+
+    public static final TypeService<Function<String, Comparable<?>>>
+        CONVERT_PREDICATE_VALUE_PARSER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> Integer::valueOf;
+                  case INT64, TIMESTAMP -> Long::valueOf;
+                  case FLOAT -> Float::valueOf;
+                  case DOUBLE -> Double::valueOf;
+                  case BOOLEAN ->
+                      valueString -> {
+                        if (valueString.equalsIgnoreCase("true")) {
+                          return Boolean.TRUE;
+                        } else if (valueString.equalsIgnoreCase("false")) {
+                          return Boolean.FALSE;
+                        }
+                        throw new IllegalArgumentException(
+                            String.format(
+                                DataNodeQueryMessages.EXCEPTION_ARG_CANNOT_BE_CAST_TO_ARG_28F0C5FC,
+                                valueString,
+                                type.getTypeEnum()));
+                      };
+                  case BLOB -> valueString -> new Binary(BaseEncoding.base16().decode(valueString));
+                  case TEXT, STRING ->
+                      valueString -> new Binary(valueString, TSFileConfig.STRING_CHARSET);
+                  case DATE -> DateTimeUtils::parseDateExpressionToInt;
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new UnsupportedOperationException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()));
+                };
+
+    public static final TypeService<Function<Literal, Comparable<?>>>
+        RELATIONAL_CONVERT_PREDICATE_VALUE_PARSER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> Integer.valueOf((int) getLongValue(value));
+                  case DATE -> value -> Integer.valueOf(((GenericLiteral) value).getValue());
+                  case INT64 -> value -> Long.valueOf(getLongValue(value));
+                  case TIMESTAMP -> TypeServices::getTimestampValue;
+                  case FLOAT -> value -> Float.valueOf((float) getDoubleValue(value));
+                  case DOUBLE -> value -> Double.valueOf(getDoubleValue(value));
+                  case BOOLEAN -> value -> Boolean.valueOf(((BooleanLiteral) value).getValue());
+                  case TEXT, STRING ->
+                      value ->
+                          new Binary(
+                              ((StringLiteral) value).getValue(), TSFileConfig.STRING_CHARSET);
+                  case BLOB -> value -> new Binary(((BinaryLiteral) value).getValue());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new UnsupportedOperationException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()));
+                };
+
+    public static final TypeService<Function<Column, Literal>>
+        UNCORRELATED_SCALAR_SUBQUERY_RESULT_LITERAL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      column -> new LongLiteral(Long.toString(type.getInt(column, 0)));
+                  case INT64, TIMESTAMP ->
+                      column -> new LongLiteral(Long.toString(type.getLong(column, 0)));
+                  case FLOAT -> column -> new FloatLiteral(type.getFloat(column, 0));
+                  case DOUBLE ->
+                      column -> new DoubleLiteral(Double.toString(type.getDouble(column, 0)));
+                  case BOOLEAN ->
+                      column -> new BooleanLiteral(Boolean.toString(type.getBoolean(column, 0)));
+                  case BLOB -> column -> new BinaryLiteral(type.getBinary(column, 0).toString());
+                  case TEXT, STRING ->
+                      column -> new StringLiteral(type.getBinary(column, 0).toString());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new IllegalArgumentException(
+                          String.format(
+                              DataNodeQueryMessages
+                                  .EXCEPTION_UNSUPPORTED_DATA_TYPE_FOR_SCALAR_SUBQUERY_RESULT_ARG_D58CBB00,
+                              type.getTypeEnum()));
+                };
+
+    private Predicate() {
+      // Utility class
+    }
+  }
+
+  public static final class Pipe {
+
+    public static final TypeService<Function<Object, Object>> OPC_UA_LAST_VALUE_CONVERTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case DATE ->
+                  value ->
+                      new DateTime(
+                          new java.util.Date(
+                              DateUtils.parseIntToDate(((Number) value).intValue()).getTime()));
+              case TIMESTAMP ->
+                  value ->
+                      new DateTime(
+                          TimestampPrecisionUtils.currPrecision.toNanos(
+                                      ((Number) value).longValue())
+                                  / 100L
+                              + 116444736000000000L);
+              case TEXT, BLOB, STRING -> String::valueOf;
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE -> Function.identity();
+              case ROW, VECTOR, OBJECT, UNKNOWN ->
+                  value -> {
+                    throw new UnSupportedDataTypeException(
+                        DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<SameTypeNumericOperatorStrategy>
+        SAME_TYPE_NUMERIC_OPERATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.INT32,
+                          AbstractSameTypeNumericOperator::getIntValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getIntValue(), stream),
+                          (operator, buffer) ->
+                              operator.setIntValue(ReadWriteIOUtils.readInt(buffer)));
+                  case INT64 ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.INT64,
+                          AbstractSameTypeNumericOperator::getLongValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getLongValue(), stream),
+                          (operator, buffer) ->
+                              operator.setLongValue(ReadWriteIOUtils.readLong(buffer)));
+                  case FLOAT ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.FLOAT,
+                          AbstractSameTypeNumericOperator::getFloatValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getFloatValue(), stream),
+                          (operator, buffer) ->
+                              operator.setFloatValue(ReadWriteIOUtils.readFloat(buffer)));
+                  case DOUBLE ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.DOUBLE,
+                          AbstractSameTypeNumericOperator::getDoubleValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getDoubleValue(), stream),
+                          (operator, buffer) ->
+                              operator.setDoubleValue(ReadWriteIOUtils.readDouble(buffer)));
+                  case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      unsupportedSameTypeNumericOperatorStrategy(
+                          TSDataType.valueOf(type.getTypeEnum().name()));
+                };
+
+    private static SameTypeNumericOperatorStrategy sameTypeNumericOperatorStrategy(
+        final TSDataType dataType,
+        final Function<AbstractSameTypeNumericOperator, Object> valueGetter,
+        final SameTypeNumericOperatorSerializer serializer,
+        final SameTypeNumericOperatorDeserializer deserializer) {
+      return new SameTypeNumericOperatorStrategy(dataType, valueGetter, serializer, deserializer);
+    }
+
+    private static SameTypeNumericOperatorStrategy unsupportedSameTypeNumericOperatorStrategy(
+        final TSDataType dataType) {
+      return new SameTypeNumericOperatorStrategy(
+          dataType,
+          operator -> null,
+          (operator, stream) -> {
+            throw new IOException(
+                String.format(DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT, dataType));
+          },
+          (operator, buffer) -> {
+            throw new IOException(
+                String.format(DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT, dataType));
+          });
+    }
+
+    public static final class SameTypeNumericOperatorStrategy {
+      private final TSDataType dataType;
+      private final Function<AbstractSameTypeNumericOperator, Object> valueGetter;
+      private final SameTypeNumericOperatorSerializer serializer;
+      private final SameTypeNumericOperatorDeserializer deserializer;
+
+      private SameTypeNumericOperatorStrategy(
+          final TSDataType dataType,
+          final Function<AbstractSameTypeNumericOperator, Object> valueGetter,
+          final SameTypeNumericOperatorSerializer serializer,
+          final SameTypeNumericOperatorDeserializer deserializer) {
+        this.dataType = dataType;
+        this.valueGetter = valueGetter;
+        this.serializer = serializer;
+        this.deserializer = deserializer;
+      }
+
+      public Pair<TSDataType, Object> getResult(final AbstractSameTypeNumericOperator operator) {
+        final Object value = valueGetter.apply(operator);
+        return value == null ? null : new Pair<>(dataType, value);
+      }
+
+      public void serialize(
+          final AbstractSameTypeNumericOperator operator, final DataOutputStream stream)
+          throws IOException {
+        serializer.serialize(operator, stream);
+      }
+
+      public void deserialize(
+          final AbstractSameTypeNumericOperator operator, final ByteBuffer buffer)
+          throws IOException {
+        deserializer.deserialize(operator, buffer);
+      }
+    }
+
+    @FunctionalInterface
+    private interface SameTypeNumericOperatorSerializer {
+      void serialize(AbstractSameTypeNumericOperator operator, DataOutputStream stream)
+          throws IOException;
+    }
+
+    @FunctionalInterface
+    private interface SameTypeNumericOperatorDeserializer {
+      void deserialize(AbstractSameTypeNumericOperator operator, ByteBuffer buffer)
+          throws IOException;
+    }
+
+    public static final TypeService<Short> OPC_DA_VARIANT_TYPE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> Variant.VT_BOOL;
+              case INT32 -> Variant.VT_I4;
+              case INT64 -> Variant.VT_I8;
+              case DATE, TIMESTAMP -> Variant.VT_DATE;
+              case FLOAT -> Variant.VT_R4;
+              case DOUBLE -> Variant.VT_R8;
+              // Note that "Variant" does not support "VT_BLOB" data, and not all the DA servers
+              // support this, thus we use "VT_BSTR" to substitute.
+              case TEXT, STRING, BLOB, OBJECT -> Variant.VT_BSTR;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<OpcDaTabletValueSetter> OPC_DA_TABLET_VALUE_SETTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_BOOL, new OaIdl.VARIANT_BOOL(((boolean[]) column)[rowIndex]));
+                    return null;
+                  };
+              case INT32 ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_I4, new WinDef.LONG(((int[]) column)[rowIndex]));
+                    return null;
+                  };
+              case DATE ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_DATE,
+                        new OaIdl.DATE(Date.valueOf(((LocalDate[]) column)[rowIndex])));
+                    return null;
+                  };
+              case INT64 ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_I8, new WinDef.LONGLONG(((long[]) column)[rowIndex]));
+                    return null;
+                  };
+              case TIMESTAMP ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_DATE,
+                        new OaIdl.DATE(new java.util.Date(((long[]) column)[rowIndex])));
+                    return null;
+                  };
+              case FLOAT ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_R4, ((float[]) column)[rowIndex]);
+                    return null;
+                  };
+              case DOUBLE ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_R8, ((double[]) column)[rowIndex]);
+                    return null;
+                  };
+              case TEXT, STRING, BLOB, OBJECT ->
+                  (value, column, rowIndex) -> {
+                    final WTypes.BSTR bstr =
+                        OleAuto.INSTANCE.SysAllocString(((Binary[]) column)[rowIndex].toString());
+                    value.setValue(Variant.VT_BSTR, bstr);
+                    return bstr;
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  (value, column, rowIndex) -> {
+                    throw new UnSupportedDataTypeException(
+                        DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Function<Object, String>> OPC_UA_VALUE_STRINGIFIER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT, BLOB, STRING -> Object::toString;
+              case DATE ->
+                  value -> ((LocalDate) value).atStartOfDay(ZoneId.systemDefault()).toString();
+              case TIMESTAMP -> value -> DateTimeUtils.convertLongToDate((long) value);
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  value -> {
+                    throw new PipeRuntimeNonCriticalException(
+                        DataNodePipeMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToIntFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_INT_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (int) (long) value;
+                  case FLOAT -> value -> (int) (float) value;
+                  case DOUBLE -> value -> (int) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to int.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<ToLongFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_LONG_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (long) value;
+                  case FLOAT -> value -> (long) (float) value;
+                  case DOUBLE -> value -> (long) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to long.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<Function<Object, Float>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_FLOAT_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (float) (int) value;
+                  case DATE ->
+                      value -> (float) DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (float) (long) value;
+                  case FLOAT -> value -> (float) value;
+                  case DOUBLE -> value -> (float) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to float.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<ToDoubleFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_DOUBLE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (long) value;
+                  case FLOAT -> value -> (float) value;
+                  case DOUBLE -> value -> (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to double.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<Function<Object, String>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_STRING_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> value -> Boolean.toString((boolean) value);
+                  case INT32 -> value -> Integer.toString((int) value);
+                  case DATE -> value -> ((LocalDate) value).toString();
+                  case INT64 -> value -> Long.toString((long) value);
+                  case TIMESTAMP ->
+                      value ->
+                          RpcUtils.formatDatetime(
+                              RpcUtils.DEFAULT_TIME_FORMAT,
+                              CommonDescriptor.getInstance().getConfig().getTimestampPrecision(),
+                              (long) value,
+                              ZoneId.systemDefault());
+                  case FLOAT -> value -> Float.toString((float) value);
+                  case DOUBLE -> value -> Double.toString((double) value);
+                  case TEXT, STRING -> value -> (String) value;
+                  case BLOB ->
+                      value ->
+                          BytesUtils.parseBlobByteArrayToString(
+                              ((org.apache.iotdb.pipe.api.type.Binary) value).getValues());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to string.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<IntFunction<Object>> AGGREGATE_TABLET_COLUMN_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  size -> {
+                    throw new UnsupportedOperationException(
+                        String.format(
+                            DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT,
+                            type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<AggregateTabletColumnValueWriter>
+        AGGREGATE_TABLET_COLUMN_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      DATE,
+                      INT64,
+                      TIMESTAMP,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      BLOB,
+                      STRING,
+                      OBJECT ->
+                      (column, rowIndex, value) -> type.addValue(rowIndex, value, column);
+                  case ROW, UNKNOWN, VECTOR ->
+                      (column, rowIndex, value) -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT,
+                                type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<TabletObjectValueGetter>
+        OPC_UA_TABLET_OBJECT_VALUE_GETTER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (column, rowIndex) -> ((boolean[]) column)[rowIndex];
+                  case INT32 -> (column, rowIndex) -> ((int[]) column)[rowIndex];
+                  case DATE ->
+                      (column, rowIndex) ->
+                          new DateTime(Date.valueOf(((LocalDate[]) column)[rowIndex]));

Review Comment:
   [P2] Do not pass java.sql.Date to Milo DateTime
   
   `Date` here is `java.sql.Date`. Milo's `DateTime(Date)` constructor calls `date.toInstant()`, but `java.sql.Date.toInstant()` always throws `UnsupportedOperationException`. A normal DATE value therefore fails in the OPC UA Client/Server tablet path before it can be published.
   
   Executed with the actual Milo dependency during the earlier review:
   
   ```java
   LocalDate date = LocalDate.of(2026, 9, 9);
   new DateTime(java.sql.Date.valueOf(date));
   ```
   
   ```text
   java.lang.UnsupportedOperationException
     at java.sql.Date.toInstant(Date.java:316)
     at org.eclipse.milo.opcua.stack.core.types.builtin.DateTime.<init>(DateTime.java:57)
   ```
   
   The old `java.util.Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant())` expression succeeds for the same value. The conversion expression is still present in this HEAD. Please retain the java.util.Date/Instant conversion. This was verified at the actual conversion boundary; it was not a full OPC UA server integration test.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/utils/TypeServices.java:
##########
@@ -0,0 +1,3927 @@
+/*
+ * 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.iotdb.calc.utils;
+
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFillFilter;
+import org.apache.iotdb.calc.execution.operator.process.fill.ILinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.DoubleLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.FloatLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.IntLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.LongLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BinaryNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BooleanNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.DoubleNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.FloatNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.IntNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.LongNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.JoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.window.partition.Partition;
+import org.apache.iotdb.calc.execution.operator.process.window.utils.ColumnList;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AbstractApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AggregationMask;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BinaryApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BlobApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BooleanApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.DoubleApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.FloatApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.IntApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.LongApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.TableAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.approximate.HyperLogLog;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.AbstractGroupedApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BinaryGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BlobGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BooleanGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.DoubleGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.FloatGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedMaxMinByBaseAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.IntGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.LongGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BinaryBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BooleanBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.DoubleBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.FloatBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.IntBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.LongBigArray;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBlobLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBooleanLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDateLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDoubleLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToFloatLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt32LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt64LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToStringLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToTimestampLiteralVisitor;
+import org.apache.iotdb.calc.transformation.dag.column.ColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBinaryMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBooleanMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InDoubleMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InFloatMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt32MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt64MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.datastructure.SortKey;
+import org.apache.iotdb.commons.exception.IoTDBRuntimeException;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+
+import java.time.ZoneId;
+import java.time.format.DateTimeParseException;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.function.IntConsumer;
+import java.util.function.IntFunction;
+import java.util.function.IntUnaryOperator;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_ARRAY_HEADER_SIZE;
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_OBJECT_HEADER_SIZE;
+
+public class TypeServices {
+
+  /**
+   * Wraps a type service whose result is immutable/stateless and can therefore be shared for all
+   * instances of the same data type. Type objects are intentionally reduced to their enum here: all
+   * services wrapped with this helper dispatch only on {@code getTypeEnum()}.
+   */
+  private static <T> TypeService<T> cached(final TypeService<T> service) {
+    final Map<Object, T> cache = new ConcurrentHashMap<>();
+    return type -> cache.computeIfAbsent(type.getTypeEnum(), ignored -> service.call(type));
+  }
+
+  private static final IdentityLinearFill IDENTITY_LINEAR_FILL = new IdentityLinearFill();
+  private static final IdentityFill IDENTITY_FILL = new IdentityFill();
+
+  // Unsupported fill types defer their exception until the returned strategy is used so check()
+  // can still validate that every TypeEnum has a service entry.
+  public static final TypeService<Supplier<ILinearFill>> LINEAR_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE -> IntLinearFill::new;
+            case INT64, TIMESTAMP -> LongLinearFill::new;
+            case FLOAT -> FloatLinearFill::new;
+            case DOUBLE -> DoubleLinearFill::new;
+            case BOOLEAN, TEXT, STRING, BLOB, OBJECT -> () -> IDENTITY_LINEAR_FILL;
+            case ROW, UNKNOWN, VECTOR ->
+                () -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, IFill>> PREVIOUS_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                filter ->
+                    filter == null
+                        ? new BooleanPreviousFill()
+                        : new BooleanPreviousFillWithTimeDuration(filter);
+            case TEXT, STRING, BLOB, OBJECT ->
+                filter ->
+                    filter == null
+                        ? new BinaryPreviousFill()
+                        : new BinaryPreviousFillWithTimeDuration(filter);
+            case INT32, DATE ->
+                filter ->
+                    filter == null
+                        ? new IntPreviousFill()
+                        : new IntPreviousFillWithTimeDuration(filter);
+            case INT64, TIMESTAMP ->
+                filter ->
+                    filter == null
+                        ? new LongPreviousFill()
+                        : new LongPreviousFillWithTimeDuration(filter);
+            case FLOAT ->
+                filter ->
+                    filter == null
+                        ? new FloatPreviousFill()
+                        : new FloatPreviousFillWithTimeDuration(filter);
+            case DOUBLE ->
+                filter ->
+                    filter == null
+                        ? new DoublePreviousFill()
+                        : new DoublePreviousFillWithTimeDuration(filter);
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, ILinearFill>> NEXT_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> BooleanNextFill::new;
+            case TEXT, STRING, BLOB, OBJECT -> BinaryNextFill::new;
+            case INT32, DATE -> IntNextFill::new;
+            case INT64, TIMESTAMP -> LongNextFill::new;
+            case FLOAT -> FloatNextFill::new;
+            case DOUBLE -> DoubleNextFill::new;
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<BooleanFunction<JoinKeyComparator>> JOIN_KEY_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    ascending ->
+                        ascending
+                            ? AscIntTypeJoinKeyComparator.getInstance()
+                            : DescIntTypeJoinKeyComparator.getInstance();
+                case INT64, TIMESTAMP ->
+                    ascending ->
+                        ascending
+                            ? AscLongTypeJoinKeyComparator.getInstance()
+                            : DescLongTypeJoinKeyComparator.getInstance();
+                case FLOAT ->
+                    ascending ->
+                        ascending
+                            ? AscFloatTypeJoinKeyComparator.getInstance()
+                            : DescFloatTypeJoinKeyComparator.getInstance();
+                case DOUBLE ->
+                    ascending ->
+                        ascending
+                            ? AscDoubleTypeJoinKeyComparator.getInstance()
+                            : DescDoubleTypeJoinKeyComparator.getInstance();
+                case BOOLEAN ->
+                    ascending ->
+                        ascending
+                            ? AscBooleanTypeJoinKeyComparator.getInstance()
+                            : DescBooleanTypeJoinKeyComparator.getInstance();
+                case STRING, BLOB, TEXT ->
+                    ascending ->
+                        ascending
+                            ? AscBinaryTypeJoinKeyComparator.getInstance()
+                            : DescBinaryTypeJoinKeyComparator.getInstance();
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    ascending -> {
+                      throw new UnsupportedOperationException(
+                          CalcMessages.UNSUPPORTED_DATA_TYPE + type);
+                    };
+              });
+
+  public static final TypeService<IntFunction<Comparator<SortKey>>> MERGE_SORT_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    index ->
+                        Comparator.comparingInt(
+                            sortKey ->
+                                type.getInt(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case INT64, TIMESTAMP ->
+                    index ->
+                        Comparator.comparingLong(
+                            sortKey ->
+                                type.getLong(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case FLOAT ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getFloat(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case DOUBLE ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getDouble(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case TEXT, STRING, BLOB, OBJECT ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBinary(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case BOOLEAN ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBoolean(
+                                    sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                // TypeService.check() must be able to build a strategy for every enum value.
+                case ROW, UNKNOWN, VECTOR ->
+                    index -> {
+                      throw new IllegalArgumentException(
+                          String.format(CalcMessages.DATA_TYPE_CANNOT_BE_ORDERED, type));
+                    };
+              });
+
+  public static final TypeService<Integer> MEMORY_USAGE_OF_ONE_MERGE_SORT_KEY_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN -> 1;
+                case INT32, FLOAT, DATE -> 4;
+                case INT64, DOUBLE, TIMESTAMP -> 8;
+                case TEXT, STRING, BLOB, OBJECT -> 16;
+                case ROW, UNKNOWN, VECTOR ->
+                    throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                        .setChecked(true);
+              });
+
+  public static final TypeService<IntUnaryOperator>
+      MEMORY_USAGE_OF_ONE_SERIALIZABLE_ROW_FIELD_SERVICE =
+          cached(
+              type ->
+                  switch (type.getTypeEnum()) {
+                    case INT32, DATE -> ignored -> ReadWriteIOUtils.INT_LEN;
+                    case INT64, TIMESTAMP -> ignored -> ReadWriteIOUtils.LONG_LEN;
+                    case FLOAT -> ignored -> ReadWriteIOUtils.FLOAT_LEN;
+                    case DOUBLE -> ignored -> ReadWriteIOUtils.DOUBLE_LEN;
+                    case BOOLEAN -> ignored -> ReadWriteIOUtils.BOOLEAN_LEN;
+                    case TEXT, BLOB, STRING, OBJECT ->
+                        byteArrayLength ->
+                            MIN_OBJECT_HEADER_SIZE + MIN_ARRAY_HEADER_SIZE + byteArrayLength;
+                    case ROW, UNKNOWN, VECTOR ->
+                        throw new UnSupportedDataTypeException(type.toString()).setChecked(true);
+                  });
+
+  public static final TypeService<ValueFillFactory> VALUE_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (literal, zoneId) -> {
+                  Boolean value = literal.accept(new CastToBooleanLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BooleanConstantFill(value);
+                };
+            case TEXT, STRING ->
+                (literal, zoneId) -> {
+                  Binary value =
+                      literal.accept(
+                          new CastToStringLiteralVisitor(TSFileConfig.STRING_CHARSET), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case BLOB ->
+                (literal, zoneId) -> {
+                  Binary value = literal.accept(new CastToBlobLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case INT32 ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToInt32LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case DATE ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToDateLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case INT64 ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToInt64LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case TIMESTAMP ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToTimestampLiteralVisitor(zoneId), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case FLOAT ->
+                (literal, zoneId) -> {
+                  Float value = literal.accept(new CastToFloatLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new FloatConstantFill(value);
+                };
+            case DOUBLE ->
+                (literal, zoneId) -> {
+                  Double value = literal.accept(new CastToDoubleLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new DoubleConstantFill(value);
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (literal, zoneId) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads values for a cast using the source type's representation. */
+  public static final TypeService<CastInputService> CAST_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castInt(columnBuilder, type.getInt(column, position));
+            case DATE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDate(columnBuilder, type.getInt(column, position), zoneId);
+            case INT64 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castLong(columnBuilder, type.getLong(column, position));
+            case TIMESTAMP ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castTimestamp(
+                        columnBuilder, type.getLong(column, position), zoneId);
+            case FLOAT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castFloat(columnBuilder, type.getFloat(column, position));
+            case DOUBLE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDouble(columnBuilder, type.getDouble(column, position));
+            case BOOLEAN ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBoolean(columnBuilder, type.getBoolean(column, position));
+            case TEXT, STRING ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castString(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case BLOB ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBlob(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case OBJECT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castObject(columnBuilder, type.getBinary(column, position));
+            case ROW, UNKNOWN, VECTOR ->
+                (column, columnBuilder, position, castValueService, zoneId) -> {
+                  throw unsupportedCastSource(type);
+                };
+          };
+
+  /** Writes values produced by a cast into a column using the target type's representation. */
+  public static final TypeService<CastValueService> CAST_VALUE_SERVICE =
+      type ->
+          new CastValueService() {
+            @Override
+            public void castInt(ColumnBuilder columnBuilder, int value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castDate(ColumnBuilder columnBuilder, int value, ZoneId zoneId) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64 -> type.writeLong(columnBuilder, value);
+                case TIMESTAMP ->
+                    type.writeLong(
+                        columnBuilder,
+                        DateTimeUtils.correctPrecision(
+                            DateUtils.parseIntToTimestamp(value, zoneId)));
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(
+                        columnBuilder, BytesUtils.valueOf(DateUtils.formatDate(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castTimestamp(ColumnBuilder columnBuilder, long value, ZoneId zoneId) {
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      type.writeInt(columnBuilder, CastFunctionUtils.castLongToInt(value));
+                  case DATE ->
+                      type.writeInt(
+                          columnBuilder,
+                          DateUtils.parseDateExpressionToInt(
+                              DateTimeUtils.convertToLocalDate(value, zoneId)));
+                  case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                  case FLOAT -> type.writeFloat(columnBuilder, value);
+                  case DOUBLE -> type.writeDouble(columnBuilder, value);
+                  case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0L);
+                  case TEXT, STRING ->
+                      type.writeBinary(
+                          columnBuilder,
+                          BytesUtils.valueOf(DateTimeUtils.convertLongToDate(value, zoneId)));
+                  case BLOB ->
+                      type.writeBinary(columnBuilder, new Binary(BytesUtils.longToBytes(value)));
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException e) {
+                throw new IoTDBRuntimeException(
+                    "Year must be between 1000 and 9999.",
+                    org.apache.iotdb.rpc.TSStatusCode.DATE_OUT_OF_RANGE.getStatusCode(),
+                    true);
+              }
+            }
+
+            @Override
+            public void castLong(ColumnBuilder columnBuilder, long value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    type.writeInt(columnBuilder, CastFunctionUtils.castLongToInt(value));
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0L);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.longToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castFloat(ColumnBuilder columnBuilder, float value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    type.writeInt(columnBuilder, CastFunctionUtils.castFloatToInt(value));
+                case INT64, TIMESTAMP ->
+                    type.writeLong(columnBuilder, CastFunctionUtils.castFloatToLong(value));
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0.0f);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.floatToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castDouble(ColumnBuilder columnBuilder, double value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    type.writeInt(columnBuilder, CastFunctionUtils.castDoubleToInt(value));
+                case INT64, TIMESTAMP ->
+                    type.writeLong(columnBuilder, CastFunctionUtils.castDoubleToLong(value));
+                case FLOAT ->
+                    type.writeFloat(columnBuilder, CastFunctionUtils.castDoubleToFloat(value));
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0.0);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.doubleToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castBoolean(ColumnBuilder columnBuilder, boolean value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value ? 1 : 0);
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value ? 1L : 0L);
+                case FLOAT -> type.writeFloat(columnBuilder, value ? 1.0f : 0);
+                case DOUBLE -> type.writeDouble(columnBuilder, value ? 1.0 : 0);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.boolToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castString(ColumnBuilder columnBuilder, Binary value, ZoneId zoneId) {
+              String stringValue = value.getStringValue(TSFileConfig.STRING_CHARSET);
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 -> type.writeInt(columnBuilder, Integer.parseInt(stringValue));
+                  case DATE ->
+                      type.writeInt(columnBuilder, DateUtils.parseDateExpressionToInt(stringValue));
+                  case INT64 -> type.writeLong(columnBuilder, Long.parseLong(stringValue));
+                  case TIMESTAMP ->
+                      type.writeLong(
+                          columnBuilder,
+                          DateTimeUtils.convertDatetimeStrToLong(stringValue, zoneId));
+                  case FLOAT ->
+                      type.writeFloat(
+                          columnBuilder, CastFunctionUtils.castTextToFloat(stringValue));
+                  case DOUBLE ->
+                      type.writeDouble(
+                          columnBuilder, CastFunctionUtils.castTextToDouble(stringValue));
+                  case BOOLEAN ->
+                      type.writeBoolean(
+                          columnBuilder, CastFunctionUtils.castTextToBoolean(stringValue));
+                  case TEXT, STRING, BLOB, OBJECT -> type.writeBinary(columnBuilder, value);
+                  case ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException | NumberFormatException e) {
+                throw new SemanticException(
+                    String.format("Cannot cast %s to %s type", stringValue, type.getDisplayName()));
+              }
+            }
+
+            @Override
+            public void castBlob(ColumnBuilder columnBuilder, Binary value, ZoneId zoneId) {
+              String stringValue = BytesUtils.parseBlobByteArrayToString(value.getValues());
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 -> type.writeInt(columnBuilder, Integer.parseInt(stringValue));
+                  case DATE ->
+                      type.writeInt(columnBuilder, DateUtils.parseDateExpressionToInt(stringValue));
+                  case INT64 -> type.writeLong(columnBuilder, Long.parseLong(stringValue));
+                  case TIMESTAMP ->
+                      type.writeLong(
+                          columnBuilder,
+                          DateTimeUtils.convertDatetimeStrToLong(stringValue, zoneId));
+                  case FLOAT ->
+                      type.writeFloat(
+                          columnBuilder, CastFunctionUtils.castTextToFloat(stringValue));
+                  case DOUBLE ->
+                      type.writeDouble(
+                          columnBuilder, CastFunctionUtils.castTextToDouble(stringValue));
+                  case BOOLEAN ->
+                      type.writeBoolean(
+                          columnBuilder, CastFunctionUtils.castTextToBoolean(stringValue));
+                  case TEXT, STRING, BLOB -> type.writeBinary(columnBuilder, value);
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException | NumberFormatException e) {
+                throw new SemanticException(
+                    String.format("Cannot cast %s to %s type", stringValue, type.getDisplayName()));
+              }
+            }
+
+            @Override
+            public void castObject(ColumnBuilder columnBuilder, Binary value) {
+              String stringValue = BytesUtils.parseObjectByteArrayToString(value.getValues());
+              switch (type.getTypeEnum()) {
+                case STRING ->
+                    type.writeBinary(
+                        columnBuilder, BytesUtils.valueOf(String.valueOf(stringValue)));
+                case INT32,
+                    INT64,
+                    FLOAT,
+                    DOUBLE,
+                    BOOLEAN,
+                    DATE,
+                    TIMESTAMP,
+                    TEXT,
+                    BLOB,
+                    OBJECT,
+                    ROW,
+                    UNKNOWN,
+                    VECTOR ->
+                    throw unsupportedCastTarget(type);
+              }
+            }
+          };
+
+  public static final TypeService<CastObjectValueService> CAST_OBJECT_VALUE_SERVICE =
+      type ->
+          new CastObjectValueService() {
+            @Override
+            public Object castInt(int value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> value;
+                case INT64, TIMESTAMP -> (long) value;
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.intToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castDate(int value, ZoneId zoneId) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> value;
+                case INT64 -> (long) value;
+                case TIMESTAMP ->
+                    DateTimeUtils.correctPrecision(DateUtils.parseIntToTimestamp(value, zoneId));
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0;
+                case TEXT, STRING -> BytesUtils.valueOf(DateUtils.formatDate(value));
+                case BLOB -> new Binary(BytesUtils.intToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castTimestamp(long value, ZoneId zoneId) {
+              return switch (type.getTypeEnum()) {
+                case INT32 -> CastFunctionUtils.castLongToInt(value);
+                case DATE ->
+                    DateUtils.parseDateExpressionToInt(
+                        DateTimeUtils.convertToLocalDate(value, zoneId));
+                case INT64, TIMESTAMP -> value;
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0L;
+                case TEXT, STRING ->
+                    BytesUtils.valueOf(DateTimeUtils.convertLongToDate(value, zoneId));
+                case BLOB -> new Binary(BytesUtils.longToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castLong(long value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> CastFunctionUtils.castLongToInt(value);
+                case INT64, TIMESTAMP -> value;
+                case FLOAT -> (float) value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0L;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.longToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castFloat(float value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> CastFunctionUtils.castFloatToInt(value);
+                case INT64, TIMESTAMP -> CastFunctionUtils.castFloatToLong(value);
+                case FLOAT -> value;
+                case DOUBLE -> (double) value;
+                case BOOLEAN -> value != 0.0f;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.floatToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castDouble(double value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> CastFunctionUtils.castDoubleToInt(value);
+                case INT64, TIMESTAMP -> CastFunctionUtils.castDoubleToLong(value);
+                case FLOAT -> CastFunctionUtils.castDoubleToFloat(value);
+                case DOUBLE -> value;
+                case BOOLEAN -> value != 0.0d;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.doubleToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castBoolean(boolean value) {
+              return switch (type.getTypeEnum()) {
+                case INT32, DATE -> value ? 1 : 0;
+                case INT64, TIMESTAMP -> value ? 1L : 0L;
+                case FLOAT -> value ? 1.0f : 0.0f;
+                case DOUBLE -> value ? 1.0d : 0.0d;
+                case BOOLEAN -> value;
+                case TEXT, STRING -> BytesUtils.valueOf(String.valueOf(value));
+                case BLOB -> new Binary(BytesUtils.boolToBytes(value));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              };
+            }
+
+            @Override
+            public Object castBinary(Binary value, ZoneId zoneId) {
+              String stringValue = value.getStringValue(TSFileConfig.STRING_CHARSET);
+              try {
+                return switch (type.getTypeEnum()) {
+                  case INT32 -> Integer.parseInt(stringValue);
+                  case DATE -> DateUtils.parseDateExpressionToInt(stringValue);
+                  case INT64 -> Long.parseLong(stringValue);
+                  case TIMESTAMP -> DateTimeUtils.convertDatetimeStrToLong(stringValue, zoneId);
+                  case FLOAT -> CastFunctionUtils.castTextToFloat(stringValue);
+                  case DOUBLE -> CastFunctionUtils.castTextToDouble(stringValue);
+                  case BOOLEAN -> CastFunctionUtils.castTextToBoolean(stringValue);
+                  case TEXT, STRING, BLOB -> value;
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                };
+              } catch (DateTimeParseException | NumberFormatException e) {
+                throw new SemanticException(
+                    String.format("Cannot cast %s to %s type", stringValue, type.getDisplayName()));
+              }
+            }
+          };
+
+  public static final TypeService<CastObjectInputService> CAST_OBJECT_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castInt(
+                        value instanceof Integer ? (int) value : ((Long) value).intValue());
+            case DATE ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castDate(
+                        value instanceof Integer ? (int) value : ((Long) value).intValue(), zoneId);
+            case INT64 ->
+                (value, castValueService, zoneId) -> castValueService.castLong((Long) value);
+            case TIMESTAMP ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castTimestamp((Long) value, zoneId);
+            case FLOAT ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castFloat(
+                        value instanceof Float ? (float) value : ((Double) value).floatValue());
+            case DOUBLE ->
+                (value, castValueService, zoneId) -> castValueService.castDouble((Double) value);
+            case BOOLEAN ->
+                (value, castValueService, zoneId) -> castValueService.castBoolean((Boolean) value);
+            case TEXT, STRING, BLOB ->
+                (value, castValueService, zoneId) ->
+                    castValueService.castBinary((Binary) value, zoneId);
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (value, castValueService, zoneId) -> {
+                  throw unsupportedCastSource(type);
+                };
+          };
+
+  public static final TypeService<FormatValueConverter> FORMAT_VALUE_CONVERTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case UNKNOWN -> (column, position, zoneId) -> null;
+            case INT32, INT64, FLOAT, DOUBLE, BOOLEAN, TEXT, STRING, BLOB ->
+                (column, position, zoneId) -> column.getObject(position);
+            // Java Formatter expects temporal objects for DATE and TIMESTAMP arguments.
+            case DATE ->
+                (column, position, zoneId) ->
+                    DateUtils.parseIntToLocalDate(column.getInt(position));
+            case TIMESTAMP ->
+                (column, position, zoneId) ->
+                    DateTimeUtils.convertToZonedDateTime(column.getLong(position), zoneId);
+            case OBJECT, ROW, VECTOR ->
+                (column, position, zoneId) -> {
+                  throw new UnsupportedOperationException(
+                      CalcMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                };
+          };
+
+  public static final TypeService<GroupedAccumulator>
+      GROUPED_APPROX_MOST_FREQUENT_ACCUMULATOR_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN -> new BooleanGroupedApproxMostFrequentAccumulator();
+                case INT32, DATE -> new IntGroupedApproxMostFrequentAccumulator();
+                case INT64, TIMESTAMP -> new LongGroupedApproxMostFrequentAccumulator();
+                case FLOAT -> new FloatGroupedApproxMostFrequentAccumulator();
+                case DOUBLE -> new DoubleGroupedApproxMostFrequentAccumulator();
+                case TEXT, STRING -> new BinaryGroupedApproxMostFrequentAccumulator();
+                case BLOB -> new BlobGroupedApproxMostFrequentAccumulator();
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    throw unsupportedApproxMostFrequentDataType(type);
+              };
+
+  public static final TypeService<TableAccumulator> APPROX_MOST_FREQUENT_ACCUMULATOR_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> new BooleanApproxMostFrequentAccumulator();
+            case INT32, DATE -> new IntApproxMostFrequentAccumulator();
+            case INT64, TIMESTAMP -> new LongApproxMostFrequentAccumulator();
+            case FLOAT -> new FloatApproxMostFrequentAccumulator();
+            case DOUBLE -> new DoubleApproxMostFrequentAccumulator();
+            case TEXT, STRING -> new BinaryApproxMostFrequentAccumulator();
+            case BLOB -> new BlobApproxMostFrequentAccumulator();
+            case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedApproxMostFrequentDataType(type);
+          };
+
+  public static final TypeService<Function<List<ColumnTransformer>, ColumnTransformer>>
+      GREATEST_COLUMN_TRANSFORMER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN ->
+                    columnTransformers ->
+                        new BooleanGreatestColumnTransformer(type, columnTransformers);
+                case INT32, DATE ->
+                    columnTransformers ->
+                        new Int32GreatestColumnTransformer(type, columnTransformers);
+                case INT64, TIMESTAMP ->
+                    columnTransformers ->
+                        new Int64GreatestColumnTransformer(type, columnTransformers);
+                case FLOAT ->
+                    columnTransformers ->
+                        new FloatGreatestColumnTransformer(type, columnTransformers);
+                case DOUBLE ->
+                    columnTransformers ->
+                        new DoubleGreatestColumnTransformer(type, columnTransformers);
+                case STRING, TEXT ->
+                    columnTransformers ->
+                        new BinaryGreatestColumnTransformer(type, columnTransformers);
+                case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    columnTransformers -> {
+                      throw unsupportedGreatestLeastDataType(type);
+                    };
+              };
+
+  public static final TypeService<Function<List<ColumnTransformer>, ColumnTransformer>>
+      LEAST_COLUMN_TRANSFORMER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN ->
+                    columnTransformers ->
+                        new BooleanLeastColumnTransformer(type, columnTransformers);
+                case INT32, DATE ->
+                    columnTransformers -> new Int32LeastColumnTransformer(type, columnTransformers);
+                case INT64, TIMESTAMP ->
+                    columnTransformers -> new Int64LeastColumnTransformer(type, columnTransformers);
+                case FLOAT ->
+                    columnTransformers -> new FloatLeastColumnTransformer(type, columnTransformers);
+                case DOUBLE ->
+                    columnTransformers ->
+                        new DoubleLeastColumnTransformer(type, columnTransformers);
+                case STRING, TEXT ->
+                    columnTransformers ->
+                        new BinaryLeastColumnTransformer(type, columnTransformers);
+                case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    columnTransformers -> {
+                      throw unsupportedGreatestLeastDataType(type);
+                    };
+              };
+
+  /**
+   * Creates a single-row column containing the value at the requested row. Delegating the write to
+   * {@link Type} preserves type-specific column metadata (for example, DATE) without another
+   * TsDataType dispatch.
+   */
+  public static final TypeService<ColumnRowFunction> UPDATE_LAST_ROW_SERVICE =
+      type ->
+          (column, rowIndex) -> {
+            // Use the status overload so specialized types such as DATE retain their data type.
+            ColumnBuilder columnBuilder = type.createColumnBuilder(null, 1);
+            type.write(columnBuilder, column, rowIndex);
+            return columnBuilder.build();
+          };
+
+  /** Copies a column value into a reusable primitive result without boxing. */
+  public static final TypeService<PrimitiveColumnValueSetter>
+      PRIMITIVE_COLUMN_VALUE_SETTER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (target, column, position) -> target.setInt(type.getInt(column, position));
+                case INT64, TIMESTAMP ->
+                    (target, column, position) -> target.setLong(type.getLong(column, position));
+                case FLOAT ->
+                    (target, column, position) -> target.setFloat(type.getFloat(column, position));
+                case DOUBLE ->
+                    (target, column, position) ->
+                        target.setDouble(type.getDouble(column, position));
+                case BOOLEAN ->
+                    (target, column, position) ->
+                        target.setBoolean(type.getBoolean(column, position));
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (target, column, position) ->
+                        target.setBinary(type.getBinary(column, position));
+                case ROW, UNKNOWN, VECTOR ->
+                    (target, column, position) -> {
+                      throw new UnSupportedDataTypeException(
+                              CalcMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                    };
+              };
+
+  /** Writes a statistics value into a reusable primitive result. */
+  public static final TypeService<StatisticsValueSetter> STATISTICS_VALUE_SETTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (target, value, exceptionSupplier) -> target.setInt(((Number) value).intValue());
+            case INT64, TIMESTAMP ->
+                (target, value, exceptionSupplier) -> target.setLong(((Number) value).longValue());
+            case FLOAT ->
+                (target, value, exceptionSupplier) ->
+                    target.setFloat(((Number) value).floatValue());
+            case DOUBLE ->
+                (target, value, exceptionSupplier) ->
+                    target.setDouble(((Number) value).doubleValue());
+            case BOOLEAN ->
+                (target, value, exceptionSupplier) -> target.setBoolean((boolean) value);
+            case TEXT, STRING, BLOB, OBJECT ->
+                (target, value, exceptionSupplier) -> target.setBinary(toBinary(value));
+            case ROW, UNKNOWN, VECTOR ->
+                (target, value, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  public static final TypeService<InColumnValueMatcherFactory> IN_COLUMN_VALUE_MATCHER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                values -> {
+                  Set<Integer> intSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      intSet.add(Integer.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> intSet.contains(type.getInt(column, position));
+                };
+            case INT64, TIMESTAMP ->
+                values -> {
+                  Set<Long> longSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      longSet.add(Long.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> longSet.contains(type.getLong(column, position));
+                };
+            case FLOAT ->
+                values -> {
+                  Set<Float> floatSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      floatSet.add(Float.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> floatSet.contains(type.getFloat(column, position));
+                };
+            case DOUBLE ->
+                values -> {
+                  Set<Double> doubleSet = new HashSet<>();
+                  for (String value : values) {
+                    try {
+                      doubleSet.add(Double.valueOf(value));
+                    } catch (IllegalArgumentException e) {
+                      throw new SemanticException(
+                          String.format(
+                              CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                    }
+                  }
+                  return (column, position) -> doubleSet.contains(type.getDouble(column, position));
+                };
+            case BOOLEAN ->
+                values -> {
+                  Set<Boolean> booleanSet = new HashSet<>();
+                  for (String value : values) {
+                    if ("true".equalsIgnoreCase(value)) {
+                      booleanSet.add(true);
+                    } else if ("false".equalsIgnoreCase(value)) {
+                      booleanSet.add(false);
+                    } else {
+                      throw new SemanticException(
+                          String.format(CalcMessages.CANNOT_CAST_TO_BOOLEAN, value));
+                    }
+                  }
+                  return (column, position) ->
+                      booleanSet.contains(type.getBoolean(column, position));
+                };
+            case TEXT, STRING ->
+                values -> {
+                  Set<Binary> stringSet =
+                      values.stream()
+                          .map(value -> new Binary(value, TSFileConfig.STRING_CHARSET))
+                          .collect(Collectors.toSet());
+                  return (column, position) -> stringSet.contains(type.getBinary(column, position));
+                };
+            case BLOB, DATE, OBJECT, ROW, UNKNOWN, VECTOR ->
+                values -> {
+                  throw new UnsupportedOperationException(
+                      CalcMessages.UNSUPPORTED_DATA_TYPE_LOWER + type.getTypeEnum());
+                };
+          };
+
+  public static final TypeService<InMultiColumnTransformerFactory>
+      IN_MULTI_COLUMN_TRANSFORMER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32 ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Integer> intSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          long v = ((LongLiteral) value).getParsedValue();
+                          if (v <= Integer.MAX_VALUE && v >= Integer.MIN_VALUE) {
+                            intSet.add((int) v);
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InInt32MultiColumnTransformer(intSet, valueColumnTransformers);
+                    };
+                case DATE ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Integer> dateSet = new HashSet<>();
+                      for (Literal value : values) {
+                        dateSet.add(Integer.parseInt(((GenericLiteral) value).getValue()));
+                      }
+                      return new InInt32MultiColumnTransformer(dateSet, valueColumnTransformers);
+                    };
+                case INT64 ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Long> longSet = new HashSet<>();
+                      for (Literal value : values) {
+                        longSet.add(((LongLiteral) value).getParsedValue());
+                      }
+                      return new InInt64MultiColumnTransformer(longSet, valueColumnTransformers);
+                    };
+                case TIMESTAMP ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Long> timestampSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          if (value instanceof LongLiteral) {
+                            timestampSet.add(((LongLiteral) value).getParsedValue());
+                          } else if (value instanceof DoubleLiteral) {
+                            timestampSet.add((long) ((DoubleLiteral) value).getValue());
+                          } else if (value instanceof FloatLiteral) {
+                            timestampSet.add((long) ((FloatLiteral) value).getValue());
+                          } else if (value instanceof GenericLiteral) {
+                            timestampSet.add(Long.parseLong(((GenericLiteral) value).getValue()));
+                          } else {
+                            throw new SemanticException(
+                                String.format(
+                                    CalcMessages.IN_LIST_LITERAL_FOR_TIMESTAMP_TYPE_RESTRICTION,
+                                    value.getClass().getSimpleName()));
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InInt64MultiColumnTransformer(
+                          timestampSet, valueColumnTransformers);
+                    };
+                case FLOAT ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Float> floatSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          if (value instanceof FloatLiteral) {
+                            floatSet.add(((FloatLiteral) value).getValue());
+                          } else {
+                            floatSet.add((float) ((DoubleLiteral) value).getValue());
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InFloatMultiColumnTransformer(floatSet, valueColumnTransformers);
+                    };
+                case DOUBLE ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Double> doubleSet = new HashSet<>();
+                      for (Literal value : values) {
+                        try {
+                          if (value instanceof FloatLiteral) {
+                            doubleSet.add((double) ((FloatLiteral) value).getValue());
+                          } else {
+                            doubleSet.add(((DoubleLiteral) value).getValue());
+                          }
+                        } catch (IllegalArgumentException e) {
+                          throw new SemanticException(
+                              String.format(
+                                  CalcMessages.CANNOT_CAST_TO_TYPE, value, type.getTypeEnum()));
+                        }
+                      }
+                      return new InDoubleMultiColumnTransformer(doubleSet, valueColumnTransformers);
+                    };
+                case BOOLEAN ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Boolean> booleanSet = new HashSet<>();
+                      for (Literal value : values) {
+                        booleanSet.add(((BooleanLiteral) value).getValue());
+                      }
+                      return new InBooleanMultiColumnTransformer(
+                          booleanSet, valueColumnTransformers);
+                    };
+                case TEXT, STRING ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Binary> stringSet = new HashSet<>();
+                      for (Literal value : values) {
+                        stringSet.add(
+                            new Binary(
+                                ((StringLiteral) value).getValue(), TSFileConfig.STRING_CHARSET));
+                      }
+                      return new InBinaryMultiColumnTransformer(stringSet, valueColumnTransformers);
+                    };
+                case BLOB ->
+                    (valueColumnTransformers, values) -> {
+                      Set<Binary> binarySet = new HashSet<>();
+                      for (Literal value : values) {
+                        binarySet.add(new Binary(((BinaryLiteral) value).getValue()));
+                      }
+                      return new InBinaryMultiColumnTransformer(binarySet, valueColumnTransformers);
+                    };
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    (valueColumnTransformers, values) -> {
+                      throw new UnsupportedOperationException(
+                          CalcMessages.UNSUPPORTED_DATA_TYPE_LOWER + type.getTypeEnum());
+                    };
+              };
+
+  /** Updates a result with the minimum value from statistics. */
+  public static final TypeService<StatisticsValueUpdater> MIN_STATISTICS_VALUE_UPDATER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  int candidate = ((Number) value).intValue();
+                  if (!initialized || candidate < result.getInt()) {
+                    result.setInt(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case INT64, TIMESTAMP ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  long candidate = ((Number) value).longValue();
+                  if (!initialized || candidate < result.getLong()) {
+                    result.setLong(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case FLOAT ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  float candidate = ((Number) value).floatValue();
+                  if (!initialized || candidate < result.getFloat()) {
+                    result.setFloat(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case DOUBLE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  double candidate = ((Number) value).doubleValue();
+                  if (!initialized || candidate < result.getDouble()) {
+                    result.setDouble(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case BOOLEAN ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  boolean candidate = (boolean) value;
+                  if (!initialized || !candidate) {
+                    result.setBoolean(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case TEXT, STRING, BLOB ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  Binary candidate = toBinary(value);
+                  if (!initialized || candidate.compareTo(result.getBinary()) < 0) {
+                    result.setBinary(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  /** Updates a result with the maximum value from statistics. */
+  public static final TypeService<StatisticsValueUpdater> MAX_STATISTICS_VALUE_UPDATER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  int candidate = ((Number) value).intValue();
+                  if (!initialized || candidate > result.getInt()) {
+                    result.setInt(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case INT64, TIMESTAMP ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  long candidate = ((Number) value).longValue();
+                  if (!initialized || candidate > result.getLong()) {
+                    result.setLong(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case FLOAT ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  float candidate = ((Number) value).floatValue();
+                  if (!initialized || candidate > result.getFloat()) {
+                    result.setFloat(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case DOUBLE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  double candidate = ((Number) value).doubleValue();
+                  if (!initialized || candidate > result.getDouble()) {
+                    result.setDouble(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case BOOLEAN ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  boolean candidate = (boolean) value;
+                  if (!initialized || candidate) {
+                    result.setBoolean(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case TEXT, STRING, BLOB ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  Binary candidate = toBinary(value);
+                  if (!initialized || candidate.compareTo(result.getBinary()) > 0) {
+                    result.setBinary(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  /** Updates a result with the greatest absolute numeric value from statistics. */
+  public static final TypeService<StatisticsValueUpdater> EXTREME_STATISTICS_VALUE_UPDATER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  int candidate = ((Number) value).intValue();
+                  if (!initialized || compareExtreme(candidate, result.getInt()) > 0) {
+                    result.setInt(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case INT64 ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  long candidate = ((Number) value).longValue();
+                  if (!initialized || compareExtreme(candidate, result.getLong()) > 0) {
+                    result.setLong(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case FLOAT ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  float candidate = ((Number) value).floatValue();
+                  float absCandidate = Math.abs(candidate);
+                  float absResult = Math.abs(result.getFloat());
+                  if (!initialized
+                      || absCandidate > absResult
+                      || absCandidate == absResult && candidate > result.getFloat()) {
+                    result.setFloat(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case DOUBLE ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  double candidate = ((Number) value).doubleValue();
+                  double absCandidate = Math.abs(candidate);
+                  double absResult = Math.abs(result.getDouble());
+                  if (!initialized
+                      || absCandidate > absResult
+                      || absCandidate == absResult && candidate > result.getDouble()) {
+                    result.setDouble(candidate);
+                    return true;
+                  }
+                  return false;
+                };
+            case BOOLEAN, DATE, TIMESTAMP, TEXT, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                (result, value, initialized, exceptionSupplier) -> {
+                  throw exceptionSupplier.get();
+                };
+          };
+
+  /** Binds an APPROX_PERCENTILE input reader to the input column's native type. */
+  public static final TypeService<
+          Function<AbstractApproxPercentileAccumulator, BiConsumer<Column[], AggregationMask>>>
+      APPROX_PERCENTILE_INPUT_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32 -> accumulator -> accumulator::addIntInput;
+                case INT64, TIMESTAMP -> accumulator -> accumulator::addLongInput;
+                case FLOAT -> accumulator -> accumulator::addFloatInput;
+                case DOUBLE -> accumulator -> accumulator::addDoubleInput;
+                case BOOLEAN, DATE, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    accumulator ->
+                        (arguments, mask) -> {
+                          throw new UnSupportedDataTypeException(
+                              String.format(
+                                  CalcMessages
+                                      .UNSUPPORTED_DATA_TYPE_IN_APPROX_PERCENTILE_AGGREGATION,
+                                  type.getTypeEnum()));
+                        };
+              };
+
+  /** Binds a grouped APPROX_PERCENTILE input reader to the input column's native type. */
+  public static final TypeService<
+          Function<
+              AbstractGroupedApproxPercentileAccumulator,
+              TriConsumer<int[], Column[], AggregationMask>>>
+      GROUPED_APPROX_PERCENTILE_INPUT_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32 -> accumulator -> accumulator::addIntInput;
+                case INT64, TIMESTAMP -> accumulator -> accumulator::addLongInput;
+                case FLOAT -> accumulator -> accumulator::addFloatInput;
+                case DOUBLE -> accumulator -> accumulator::addDoubleInput;
+                case BOOLEAN, DATE, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    accumulator ->
+                        (groupIds, arguments, mask) -> {
+                          throw new UnSupportedDataTypeException(
+                              String.format(
+                                  CalcMessages
+                                      .UNSUPPORTED_DATA_TYPE_IN_APPROX_PERCENTILE_AGGREGATION,
+                                  type.getTypeEnum()));
+                        };
+              };
+
+  /** Provides storage operations for grouped accumulators backed by primitive big arrays. */
+  public static final TypeService<GroupedValueService> GROUPED_VALUE_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeIntValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getIntValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getIntValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getIntValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeInt(accessor.getIntValues().get(groupId));
+                  }
+                };
+            case INT64, TIMESTAMP ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeLongValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getLongValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getLongValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getLongValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeLong(accessor.getLongValues().get(groupId));
+                  }
+                };
+            case FLOAT ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeFloatValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getFloatValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getFloatValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getFloatValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeFloat(accessor.getFloatValues().get(groupId));
+                  }
+                };
+            case DOUBLE ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeDoubleValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getDoubleValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getDoubleValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getDoubleValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeDouble(accessor.getDoubleValues().get(groupId));
+                  }
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeBinaryValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getBinaryValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getBinaryValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getBinaryValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeBinary(accessor.getBinaryValues().get(groupId));
+                  }
+                };
+            case BOOLEAN ->
+                new GroupedValueService() {
+                  @Override
+                  public void initialize(GroupedValueAccessor accessor) {
+                    accessor.initializeBooleanValues();
+                  }
+
+                  @Override
+                  public void ensureCapacity(GroupedValueAccessor accessor, long groupCount) {
+                    accessor.getBooleanValues().ensureCapacity(groupCount);
+                  }
+
+                  @Override
+                  public long sizeOf(GroupedValueAccessor accessor) {
+                    return accessor.getBooleanValues().sizeOf();
+                  }
+
+                  @Override
+                  public void reset(GroupedValueAccessor accessor) {
+                    accessor.getBooleanValues().reset();
+                  }
+
+                  @Override
+                  public void write(
+                      GroupedValueAccessor accessor, int groupId, ColumnBuilder columnBuilder) {
+                    columnBuilder.writeBoolean(accessor.getBooleanValues().get(groupId));
+                  }
+                };
+            case ROW, UNKNOWN, VECTOR -> unsupportedGroupedValueService(type);
+          };
+
+  /** Reads grouped input and intermediate columns using the native column accessor. */
+  public static final TypeService<GroupedInputReader> GROUPED_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateInt(groupIds[position], arguments[0].getInt(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateInt(groupIds[i], argument.getInt(i));
+                      }
+                    }
+                  }
+                };
+            case INT64, TIMESTAMP ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateLong(
+                                groupIds[position], arguments[0].getLong(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateLong(groupIds[i], argument.getLong(i));
+                      }
+                    }
+                  }
+                };
+            case FLOAT ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateFloat(
+                                groupIds[position], arguments[0].getFloat(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateFloat(groupIds[i], argument.getFloat(i));
+                      }
+                    }
+                  }
+                };
+            case DOUBLE ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateDouble(
+                                groupIds[position], arguments[0].getDouble(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateDouble(groupIds[i], argument.getDouble(i));
+                      }
+                    }
+                  }
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBinary(
+                                groupIds[position], arguments[0].getBinary(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateBinary(groupIds[i], argument.getBinary(i));
+                      }
+                    }
+                  }
+                };
+            case BOOLEAN ->
+                new GroupedInputReader() {
+                  @Override
+                  public void addInput(
+                      int[] groupIds,
+                      Column[] arguments,
+                      AggregationMask mask,
+                      GroupedInputConsumer consumer) {
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBoolean(
+                                groupIds[position], arguments[0].getBoolean(position)));
+                  }
+
+                  @Override
+                  public void addIntermediate(
+                      int[] groupIds, Column argument, GroupedInputConsumer consumer) {
+                    for (int i = 0; i < groupIds.length; i++) {
+                      if (!argument.isNull(i)) {
+                        consumer.updateBoolean(groupIds[i], argument.getBoolean(i));
+                      }
+                    }
+                  }
+                };
+            case ROW, UNKNOWN, VECTOR -> unsupportedGroupedInputReader(type);
+          };
+
+  /** Restricts grouped EXTREME to the numeric types supported by the aggregate. */
+  public static final TypeService<GroupedValueService> GROUPED_EXTREME_VALUE_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, INT64, FLOAT, DOUBLE -> GROUPED_VALUE_SERVICE.call(type);
+            case BOOLEAN, DATE, TIMESTAMP, TEXT, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                unsupportedGroupedValueService(type);
+          };
+
+  public static final TypeService<GroupedInputReader> GROUPED_EXTREME_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, INT64, FLOAT, DOUBLE -> GROUPED_INPUT_READER_SERVICE.call(type);
+            case BOOLEAN, DATE, TIMESTAMP, TEXT, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                unsupportedGroupedInputReader(type);
+          };
+
+  /** Reads a value column together with its optional ordering-time column. */
+  public static final TypeService<GroupedTimeInputReader> GROUPED_TIME_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateInt(
+                                groupIds[position],
+                                arguments[0].getInt(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case INT64, TIMESTAMP ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateLong(
+                                groupIds[position],
+                                arguments[0].getLong(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case FLOAT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateFloat(
+                                groupIds[position],
+                                arguments[0].getFloat(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case DOUBLE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateDouble(
+                                groupIds[position],
+                                arguments[0].getDouble(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBinary(
+                                groupIds[position],
+                                arguments[0].getBinary(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case BOOLEAN ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[0],
+                        mask,
+                        position ->
+                            consumer.updateBoolean(
+                                groupIds[position],
+                                arguments[0].getBoolean(position),
+                                arguments[1].isNull(position),
+                                arguments[1].isNull(position)
+                                    ? 0
+                                    : arguments[1].getLong(position)));
+            case ROW, UNKNOWN, VECTOR ->
+                (groupIds, arguments, mask, consumer) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads x values for FIRST_BY/LAST_BY while filtering null y values. */
+  public static final TypeService<GroupedByInputReader> GROUPED_BY_INPUT_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateInt(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getInt(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case INT64, TIMESTAMP ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateLong(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getLong(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case FLOAT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateFloat(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getFloat(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case DOUBLE ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateDouble(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getDouble(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateBinary(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getBinary(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case BOOLEAN ->
+                (groupIds, arguments, mask, consumer) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            consumer.updateBoolean(
+                                groupIds[position],
+                                arguments[0].isNull(position),
+                                arguments[0].getBoolean(position),
+                                arguments[2].isNull(position),
+                                arguments[2].isNull(position)
+                                    ? 0
+                                    : arguments[2].getLong(position)));
+            case ROW, UNKNOWN, VECTOR ->
+                (groupIds, arguments, mask, consumer) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Serializes/deserializes a grouped value in the native intermediate format. */
+  public static final TypeService<GroupedValueSerializer> GROUPED_VALUE_SERIALIZER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Integer.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getIntValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case INT64, TIMESTAMP ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Long.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getLongValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case FLOAT ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Float.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getFloatValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case DOUBLE ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Double.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getDoubleValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Integer.BYTES + accessor.getBinaryValues().get(index).getLength();
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    accessor.getBinaryValues().toBytes(index, bytes, offset);
+                  }
+                };
+            case BOOLEAN ->
+                new GroupedValueSerializer() {
+                  @Override
+                  public int calcTypeSize(GroupedValueAccessor accessor, long index) {
+                    return Byte.BYTES;
+                  }
+
+                  @Override
+                  public void serialize(
+                      GroupedValueAccessor accessor, long index, byte[] bytes, int offset) {
+                    BytesUtils.boolToBytes(accessor.getBooleanValues().get(index), bytes, offset);
+                  }
+                };
+            case ROW, UNKNOWN, VECTOR -> unsupportedGroupedValueSerializer(type);
+          };
+
+  /** Stores a column value in the typed big array selected for a grouped accumulator. */
+  public static final TypeService<GroupedValueSetter> GROUPED_VALUE_SETTER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (accessor, index, column, position) ->
+                    accessor.getIntValues().set(index, type.getInt(column, position));
+            case INT64, TIMESTAMP ->
+                (accessor, index, column, position) ->
+                    accessor.getLongValues().set(index, type.getLong(column, position));
+            case FLOAT ->
+                (accessor, index, column, position) ->
+                    accessor.getFloatValues().set(index, type.getFloat(column, position));
+            case DOUBLE ->
+                (accessor, index, column, position) ->
+                    accessor.getDoubleValues().set(index, type.getDouble(column, position));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (accessor, index, column, position) ->
+                    accessor.getBinaryValues().set(index, type.getBinary(column, position));
+            case BOOLEAN ->
+                (accessor, index, column, position) ->
+                    accessor.getBooleanValues().set(index, type.getBoolean(column, position));
+            case ROW, UNKNOWN, VECTOR ->
+                (accessor, index, column, position) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads a grouped value from bytes into a typed callback. */
+  public static final TypeService<GroupedTimeValueDeserializer>
+      GROUPED_TIME_VALUE_DESERIALIZER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateInt(
+                            groupId, BytesUtils.bytesToInt(bytes, offset), timeNull, time);
+                case INT64, TIMESTAMP ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateLong(
+                            groupId,
+                            BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                            timeNull,
+                            time);
+                case FLOAT ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateFloat(
+                            groupId, BytesUtils.bytesToFloat(bytes, offset), timeNull, time);
+                case DOUBLE ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateDouble(
+                            groupId, BytesUtils.bytesToDouble(bytes, offset), timeNull, time);
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (bytes, offset, groupId, time, timeNull, consumer) -> {
+                      int length = BytesUtils.bytesToInt(bytes, offset);
+                      consumer.updateBinary(
+                          groupId,
+                          new Binary(BytesUtils.subBytes(bytes, offset + Integer.BYTES, length)),
+                          timeNull,
+                          time);
+                    };
+                case BOOLEAN ->
+                    (bytes, offset, groupId, time, timeNull, consumer) ->
+                        consumer.updateBoolean(
+                            groupId, BytesUtils.bytesToBool(bytes, offset), timeNull, time);
+                case ROW, UNKNOWN, VECTOR ->
+                    (bytes, offset, groupId, time, timeNull, consumer) -> {
+                      throw unsupportedDataType(type);
+                    };
+              };
+
+  /** Reads x values from FIRST_BY/LAST_BY intermediate bytes. */
+  public static final TypeService<GroupedByValueDeserializer>
+      GROUPED_BY_VALUE_DESERIALIZER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateInt(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToInt(bytes, offset),
+                            timeNull,
+                            time);
+                case INT64, TIMESTAMP ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateLong(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                            timeNull,
+                            time);
+                case FLOAT ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateFloat(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToFloat(bytes, offset),
+                            timeNull,
+                            time);
+                case DOUBLE ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateDouble(
+                            groupId,
+                            xNull,
+                            xNull ? 0 : BytesUtils.bytesToDouble(bytes, offset),
+                            timeNull,
+                            time);
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) -> {
+                      Binary value = null;
+                      if (!xNull) {
+                        int length = BytesUtils.bytesToInt(bytes, offset);
+                        value =
+                            new Binary(BytesUtils.subBytes(bytes, offset + Integer.BYTES, length));
+                      }
+                      consumer.updateBinary(groupId, xNull, value, timeNull, time);
+                    };
+                case BOOLEAN ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) ->
+                        consumer.updateBoolean(
+                            groupId,
+                            xNull,
+                            xNull ? false : BytesUtils.bytesToBool(bytes, offset),
+                            timeNull,
+                            time);
+                case ROW, UNKNOWN, VECTOR ->
+                    (bytes, offset, groupId, xNull, time, timeNull, consumer) -> {
+                      throw unsupportedDataType(type);
+                    };
+              };
+
+  /** Selects the y-column reader used by MAX_BY and MIN_BY input processing. */
+  public static final TypeService<MaxMinByInput> MAX_MIN_BY_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateInt(
+                                arguments[1].getInt(position), arguments[0], position));
+            case INT64, TIMESTAMP ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateLong(
+                                arguments[1].getLong(position), arguments[0], position));
+            case FLOAT ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateFloat(
+                                arguments[1].getFloat(position), arguments[0], position));
+            case DOUBLE ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateDouble(
+                                arguments[1].getDouble(position), arguments[0], position));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBinary(
+                                arguments[1].getBinary(position), arguments[0], position));
+            case BOOLEAN ->
+                (arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBoolean(
+                                arguments[1].getBoolean(position), arguments[0], position));
+            case ROW, UNKNOWN, VECTOR ->
+                (arguments, mask, updater) -> {
+                  throw unsupportedMaxMinByDataType(type);
+                };
+          };
+
+  /** Selects the y-value decoder used by MAX_BY and MIN_BY intermediate input processing. */
+  public static final TypeService<MaxMinByIntermediateInput> MAX_MIN_BY_INTERMEDIATE_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  int value = BytesUtils.bytesToInt(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, Integer.BYTES, xType, columnBuilder);
+                  updater.updateInt(value, columnBuilder.build(), 0);
+                };
+            case INT64, TIMESTAMP ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  long value = BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, 0);
+                  readMaxMinByXFromBytes(bytes, Long.BYTES, xType, columnBuilder);
+                  updater.updateLong(value, columnBuilder.build(), 0);
+                };
+            case FLOAT ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  float value = BytesUtils.bytesToFloat(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, Float.BYTES, xType, columnBuilder);
+                  updater.updateFloat(value, columnBuilder.build(), 0);
+                };
+            case DOUBLE ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  double value = BytesUtils.bytesToDouble(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, Double.BYTES, xType, columnBuilder);
+                  updater.updateDouble(value, columnBuilder.build(), 0);
+                };
+            case TEXT, STRING, BLOB, OBJECT ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  int length = BytesUtils.bytesToInt(bytes, 0);
+                  int xOffset = Integer.BYTES + length;
+                  Binary value = new Binary(BytesUtils.subBytes(bytes, Integer.BYTES, length));
+                  readMaxMinByXFromBytes(bytes, xOffset, xType, columnBuilder);
+                  updater.updateBinary(value, columnBuilder.build(), 0);
+                };
+            case BOOLEAN ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  boolean value = BytesUtils.bytesToBool(bytes, 0);
+                  readMaxMinByXFromBytes(bytes, 1, xType, columnBuilder);
+                  updater.updateBoolean(value, columnBuilder.build(), 0);
+                };
+            case ROW, UNKNOWN, VECTOR ->
+                (bytes, xType, columnBuilder, updater) -> {
+                  throw unsupportedMaxMinByDataType(type);
+                };
+          };
+
+  /** Selects the y-column reader used by grouped MAX_BY and MIN_BY input processing. */
+  public static final TypeService<GroupedMaxMinByInput> GROUPED_MAX_MIN_BY_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateInt(
+                                groupIds[position],
+                                arguments[1].getInt(position),
+                                arguments[0],
+                                position));
+            case INT64, TIMESTAMP ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateLong(
+                                groupIds[position],
+                                arguments[1].getLong(position),
+                                arguments[0],
+                                position));
+            case FLOAT ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateFloat(
+                                groupIds[position],
+                                arguments[1].getFloat(position),
+                                arguments[0],
+                                position));
+            case DOUBLE ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateDouble(
+                                groupIds[position],
+                                arguments[1].getDouble(position),
+                                arguments[0],
+                                position));
+            case TEXT, STRING, BLOB, OBJECT ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBinary(
+                                groupIds[position],
+                                arguments[1].getBinary(position),
+                                arguments[0],
+                                position));
+            case BOOLEAN ->
+                (groupIds, arguments, mask, updater) ->
+                    forEachSelectedPosition(
+                        arguments[1],
+                        mask,
+                        position ->
+                            updater.updateBoolean(
+                                groupIds[position],
+                                arguments[1].getBoolean(position),
+                                arguments[0],
+                                position));
+            case ROW, UNKNOWN, VECTOR ->
+                (groupIds, arguments, mask, updater) -> {
+                  throw unsupportedMaxMinByDataType(type);
+                };
+          };
+
+  /** Selects the y-value decoder used by grouped MAX_BY and MIN_BY intermediate input. */
+  public static final TypeService<GroupedMaxMinByIntermediateInput>
+      GROUPED_MAX_MIN_BY_INTERMEDIATE_INPUT_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      int value = BytesUtils.bytesToInt(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Integer.BYTES, xType, columnBuilder);
+                      updater.updateInt(groupId, value, columnBuilder.build(), 0);
+                    };
+                case INT64, TIMESTAMP ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      long value = BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, 0);
+                      readMaxMinByXFromBytes(bytes, Long.BYTES, xType, columnBuilder);
+                      updater.updateLong(groupId, value, columnBuilder.build(), 0);
+                    };
+                case FLOAT ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      float value = BytesUtils.bytesToFloat(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Float.BYTES, xType, columnBuilder);
+                      updater.updateFloat(groupId, value, columnBuilder.build(), 0);
+                    };
+                case DOUBLE ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      double value = BytesUtils.bytesToDouble(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Double.BYTES, xType, columnBuilder);
+                      updater.updateDouble(groupId, value, columnBuilder.build(), 0);
+                    };
+                case TEXT, STRING, BLOB, OBJECT ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      int length = BytesUtils.bytesToInt(bytes, 0);
+                      int xOffset = Integer.BYTES + length;
+                      Binary value = new Binary(BytesUtils.subBytes(bytes, Integer.BYTES, length));
+                      readMaxMinByXFromBytes(bytes, xOffset, xType, columnBuilder);
+                      updater.updateBinary(groupId, value, columnBuilder.build(), 0);
+                    };
+                case BOOLEAN ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      boolean value = BytesUtils.bytesToBool(bytes, 0);
+                      readMaxMinByXFromBytes(bytes, Byte.BYTES, xType, columnBuilder);
+                      updater.updateBoolean(groupId, value, columnBuilder.build(), 0);
+                    };
+                case ROW, UNKNOWN, VECTOR ->
+                    (groupId, bytes, xType, columnBuilder, updater) -> {
+                      throw unsupportedMaxMinByDataType(type);
+                    };
+              };
+
+  /** Selects the type-specific decoder for a LAST intermediate value. */
+  public static final TypeService<LastValueDeserializer> LAST_VALUE_DESERIALIZER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  int value = BytesUtils.bytesToInt(bytes, offset);
+                  updater.updateInt(value, time, isOrderTimeNull);
+                };
+            case INT64, TIMESTAMP ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  long value = BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset);
+                  updater.updateLong(value, time, isOrderTimeNull);
+                };
+            case FLOAT ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  float value = BytesUtils.bytesToFloat(bytes, offset);
+                  updater.updateFloat(value, time, isOrderTimeNull);
+                };
+            case DOUBLE ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  double value = BytesUtils.bytesToDouble(bytes, offset);
+                  updater.updateDouble(value, time, isOrderTimeNull);
+                };
+            case TEXT, BLOB, OBJECT, STRING ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  int length = BytesUtils.bytesToInt(bytes, offset);
+                  Binary value =
+                      new Binary(BytesUtils.subBytes(bytes, offset + Integer.BYTES, length));
+                  updater.updateBinary(value, time, isOrderTimeNull);
+                };
+            case BOOLEAN ->
+                (bytes, offset, time, isOrderTimeNull, updater) ->
+                    updater.updateBoolean(
+                        BytesUtils.bytesToBool(bytes, offset), time, isOrderTimeNull);
+            case ROW, UNKNOWN, VECTOR ->
+                (bytes, offset, time, isOrderTimeNull, updater) -> {
+                  throw new UnSupportedDataTypeException(
+                      CalcMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                };
+          };
+
+  public static final TypeService<Function<TsPrimitiveType, Object>>
+      PRIMITIVE_TYPE_VALUE_EXTRACTOR_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> TsPrimitiveType::getValue;
+                case DATE -> primitiveType -> DateUtils.parseIntToLocalDate(primitiveType.getInt());
+                case TEXT, BLOB, STRING ->
+                    primitiveType -> {
+                      final Binary binary = primitiveType.getBinary();
+                      return binary == null || binary.getValues() == null
+                          ? Binary.EMPTY_VALUE
+                          : binary;
+                    };
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    primitiveType -> {
+                      throw new UnSupportedDataTypeException(
+                              CalcMessages.UNSUPPORTED_DATA_TYPE + primitiveType.getDataType())
+                          .setChecked(true);
+                    };
+              };
+
+  /** Reads, serializes, deserializes, and writes Mode values without TsPrimitiveType conversion. */
+  public static final TypeService<ModeValueService> MODE_VALUE_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                modeValueService(
+                    type,
+                    type::getBoolean,
+                    BytesUtils::bytesToBool,
+                    (value, bytes, offset) -> {
+                      BytesUtils.boolToBytes((boolean) value, bytes, offset);
+                      return Byte.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeBoolean(columnBuilder, (boolean) value));
+            case INT32, DATE ->
+                modeValueService(
+                    type,
+                    type::getInt,
+                    BytesUtils::bytesToInt,
+                    (value, bytes, offset) -> {
+                      BytesUtils.intToBytes((int) value, bytes, offset);
+                      return Integer.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeInt(columnBuilder, (int) value));
+            case INT64, TIMESTAMP ->
+                modeValueService(
+                    type,
+                    type::getLong,
+                    (bytes, offset) -> BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                    (value, bytes, offset) -> {
+                      BytesUtils.longToBytes((long) value, bytes, offset);
+                      return Long.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeLong(columnBuilder, (long) value));
+            case FLOAT ->
+                modeValueService(
+                    type,
+                    type::getFloat,
+                    BytesUtils::bytesToFloat,
+                    (value, bytes, offset) -> {
+                      BytesUtils.floatToBytes((float) value, bytes, offset);
+                      return Float.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeFloat(columnBuilder, (float) value));
+            case DOUBLE ->
+                modeValueService(
+                    type,
+                    type::getDouble,
+                    BytesUtils::bytesToDouble,
+                    (value, bytes, offset) -> {
+                      BytesUtils.doubleToBytes((double) value, bytes, offset);
+                      return Double.BYTES;
+                    },
+                    (columnBuilder, value) -> type.writeDouble(columnBuilder, (double) value));
+            case TEXT, STRING, BLOB ->
+                modeValueService(
+                    type,
+                    type::getBinary,
+                    TypeServices::deserializeModeBinary,
+                    TypeServices::serializeModeBinary,
+                    (columnBuilder, value) -> type.writeBinary(columnBuilder, (Binary) value));
+            case OBJECT, ROW, UNKNOWN, VECTOR -> unsupportedModeValueService(type);
+          };
+
+  // The caller supplies the exception so shared conversion keeps each aggregation API's contract.
+  public static final TypeService<ColumnToDoubleConverterFactory>
+      NUMERIC_COLUMN_TO_DOUBLE_CONVERTER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> ignored -> type::getDouble;
+                case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                    exceptionSupplier ->
+                        (column, position) -> {
+                          throw exceptionSupplier.get();
+                        };
+              };
+
+  /** Numeric inputs supported by SUM, AVG and percentile aggregations. */
+  public static final TypeService<ColumnToDoubleConverterFactory>
+      AGGREGATION_NUMERIC_COLUMN_TO_DOUBLE_CONVERTER_SERVICE =
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, INT64, FLOAT, DOUBLE -> ignored -> type::getDouble;

Review Comment:
   [P2] Preserve mixed-type throughput when consolidating SUM's input loops
   
   Before the refactor, SUM selected a type-specific loop once per block; the inner loop called `getInt`, `getLong`, `getFloat` or `getDouble` directly. Now all four types use the same converter expression and a common inner loop invoking `valueConverter.convert(column, position)` for each value. The converter is already stored per accumulator, so this is not an allegation of a new allocation or switch for every row.
   
   I measured the actual BASE/PR SumAccumulator implementations in separate JVMs, with four accumulators (INT32/INT64/FLOAT/DOUBLE) alternating at 1,024-row batch boundaries. Both used the same TsFile dependency to isolate the Java refactor. Each run warmed up for 20.48 million rows, then took five samples of 4.096 million rows using ThreadMXBean current-thread CPU time. Final values were consumed into a volatile checksum (`3.2664E7` on both sides), then accumulators were reset.
   
   | Runtime / workload | BASE ns/value | PR ns/value |
   |---|---:|---:|
   | Corretto 17.0.5 arm64, mixed types | 0.89–0.92 | 5.60–5.69 |
   | OpenJDK 24.0.2 arm64, mixed types | 0.887–0.902 | 5.49–5.65 |
   | OpenJDK 24.0.2 arm64, INT32 only | about 0.90 | about 0.90 |
   
   These measurements were taken during the earlier review against BASE `25ab7941ce` and the PR implementation at `0b6c4eb8b6`; they are not a new benchmark of `6ac266b065`. The affected SUM loop and this conversion strategy are still unchanged. No extra per-value allocation was measured after warm-up. The shared polymorphic call path is a plausible JIT explanation, but I did not inspect generated assembly to establish the exact optimization lost.
   
   This is an aggregation-kernel result, not evidence that end-to-end SQL is six times slower. Please retain/select type-specific batch strategies, or add an equivalent warmed mixed-type benchmark demonstrating that the shared loop preserves throughput. The new cached-service helper does not change this per-value path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4023232004


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/TableCorrelationAccumulator.java:
##########
@@ -82,31 +81,15 @@ public void addInput(Column[] arguments, AggregationMask mask) {
         if (arguments[0].isNull(position) || arguments[1].isNull(position)) {
           continue;
         }
-        double x = getDoubleValue(arguments[0], position, xDataType);
-        double y = getDoubleValue(arguments[1], position, yDataType);
+        double x = getDoubleValue(arguments[0], position);
+        double y = getDoubleValue(arguments[1], position);
         update(x, y);
       }
     }
   }
 
-  private double getDoubleValue(Column column, int position, TSDataType dataType) {
-    switch (dataType) {
-      case INT32:
-      case DATE:
-        return column.getInt(position);
-      case INT64:
-      case TIMESTAMP:
-        return column.getLong(position);
-      case FLOAT:
-        return column.getFloat(position);
-      case DOUBLE:
-        return column.getDouble(position);
-      default:
-        throw new UnSupportedDataTypeException(
-            String.format(
-                CalcMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_CORRELATION_AGGREGATION_ARG_2FF29597,
-                dataType));
-    }
+  private double getDoubleValue(Column column, int position) {
+    return column.getDouble(position);

Review Comment:
   Fixed by upgrading `tsfile.version` to `2.4.1-260915-SNAPSHOT`, which contains apache/tsfile#961 (`8fdbc49bc80e`). `TimeColumn.getDouble(position)` now delegates to the native long getter and widens the result, preserving region offsets. I tested the actual published `2.4.1-260915-20260915.102750-1` JARs against the old 260909 snapshot using the same IoTDB aggregation classes. Tree, table and grouped corr/covar_pop/regr_slope pass with direct, region, dictionary and RLE time columns. Your example returns `[1.0, 1.4375, 0.17391304347826086]`. Across both P1 reproductions, the old snapshot fails all 76 targeted checks and the new one passes all 76. These are class-level checks; I have not rerun the live-instance SQL reproduction.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedModeAccumulator.java:
##########
@@ -188,121 +135,52 @@ public void reset() {
     nullCounts.reset();
   }
 
+  private void addInput(int[] groupIds, Column column, AggregationMask mask) {
+    int positionCount = mask.getSelectedPositionCount();
+    if (mask.isSelectAll()) {
+      for (int i = 0; i < positionCount; i++) {
+        addValue(groupIds[i], column, i);
+      }
+    } else {
+      int[] selectedPositions = mask.getSelectedPositions();
+      for (int i = 0; i < positionCount; i++) {
+        int position = selectedPositions[i];
+        addValue(groupIds[position], column, position);
+      }
+    }
+  }
+
+  private void addValue(int groupId, Column column, int position) {
+    HashMap<TsPrimitiveType, Long> countMap = countMaps.get(groupId);
+    if (column.isNull(position)) {
+      nullCounts.increment(groupId);
+    } else {
+      countMap.compute(
+          column.getTsPrimitiveType(position), (key, count) -> count == null ? 1L : count + 1);

Review Comment:
   Fixed by the same TsFile upgrade to `2.4.1-260915-SNAPSHOT` (apache/tsfile#961). `TimeColumn.getTsPrimitiveType` now returns a `TsLong` from `getLong(position)`, and `DictionaryColumn.getTsPrimitiveType` applies `getId(position)` before reading its dictionary. The actual published JAR passes the time-column MODE checks and non-identity/repeated mappings for all 10 supported types, including nested dictionaries, dictionary/ID offsets and the real `DistinctGroupedAccumulator` created through `AccumulatorFactory` with a selected mask. The `[3,4,5]` example now returns `100` instead of `10`. The combined P1 probe changes from 0/76 to 76/76 passing checks. This validates the concrete accumulator paths, not an end-to-end SQL rerun.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/TypeServices.java:
##########
@@ -0,0 +1,4276 @@
+/*
+ * 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.iotdb.db.utils;
+
+import org.apache.iotdb.calc.exception.QueryProcessException;
+import org.apache.iotdb.calc.execution.aggregation.Accumulator;
+import org.apache.iotdb.calc.execution.aggregation.BinaryModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.BooleanModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.DoubleModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.FloatModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.IntModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.LongModeAccumulator;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.TypeServices.PrimitiveColumnValueSetter;
+import org.apache.iotdb.calc.utils.constant.SqlConstant;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.exception.pipe.PipeRuntimeNonCriticalException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
+import org.apache.iotdb.db.pipe.processor.aggregate.TimeSeriesRuntimeState;
+import org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.AbstractSameTypeNumericOperator;
+import org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.WindowOutput;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBinaryWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBooleanWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowParameter;
+import org.apache.iotdb.db.queryengine.statistics.StatisticsManager;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.ArithmeticNegationTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.InTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.DiffFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.RoundFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.datastructure.util.ValueRecorder;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.IWALByteBufferView;
+import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALWriteUtils;
+import org.apache.iotdb.db.utils.datastructure.AlignedTVList;
+import org.apache.iotdb.db.utils.datastructure.BinaryTVList;
+import org.apache.iotdb.db.utils.datastructure.BooleanTVList;
+import org.apache.iotdb.db.utils.datastructure.DoubleTVList;
+import org.apache.iotdb.db.utils.datastructure.FloatTVList;
+import org.apache.iotdb.db.utils.datastructure.IntTVList;
+import org.apache.iotdb.db.utils.datastructure.LongTVList;
+import org.apache.iotdb.db.utils.datastructure.TVList;
+import org.apache.iotdb.db.utils.windowing.window.EvictableBatchList;
+import org.apache.iotdb.db.utils.windowing.window.WindowImpl;
+import org.apache.iotdb.pipe.api.access.Row;
+import org.apache.iotdb.rpc.RpcUtils;
+
+import com.google.common.io.BaseEncoding;
+import com.sun.jna.platform.win32.OaIdl;
+import com.sun.jna.platform.win32.OleAuto;
+import com.sun.jna.platform.win32.Variant;
+import com.sun.jna.platform.win32.WTypes;
+import com.sun.jna.platform.win32.WinDef;
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.encoding.decoder.Decoder;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.external.commons.lang3.StringUtils;
+import org.apache.tsfile.file.metadata.IChunkMetadata;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.file.metadata.statistics.DateStatistics;
+import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.BatchData;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.read.common.block.column.BinaryColumnBuilder;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.read.filter.basic.Filter;
+import org.apache.tsfile.read.reader.series.PaginationController;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.RamUsageEstimator;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ValueChunkWriter;
+import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.sql.Date;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import java.util.function.ToDoubleFunction;
+import java.util.function.ToIntFunction;
+import java.util.function.ToLongFunction;
+
+public class TypeServices {
+
+  public static final int DEFAULT_DATE =
+      DateUtils.parseDateExpressionToInt(LocalDate.of(1970, 1, 1));
+  private static final LocalDate EMPTY_LOCAL_DATE = LocalDate.of(1000, 1, 1);
+
+  public static final class Memory {
+
+    public static final TypeService<LongSupplier> STATEMENT_VALUE_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::estimateValueSize;
+              case TEXT, BLOB, STRING ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        CalcMessages.UNKNOWN_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToLongFunction<Object>> INSERT_NODE_VALUE_SIZE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  value ->
+                      RamUsageEstimator.alignObjectSize(
+                          type.estimateValueSize() + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER);
+              case TEXT, BLOB, STRING ->
+                  value -> Objects.nonNull(value) ? ((Binary) value).ramBytesUsed() : 0L;
+              case OBJECT, ROW, UNKNOWN, VECTOR -> value -> 0L;
+            };
+
+    static {
+      STATEMENT_VALUE_SIZE_PER_LINE_SERVICE.check();
+      INSERT_NODE_VALUE_SIZE_SERVICE.check();
+    }
+
+    private Memory() {
+      // Utility class
+    }
+  }
+
+  public static final class Transformation {
+
+    public static final TypeService<Function<Object, Column>> CONSTANT_COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT ->
+                  value -> {
+                    final ColumnBuilder builder = type.createColumnBuilder(1);
+                    type.writeObject(builder, value);
+                    return builder.build();
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<
+            Function<org.apache.iotdb.db.queryengine.plan.statement.literal.Literal, IFill>>
+        CONSTANT_FILL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> literal -> new BooleanConstantFill(literal.getBoolean());
+                  case INT32 -> literal -> new IntConstantFill(literal.getInt());
+                  case DATE -> literal -> new IntConstantFill(literal.getDate());
+                  case INT64, TIMESTAMP -> literal -> new LongConstantFill(literal.getLong());
+                  case FLOAT -> literal -> new FloatConstantFill(literal.getFloat());
+                  case DOUBLE -> literal -> new DoubleConstantFill(literal.getDouble());
+                  case TEXT, BLOB, STRING -> literal -> new BinaryConstantFill(literal.getBinary());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      literal -> {
+                        throw new IllegalArgumentException(
+                            CommonOperatorUtils.UNKNOWN_DATATYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<ColumnBuilder>> COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createColumnBuilder;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()))
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ColumnToDoubleConverter> VALUE_TO_DOUBLE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> type::getInt;
+              case INT64, TIMESTAMP -> type::getLong;
+              case FLOAT -> type::getFloat;
+              case DOUBLE -> type::getDouble;
+              case BOOLEAN -> (column, index) -> type.getBoolean(column, index) ? 1 : 0;
+              case TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (column, index) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ColumnValueWriter> TRANSFORM_COLUMN_VALUE_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::write;
+              case ROW, UNKNOWN, VECTOR ->
+                  (builder, column, index) -> {
+                    throw new UnSupportedDataTypeException(
+                        String.format(
+                            DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                            type.getTypeEnum()));
+                  };
+            };
+
+    // Schema evolution keeps physically compatible columns, widens supported values, and exposes
+    // incompatible historical values as nulls instead of interpreting their raw storage.
+    public static final TypeService<AlteredDataTypeColumnTransformer>
+        ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      INT64,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      STRING,
+                      TIMESTAMP,
+                      DATE,
+                      BLOB -> {
+                    final TSDataType targetType = TSDataType.valueOf(type.getTypeEnum().name());
+                    yield (source, positionCount) -> {
+                      final TSDataType sourceType = source.getDataType();
+                      // DATE shares INT32's physical column but was historically incompatible with
+                      // a schema change to INT32, while the other shared-column pairs are reusable.
+                      if (sourceType == targetType
+                          || (targetType != TSDataType.INT32
+                              && SchemaUtils.isUsingSameColumn(sourceType, targetType))) {
+                        return source;
+                      }
+                      return targetType.isCompatible(sourceType)
+                          ? source.convertTo(targetType)
+                          : type.createNullColumn(positionCount);
+                    };
+                  }
+                  case OBJECT -> (source, positionCount) -> source;
+                  case ROW, UNKNOWN, VECTOR -> (source, positionCount) -> null;
+                };
+
+    public static final TypeService<RoundTransformer> ROUND_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> RoundFunctionTransformer::transformInt;
+              case INT64 -> RoundFunctionTransformer::transformLong;
+              case FLOAT -> RoundFunctionTransformer::transformFloat;
+              case DOUBLE -> RoundFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new UnsupportedOperationException(
+                        String.format("Unsupported source dataType: %s", type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<DiffTransformer> DIFF_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> DiffFunctionTransformer::transformInt;
+              case INT64 -> DiffFunctionTransformer::transformLong;
+              case FLOAT -> DiffFunctionTransformer::transformFloat;
+              case DOUBLE -> DiffFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<NegationTransformer> NEGATION_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> ArithmeticNegationTransformer::transformInt;
+              case INT64 -> ArithmeticNegationTransformer::transformLong;
+              case FLOAT -> ArithmeticNegationTransformer::transformFloat;
+              case DOUBLE -> ArithmeticNegationTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<StateWindowSplitter> STATE_WINDOW_SPLITTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordInt(type.getInt(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getInt(values, index) - valueRecorder.getInt()) > delta;
+                    if (split) {
+                      valueRecorder.recordInt(type.getInt(values, index));
+                    }
+                    return split;
+                  };
+              case INT64 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordLong(type.getLong(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getLong(values, index) - valueRecorder.getLong()) > delta;
+                    if (split) {
+                      valueRecorder.recordLong(type.getLong(values, index));
+                    }
+                    return split;
+                  };
+              case FLOAT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordFloat(type.getFloat(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getFloat(values, index) - valueRecorder.getFloat()) > delta;
+                    if (split) {
+                      valueRecorder.recordFloat(type.getFloat(values, index));
+                    }
+                    return split;
+                  };
+              case DOUBLE ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordDouble(type.getDouble(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getDouble(values, index) - valueRecorder.getDouble()) > delta;
+                    if (split) {
+                      valueRecorder.recordDouble(type.getDouble(values, index));
+                    }
+                    return split;
+                  };
+              case BOOLEAN ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        type.getBoolean(values, index) != valueRecorder.getBoolean();
+                    if (split) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index));
+                    }
+                    return split;
+                  };
+              case TEXT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordString(type.getBinary(values, index - 1).toString());
+                      valueRecorder.setRecorded(true);
+                    }
+                    final String value = type.getBinary(values, index).toString();
+                    final boolean split = !value.equals(valueRecorder.getString());
+                    if (split) {
+                      valueRecorder.recordString(value);
+                    }
+                    return split;
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (valueRecorder, delta, values, index) -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages
+                            .EXCEPTION_THE_DATA_TYPE_OF_THE_STATE_WINDOW_STRATEGY_IS_NOT_VALID_61F4E273);
+                  };
+            };
+
+    public static final TypeService<InTransformerSetInitializer>
+        IN_TRANSFORMER_SET_INITIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::initIntSet;
+                  case INT64, TIMESTAMP -> InTransformer::initLongSet;
+                  case FLOAT -> InTransformer::initFloatSet;
+                  case DOUBLE -> InTransformer::initDoubleSet;
+                  case BOOLEAN -> InTransformer::initBooleanSet;
+                  case TEXT, STRING -> InTransformer::initStringSet;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, values) -> {
+                        throw new UnsupportedOperationException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<InTransformerColumnTransformer>
+        IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::transformInt;
+                  case INT64, TIMESTAMP -> InTransformer::transformLong;
+                  case FLOAT -> InTransformer::transformFloat;
+                  case DOUBLE -> InTransformer::transformDouble;
+                  case BOOLEAN -> InTransformer::transformBoolean;
+                  case TEXT, STRING -> InTransformer::transformBinary;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, columns, builder) -> {
+                        throw new QueryProcessException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<TypeService<CastColumnStrategy>> CAST_COLUMN_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(builder, type.getInt(column, index)));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getInt(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getInt(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getInt(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getInt(column, index) != 0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getInt(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case INT64 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castLongToInt(
+                                            type.getLong(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getLong(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getLong(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getLong(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getLong(column, index) != 0L));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getLong(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case FLOAT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castFloatToInt(
+                                            type.getFloat(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castFloatToLong(
+                                            type.getFloat(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getFloat(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getFloat(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getFloat(column, index) != 0.0f));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getFloat(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DOUBLE ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToInt(
+                                            type.getDouble(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToLong(
+                                            type.getDouble(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToFloat(
+                                            type.getDouble(column, index))));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getDouble(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getDouble(column, index) != 0.0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getDouble(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case BOOLEAN ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder, type.getBoolean(column, index) ? 1 : 0));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder, type.getBoolean(column, index) ? 1L : 0L));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder, type.getBoolean(column, index) ? 1.0f : 0.0f));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(
+                                        builder, type.getBoolean(column, index) ? 1.0 : 0.0));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getBoolean(column, index)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getBoolean(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case TEXT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeInt(builder, Integer.parseInt(value)));
+                        case INT64 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeLong(builder, Long.parseLong(value)));
+                        case FLOAT ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeFloat(
+                                        builder, CastFunctionUtils.castTextToFloat(value)));
+                        case DOUBLE ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeDouble(
+                                        builder, CastFunctionUtils.castTextToDouble(value)));
+                        case BOOLEAN ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, CastFunctionUtils.castTextToBoolean(value)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(builder, type.getBinary(column, index)));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  targetType -> unsupportedSourceCastStrategy(type);
+            };
+
+    private static CastColumnStrategy castColumnStrategy(
+        final Type targetType, final CastColumnWriter writer) {
+      return new CastColumnStrategy(() -> {}, targetType::createColumnBuilder, writer);
+    }
+
+    private static CastColumnStrategy castBinaryColumnStrategy(
+        final Type sourceType, final Type targetType, final BinaryStringCastWriter writer) {
+      return castColumnStrategy(
+          targetType,
+          (column, index, builder) ->
+              writer.write(
+                  sourceType.getBinary(column, index).getStringValue(TSFileConfig.STRING_CHARSET),
+                  builder));
+    }
+
+    private static CastColumnStrategy unsupportedSourceCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported source dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedTargetCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported target dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedCastStrategy(final String message) {
+      return new CastColumnStrategy(
+          () -> {
+            throw new UnsupportedOperationException(message);
+          },
+          ignored -> {
+            throw new UnsupportedOperationException(message);
+          },
+          (column, index, builder) -> {
+            throw new UnsupportedOperationException(message);
+          });
+    }
+
+    public static final class CastColumnStrategy {
+      private final Runnable validator;
+      private final IntFunction<ColumnBuilder> builderFactory;
+      private final CastColumnWriter writer;
+
+      private CastColumnStrategy(
+          final Runnable validator,
+          final IntFunction<ColumnBuilder> builderFactory,
+          final CastColumnWriter writer) {
+        this.validator = validator;
+        this.builderFactory = builderFactory;
+        this.writer = writer;
+      }
+
+      public void validate() {
+        validator.run();
+      }
+
+      public ColumnBuilder createBuilder(final int expectedEntries) {
+        return builderFactory.apply(expectedEntries);
+      }
+
+      public void cast(final Column column, final int index, final ColumnBuilder builder) {
+        writer.write(column, index, builder);
+      }
+    }
+
+    @FunctionalInterface
+    private interface CastColumnWriter {
+      void write(Column column, int index, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    private interface BinaryStringCastWriter {
+      void write(String value, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    public interface ColumnToDoubleConverter {
+      double convert(Column column, int index) throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface ColumnValueWriter {
+      void write(ColumnBuilder builder, Column column, int index);
+    }
+
+    @FunctionalInterface
+    public interface AlteredDataTypeColumnTransformer {
+      Column transform(Column source, int positionCount);
+    }
+
+    @FunctionalInterface
+    public interface RoundTransformer {
+      void transform(RoundFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface DiffTransformer {
+      void transform(DiffFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface NegationTransformer {
+      void transform(
+          ArithmeticNegationTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface StateWindowSplitter {
+      boolean split(ValueRecorder valueRecorder, double delta, Column values, int index);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerSetInitializer {
+      void initialize(InTransformer transformer, Set<String> values);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerColumnTransformer {
+      void transform(InTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    static {
+      CONSTANT_COLUMN_BUILDER_SERVICE.check();
+      CONSTANT_FILL_SERVICE.check();
+      COLUMN_BUILDER_SERVICE.check();
+      VALUE_TO_DOUBLE_SERVICE.check();
+      TRANSFORM_COLUMN_VALUE_WRITER_SERVICE.check();
+      ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE.check();
+      ROUND_TRANSFORMER_SERVICE.check();
+      DIFF_TRANSFORMER_SERVICE.check();
+      NEGATION_TRANSFORMER_SERVICE.check();
+      STATE_WINDOW_SPLITTER_SERVICE.check();
+      IN_TRANSFORMER_SET_INITIALIZER_SERVICE.check();
+      IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE.check();
+      CAST_COLUMN_SERVICE.check();
+    }
+
+    private Transformation() {
+      // Utility class
+    }
+  }
+
+  public static final class Aggregation {
+
+    public static final TypeService<ExtremeValueAccumulatorStrategy>
+        EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateIntResult(column.getInt(index)),
+                          (accumulator, value) ->
+                              accumulator.updateIntResult(((Number) value).intValue()),
+                          (accumulator, column) -> accumulator.getResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateLongResult(column.getLong(index)),
+                          (accumulator, value) ->
+                              accumulator.updateLongResult(((Number) value).longValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateFloatResult(column.getFloat(index)),
+                          (accumulator, value) ->
+                              accumulator.updateFloatResult(((Number) value).floatValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateDoubleResult(column.getDouble(index)),
+                          (accumulator, value) ->
+                              accumulator.updateDoubleResult(((Number) value).doubleValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case STRING ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateBinaryResult(column.getBinary(index)),
+                          (accumulator, value) -> accumulator.updateBinaryResult((Binary) value),
+                          (accumulator, column) ->
+                              accumulator.getResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN, TEXT, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      ExtremeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<TimeValueAccumulatorStrategy>
+        TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateIntResult(column.getInt(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateIntResult(
+                                  ((Number) getStatisticsValue(statistics, first)).intValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateLongResult(column.getLong(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateLongResult(
+                                  ((Number) getStatisticsValue(statistics, first)).longValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateFloatResult(column.getFloat(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateFloatResult(
+                                  ((Number) getStatisticsValue(statistics, first)).floatValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateDoubleResult(column.getDouble(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateDoubleResult(
+                                  ((Number) getStatisticsValue(statistics, first)).doubleValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBinaryResult(column.getBinary(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBinaryResult(
+                                  getBinaryStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBooleanResult(column.getBoolean(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBooleanResult(
+                                  (boolean) getStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBoolean(column.getBoolean(0)),
+                          (builder, result) -> builder.writeBoolean(result.getBoolean()));
+                  case ROW, UNKNOWN, VECTOR -> TimeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<MaxMinByAccumulatorStrategy>
+        MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateIntResult(
+                                  time, yColumn.getInt(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateIntResult(
+                                  time,
+                                  BytesUtils.bytesToInt(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Integer.BYTES),
+                                  0));
+                  case INT64, TIMESTAMP ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateLongResult(
+                                  time, yColumn.getLong(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateLongResult(
+                                  time,
+                                  BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Long.BYTES),
+                                  0));
+                  case FLOAT ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateFloatResult(
+                                  time, yColumn.getFloat(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateFloatResult(
+                                  time,
+                                  BytesUtils.bytesToFloat(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Float.BYTES),
+                                  0));
+                  case DOUBLE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateDoubleResult(
+                                  time, yColumn.getDouble(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateDoubleResult(
+                                  time,
+                                  BytesUtils.bytesToDouble(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Double.BYTES),
+                                  0));
+                  case STRING ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateBinaryResult(
+                                  time, yColumn.getBinary(yIndex), xColumn, xIndex),
+                          TypeServices.Aggregation::updateBinaryIntermediate);
+                  case TEXT, BLOB, OBJECT -> maxMinByAccumulatorStrategy(type, null, null);
+                  case BOOLEAN -> maxMinByAccumulatorStrategy(type, null, null);
+                  case ROW, UNKNOWN, VECTOR -> MaxMinByAccumulatorStrategy.unsupported(type);
+                };
+
+    public static final TypeService<EventWindowManagerProvider>
+        EVENT_WINDOW_MANAGER_PROVIDER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      eventWindowManagerProvider(
+                          EqualIntWindowManager::new, VariationIntWindowManager::new);
+                  case INT64 ->
+                      eventWindowManagerProvider(
+                          EqualLongWindowManager::new, VariationLongWindowManager::new);
+                  case FLOAT ->
+                      eventWindowManagerProvider(
+                          EqualFloatWindowManager::new, VariationFloatWindowManager::new);
+                  case DOUBLE ->
+                      eventWindowManagerProvider(
+                          EqualDoubleWindowManager::new, VariationDoubleWindowManager::new);
+                  case TEXT -> eventWindowManagerProvider(EqualBinaryWindowManager::new, null);
+                  case BOOLEAN -> eventWindowManagerProvider(EqualBooleanWindowManager::new, null);
+                  case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      EventWindowManagerProvider.unsupported();
+                };
+
+    private static EventWindowManagerProvider eventWindowManagerProvider(
+        final EventWindowManagerFactory equalFactory,
+        final EventWindowManagerFactory variationFactory) {
+      return new EventWindowManagerProvider(equalFactory, variationFactory);
+    }
+
+    private static void updateBinaryIntermediate(
+        final MaxMinByAccumulator accumulator,
+        final long time,
+        final byte[] bytes,
+        final int offset) {
+      final int length = BytesUtils.bytesToInt(bytes, offset);
+      final int valueOffset = offset + Integer.BYTES;
+      accumulator.updateBinaryResult(
+          time,
+          new Binary(BytesUtils.subBytes(bytes, valueOffset, length)),
+          accumulator.readXFromBytesIntermediateInput(bytes, valueOffset + length),
+          0);
+    }
+
+    private static MaxMinByAccumulatorStrategy maxMinByAccumulatorStrategy(
+        final Type type,
+        final MaxMinByYColumnUpdater yColumnUpdater,
+        final MaxMinByYBytesUpdater yBytesUpdater) {
+      return new MaxMinByAccumulatorStrategy(type, true, yColumnUpdater, yBytesUpdater);
+    }
+
+    private static TimeValueAccumulatorStrategy timeValueAccumulatorStrategy(
+        final TimeValueColumnUpdater columnUpdater,
+        final TimeValueStatisticsUpdater statisticsUpdater,
+        final TimeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new TimeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    private static Object getStatisticsValue(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getFirstValue() : statistics.getLastValue();
+    }
+
+    private static long getStatisticsTime(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getStartTime() : statistics.getEndTime();
+    }
+
+    private static Binary getBinaryStatisticsValue(
+        final Statistics<?> statistics, final boolean first) {
+      final Object value = getStatisticsValue(statistics, first);
+      if (statistics instanceof DateStatistics) {
+        return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+      }
+      return value instanceof Binary
+          ? (Binary) value
+          : new Binary(String.valueOf(value), StandardCharsets.UTF_8);
+    }
+
+    public static final class TimeValueAccumulatorStrategy {
+      private final TimeValueColumnUpdater columnUpdater;
+      private final TimeValueStatisticsUpdater statisticsUpdater;
+      private final TimeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private TimeValueAccumulatorStrategy(
+          final TimeValueColumnUpdater columnUpdater,
+          final TimeValueStatisticsUpdater statisticsUpdater,
+          final TimeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static TimeValueAccumulatorStrategy unsupported() {
+        return new TimeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final TimeValueAccumulator accumulator,
+          final Column[] columns,
+          final BitMap bitMap,
+          final boolean stopAfterFirstValue,
+          final boolean bitmapMarksSelected) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && bitmapMarksSelected != bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i, columns[0].getLong(i));
+            if (stopAfterFirstValue) {
+              return;
+            }
+          }
+        }
+      }
+
+      public void addIntermediate(
+          final TimeValueAccumulator accumulator,
+          final Column valueColumn,
+          final Column timeColumn) {
+        columnUpdater.update(accumulator, valueColumn, 0, timeColumn.getLong(0));
+      }
+
+      public void addStatistics(
+          final TimeValueAccumulator accumulator,
+          final Statistics<?> statistics,
+          final boolean first) {
+        statisticsUpdater.update(accumulator, statistics, first);
+      }
+
+      public void setFinal(final TimeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final class MaxMinByAccumulatorStrategy {
+      private final Type type;
+      private final PrimitiveColumnValueSetter xValueSetter;
+      private final boolean xSupported;
+      private final MaxMinByYColumnUpdater yColumnUpdater;
+      private final MaxMinByYBytesUpdater yBytesUpdater;
+
+      private MaxMinByAccumulatorStrategy(
+          final Type type,
+          final boolean xSupported,
+          final MaxMinByYColumnUpdater yColumnUpdater,
+          final MaxMinByYBytesUpdater yBytesUpdater) {
+        this.type = type;
+        this.xValueSetter =
+            org.apache.iotdb.calc.utils.TypeServices.PRIMITIVE_COLUMN_VALUE_SETTER_SERVICE.call(
+                type);
+        this.xSupported = xSupported;
+        this.yColumnUpdater = yColumnUpdater;
+        this.yBytesUpdater = yBytesUpdater;
+      }
+
+      private static MaxMinByAccumulatorStrategy unsupported(final Type type) {
+        return new MaxMinByAccumulatorStrategy(type, false, null, null);
+      }
+
+      public boolean isXSupported() {
+        return xSupported;
+      }
+
+      public boolean isYSupported() {
+        return yColumnUpdater != null;
+      }
+
+      public void addInput(
+          final MaxMinByAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[2].isNull(i)) {
+            yColumnUpdater.update(accumulator, columns[0].getLong(i), columns[2], i, columns[1], i);
+          }
+        }
+      }
+
+      public void setXResult(final TsPrimitiveType result, final Column column, final int index) {
+        // Type.setTo copies the primitive into the column; aggregation must read the input instead.
+        xValueSetter.set(result, column, index);
+      }
+
+      public void writeXResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        type.write(builder, result);
+      }
+
+      public void writeSerializedValue(
+          final byte[] bytes, final int offset, final ColumnBuilder builder) {
+        type.write(builder, bytes, offset);
+      }
+
+      public void updateIntermediate(
+          final MaxMinByAccumulator accumulator,
+          final long time,
+          final byte[] bytes,
+          final int offset) {
+        yBytesUpdater.update(accumulator, time, bytes, offset);
+      }
+    }
+
+    public static final class EventWindowManagerProvider {
+      private static final EventWindowManagerProvider UNSUPPORTED =
+          new EventWindowManagerProvider(null, null);
+
+      private final EventWindowManagerFactory equalFactory;
+      private final EventWindowManagerFactory variationFactory;
+
+      private EventWindowManagerProvider(
+          final EventWindowManagerFactory equalFactory,
+          final EventWindowManagerFactory variationFactory) {
+        this.equalFactory = equalFactory;
+        this.variationFactory = variationFactory;
+      }
+
+      private static EventWindowManagerProvider unsupported() {
+        return UNSUPPORTED;
+      }
+
+      public VariationWindowManager createEqual(
+          final VariationWindowParameter parameter, final boolean ascending) {
+        if (equalFactory == null) {
+          throw new UnSupportedDataTypeException(
+              String.format(
+                  DataNodeQueryMessages
+                      .EXCEPTION_UNSUPPORTED_DATA_TYPE_IN_EQUAL_EVENT_AGGREGATION_ARG_77E085EB,
+                  parameter.getDataType()));
+        }
+        return equalFactory.create(parameter, ascending);
+      }
+
+      public VariationWindowManager createVariation(
+          final VariationWindowParameter parameter, final boolean ascending) {
+        if (variationFactory == null) {
+          throw new UnSupportedDataTypeException(
+              String.format(
+                  DataNodeQueryMessages
+                      .EXCEPTION_UNSUPPORTED_DATA_TYPE_IN_VARIATION_EVENT_AGGREGATION_ARG_3D0F0388,
+                  parameter.getDataType()));
+        }
+        return variationFactory.create(parameter, ascending);
+      }
+    }
+
+    private static ExtremeValueAccumulatorStrategy extremeValueAccumulatorStrategy(
+        final ExtremeValueColumnUpdater columnUpdater,
+        final ExtremeValueStatisticsUpdater statisticsUpdater,
+        final ExtremeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new ExtremeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    public static final class ExtremeValueAccumulatorStrategy {
+      private final ExtremeValueColumnUpdater columnUpdater;
+      private final ExtremeValueStatisticsUpdater statisticsUpdater;
+      private final ExtremeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private ExtremeValueAccumulatorStrategy(
+          final ExtremeValueColumnUpdater columnUpdater,
+          final ExtremeValueStatisticsUpdater statisticsUpdater,
+          final ExtremeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static ExtremeValueAccumulatorStrategy unsupported() {
+        return new ExtremeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final ExtremeValueAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i);
+          }
+        }
+      }
+
+      public void addIntermediate(final ExtremeValueAccumulator accumulator, final Column column) {
+        columnUpdater.update(accumulator, column, 0);
+      }
+
+      public void addStatistics(
+          final ExtremeValueAccumulator accumulator, final Object statisticsValue) {
+        statisticsUpdater.update(accumulator, statisticsValue);
+      }
+
+      public void setFinal(final ExtremeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final TypeService<LongSupplier> OUTPUT_COLUMN_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  () -> type.estimateValueSize() + Byte.BYTES;
+              case TEXT, BLOB, STRING, OBJECT ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages.UNKNOWN_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Supplier<Accumulator>> MODE_ACCUMULATOR_PROVIDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> BooleanModeAccumulator::new;
+              case TEXT, BLOB, STRING -> BinaryModeAccumulator::new;
+              case INT32, DATE -> IntModeAccumulator::new;
+              case INT64, TIMESTAMP -> LongModeAccumulator::new;
+              case FLOAT -> FloatModeAccumulator::new;
+              case DOUBLE -> DoubleModeAccumulator::new;
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new IllegalArgumentException(
+                        DataNodeQueryMessages.UNKNOWN_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    static {
+      EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE.check();
+      TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE.check();
+      MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE.check();
+      EVENT_WINDOW_MANAGER_PROVIDER_SERVICE.check();
+      OUTPUT_COLUMN_SIZE_PER_LINE_SERVICE.check();
+      MODE_ACCUMULATOR_PROVIDER_SERVICE.check();
+    }
+
+    private Aggregation() {
+      // Utility class
+    }
+
+    public interface ExtremeValueAccumulator {
+      TsPrimitiveType getResult();
+
+      void updateIntResult(int value);
+
+      void updateLongResult(long value);
+
+      void updateFloatResult(float value);
+
+      void updateDoubleResult(double value);
+
+      void updateBinaryResult(Binary value);
+    }
+
+    public interface TimeValueAccumulator {
+      TsPrimitiveType getTimeValueResult();
+
+      void updateIntResult(int value, long time);
+
+      void updateLongResult(long value, long time);
+
+      void updateFloatResult(float value, long time);
+
+      void updateDoubleResult(double value, long time);
+
+      void updateBinaryResult(Binary value, long time);
+
+      void updateBooleanResult(boolean value, long time);
+    }
+
+    public interface MaxMinByAccumulator {
+      Column readXFromBytesIntermediateInput(byte[] bytes, int offset);
+
+      void updateIntResult(long time, int yValue, Column xColumn, int xIndex);
+
+      void updateLongResult(long time, long yValue, Column xColumn, int xIndex);
+
+      void updateFloatResult(long time, float yValue, Column xColumn, int xIndex);
+
+      void updateDoubleResult(long time, double yValue, Column xColumn, int xIndex);
+
+      void updateBinaryResult(long time, Binary yValue, Column xColumn, int xIndex);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueColumnUpdater {
+      void update(ExtremeValueAccumulator accumulator, Column column, int index);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueStatisticsUpdater {
+      void update(ExtremeValueAccumulator accumulator, Object value);
+    }
+
+    @FunctionalInterface
+    private interface ExtremeValueFinalSetter {
+      void set(ExtremeValueAccumulator accumulator, Column column);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueColumnUpdater {
+      void update(TimeValueAccumulator accumulator, Column column, int index, long time);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueStatisticsUpdater {
+      void update(TimeValueAccumulator accumulator, Statistics<?> statistics, boolean first);
+    }
+
+    @FunctionalInterface
+    private interface TimeValueFinalSetter {
+      void set(TimeValueAccumulator accumulator, Column column);
+    }
+
+    @FunctionalInterface
+    private interface MaxMinByYColumnUpdater {
+      void update(
+          MaxMinByAccumulator accumulator,
+          long time,
+          Column yColumn,
+          int yIndex,
+          Column xColumn,
+          int xIndex);
+    }
+
+    @FunctionalInterface
+    private interface MaxMinByYBytesUpdater {
+      void update(MaxMinByAccumulator accumulator, long time, byte[] bytes, int offset);
+    }
+
+    @FunctionalInterface
+    private interface EventWindowManagerFactory {
+      VariationWindowManager create(VariationWindowParameter parameter, boolean ascending);
+    }
+  }
+
+  public static final class ValueConversion {
+
+    public static final TypeService<Function<String, Object>> VALUE_PARSER_NO_EXCEPTION_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> Boolean::parseBoolean;
+              case INT32 -> TypeServices::parseInteger;
+              case INT64 -> TypeServices::parseLong;
+              case FLOAT -> TypeServices::parseFloat;
+              case DOUBLE -> TypeServices::parseDouble;
+              case TEXT -> TypeServices::parseText;
+              case TIMESTAMP -> TypeServices::parseTimestamp;
+              case DATE -> TypeServices::parseDate;
+              case BLOB -> TypeServices::parseBlob;
+              case STRING -> TypeServices::parseString;
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ContextualValueParser> VALUE_PARSER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (value, zoneId) -> CommonUtils.parseBoolean(value);
+              case INT32 ->
+                  (value, zoneId) -> {
+                    try {
+                      return Integer.parseInt(StringUtils.trim(value));
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                  };
+              case INT64 ->
+                  (value, zoneId) -> {
+                    try {
+                      return Long.parseLong(StringUtils.trim(value));
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                  };
+              case TIMESTAMP ->
+                  (value, zoneId) -> {
+                    try {
+                      return TypeInferenceUtils.isNumber(value)
+                          ? Long.parseLong(value)
+                          : DataNodeDateTimeUtils.parseDateTimeExpressionToLong(
+                              StringUtils.trim(value), zoneId);
+                    } catch (final Throwable e) {
+                      throw new NumberFormatException(
+                          String.format(
+                              DataNodeMiscMessages
+                                  .EXCEPTION_DATA_TYPE_IS_NOT_CONSISTENT_INPUT_ARG_REGISTERED_ARG_BECAUSE_ARG_C8637858,
+                              value,
+                              type.getTypeEnum(),
+                              e.getMessage()));
+                    }
+                  };
+              case DATE -> (value, zoneId) -> CommonUtils.parseIntFromString(value);
+              case FLOAT ->
+                  (value, zoneId) -> {
+                    final float result;
+                    try {
+                      result = Float.parseFloat(value);
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                    if (Float.isInfinite(result)) {
+                      throw new NumberFormatException(DataNodeMiscMessages.INPUT_FLOAT_INFINITY);
+                    }
+                    return result;
+                  };
+              case DOUBLE ->
+                  (value, zoneId) -> {
+                    final double result;
+                    try {
+                      result = Double.parseDouble(value);
+                    } catch (final NumberFormatException e) {
+                      throw inconsistentValueException(value, type);
+                    }
+                    if (Double.isInfinite(result)) {
+                      throw new NumberFormatException(DataNodeMiscMessages.INPUT_DOUBLE_INFINITY);
+                    }
+                    return result;
+                  };
+              case TEXT, STRING ->
+                  (value, zoneId) ->
+                      new Binary(stripQuotesIfPresent(value), TSFileConfig.STRING_CHARSET);
+              case BLOB ->
+                  (value, zoneId) ->
+                      new Binary(
+                          CommonUtils.parseBlobStringToByteArray(stripQuotesIfPresent(value)));
+              case OBJECT ->
+                  (value, zoneId) -> {
+                    throw inconsistentValueException(value, type);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  (value, zoneId) -> {
+                    throw new QueryProcessException(
+                        DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<java.util.function.Predicate<TSDataType>> AUTO_CAST_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      targetType == TSDataType.INT64
+                          || targetType == TSDataType.FLOAT
+                          || targetType == TSDataType.DOUBLE;
+              case INT64, FLOAT -> targetType -> targetType == TSDataType.DOUBLE;
+              case BOOLEAN, DATE, TIMESTAMP, DOUBLE, TEXT, BLOB, STRING, OBJECT ->
+                  targetType -> false;
+              case ROW, UNKNOWN, VECTOR ->
+                  targetType -> {
+                    throw new IllegalArgumentException(
+                        DataNodeMiscMessages.UNKNOWN_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Function<Object, Pair<Literal, String>>>
+        PREPARED_PARAMETER_LITERAL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      value -> {
+                        final String text = Boolean.toString((Boolean) value);
+                        return new Pair<>(new BooleanLiteral(text), text);
+                      };
+                  case INT32, INT64 ->
+                      value -> {
+                        final String text = String.valueOf(value);
+                        return new Pair<>(new LongLiteral(text), text);
+                      };
+                  case FLOAT ->
+                      value -> new Pair<>(new DoubleLiteral((Float) value), String.valueOf(value));
+                  case DOUBLE ->
+                      value -> new Pair<>(new DoubleLiteral((Double) value), String.valueOf(value));
+                  case TEXT, STRING ->
+                      value -> {
+                        final String text = (String) value;
+                        return new Pair<>(
+                            new StringLiteral(text), "'" + text.replace("'", "''") + "'");
+                      };
+                  case BLOB ->
+                      value -> {
+                        final BinaryLiteral literal = new BinaryLiteral((byte[]) value);
+                        return new Pair<>(literal, "X'" + literal.toHexString() + "'");
+                      };
+                  case DATE, TIMESTAMP, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new IllegalArgumentException(
+                            DataNodeMiscMessages.UNKNOWN_PARAMETER_TYPE + type.getTypeEnum());
+                      };
+                };
+
+    static {
+      VALUE_PARSER_NO_EXCEPTION_SERVICE.check();
+      VALUE_PARSER_SERVICE.check();
+      AUTO_CAST_SERVICE.check();
+      PREPARED_PARAMETER_LITERAL_SERVICE.check();
+    }
+
+    private static NumberFormatException inconsistentValueException(
+        final String value, final Type type) {
+      return new NumberFormatException(
+          String.format(
+              DataNodeMiscMessages
+                  .EXCEPTION_DATA_TYPE_IS_NOT_CONSISTENT_INPUT_ARG_REGISTERED_ARG_0EF32FD3,
+              value,
+              type.getTypeEnum()));
+    }
+
+    private static String stripQuotesIfPresent(final String value) {
+      if ((value.startsWith(SqlConstant.QUOTE) && value.endsWith(SqlConstant.QUOTE))
+          || (value.startsWith(SqlConstant.DQUOTE) && value.endsWith(SqlConstant.DQUOTE))) {
+        return value.length() == 1 ? value : value.substring(1, value.length() - 1);
+      }
+      return value;
+    }
+
+    @FunctionalInterface
+    public interface ContextualValueParser {
+      Object parse(String value, ZoneId zoneId) throws QueryProcessException;
+    }
+
+    private ValueConversion() {
+      // Utility class
+    }
+  }
+
+  public static final class StorageEngine {
+
+    public static final TypeService<ToIntFunction<Object>>
+        INSERT_ROW_SERIALIZED_VALUE_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> value -> Byte.BYTES;
+                  case INT32, DATE, FLOAT -> value -> Integer.BYTES;
+                  case INT64, TIMESTAMP, DOUBLE -> value -> Long.BYTES;
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      value -> ReadWriteIOUtils.sizeToWrite((Binary) value);
+                  case ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnSupportedDataTypeException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<SerializedColumnSizeCalculator>
+        INSERT_TABLET_SERIALIZED_COLUMN_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (column, start, end) -> (end - start) * Byte.BYTES;
+                  case INT32, DATE, FLOAT -> (column, start, end) -> (end - start) * Integer.BYTES;
+                  case INT64, TIMESTAMP, DOUBLE ->
+                      (column, start, end) -> (end - start) * Long.BYTES;
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (column, start, end) -> {
+                        int size = 0;
+                        Binary[] values = (Binary[]) column;
+                        // Tablet and WAL use a length prefix without TsFile's presence byte.
+                        // Count only the selected range, including placeholders for null values.
+                        for (int i = start; i < end; i++) {
+                          byte[] bytes =
+                              values == null || values[i] == null ? null : values[i].getValues();
+                          size += Integer.BYTES + (bytes == null ? 0 : bytes.length);
+                        }
+                        return size;
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      (column, start, end) -> {
+                        throw new UnSupportedDataTypeException(
+                            String.format(
+                                DataNodeQueryMessages
+                                    .QUERY_EXCEPTION_DATA_TYPE_S_IS_NOT_SUPPORTED_5D5C02E4,
+                                type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<RawArrayByteBufferSerializer>
+        RAW_ARRAY_BYTE_BUFFER_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                      type::serializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (column, rows, buffer) -> {
+                        Binary[] values = (Binary[]) column;
+                        // Preserve the Tablet wire format: nullness lives in the separate bitmap.
+                        for (int i = 0; i < rows; i++) {
+                          if (values[i] != null && values[i].getValues() != null) {
+                            ReadWriteIOUtils.write(values[i], buffer);
+                          } else {
+                            buffer.putInt(0);
+                          }
+                        }
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<RawArrayOutputStreamSerializer>
+        RAW_ARRAY_OUTPUT_STREAM_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                      type::serializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (column, rows, stream) -> {
+                        Binary[] values = (Binary[]) column;
+                        // Match the ByteBuffer writer, including zero-length null placeholders.
+                        for (int i = 0; i < rows; i++) {
+                          if (values[i] != null && values[i].getValues() != null) {
+                            ReadWriteIOUtils.write(values[i], stream);
+                          } else {
+                            stream.writeInt(0);
+                          }
+                        }
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Boolean> TABLET_PLAIN_FAST_PATH_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, DATE, INT32, TIMESTAMP, INT64, FLOAT, DOUBLE, STRING, BLOB, TEXT ->
+                  true;
+              case ROW, VECTOR, UNKNOWN, OBJECT -> false;
+            };
+
+    public static final TypeService<AlignedTVListColumnWriter>
+        ALIGNED_TV_LIST_COLUMN_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, !isNull && list.getBooleanByValueIndex(row, column), isNull);
+                  case INT32, DATE ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0 : list.getIntByValueIndex(row, column), isNull);
+                  case INT64, TIMESTAMP ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0L : list.getLongByValueIndex(row, column), isNull);
+                  case FLOAT ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0F : list.getFloatByValueIndex(row, column), isNull);
+                  case DOUBLE ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time, isNull ? 0D : list.getDoubleByValueIndex(row, column), isNull);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, time, list, row, column, isNull) ->
+                          writer.writeByColumn(
+                              time,
+                              isNull ? null : list.getBinaryByValueIndex(row, column),
+                              isNull);
+                  // Preserve the flush path's no-op behavior for non-value types.
+                  case ROW, UNKNOWN, VECTOR -> (writer, time, list, row, column, isNull) -> {};
+                };
+
+    private static final Binary EMPTY_BINARY = new Binary("", StandardCharsets.UTF_8);
+
+    public static final TypeService<ChunkMetadataStatisticsConverter>
+        CHUNK_METADATA_STATISTICS_CONVERTER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, INT64, TIMESTAMP, FLOAT, DOUBLE, BOOLEAN ->
+                      StorageEngine::convertNumericOrBooleanStatistics;
+                  case DATE -> StorageEngine::convertDateStatistics;
+                  case STRING -> StorageEngine::convertStringStatistics;
+                  case TEXT -> StorageEngine::convertTextStatistics;
+                  case BLOB -> StorageEngine::convertBlobStatistics;
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (chunkMetadata, targetDataType, statistics) -> statistics;
+                };
+
+    public static final TypeService<BiConsumer<Object, IWALByteBufferView>>
+        WAL_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (value, buffer) -> WALWriteUtils.write((Boolean) value, buffer);
+                  case INT32, DATE ->
+                      (value, buffer) -> WALWriteUtils.write((Integer) value, buffer);
+                  case INT64, TIMESTAMP ->
+                      (value, buffer) -> WALWriteUtils.write((Long) value, buffer);
+                  case FLOAT -> (value, buffer) -> WALWriteUtils.write((Float) value, buffer);
+                  case DOUBLE -> (value, buffer) -> WALWriteUtils.write((Double) value, buffer);
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (value, buffer) -> WALWriteUtils.write((Binary) value, buffer);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    // Unmaterialized blocks still write zero placeholders; the bitmap carries nullness in WAL.
+    public static final TypeService<WALColumnWriter> WAL_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (column, buffer, start, end) -> {
+                    int[] values = (int[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putInt(values == null ? 0 : values[i]);
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (column, buffer, start, end) -> {
+                    long[] values = (long[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putLong(values == null ? 0L : values[i]);
+                    }
+                  };
+              case FLOAT ->
+                  (column, buffer, start, end) -> {
+                    float[] values = (float[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putFloat(values == null ? 0F : values[i]);
+                    }
+                  };
+              case DOUBLE ->
+                  (column, buffer, start, end) -> {
+                    double[] values = (double[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.putDouble(values == null ? 0D : values[i]);
+                    }
+                  };
+              case BOOLEAN ->
+                  (column, buffer, start, end) -> {
+                    boolean[] values = (boolean[]) column;
+                    for (int i = start; i < end; i++) {
+                      buffer.put((byte) (values != null && values[i] ? 1 : 0));
+                    }
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (column, buffer, start, end) -> {
+                    Binary[] values = (Binary[]) column;
+                    for (int i = start; i < end; i++) {
+                      if (values != null && values[i] != null && values[i].getValues() != null) {
+                        WALWriteUtils.write(values[i], buffer);
+                      } else {
+                        buffer.putInt(0);
+                      }
+                    }
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedValueChunkWriter> DECODED_VALUE_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0 : ReadWriteIOUtils.readInt(stream), isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0L : ReadWriteIOUtils.readLong(stream), isNull);
+              case FLOAT ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0F : ReadWriteIOUtils.readFloat(stream), isNull);
+              case DOUBLE ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, isNull ? 0D : ReadWriteIOUtils.readDouble(stream), isNull);
+              case BOOLEAN ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(time, !isNull && ReadWriteIOUtils.readBool(stream), isNull);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, stream, isNull) ->
+                      writer.write(
+                          time, isNull ? null : ReadWriteIOUtils.readBinary(stream), isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<SegmentedArraySerializedSizeCalculator>
+        SEGMENTED_ARRAY_SERIALIZED_SIZE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (valueArrays, rowCount, arraySize) -> rowCount * Byte.BYTES;
+                  case INT32, DATE ->
+                      (valueArrays, rowCount, arraySize) -> rowCount * Integer.BYTES;
+                  case INT64, TIMESTAMP ->
+                      (valueArrays, rowCount, arraySize) -> rowCount * Long.BYTES;
+                  case FLOAT -> (valueArrays, rowCount, arraySize) -> rowCount * Float.BYTES;
+                  case DOUBLE -> (valueArrays, rowCount, arraySize) -> rowCount * Double.BYTES;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (valueArrays, rowCount, arraySize) -> {
+                        int size = 0;
+                        int remaining = rowCount;
+                        for (Object valueArray : valueArrays) {
+                          int length = Math.min(remaining, arraySize);
+                          // WAL uses length-prefixed binaries, without TsFile array presence bytes.
+                          Binary[] binaryValues = (Binary[]) valueArray;
+                          for (int i = 0; i < length; i++) {
+                            Binary value = binaryValues == null ? null : binaryValues[i];
+                            size += Integer.BYTES;
+                            if (value != null && value.getValues() != null) {
+                              size += value.getLength();
+                            }
+                          }
+                          remaining -= length;
+                          if (remaining == 0) {
+                            break;
+                          }
+                        }
+                        return size;
+                      };
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<ArrayValueColumnWriter> ARRAY_VALUE_COLUMN_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeBoolean(((boolean[]) values)[index]);
+              case INT32 ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeInt(((int[]) values)[index]);
+              case DATE ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    int value = ((int[]) values)[index];
+                    if (builder instanceof BinaryColumnBuilder) {
+                      ((BinaryColumnBuilder) builder).writeDate(value);
+                    } else {
+                      builder.writeInt(value);
+                    }
+                  };
+              case INT64, TIMESTAMP ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeLong(((long[]) values)[index]);
+              case FLOAT ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    float value = ((float[]) values)[index];
+                    if (encoding != null
+                        && !Float.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    builder.writeFloat(value);
+                  };
+              case DOUBLE ->
+                  (builder, values, index, floatPrecision, encoding) -> {
+                    double value = ((double[]) values)[index];
+                    if (encoding != null
+                        && !Double.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    builder.writeDouble(value);
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (builder, values, index, floatPrecision, encoding) ->
+                      builder.writeBinary(((Binary[]) values)[index]);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<BatchDataColumnWriter> BATCH_DATA_COLUMN_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (batchData, time, column, index) ->
+                      batchData.putBoolean(time, type.getBoolean(column, index));
+              case INT32, DATE ->
+                  (batchData, time, column, index) ->
+                      batchData.putInt(time, type.getInt(column, index));
+              case INT64, TIMESTAMP ->
+                  (batchData, time, column, index) ->
+                      batchData.putLong(time, type.getLong(column, index));
+              case FLOAT ->
+                  (batchData, time, column, index) ->
+                      batchData.putFloat(time, type.getFloat(column, index));
+              case DOUBLE ->
+                  (batchData, time, column, index) ->
+                      batchData.putDouble(time, type.getDouble(column, index));
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (batchData, time, column, index) ->
+                      batchData.putBinary(time, type.getBinary(column, index));
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueSerializer<Object>> OBJECT_VALUE_SERIALIZER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> (value, stream) -> ReadWriteIOUtils.write((int) value, stream);
+              case INT64, TIMESTAMP ->
+                  (value, stream) -> ReadWriteIOUtils.write((long) value, stream);
+              case FLOAT -> (value, stream) -> ReadWriteIOUtils.write((float) value, stream);
+              case DOUBLE -> (value, stream) -> ReadWriteIOUtils.write((double) value, stream);
+              case BOOLEAN -> (value, stream) -> ReadWriteIOUtils.write((boolean) value, stream);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (value, stream) -> ReadWriteIOUtils.write((Binary) value, stream);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueSerializer<TsPrimitiveType>>
+        TS_PRIMITIVE_VALUE_SERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getInt(), stream);
+                  case INT64, TIMESTAMP ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getLong(), stream);
+                  case FLOAT -> (value, stream) -> ReadWriteIOUtils.write(value.getFloat(), stream);
+                  case DOUBLE ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getDouble(), stream);
+                  case BOOLEAN ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getBoolean(), stream);
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (value, stream) -> ReadWriteIOUtils.write(value.getBinary(), stream);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Supplier<TsPrimitiveType>>
+        EMPTY_TS_PRIMITIVE_TYPE_FACTORY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, FLOAT, DOUBLE -> type::getTsPrimitiveType;
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::getTsPrimitiveType;
+                  case TIMESTAMP -> Type.fromTsDataType(TSDataType.INT64)::getTsPrimitiveType;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      () ->
+                          Type.fromTsDataType(TSDataType.TEXT)
+                              .getTsPrimitiveType(new Binary("", TSFileConfig.STRING_CHARSET));
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<Function<IoTDBConfig, TSEncoding>> DEFAULT_ENCODING_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> IoTDBConfig::getDefaultBooleanEncoding;
+              case INT32, DATE -> IoTDBConfig::getDefaultInt32Encoding;
+              case INT64, TIMESTAMP -> IoTDBConfig::getDefaultInt64Encoding;
+              case FLOAT -> IoTDBConfig::getDefaultFloatEncoding;
+              case DOUBLE -> IoTDBConfig::getDefaultDoubleEncoding;
+              case TEXT, BLOB, STRING, OBJECT -> IoTDBConfig::getDefaultTextEncoding;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TabletColumnDecoder> TABLET_COLUMN_DECODER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    int[] values = new int[rowCount];
+                    // PlainEncoder uses var int, which may cause compatibility problems.
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] =
+                          encoding == TSEncoding.PLAIN
+                              ? ReadWriteIOUtils.readInt(buffer)
+                              : decoder.readInt(buffer);
+                    }
+                    return values;
+                  };
+              case INT64, TIMESTAMP ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    long[] values = new long[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readLong(buffer);
+                    }
+                    return values;
+                  };
+              case FLOAT ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    float[] values = new float[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readFloat(buffer);
+                    }
+                    return values;
+                  };
+              case DOUBLE ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    double[] values = new double[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readDouble(buffer);
+                    }
+                    return values;
+                  };
+              case BOOLEAN ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    boolean[] values = new boolean[rowCount];
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] = decoder.readBoolean(buffer);
+                    }
+                    return values;
+                  };
+              case TEXT, BLOB, STRING ->
+                  (decoder, buffer, rowCount, encoding) -> {
+                    Binary[] values = new Binary[rowCount];
+                    // PlainEncoder uses var int, which may cause compatibility problems.
+                    for (int i = 0; i < rowCount; i++) {
+                      values[i] =
+                          encoding == TSEncoding.PLAIN
+                              ? ReadWriteIOUtils.readBinary(buffer)
+                              : decoder.readBinary(buffer);
+                    }
+                    return values;
+                  };
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedArrayValueReader> DECODED_ARRAY_VALUE_READER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (values, index, stream) ->
+                      ((int[]) values)[index] = ReadWriteIOUtils.readInt(stream);
+              case INT64, TIMESTAMP ->
+                  (values, index, stream) ->
+                      ((long[]) values)[index] = ReadWriteIOUtils.readLong(stream);
+              case FLOAT ->
+                  (values, index, stream) ->
+                      ((float[]) values)[index] = ReadWriteIOUtils.readFloat(stream);
+              case DOUBLE ->
+                  (values, index, stream) ->
+                      ((double[]) values)[index] = ReadWriteIOUtils.readDouble(stream);
+              case BOOLEAN ->
+                  (values, index, stream) ->
+                      ((boolean[]) values)[index] = ReadWriteIOUtils.readBool(stream);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (values, index, stream) ->
+                      ((Binary[]) values)[index] = ReadWriteIOUtils.readBinary(stream);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<DecodedChunkWriter> DECODED_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readInt(stream));
+              case INT64, TIMESTAMP ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readLong(stream));
+              case FLOAT ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readFloat(stream));
+              case DOUBLE ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readDouble(stream));
+              case BOOLEAN ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readBool(stream));
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, stream) -> writer.write(time, ReadWriteIOUtils.readBinary(stream));
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListArrayWriter> TV_LIST_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putBooleans(times, (boolean[]) values, bitMap, start, end);
+              case INT32, DATE ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putInts(times, (int[]) values, bitMap, start, end);
+              case INT64, TIMESTAMP ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putLongs(times, (long[]) values, bitMap, start, end);
+              case FLOAT ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putFloats(times, (float[]) values, bitMap, start, end);
+              case DOUBLE ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putDoubles(times, (double[]) values, bitMap, start, end);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (tvList, times, values, bitMap, start, end) ->
+                      tvList.putBinaries(times, (Binary[]) values, bitMap, start, end);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListObjectWriter> TV_LIST_OBJECT_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (tvList, time, value) -> tvList.putBoolean(time, (boolean) value);
+              case INT32, DATE -> (tvList, time, value) -> tvList.putInt(time, (int) value);
+              case INT64, TIMESTAMP -> (tvList, time, value) -> tvList.putLong(time, (long) value);
+              case FLOAT -> (tvList, time, value) -> tvList.putFloat(time, (float) value);
+              case DOUBLE -> (tvList, time, value) -> tvList.putDouble(time, (double) value);
+              case TEXT, BLOB, STRING ->
+                  (tvList, time, value) -> tvList.putBinary(time, (Binary) value);
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    private static final TVListProvider UNSUPPORTED_TV_LIST_PROVIDER =
+        new TVListProvider(() -> null, stream -> null, stream -> null);
+
+    public static final TypeService<TVListProvider> TV_LIST_PROVIDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  new TVListProvider(
+                      BooleanTVList::newList,
+                      BooleanTVList::deserialize,
+                      BooleanTVList::deserializeWithoutBitMap);
+              case INT32 ->
+                  new TVListProvider(
+                      () -> IntTVList.newList(TSDataType.INT32),
+                      stream -> IntTVList.deserialize(stream, TSDataType.INT32),
+                      stream -> IntTVList.deserializeWithoutBitMap(stream, TSDataType.INT32));
+              case DATE ->
+                  new TVListProvider(
+                      () -> IntTVList.newList(TSDataType.DATE),
+                      stream -> IntTVList.deserialize(stream, TSDataType.DATE),
+                      stream -> IntTVList.deserializeWithoutBitMap(stream, TSDataType.DATE));
+              case INT64, TIMESTAMP ->
+                  new TVListProvider(
+                      LongTVList::newList,
+                      LongTVList::deserialize,
+                      LongTVList::deserializeWithoutBitMap);
+              case FLOAT ->
+                  new TVListProvider(
+                      FloatTVList::newList,
+                      FloatTVList::deserialize,
+                      FloatTVList::deserializeWithoutBitMap);
+              case DOUBLE ->
+                  new TVListProvider(
+                      DoubleTVList::newList,
+                      DoubleTVList::deserialize,
+                      DoubleTVList::deserializeWithoutBitMap);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  new TVListProvider(
+                      BinaryTVList::newList,
+                      BinaryTVList::deserialize,
+                      BinaryTVList::deserializeWithoutBitMap);
+              case ROW, UNKNOWN, VECTOR -> UNSUPPORTED_TV_LIST_PROVIDER;
+            };
+
+    public static final TypeService<TVListChunkWriter> TV_LIST_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getBoolean(index));
+                    return 8L + 1L;
+                  };
+              case INT32, DATE ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getInt(index));
+                    return 8L + 4L;
+                  };
+              case INT64, TIMESTAMP ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getLong(index));
+                    return 8L + 8L;
+                  };
+              case FLOAT ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getFloat(index));
+                    return 8L + 4L;
+                  };
+              case DOUBLE ->
+                  (writer, time, tvList, index) -> {
+                    writer.write(time, tvList.getDouble(index));
+                    return 8L + 8L;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, tvList, index) -> {
+                    Binary value = tvList.getBinary(index);
+                    writer.write(time, value);
+                    return 8L + MemUtils.getBinarySize(value);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<TVListBatchWriter> TV_LIST_BATCH_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    boolean value = tvList.getBoolean(index);
+                    if (filter != null && !filter.satisfyBoolean(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeBoolean(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case INT32, DATE ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    int value = tvList.getInt(index);
+                    if (filter != null && !filter.satisfyInteger(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeInt(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case INT64, TIMESTAMP ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    long value = tvList.getLong(index);
+                    if (filter != null && !filter.satisfyLong(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeLong(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case FLOAT ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    float value = tvList.getFloat(index);
+                    if (!Float.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    if (filter != null && !filter.satisfyFloat(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeFloat(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case DOUBLE ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    double value = tvList.getDouble(index);
+                    if (!Double.isNaN(value)
+                        && (encoding == TSEncoding.RLE || encoding == TSEncoding.TS_2DIFF)) {
+                      value = MathUtils.roundWithGivenPrecision(value, floatPrecision);
+                    }
+                    if (filter != null && !filter.satisfyDouble(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeDouble(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (tvList, index, time, filter, builder, floatPrecision, encoding, pagination) -> {
+                    Binary value = tvList.getBinary(index);
+                    if (filter != null && !filter.satisfyBinary(time, value)) {
+                      return false;
+                    }
+                    if (consumeOffset(pagination)) {
+                      return true;
+                    }
+                    consumeLimit(pagination);
+                    builder.getTimeColumnBuilder().writeLong(time);
+                    builder.getColumnBuilder(0).writeBinary(value);
+                    builder.declarePosition();
+                    return true;
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    private static boolean consumeOffset(PaginationController paginationController) {
+      if (paginationController != null && paginationController.hasCurOffset()) {
+        paginationController.consumeOffset();
+        return true;
+      }
+      return false;
+    }
+
+    private static void consumeLimit(PaginationController paginationController) {
+      if (paginationController != null) {
+        paginationController.consumeLimit();
+      }
+    }
+
+    public static final TypeService<AlignedTVListChunkWriter> ALIGNED_TV_LIST_CHUNK_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? false : tvList.getBooleanByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case INT32, DATE ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0 : tvList.getIntByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0L : tvList.getLongByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case FLOAT ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0F : tvList.getFloatByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case DOUBLE ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? 0D : tvList.getDoubleByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (writer, time, tvList, rowIndex, columnIndex, isNull) ->
+                      writer.write(
+                          time,
+                          isNull ? null : tvList.getBinaryByValueIndex(rowIndex, columnIndex),
+                          isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueChunkArrayWriter> VALUE_CHUNK_ARRAY_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, !isNull && values != null && ((boolean[]) values)[index], isNull);
+              case INT32, DATE ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0 : ((int[]) values)[index], isNull);
+              case INT64, TIMESTAMP ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0L : ((long[]) values)[index], isNull);
+              case FLOAT ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0F : ((float[]) values)[index], isNull);
+              case DOUBLE ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time, isNull || values == null ? 0D : ((double[]) values)[index], isNull);
+              case TEXT, STRING, BLOB, OBJECT ->
+                  (writer, time, values, index, isNull) ->
+                      writer.write(
+                          time,
+                          isNull || values == null ? null : ((Binary[]) values)[index],
+                          isNull);
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ValueChunkArrayBatchWriter>
+        VALUE_CHUNK_ARRAY_BATCH_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (boolean[]) values, nulls, count, offset);
+                  case INT32, DATE ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (int[]) values, nulls, count, offset);
+                  case INT64, TIMESTAMP ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (long[]) values, nulls, count, offset);
+                  case FLOAT ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (float[]) values, nulls, count, offset);
+                  case DOUBLE ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (double[]) values, nulls, count, offset);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, times, values, nulls, offset, count) ->
+                          writer.write(times, (Binary[]) values, nulls, count, offset);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    // Preserve the bitmap path so nulls do not require a temporary boolean array or value encoding.
+    public static final TypeService<ValueChunkArrayBitmapWriter>
+        VALUE_CHUNK_ARRAY_BITMAP_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (boolean[]) values, bitMap, offset, count, offset);
+                  case INT32, DATE ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (int[]) values, bitMap, offset, count, offset);
+                  case INT64, TIMESTAMP ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (long[]) values, bitMap, offset, count, offset);
+                  case FLOAT ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (float[]) values, bitMap, offset, count, offset);
+                  case DOUBLE ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (double[]) values, bitMap, offset, count, offset);
+                  case TEXT, STRING, BLOB, OBJECT ->
+                      (writer, times, values, bitMap, offset, count) ->
+                          writer
+                              .getPageWriter()
+                              .write(times, (Binary[]) values, bitMap, offset, count, offset);
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(
+                              DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<IntFunction<Object>> PRIMITIVE_ARRAY_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE, TEXT, BLOB, STRING, OBJECT ->
+                  type::createArray;
+              case DATE -> Type.fromTsDataType(TSDataType.INT32)::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<SourceColumnToTabletValueWriter>
+        SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((boolean[]) targetColumn)[targetIndex] =
+                              sourceType.getBoolean(sourceColumn, sourceIndex);
+                  case INT32, DATE ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((int[]) targetColumn)[targetIndex] =
+                              sourceType.getInt(sourceColumn, sourceIndex);
+                  case INT64, TIMESTAMP ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((long[]) targetColumn)[targetIndex] =
+                              sourceType.getLong(sourceColumn, sourceIndex);
+                  case FLOAT ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((float[]) targetColumn)[targetIndex] =
+                              sourceType.getFloat(sourceColumn, sourceIndex);
+                  case DOUBLE ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((double[]) targetColumn)[targetIndex] =
+                              sourceType.getDouble(sourceColumn, sourceIndex);
+                  case TEXT, BLOB, STRING ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) ->
+                          ((Binary[]) targetColumn)[targetIndex] =
+                              sourceType.getBinary(sourceColumn, sourceIndex);
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (sourceType, sourceColumn, sourceIndex, targetColumn, targetIndex) -> {
+                        throw new UnSupportedDataTypeException(
+                            DataNodeMiscMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<Object>> TABLET_COLUMN_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<IntFunction<Object>> EMPTY_TABLET_COLUMN_FACTORY_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::createArray;
+              case DATE ->
+                  size -> {
+                    LocalDate[] values = (LocalDate[]) type.createArray(size);
+                    Arrays.fill(values, LocalDate.of(1000, 1, 1));
+                    return values;
+                  };
+              case TEXT, BLOB, STRING ->
+                  size -> {
+                    Binary[] values = (Binary[]) type.createArray(size);
+                    Arrays.fill(values, Binary.EMPTY_VALUE);
+                    return values;
+                  };
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<WindowValueArrayBuilder> WINDOW_VALUE_ARRAY_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE ->
+                  (window, list, begin, size) -> {
+                    int[] values = new int[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getIntByIndex(begin + i);
+                    }
+                    window.setIntValues(values);
+                  };
+              case INT64, TIMESTAMP ->
+                  (window, list, begin, size) -> {
+                    long[] values = new long[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getLongByIndex(begin + i);
+                    }
+                    window.setLongValues(values);
+                  };
+              case FLOAT ->
+                  (window, list, begin, size) -> {
+                    float[] values = new float[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getFloatByIndex(begin + i);
+                    }
+                    window.setFloatValues(values);
+                  };
+              case DOUBLE ->
+                  (window, list, begin, size) -> {
+                    double[] values = new double[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getDoubleByIndex(begin + i);
+                    }
+                    window.setDoubleValues(values);
+                  };
+              case BOOLEAN ->
+                  (window, list, begin, size) -> {
+                    boolean[] values = new boolean[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getBooleanByIndex(begin + i);
+                    }
+                    window.setBooleanValues(values);
+                  };
+              case TEXT, BLOB, STRING, OBJECT ->
+                  (window, list, begin, size) -> {
+                    Binary[] values = new Binary[size];
+                    for (int i = 0; i < size; i++) {
+                      values[i] = list.getBinaryByIndex(begin + i);
+                    }
+                    window.setBinaryValues(values);
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<BiFunction<ByteBuffer, Integer, Object>>
+        RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::deserializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (buffer, size) -> {
+                        // Tablet RPC has no per-value presence byte; nulls use a separate bitmap.
+                        Binary[] values = new Binary[size];
+                        for (int i = 0; i < size; i++) {
+                          values[i] = ReadWriteIOUtils.readBinary(buffer);
+                        }
+                        return values;
+                      };
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::deserializeArray;
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<RawArrayInputStreamDeserializer>
+        RAW_ARRAY_INPUT_STREAM_DESERIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN, INT32, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::deserializeArray;
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      (stream, size) -> {
+                        // Match the ByteBuffer tablet reader, not TsFile's array wire format.
+                        Binary[] values = new Binary[size];
+                        for (int i = 0; i < size; i++) {
+                          values[i] = ReadWriteIOUtils.readBinary(stream);
+                        }
+                        return values;
+                      };
+                  case DATE -> Type.fromTsDataType(TSDataType.INT32)::deserializeArray;
+                  case ROW, UNKNOWN, VECTOR ->
+                      throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                          .setChecked(true);
+                };
+
+    public static final TypeService<ArrayValueGetter> ARRAY_VALUE_GETTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> (array, index) -> ((boolean[]) array)[index];
+              case INT32, DATE -> (array, index) -> ((int[]) array)[index];
+              case INT64, TIMESTAMP -> (array, index) -> ((long[]) array)[index];
+              case FLOAT -> (array, index) -> ((float[]) array)[index];
+              case DOUBLE -> (array, index) -> ((double[]) array)[index];
+              case TEXT, BLOB, STRING, OBJECT -> (array, index) -> ((Binary[]) array)[index];
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(type.getTypeEnum().name())
+                      .setChecked(true);
+            };
+
+    static {
+      CHUNK_METADATA_STATISTICS_CONVERTER_SERVICE.check();
+      INSERT_ROW_SERIALIZED_VALUE_SIZE_SERVICE.check();
+      INSERT_TABLET_SERIALIZED_COLUMN_SIZE_SERVICE.check();
+      RAW_ARRAY_BYTE_BUFFER_SERIALIZER_SERVICE.check();
+      RAW_ARRAY_OUTPUT_STREAM_SERIALIZER_SERVICE.check();
+      TABLET_PLAIN_FAST_PATH_SERVICE.check();
+      ALIGNED_TV_LIST_COLUMN_WRITER_SERVICE.check();
+      TV_LIST_ARRAY_WRITER_SERVICE.check();
+      TV_LIST_OBJECT_WRITER_SERVICE.check();
+      TV_LIST_PROVIDER_SERVICE.check();
+      TV_LIST_CHUNK_WRITER_SERVICE.check();
+      TV_LIST_BATCH_WRITER_SERVICE.check();
+      ALIGNED_TV_LIST_CHUNK_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_BATCH_WRITER_SERVICE.check();
+      VALUE_CHUNK_ARRAY_BITMAP_WRITER_SERVICE.check();
+      PRIMITIVE_ARRAY_ALLOCATOR_SERVICE.check();
+      SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE.check();
+      TABLET_COLUMN_ALLOCATOR_SERVICE.check();
+      EMPTY_TABLET_COLUMN_FACTORY_SERVICE.check();
+      WINDOW_VALUE_ARRAY_BUILDER_SERVICE.check();
+      RAW_ARRAY_BYTE_BUFFER_DESERIALIZER_SERVICE.check();
+      RAW_ARRAY_INPUT_STREAM_DESERIALIZER_SERVICE.check();
+      ARRAY_VALUE_GETTER_SERVICE.check();
+      DECODED_VALUE_CHUNK_WRITER_SERVICE.check();
+      SEGMENTED_ARRAY_SERIALIZED_SIZE_SERVICE.check();
+      ARRAY_VALUE_COLUMN_WRITER_SERVICE.check();
+      BATCH_DATA_COLUMN_WRITER_SERVICE.check();
+      OBJECT_VALUE_SERIALIZER_SERVICE.check();
+      TS_PRIMITIVE_VALUE_SERIALIZER_SERVICE.check();
+      EMPTY_TS_PRIMITIVE_TYPE_FACTORY_SERVICE.check();
+      DEFAULT_ENCODING_SERVICE.check();
+      TABLET_COLUMN_DECODER_SERVICE.check();
+      DECODED_ARRAY_VALUE_READER_SERVICE.check();
+      DECODED_CHUNK_WRITER_SERVICE.check();
+    }
+
+    private static Statistics<?> convertNumericOrBooleanStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING) {
+        Binary[] binaryValues = new Binary[4];
+        binaryValues[0] =
+            new Binary(
+                chunkMetadata.getStatistics().getFirstValue().toString(), StandardCharsets.UTF_8);
+        binaryValues[1] =
+            new Binary(
+                chunkMetadata.getStatistics().getLastValue().toString(), StandardCharsets.UTF_8);
+        if (chunkMetadata.getDataType() == TSDataType.BOOLEAN) {
+          binaryValues[2] = new Binary(Boolean.FALSE.toString(), StandardCharsets.UTF_8);
+          binaryValues[3] = new Binary(Boolean.TRUE.toString(), StandardCharsets.UTF_8);
+        } else {
+          binaryValues[2] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8);
+          binaryValues[3] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8);
+        }
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.TEXT) {
+        Binary[] binaryValues = new Binary[2];
+        if (chunkMetadata.getDataType() == TSDataType.BOOLEAN) {
+          binaryValues[0] = new Binary(Boolean.FALSE.toString(), StandardCharsets.UTF_8);
+          binaryValues[1] = new Binary(Boolean.TRUE.toString(), StandardCharsets.UTF_8);
+        } else {
+          binaryValues[0] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8);
+          binaryValues[1] =
+              new Binary(
+                  chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8);
+        }
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertDateStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType != TSDataType.STRING && targetDataType != TSDataType.TEXT) {
+        return statistics;
+      }
+      int valueCount = targetDataType == TSDataType.STRING ? 4 : 2;
+      Binary[] binaryValues = new Binary[valueCount];
+      binaryValues[0] = toDateBinary(chunkMetadata.getStatistics().getFirstValue());
+      binaryValues[1] = toDateBinary(chunkMetadata.getStatistics().getLastValue());
+      if (targetDataType == TSDataType.STRING) {
+        binaryValues[2] = toDateBinary(chunkMetadata.getStatistics().getMinValue());
+        binaryValues[3] = toDateBinary(chunkMetadata.getStatistics().getMaxValue());
+      }
+      updateStatistics(statistics, chunkMetadata, binaryValues);
+      return statistics;
+    }
+
+    private static Statistics<?> convertStringStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.TEXT) {
+        Binary[] binaryValues = {
+          new Binary(
+              chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8),
+          new Binary(chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8)
+        };
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.BLOB) {
+        statistics.update(
+            chunkMetadata.getStatistics().getStartTime(),
+            new Binary(
+                chunkMetadata.getStatistics().getMinValue().toString(), StandardCharsets.UTF_8));
+        statistics.update(
+            chunkMetadata.getStatistics().getEndTime(),
+            new Binary(
+                chunkMetadata.getStatistics().getMaxValue().toString(), StandardCharsets.UTF_8));
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertTextStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING) {
+        Binary[] binaryValues = {
+          (Binary) chunkMetadata.getStatistics().getFirstValue(),
+          (Binary) chunkMetadata.getStatistics().getLastValue()
+        };
+        updateStatistics(statistics, chunkMetadata, binaryValues);
+        return statistics;
+      }
+      if (targetDataType == TSDataType.BLOB) {
+        statistics.update(chunkMetadata.getStatistics().getStartTime(), EMPTY_BINARY);
+        statistics.update(chunkMetadata.getStatistics().getEndTime(), EMPTY_BINARY);
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Statistics<?> convertBlobStatistics(
+        IChunkMetadata chunkMetadata, TSDataType targetDataType, Statistics<?> statistics) {
+      if (targetDataType == TSDataType.STRING || targetDataType == TSDataType.TEXT) {
+        updateStatistics(statistics, chunkMetadata, new Binary[] {EMPTY_BINARY, EMPTY_BINARY});
+        return statistics;
+      }
+      return chunkMetadata.getStatistics();
+    }
+
+    private static Binary toDateBinary(Object value) {
+      return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+    }
+
+    private static void updateStatistics(
+        Statistics<?> statistics, IChunkMetadata chunkMetadata, Binary[] binaryValues) {
+      long[] longValues = new long[binaryValues.length];
+      longValues[0] = chunkMetadata.getStatistics().getStartTime();
+      longValues[1] = chunkMetadata.getStatistics().getEndTime();
+      Arrays.fill(longValues, 2, longValues.length, longValues[1]);
+      statistics.update(longValues, binaryValues, binaryValues.length);
+    }
+
+    private StorageEngine() {
+      // Utility class
+    }
+  }
+
+  public static final class Predicate {
+
+    public static final TypeService<Function<String, Comparable<?>>>
+        CONVERT_PREDICATE_VALUE_PARSER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> Integer::valueOf;
+                  case INT64, TIMESTAMP -> Long::valueOf;
+                  case FLOAT -> Float::valueOf;
+                  case DOUBLE -> Double::valueOf;
+                  case BOOLEAN ->
+                      valueString -> {
+                        if (valueString.equalsIgnoreCase("true")) {
+                          return Boolean.TRUE;
+                        } else if (valueString.equalsIgnoreCase("false")) {
+                          return Boolean.FALSE;
+                        }
+                        throw new IllegalArgumentException(
+                            String.format(
+                                DataNodeQueryMessages.EXCEPTION_ARG_CANNOT_BE_CAST_TO_ARG_28F0C5FC,
+                                valueString,
+                                type.getTypeEnum()));
+                      };
+                  case BLOB -> valueString -> new Binary(BaseEncoding.base16().decode(valueString));
+                  case TEXT, STRING ->
+                      valueString -> new Binary(valueString, TSFileConfig.STRING_CHARSET);
+                  case DATE -> DateTimeUtils::parseDateExpressionToInt;
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new UnsupportedOperationException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()));
+                };
+
+    public static final TypeService<Function<Literal, Comparable<?>>>
+        RELATIONAL_CONVERT_PREDICATE_VALUE_PARSER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> Integer.valueOf((int) getLongValue(value));
+                  case DATE -> value -> Integer.valueOf(((GenericLiteral) value).getValue());
+                  case INT64 -> value -> Long.valueOf(getLongValue(value));
+                  case TIMESTAMP -> TypeServices::getTimestampValue;
+                  case FLOAT -> value -> Float.valueOf((float) getDoubleValue(value));
+                  case DOUBLE -> value -> Double.valueOf(getDoubleValue(value));
+                  case BOOLEAN -> value -> Boolean.valueOf(((BooleanLiteral) value).getValue());
+                  case TEXT, STRING ->
+                      value ->
+                          new Binary(
+                              ((StringLiteral) value).getValue(), TSFileConfig.STRING_CHARSET);
+                  case BLOB -> value -> new Binary(((BinaryLiteral) value).getValue());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new UnsupportedOperationException(
+                          String.format(
+                              DataNodeQueryMessages.EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_751BF348,
+                              type.getTypeEnum()));
+                };
+
+    public static final TypeService<Function<Column, Literal>>
+        UNCORRELATED_SCALAR_SUBQUERY_RESULT_LITERAL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      column -> new LongLiteral(Long.toString(type.getInt(column, 0)));
+                  case INT64, TIMESTAMP ->
+                      column -> new LongLiteral(Long.toString(type.getLong(column, 0)));
+                  case FLOAT -> column -> new FloatLiteral(type.getFloat(column, 0));
+                  case DOUBLE ->
+                      column -> new DoubleLiteral(Double.toString(type.getDouble(column, 0)));
+                  case BOOLEAN ->
+                      column -> new BooleanLiteral(Boolean.toString(type.getBoolean(column, 0)));
+                  case BLOB -> column -> new BinaryLiteral(type.getBinary(column, 0).toString());
+                  case TEXT, STRING ->
+                      column -> new StringLiteral(type.getBinary(column, 0).toString());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      throw new IllegalArgumentException(
+                          String.format(
+                              DataNodeQueryMessages
+                                  .EXCEPTION_UNSUPPORTED_DATA_TYPE_FOR_SCALAR_SUBQUERY_RESULT_ARG_D58CBB00,
+                              type.getTypeEnum()));
+                };
+
+    private Predicate() {
+      // Utility class
+    }
+  }
+
+  public static final class Pipe {
+
+    public static final TypeService<Function<Object, Object>> OPC_UA_LAST_VALUE_CONVERTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case DATE ->
+                  value ->
+                      new DateTime(
+                          new java.util.Date(
+                              DateUtils.parseIntToDate(((Number) value).intValue()).getTime()));
+              case TIMESTAMP ->
+                  value ->
+                      new DateTime(
+                          TimestampPrecisionUtils.currPrecision.toNanos(
+                                      ((Number) value).longValue())
+                                  / 100L
+                              + 116444736000000000L);
+              case TEXT, BLOB, STRING -> String::valueOf;
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE -> Function.identity();
+              case ROW, VECTOR, OBJECT, UNKNOWN ->
+                  value -> {
+                    throw new UnSupportedDataTypeException(
+                        DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<SameTypeNumericOperatorStrategy>
+        SAME_TYPE_NUMERIC_OPERATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.INT32,
+                          AbstractSameTypeNumericOperator::getIntValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getIntValue(), stream),
+                          (operator, buffer) ->
+                              operator.setIntValue(ReadWriteIOUtils.readInt(buffer)));
+                  case INT64 ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.INT64,
+                          AbstractSameTypeNumericOperator::getLongValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getLongValue(), stream),
+                          (operator, buffer) ->
+                              operator.setLongValue(ReadWriteIOUtils.readLong(buffer)));
+                  case FLOAT ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.FLOAT,
+                          AbstractSameTypeNumericOperator::getFloatValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getFloatValue(), stream),
+                          (operator, buffer) ->
+                              operator.setFloatValue(ReadWriteIOUtils.readFloat(buffer)));
+                  case DOUBLE ->
+                      sameTypeNumericOperatorStrategy(
+                          TSDataType.DOUBLE,
+                          AbstractSameTypeNumericOperator::getDoubleValue,
+                          (operator, stream) ->
+                              ReadWriteIOUtils.write(operator.getDoubleValue(), stream),
+                          (operator, buffer) ->
+                              operator.setDoubleValue(ReadWriteIOUtils.readDouble(buffer)));
+                  case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      unsupportedSameTypeNumericOperatorStrategy(
+                          TSDataType.valueOf(type.getTypeEnum().name()));
+                };
+
+    private static SameTypeNumericOperatorStrategy sameTypeNumericOperatorStrategy(
+        final TSDataType dataType,
+        final Function<AbstractSameTypeNumericOperator, Object> valueGetter,
+        final SameTypeNumericOperatorSerializer serializer,
+        final SameTypeNumericOperatorDeserializer deserializer) {
+      return new SameTypeNumericOperatorStrategy(dataType, valueGetter, serializer, deserializer);
+    }
+
+    private static SameTypeNumericOperatorStrategy unsupportedSameTypeNumericOperatorStrategy(
+        final TSDataType dataType) {
+      return new SameTypeNumericOperatorStrategy(
+          dataType,
+          operator -> null,
+          (operator, stream) -> {
+            throw new IOException(
+                String.format(DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT, dataType));
+          },
+          (operator, buffer) -> {
+            throw new IOException(
+                String.format(DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT, dataType));
+          });
+    }
+
+    public static final class SameTypeNumericOperatorStrategy {
+      private final TSDataType dataType;
+      private final Function<AbstractSameTypeNumericOperator, Object> valueGetter;
+      private final SameTypeNumericOperatorSerializer serializer;
+      private final SameTypeNumericOperatorDeserializer deserializer;
+
+      private SameTypeNumericOperatorStrategy(
+          final TSDataType dataType,
+          final Function<AbstractSameTypeNumericOperator, Object> valueGetter,
+          final SameTypeNumericOperatorSerializer serializer,
+          final SameTypeNumericOperatorDeserializer deserializer) {
+        this.dataType = dataType;
+        this.valueGetter = valueGetter;
+        this.serializer = serializer;
+        this.deserializer = deserializer;
+      }
+
+      public Pair<TSDataType, Object> getResult(final AbstractSameTypeNumericOperator operator) {
+        final Object value = valueGetter.apply(operator);
+        return value == null ? null : new Pair<>(dataType, value);
+      }
+
+      public void serialize(
+          final AbstractSameTypeNumericOperator operator, final DataOutputStream stream)
+          throws IOException {
+        serializer.serialize(operator, stream);
+      }
+
+      public void deserialize(
+          final AbstractSameTypeNumericOperator operator, final ByteBuffer buffer)
+          throws IOException {
+        deserializer.deserialize(operator, buffer);
+      }
+    }
+
+    @FunctionalInterface
+    private interface SameTypeNumericOperatorSerializer {
+      void serialize(AbstractSameTypeNumericOperator operator, DataOutputStream stream)
+          throws IOException;
+    }
+
+    @FunctionalInterface
+    private interface SameTypeNumericOperatorDeserializer {
+      void deserialize(AbstractSameTypeNumericOperator operator, ByteBuffer buffer)
+          throws IOException;
+    }
+
+    public static final TypeService<Short> OPC_DA_VARIANT_TYPE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN -> Variant.VT_BOOL;
+              case INT32 -> Variant.VT_I4;
+              case INT64 -> Variant.VT_I8;
+              case DATE, TIMESTAMP -> Variant.VT_DATE;
+              case FLOAT -> Variant.VT_R4;
+              case DOUBLE -> Variant.VT_R8;
+              // Note that "Variant" does not support "VT_BLOB" data, and not all the DA servers
+              // support this, thus we use "VT_BSTR" to substitute.
+              case TEXT, STRING, BLOB, OBJECT -> Variant.VT_BSTR;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<OpcDaTabletValueSetter> OPC_DA_TABLET_VALUE_SETTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_BOOL, new OaIdl.VARIANT_BOOL(((boolean[]) column)[rowIndex]));
+                    return null;
+                  };
+              case INT32 ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_I4, new WinDef.LONG(((int[]) column)[rowIndex]));
+                    return null;
+                  };
+              case DATE ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_DATE,
+                        new OaIdl.DATE(Date.valueOf(((LocalDate[]) column)[rowIndex])));
+                    return null;
+                  };
+              case INT64 ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_I8, new WinDef.LONGLONG(((long[]) column)[rowIndex]));
+                    return null;
+                  };
+              case TIMESTAMP ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(
+                        Variant.VT_DATE,
+                        new OaIdl.DATE(new java.util.Date(((long[]) column)[rowIndex])));
+                    return null;
+                  };
+              case FLOAT ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_R4, ((float[]) column)[rowIndex]);
+                    return null;
+                  };
+              case DOUBLE ->
+                  (value, column, rowIndex) -> {
+                    value.setValue(Variant.VT_R8, ((double[]) column)[rowIndex]);
+                    return null;
+                  };
+              case TEXT, STRING, BLOB, OBJECT ->
+                  (value, column, rowIndex) -> {
+                    final WTypes.BSTR bstr =
+                        OleAuto.INSTANCE.SysAllocString(((Binary[]) column)[rowIndex].toString());
+                    value.setValue(Variant.VT_BSTR, bstr);
+                    return bstr;
+                  };
+              case ROW, UNKNOWN, VECTOR ->
+                  (value, column, rowIndex) -> {
+                    throw new UnSupportedDataTypeException(
+                        DataNodePipeMessages.UNSUPPORTED_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<Function<Object, String>> OPC_UA_VALUE_STRINGIFIER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT, BLOB, STRING -> Object::toString;
+              case DATE ->
+                  value -> ((LocalDate) value).atStartOfDay(ZoneId.systemDefault()).toString();
+              case TIMESTAMP -> value -> DateTimeUtils.convertLongToDate((long) value);
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  value -> {
+                    throw new PipeRuntimeNonCriticalException(
+                        DataNodePipeMessages.UNSUPPORTED_DATA_TYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToIntFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_INT_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (int) (long) value;
+                  case FLOAT -> value -> (int) (float) value;
+                  case DOUBLE -> value -> (int) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to int.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<ToLongFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_LONG_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (long) value;
+                  case FLOAT -> value -> (long) (float) value;
+                  case DOUBLE -> value -> (long) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to long.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<Function<Object, Float>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_FLOAT_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (float) (int) value;
+                  case DATE ->
+                      value -> (float) DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (float) (long) value;
+                  case FLOAT -> value -> (float) value;
+                  case DOUBLE -> value -> (float) (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to float.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<ToDoubleFunction<Object>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_DOUBLE_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 -> value -> (int) value;
+                  case DATE -> value -> DateUtils.parseDateExpressionToInt((LocalDate) value);
+                  case INT64, TIMESTAMP -> value -> (long) value;
+                  case FLOAT -> value -> (float) value;
+                  case DOUBLE -> value -> (double) value;
+                  case BOOLEAN, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to double.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<Function<Object, String>>
+        CUSTOMIZED_INTERMEDIATE_RESULT_TO_STRING_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> value -> Boolean.toString((boolean) value);
+                  case INT32 -> value -> Integer.toString((int) value);
+                  case DATE -> value -> ((LocalDate) value).toString();
+                  case INT64 -> value -> Long.toString((long) value);
+                  case TIMESTAMP ->
+                      value ->
+                          RpcUtils.formatDatetime(
+                              RpcUtils.DEFAULT_TIME_FORMAT,
+                              CommonDescriptor.getInstance().getConfig().getTimestampPrecision(),
+                              (long) value,
+                              ZoneId.systemDefault());
+                  case FLOAT -> value -> Float.toString((float) value);
+                  case DOUBLE -> value -> Double.toString((double) value);
+                  case TEXT, STRING -> value -> (String) value;
+                  case BLOB ->
+                      value ->
+                          BytesUtils.parseBlobByteArrayToString(
+                              ((org.apache.iotdb.pipe.api.type.Binary) value).getValues());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      value -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                "The type %s cannot be casted to string.", type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<IntFunction<Object>> AGGREGATE_TABLET_COLUMN_ALLOCATOR_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createArray;
+              case ROW, UNKNOWN, VECTOR ->
+                  size -> {
+                    throw new UnsupportedOperationException(
+                        String.format(
+                            DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT,
+                            type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<AggregateTabletColumnValueWriter>
+        AGGREGATE_TABLET_COLUMN_VALUE_WRITER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      DATE,
+                      INT64,
+                      TIMESTAMP,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      BLOB,
+                      STRING,
+                      OBJECT ->
+                      (column, rowIndex, value) -> type.addValue(rowIndex, value, column);
+                  case ROW, UNKNOWN, VECTOR ->
+                      (column, rowIndex, value) -> {
+                        throw new UnsupportedOperationException(
+                            String.format(
+                                DataNodePipeMessages.UNSUPPORTED_OUTPUT_DATATYPE_FMT,
+                                type.getTypeEnum()));
+                      };
+                };
+
+    public static final TypeService<TabletObjectValueGetter>
+        OPC_UA_TABLET_OBJECT_VALUE_GETTER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> (column, rowIndex) -> ((boolean[]) column)[rowIndex];
+                  case INT32 -> (column, rowIndex) -> ((int[]) column)[rowIndex];
+                  case DATE ->
+                      (column, rowIndex) ->
+                          new DateTime(Date.valueOf(((LocalDate[]) column)[rowIndex]));

Review Comment:
   Restored `java.util.Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant())` before constructing Milo's `DateTime`. This preserves the previous time-zone conversion and avoids `java.sql.Date.toInstant()`. Added a regression at the actual Milo conversion boundary in `TypeServicesTest`; it passes with the upgraded TsFile dependency. This is not a full OPC UA server integration test.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/TimeSeriesRuntimeState.java:
##########
@@ -74,6 +79,22 @@ public TimeSeriesRuntimeState(
     this.windowingProcessor = windowingProcessor;
   }
 
+  public Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> updateWindows(
+      final long timestamp,
+      final Row row,
+      final int columnIndex,
+      final long outputMinReportIntervalMilliseconds)
+      throws IOException {
+    if (rowValueUpdater == null) {

Review Comment:
   The cached updater now stores its associated `TSDataType` and is refreshed whenever the incoming row's type changes. This lets a recreated path reach the existing typed/window handling instead of invoking a stale primitive getter. `TimeSeriesRuntimeStateTest` exercises the real Row entry point with PipeRow values changing INT32 -> DOUBLE -> INT32 and verifies the typed dispatch and values. The test passes; it does not run the full Pipe lifecycle.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/utils/TypeServices.java:
##########
@@ -0,0 +1,3927 @@
+/*
+ * 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.iotdb.calc.utils;
+
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFillFilter;
+import org.apache.iotdb.calc.execution.operator.process.fill.ILinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.identity.IdentityLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.DoubleLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.FloatLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.IntLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.linear.LongLinearFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BinaryNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.BooleanNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.DoubleNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.FloatNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.IntNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.next.LongNextFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BinaryPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.BooleanPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.DoublePreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.FloatPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.IntPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.previous.LongPreviousFillWithTimeDuration;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.AscLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBinaryTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescBooleanTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescDoubleTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescFloatTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescIntTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.DescLongTypeJoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.join.merge.comparator.JoinKeyComparator;
+import org.apache.iotdb.calc.execution.operator.process.window.partition.Partition;
+import org.apache.iotdb.calc.execution.operator.process.window.utils.ColumnList;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AbstractApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.AggregationMask;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BinaryApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BlobApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.BooleanApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.DoubleApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.FloatApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.IntApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.LongApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.TableAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.approximate.HyperLogLog;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.AbstractGroupedApproxPercentileAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BinaryGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BlobGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.BooleanGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.DoubleGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.FloatGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.GroupedMaxMinByBaseAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.IntGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.LongGroupedApproxMostFrequentAccumulator;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BinaryBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.BooleanBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.DoubleBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.FloatBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.IntBigArray;
+import org.apache.iotdb.calc.execution.operator.source.relational.aggregation.grouped.array.LongBigArray;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBlobLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToBooleanLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDateLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToDoubleLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToFloatLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt32LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToInt64LiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToStringLiteralVisitor;
+import org.apache.iotdb.calc.plan.relational.planner.CastToTimestampLiteralVisitor;
+import org.apache.iotdb.calc.transformation.dag.column.ColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BinaryLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.BooleanLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.DoubleLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatGreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.FloatLeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBinaryMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InBooleanMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InDoubleMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InFloatMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt32MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InInt64MultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.InMultiColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int32LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64GreatestColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.column.multi.Int64LeastColumnTransformer;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.datastructure.SortKey;
+import org.apache.iotdb.commons.exception.IoTDBRuntimeException;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+
+import java.time.ZoneId;
+import java.time.format.DateTimeParseException;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.function.IntConsumer;
+import java.util.function.IntFunction;
+import java.util.function.IntUnaryOperator;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_ARRAY_HEADER_SIZE;
+import static org.apache.iotdb.calc.transformation.datastructure.util.BinaryUtils.MIN_OBJECT_HEADER_SIZE;
+
+public class TypeServices {
+
+  /**
+   * Wraps a type service whose result is immutable/stateless and can therefore be shared for all
+   * instances of the same data type. Type objects are intentionally reduced to their enum here: all
+   * services wrapped with this helper dispatch only on {@code getTypeEnum()}.
+   */
+  private static <T> TypeService<T> cached(final TypeService<T> service) {
+    final Map<Object, T> cache = new ConcurrentHashMap<>();
+    return type -> cache.computeIfAbsent(type.getTypeEnum(), ignored -> service.call(type));
+  }
+
+  private static final IdentityLinearFill IDENTITY_LINEAR_FILL = new IdentityLinearFill();
+  private static final IdentityFill IDENTITY_FILL = new IdentityFill();
+
+  // Unsupported fill types defer their exception until the returned strategy is used so check()
+  // can still validate that every TypeEnum has a service entry.
+  public static final TypeService<Supplier<ILinearFill>> LINEAR_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32, DATE -> IntLinearFill::new;
+            case INT64, TIMESTAMP -> LongLinearFill::new;
+            case FLOAT -> FloatLinearFill::new;
+            case DOUBLE -> DoubleLinearFill::new;
+            case BOOLEAN, TEXT, STRING, BLOB, OBJECT -> () -> IDENTITY_LINEAR_FILL;
+            case ROW, UNKNOWN, VECTOR ->
+                () -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, IFill>> PREVIOUS_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                filter ->
+                    filter == null
+                        ? new BooleanPreviousFill()
+                        : new BooleanPreviousFillWithTimeDuration(filter);
+            case TEXT, STRING, BLOB, OBJECT ->
+                filter ->
+                    filter == null
+                        ? new BinaryPreviousFill()
+                        : new BinaryPreviousFillWithTimeDuration(filter);
+            case INT32, DATE ->
+                filter ->
+                    filter == null
+                        ? new IntPreviousFill()
+                        : new IntPreviousFillWithTimeDuration(filter);
+            case INT64, TIMESTAMP ->
+                filter ->
+                    filter == null
+                        ? new LongPreviousFill()
+                        : new LongPreviousFillWithTimeDuration(filter);
+            case FLOAT ->
+                filter ->
+                    filter == null
+                        ? new FloatPreviousFill()
+                        : new FloatPreviousFillWithTimeDuration(filter);
+            case DOUBLE ->
+                filter ->
+                    filter == null
+                        ? new DoublePreviousFill()
+                        : new DoublePreviousFillWithTimeDuration(filter);
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<Function<IFillFilter, ILinearFill>> NEXT_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN -> BooleanNextFill::new;
+            case TEXT, STRING, BLOB, OBJECT -> BinaryNextFill::new;
+            case INT32, DATE -> IntNextFill::new;
+            case INT64, TIMESTAMP -> LongNextFill::new;
+            case FLOAT -> FloatNextFill::new;
+            case DOUBLE -> DoubleNextFill::new;
+            case ROW, UNKNOWN, VECTOR ->
+                filter -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  public static final TypeService<BooleanFunction<JoinKeyComparator>> JOIN_KEY_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    ascending ->
+                        ascending
+                            ? AscIntTypeJoinKeyComparator.getInstance()
+                            : DescIntTypeJoinKeyComparator.getInstance();
+                case INT64, TIMESTAMP ->
+                    ascending ->
+                        ascending
+                            ? AscLongTypeJoinKeyComparator.getInstance()
+                            : DescLongTypeJoinKeyComparator.getInstance();
+                case FLOAT ->
+                    ascending ->
+                        ascending
+                            ? AscFloatTypeJoinKeyComparator.getInstance()
+                            : DescFloatTypeJoinKeyComparator.getInstance();
+                case DOUBLE ->
+                    ascending ->
+                        ascending
+                            ? AscDoubleTypeJoinKeyComparator.getInstance()
+                            : DescDoubleTypeJoinKeyComparator.getInstance();
+                case BOOLEAN ->
+                    ascending ->
+                        ascending
+                            ? AscBooleanTypeJoinKeyComparator.getInstance()
+                            : DescBooleanTypeJoinKeyComparator.getInstance();
+                case STRING, BLOB, TEXT ->
+                    ascending ->
+                        ascending
+                            ? AscBinaryTypeJoinKeyComparator.getInstance()
+                            : DescBinaryTypeJoinKeyComparator.getInstance();
+                case OBJECT, ROW, UNKNOWN, VECTOR ->
+                    ascending -> {
+                      throw new UnsupportedOperationException(
+                          CalcMessages.UNSUPPORTED_DATA_TYPE + type);
+                    };
+              });
+
+  public static final TypeService<IntFunction<Comparator<SortKey>>> MERGE_SORT_COMPARATOR_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case INT32, DATE ->
+                    index ->
+                        Comparator.comparingInt(
+                            sortKey ->
+                                type.getInt(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case INT64, TIMESTAMP ->
+                    index ->
+                        Comparator.comparingLong(
+                            sortKey ->
+                                type.getLong(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case FLOAT ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getFloat(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case DOUBLE ->
+                    index ->
+                        Comparator.comparingDouble(
+                            sortKey ->
+                                type.getDouble(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case TEXT, STRING, BLOB, OBJECT ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBinary(sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                case BOOLEAN ->
+                    index ->
+                        Comparator.comparing(
+                            sortKey ->
+                                type.getBoolean(
+                                    sortKey.tsBlock.getColumn(index), sortKey.rowIndex));
+                // TypeService.check() must be able to build a strategy for every enum value.
+                case ROW, UNKNOWN, VECTOR ->
+                    index -> {
+                      throw new IllegalArgumentException(
+                          String.format(CalcMessages.DATA_TYPE_CANNOT_BE_ORDERED, type));
+                    };
+              });
+
+  public static final TypeService<Integer> MEMORY_USAGE_OF_ONE_MERGE_SORT_KEY_SERVICE =
+      cached(
+          type ->
+              switch (type.getTypeEnum()) {
+                case BOOLEAN -> 1;
+                case INT32, FLOAT, DATE -> 4;
+                case INT64, DOUBLE, TIMESTAMP -> 8;
+                case TEXT, STRING, BLOB, OBJECT -> 16;
+                case ROW, UNKNOWN, VECTOR ->
+                    throw new UnSupportedDataTypeException(CalcMessages.UNKNOWN_DATATYPE + type)
+                        .setChecked(true);
+              });
+
+  public static final TypeService<IntUnaryOperator>
+      MEMORY_USAGE_OF_ONE_SERIALIZABLE_ROW_FIELD_SERVICE =
+          cached(
+              type ->
+                  switch (type.getTypeEnum()) {
+                    case INT32, DATE -> ignored -> ReadWriteIOUtils.INT_LEN;
+                    case INT64, TIMESTAMP -> ignored -> ReadWriteIOUtils.LONG_LEN;
+                    case FLOAT -> ignored -> ReadWriteIOUtils.FLOAT_LEN;
+                    case DOUBLE -> ignored -> ReadWriteIOUtils.DOUBLE_LEN;
+                    case BOOLEAN -> ignored -> ReadWriteIOUtils.BOOLEAN_LEN;
+                    case TEXT, BLOB, STRING, OBJECT ->
+                        byteArrayLength ->
+                            MIN_OBJECT_HEADER_SIZE + MIN_ARRAY_HEADER_SIZE + byteArrayLength;
+                    case ROW, UNKNOWN, VECTOR ->
+                        throw new UnSupportedDataTypeException(type.toString()).setChecked(true);
+                  });
+
+  public static final TypeService<ValueFillFactory> VALUE_FILL_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (literal, zoneId) -> {
+                  Boolean value = literal.accept(new CastToBooleanLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BooleanConstantFill(value);
+                };
+            case TEXT, STRING ->
+                (literal, zoneId) -> {
+                  Binary value =
+                      literal.accept(
+                          new CastToStringLiteralVisitor(TSFileConfig.STRING_CHARSET), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case BLOB ->
+                (literal, zoneId) -> {
+                  Binary value = literal.accept(new CastToBlobLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new BinaryConstantFill(value);
+                };
+            case INT32 ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToInt32LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case DATE ->
+                (literal, zoneId) -> {
+                  Integer value = literal.accept(new CastToDateLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new IntConstantFill(value);
+                };
+            case INT64 ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToInt64LiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case TIMESTAMP ->
+                (literal, zoneId) -> {
+                  Long value = literal.accept(new CastToTimestampLiteralVisitor(zoneId), null);
+                  return value == null ? IDENTITY_FILL : new LongConstantFill(value);
+                };
+            case FLOAT ->
+                (literal, zoneId) -> {
+                  Float value = literal.accept(new CastToFloatLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new FloatConstantFill(value);
+                };
+            case DOUBLE ->
+                (literal, zoneId) -> {
+                  Double value = literal.accept(new CastToDoubleLiteralVisitor(), null);
+                  return value == null ? IDENTITY_FILL : new DoubleConstantFill(value);
+                };
+            case OBJECT, ROW, UNKNOWN, VECTOR ->
+                (literal, zoneId) -> {
+                  throw unsupportedDataType(type);
+                };
+          };
+
+  /** Reads values for a cast using the source type's representation. */
+  public static final TypeService<CastInputService> CAST_INPUT_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case INT32 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castInt(columnBuilder, type.getInt(column, position));
+            case DATE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDate(columnBuilder, type.getInt(column, position), zoneId);
+            case INT64 ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castLong(columnBuilder, type.getLong(column, position));
+            case TIMESTAMP ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castTimestamp(
+                        columnBuilder, type.getLong(column, position), zoneId);
+            case FLOAT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castFloat(columnBuilder, type.getFloat(column, position));
+            case DOUBLE ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castDouble(columnBuilder, type.getDouble(column, position));
+            case BOOLEAN ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBoolean(columnBuilder, type.getBoolean(column, position));
+            case TEXT, STRING ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castString(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case BLOB ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castBlob(
+                        columnBuilder, type.getBinary(column, position), zoneId);
+            case OBJECT ->
+                (column, columnBuilder, position, castValueService, zoneId) ->
+                    castValueService.castObject(columnBuilder, type.getBinary(column, position));
+            case ROW, UNKNOWN, VECTOR ->
+                (column, columnBuilder, position, castValueService, zoneId) -> {
+                  throw unsupportedCastSource(type);
+                };
+          };
+
+  /** Writes values produced by a cast into a column using the target type's representation. */
+  public static final TypeService<CastValueService> CAST_VALUE_SERVICE =
+      type ->
+          new CastValueService() {
+            @Override
+            public void castInt(ColumnBuilder columnBuilder, int value) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(columnBuilder, BytesUtils.valueOf(String.valueOf(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castDate(ColumnBuilder columnBuilder, int value, ZoneId zoneId) {
+              switch (type.getTypeEnum()) {
+                case INT32, DATE -> type.writeInt(columnBuilder, value);
+                case INT64 -> type.writeLong(columnBuilder, value);
+                case TIMESTAMP ->
+                    type.writeLong(
+                        columnBuilder,
+                        DateTimeUtils.correctPrecision(
+                            DateUtils.parseIntToTimestamp(value, zoneId)));
+                case FLOAT -> type.writeFloat(columnBuilder, value);
+                case DOUBLE -> type.writeDouble(columnBuilder, value);
+                case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0);
+                case TEXT, STRING ->
+                    type.writeBinary(
+                        columnBuilder, BytesUtils.valueOf(DateUtils.formatDate(value)));
+                case BLOB ->
+                    type.writeBinary(columnBuilder, new Binary(BytesUtils.intToBytes(value)));
+                case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+              }
+            }
+
+            @Override
+            public void castTimestamp(ColumnBuilder columnBuilder, long value, ZoneId zoneId) {
+              try {
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      type.writeInt(columnBuilder, CastFunctionUtils.castLongToInt(value));
+                  case DATE ->
+                      type.writeInt(
+                          columnBuilder,
+                          DateUtils.parseDateExpressionToInt(
+                              DateTimeUtils.convertToLocalDate(value, zoneId)));
+                  case INT64, TIMESTAMP -> type.writeLong(columnBuilder, value);
+                  case FLOAT -> type.writeFloat(columnBuilder, value);
+                  case DOUBLE -> type.writeDouble(columnBuilder, value);
+                  case BOOLEAN -> type.writeBoolean(columnBuilder, value != 0L);
+                  case TEXT, STRING ->
+                      type.writeBinary(
+                          columnBuilder,
+                          BytesUtils.valueOf(DateTimeUtils.convertLongToDate(value, zoneId)));
+                  case BLOB ->
+                      type.writeBinary(columnBuilder, new Binary(BytesUtils.longToBytes(value)));
+                  case OBJECT, ROW, UNKNOWN, VECTOR -> throw unsupportedCastTarget(type);
+                }
+              } catch (DateTimeParseException e) {
+                throw new IoTDBRuntimeException(
+                    "Year must be between 1000 and 9999.",

Review Comment:
   Restored the existing `CalcMessages` constants for the year-range and cast failures and the SUM/AVG argument checks, including grouped SUM/AVG. The new batch strategies also use the existing localized unsupported-type messages. Both English and Chinese affected-module builds were validated; no new message keys are needed for these fixes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r4023238592


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/NaiveIncreaseAccumulator.java:
##########
@@ -58,30 +60,27 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.INCREASE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.INCREASE);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.INCREASE, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(
-              arguments[2], position, RateFunctionType.INCREASE, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(
-              arguments[3], position, RateFunctionType.INCREASE, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.INCREASE, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(currentWindowStart, currentWindowEnd);
-      samples.add(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   NaiveIncreaseAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/NaiveIrateAccumulator.java:
##########
@@ -58,21 +60,18 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.IRATE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.IRATE);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.IRATE, 2);
-      samples.add(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   NaiveIrateAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/NaiveRateAccumulator.java:
##########
@@ -58,27 +60,27 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.RATE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.RATE);
-      long time =
-          RateFunctionValidation.readRequiredTime(arguments[1], position, RateFunctionType.RATE, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(arguments[2], position, RateFunctionType.RATE, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(arguments[3], position, RateFunctionType.RATE, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.RATE, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(currentWindowStart, currentWindowEnd);
-      samples.add(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   NaiveRateAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/OrderedDeltaAccumulator.java:
##########
@@ -56,30 +58,27 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.DELTA);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.DELTA);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.DELTA, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(
-              arguments[2], position, RateFunctionType.DELTA, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(
-              arguments[3], position, RateFunctionType.DELTA, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.DELTA, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(currentWindowStart, currentWindowEnd);
-      update(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   OrderedDeltaAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/OrderedIncreaseAccumulator.java:
##########
@@ -57,30 +59,27 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.INCREASE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.INCREASE);
-      long time =
-          RateFunctionValidation.readRequiredTime(
-              arguments[1], position, RateFunctionType.INCREASE, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(
-              arguments[2], position, RateFunctionType.INCREASE, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(
-              arguments[3], position, RateFunctionType.INCREASE, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.INCREASE, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(currentWindowStart, currentWindowEnd);
-      update(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   OrderedIncreaseAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/OrderedRateAccumulator.java:
##########
@@ -57,27 +59,27 @@ public TableAccumulator copy() {
   @Override
   public void addInput(Column[] arguments, AggregationMask mask) {
     RateFunctionValidation.validateArgumentCount(arguments, RateFunctionType.RATE);
-    int selectedCount = mask.getSelectedPositionCount();
-    int[] selectedPositions = mask.isSelectAll() ? null : mask.getSelectedPositions();
-    for (int index = 0; index < selectedCount; index++) {
-      int position = mask.isSelectAll() ? index : selectedPositions[index];
-      if (arguments[0].isNull(position)) {
-        continue;
-      }
-      double value =
-          RateFunctionValidation.readValue(
-              arguments[0], position, valueDataType, RateFunctionType.RATE);
-      long time =
-          RateFunctionValidation.readRequiredTime(arguments[1], position, RateFunctionType.RATE, 2);
-      long currentWindowStart =
-          RateFunctionValidation.readRequiredTime(arguments[2], position, RateFunctionType.RATE, 3);
-      long currentWindowEnd =
-          RateFunctionValidation.readRequiredTime(arguments[3], position, RateFunctionType.RATE, 4);
-      RateFunctionValidation.validateWindow(
-          RateFunctionType.RATE, time, currentWindowStart, currentWindowEnd);
-      initializeOrValidateWindow(currentWindowStart, currentWindowEnd);
-      update(time, value);
-    }
+    TypeServices.RATE_INPUT_SERVICE

Review Comment:
   OrderedRateAccumulator now dispatches to a native batch reader through RATE_INPUT_SERVICE. It preserves value validation before time/window validation and keeps the existing state update callback, including logical group positions where applicable. RateBatchInputTest exercises all 16 implementations with native and wrapped columns, masks/nulls and validation cases. This is one of the 12 retained rate candidates; the other four were restored after fixed-DOUBLE benchmarks showed regressions.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/rate/RateFunctionValidation.java:
##########
@@ -86,6 +79,25 @@ public static double readValue(
     return value;
   }
 
+  public static void validateValue(double value, RateFunctionType functionType) {

Review Comment:
   Expose the existing finite/nonnegative value checks to the typed batch readers without changing exception order or messages. Keep readValue’s scalar checks inline: replacing them with a helper changed the scalar benchmark behavior on paths whose batch refactor was rejected. RateBatchInputTest covers these validation semantics.



##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/transformation/dag/column/unary/scalar/AbstractCastFunctionColumnTransformer.java:
##########
@@ -19,46 +19,40 @@
 
 package org.apache.iotdb.calc.transformation.dag.column.unary.scalar;
 
-import org.apache.iotdb.calc.i18n.CalcMessages;
 import org.apache.iotdb.calc.transformation.dag.column.ColumnTransformer;
 import org.apache.iotdb.calc.transformation.dag.column.unary.UnaryColumnTransformer;
-import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
-import org.apache.iotdb.commons.exception.IoTDBRuntimeException;
-import org.apache.iotdb.commons.exception.SemanticException;
-import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.calc.utils.TypeServices;
 
 import org.apache.tsfile.block.column.Column;
 import org.apache.tsfile.block.column.ColumnBuilder;
-import org.apache.tsfile.common.conf.TSFileConfig;
 import org.apache.tsfile.read.common.type.Type;
-import org.apache.tsfile.read.common.type.TypeEnum;
-import org.apache.tsfile.utils.Binary;
-import org.apache.tsfile.utils.BytesUtils;
-import org.apache.tsfile.utils.DateUtils;
 
 import java.time.ZoneId;
-import java.time.format.DateTimeParseException;
-
-import static org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils.ERROR_MSG;
-import static org.apache.iotdb.rpc.TSStatusCode.DATE_OUT_OF_RANGE;
 
 public abstract class AbstractCastFunctionColumnTransformer extends UnaryColumnTransformer {
 
   private final ZoneId zoneId;
+  private final TypeServices.NumericCastBatch numericCastBatch;
+  private final TypeServices.CastInputService castInputService;
+  private final TypeServices.CastValueService castValueService;
 
   protected AbstractCastFunctionColumnTransformer(
       Type returnType, ColumnTransformer childColumnTransformer, ZoneId zoneId) {
     super(returnType, childColumnTransformer);
     this.zoneId = zoneId;
+    this.numericCastBatch =

Review Comment:
   Select the numeric source/target batch strategy once for CAST/TRY_CAST. The 16 INT32/INT64/FLOAT/DOUBLE pairs use native loops; other types keep the existing conversion path. NumericCastBatchTest covers overflow, NaN, null/selection, region and RLE inputs, including TRY_CAST null results. Local mixed-type kernels improved 2.11–2.83x; fixed DOUBLE-to-DOUBLE was mostly smaller gains or flat.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r3977846585


##########
iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/source/relational/aggregation/grouped/GroupedMaxAccumulator.java:
##########
@@ -519,4 +287,100 @@ protected void updateBooleanValue(int groupId, boolean value) {
       booleanValues.set(groupId, value);
     }
   }
+
+  @Override
+  public RuntimeException unsupportedException() {
+    return new UnSupportedDataTypeException(
+        String.format(CalcMessages.UNSUPPORTED_DATA_TYPE_IN_MAX_AGGREGATION, seriesDataType));
+  }
+
+  @Override
+  public void initializeIntValues() {
+    intValues = new IntBigArray(Integer.MIN_VALUE);
+  }
+
+  @Override
+  public void initializeLongValues() {
+    longValues = new LongBigArray(Long.MIN_VALUE);
+  }
+
+  @Override
+  public void initializeFloatValues() {
+    floatValues = new FloatBigArray(Float.MIN_VALUE);

Review Comment:
   Fixed in the updated branch: grouped FLOAT/DOUBLE MAX now initializes with Float.NEGATIVE_INFINITY and Double.NEGATIVE_INFINITY, so zero and negative values can initialize the result. All 3 GroupedMaxAccumulatorTest cases pass, including non-positive intermediate input.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/TypeServices.java:
##########
@@ -0,0 +1,4012 @@
+/*
+ * 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.iotdb.db.utils;
+
+import org.apache.iotdb.calc.exception.QueryProcessException;
+import org.apache.iotdb.calc.execution.aggregation.Accumulator;
+import org.apache.iotdb.calc.execution.aggregation.BinaryModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.BooleanModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.DoubleModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.FloatModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.IntModeAccumulator;
+import org.apache.iotdb.calc.execution.aggregation.LongModeAccumulator;
+import org.apache.iotdb.calc.execution.operator.process.fill.IFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BinaryConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.BooleanConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.DoubleConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.FloatConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.IntConstantFill;
+import org.apache.iotdb.calc.execution.operator.process.fill.constant.LongConstantFill;
+import org.apache.iotdb.calc.i18n.CalcMessages;
+import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils;
+import org.apache.iotdb.calc.transformation.dag.util.CastFunctionUtils;
+import org.apache.iotdb.calc.utils.constant.SqlConstant;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.exception.pipe.PipeRuntimeNonCriticalException;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BinaryLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FloatLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
+import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral;
+import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
+import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
+import org.apache.iotdb.db.pipe.processor.aggregate.TimeSeriesRuntimeState;
+import org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.AbstractSameTypeNumericOperator;
+import org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.WindowOutput;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBinaryWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualBooleanWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.EqualLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationDoubleWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationFloatWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationIntWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationLongWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowManager;
+import org.apache.iotdb.db.queryengine.execution.operator.window.VariationWindowParameter;
+import org.apache.iotdb.db.queryengine.statistics.StatisticsManager;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.ArithmeticNegationTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.InTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.DiffFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.dag.transformer.unary.scalar.RoundFunctionTransformer;
+import org.apache.iotdb.db.queryengine.transformation.datastructure.util.ValueRecorder;
+import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.IWALByteBufferView;
+import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALWriteUtils;
+import org.apache.iotdb.db.utils.datastructure.AlignedTVList;
+import org.apache.iotdb.db.utils.datastructure.BinaryTVList;
+import org.apache.iotdb.db.utils.datastructure.BooleanTVList;
+import org.apache.iotdb.db.utils.datastructure.DoubleTVList;
+import org.apache.iotdb.db.utils.datastructure.FloatTVList;
+import org.apache.iotdb.db.utils.datastructure.IntTVList;
+import org.apache.iotdb.db.utils.datastructure.LongTVList;
+import org.apache.iotdb.db.utils.datastructure.TVList;
+import org.apache.iotdb.db.utils.windowing.window.EvictableBatchList;
+import org.apache.iotdb.db.utils.windowing.window.WindowImpl;
+import org.apache.iotdb.pipe.api.access.Row;
+import org.apache.iotdb.rpc.RpcUtils;
+
+import com.google.common.io.BaseEncoding;
+import com.sun.jna.platform.win32.OaIdl;
+import com.sun.jna.platform.win32.OleAuto;
+import com.sun.jna.platform.win32.Variant;
+import com.sun.jna.platform.win32.WTypes;
+import com.sun.jna.platform.win32.WinDef;
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.block.column.ColumnBuilder;
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.encoding.decoder.Decoder;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.external.commons.lang3.StringUtils;
+import org.apache.tsfile.file.metadata.IChunkMetadata;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.file.metadata.statistics.DateStatistics;
+import org.apache.tsfile.file.metadata.statistics.Statistics;
+import org.apache.tsfile.read.common.BatchData;
+import org.apache.tsfile.read.common.block.TsBlockBuilder;
+import org.apache.tsfile.read.common.block.column.BinaryColumnBuilder;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.read.filter.basic.Filter;
+import org.apache.tsfile.read.reader.series.PaginationController;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
+import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.DateUtils;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.RamUsageEstimator;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ChunkWriterImpl;
+import org.apache.tsfile.write.chunk.ValueChunkWriter;
+import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.sql.Date;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.IntFunction;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import java.util.function.ToDoubleFunction;
+import java.util.function.ToIntFunction;
+import java.util.function.ToLongFunction;
+
+public class TypeServices {
+
+  public static final int DEFAULT_DATE =
+      DateUtils.parseDateExpressionToInt(LocalDate.of(1970, 1, 1));
+  private static final LocalDate EMPTY_LOCAL_DATE = LocalDate.of(1000, 1, 1);
+
+  public static final class Memory {
+
+    public static final TypeService<LongSupplier> STATEMENT_VALUE_SIZE_PER_LINE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE -> type::estimateValueSize;
+              case TEXT, BLOB, STRING ->
+                  () -> StatisticsManager.getInstance().getMaxBinarySizeInBytes();
+              case OBJECT, ROW, UNKNOWN, VECTOR ->
+                  () -> {
+                    throw new UnsupportedOperationException(
+                        CalcMessages.UNKNOWN_DATATYPE + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ToLongFunction<Object>> INSERT_NODE_VALUE_SIZE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, DATE, INT64, TIMESTAMP, FLOAT, DOUBLE ->
+                  value ->
+                      RamUsageEstimator.alignObjectSize(
+                          type.estimateValueSize() + RamUsageEstimator.NUM_BYTES_OBJECT_HEADER);
+              case TEXT, BLOB, STRING ->
+                  value -> Objects.nonNull(value) ? ((Binary) value).ramBytesUsed() : 0L;
+              case OBJECT, ROW, UNKNOWN, VECTOR -> value -> 0L;
+            };
+
+    static {
+      STATEMENT_VALUE_SIZE_PER_LINE_SERVICE.check();
+      INSERT_NODE_VALUE_SIZE_SERVICE.check();
+    }
+
+    private Memory() {
+      // Utility class
+    }
+  }
+
+  public static final class Transformation {
+
+    public static final TypeService<Function<Object, Column>> CONSTANT_COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT ->
+                  value -> {
+                    final ColumnBuilder builder = type.createColumnBuilder(1);
+                    type.writeObject(builder, value);
+                    return builder.build();
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          DataNodeQueryMessages.UNSUPPORTED_TYPE + type.getTypeEnum())
+                      .setChecked(true);
+            };
+
+    public static final TypeService<
+            Function<org.apache.iotdb.db.queryengine.plan.statement.literal.Literal, IFill>>
+        CONSTANT_FILL_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN -> literal -> new BooleanConstantFill(literal.getBoolean());
+                  case INT32 -> literal -> new IntConstantFill(literal.getInt());
+                  case DATE -> literal -> new IntConstantFill(literal.getDate());
+                  case INT64, TIMESTAMP -> literal -> new LongConstantFill(literal.getLong());
+                  case FLOAT -> literal -> new FloatConstantFill(literal.getFloat());
+                  case DOUBLE -> literal -> new DoubleConstantFill(literal.getDouble());
+                  case TEXT, BLOB, STRING -> literal -> new BinaryConstantFill(literal.getBinary());
+                  case OBJECT, ROW, UNKNOWN, VECTOR ->
+                      literal -> {
+                        throw new IllegalArgumentException(
+                            CommonOperatorUtils.UNKNOWN_DATATYPE + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<IntFunction<ColumnBuilder>> COLUMN_BUILDER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::createColumnBuilder;
+              case ROW, UNKNOWN, VECTOR ->
+                  throw new UnSupportedDataTypeException(
+                          String.format(
+                              DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_FMT, type.getTypeEnum()))
+                      .setChecked(true);
+            };
+
+    public static final TypeService<ColumnToDoubleConverter> VALUE_TO_DOUBLE_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32, DATE -> type::getInt;
+              case INT64, TIMESTAMP -> type::getLong;
+              case FLOAT -> type::getFloat;
+              case DOUBLE -> type::getDouble;
+              case BOOLEAN -> (column, index) -> type.getBoolean(column, index) ? 1 : 0;
+              case TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (column, index) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<ColumnValueWriter> TRANSFORM_COLUMN_VALUE_WRITER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case BOOLEAN,
+                  INT32,
+                  DATE,
+                  INT64,
+                  TIMESTAMP,
+                  FLOAT,
+                  DOUBLE,
+                  TEXT,
+                  BLOB,
+                  STRING,
+                  OBJECT ->
+                  type::write;
+              case ROW, UNKNOWN, VECTOR ->
+                  (builder, column, index) -> {
+                    throw new UnSupportedDataTypeException(
+                        String.format(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_FMT, type.getTypeEnum()));
+                  };
+            };
+
+    // Schema evolution keeps physically compatible columns, widens supported values, and exposes
+    // incompatible historical values as nulls instead of interpreting their raw storage.
+    public static final TypeService<AlteredDataTypeColumnTransformer>
+        ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case BOOLEAN,
+                      INT32,
+                      INT64,
+                      FLOAT,
+                      DOUBLE,
+                      TEXT,
+                      STRING,
+                      TIMESTAMP,
+                      DATE,
+                      BLOB -> {
+                    final TSDataType targetType = TSDataType.valueOf(type.getTypeEnum().name());
+                    yield (source, positionCount) -> {
+                      final TSDataType sourceType = source.getDataType();
+                      // DATE shares INT32's physical column but was historically incompatible with
+                      // a schema change to INT32, while the other shared-column pairs are reusable.
+                      if (sourceType == targetType
+                          || (targetType != TSDataType.INT32
+                              && SchemaUtils.isUsingSameColumn(sourceType, targetType))) {
+                        return source;
+                      }
+                      return targetType.isCompatible(sourceType)
+                          ? source.convertTo(targetType)
+                          : type.createNullColumn(positionCount);
+                    };
+                  }
+                  case OBJECT -> (source, positionCount) -> source;
+                  case ROW, UNKNOWN, VECTOR -> (source, positionCount) -> null;
+                };
+
+    public static final TypeService<RoundTransformer> ROUND_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> RoundFunctionTransformer::transformInt;
+              case INT64 -> RoundFunctionTransformer::transformLong;
+              case FLOAT -> RoundFunctionTransformer::transformFloat;
+              case DOUBLE -> RoundFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new UnsupportedOperationException(
+                        String.format("Unsupported source dataType: %s", type.getTypeEnum()));
+                  };
+            };
+
+    public static final TypeService<DiffTransformer> DIFF_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> DiffFunctionTransformer::transformInt;
+              case INT64 -> DiffFunctionTransformer::transformLong;
+              case FLOAT -> DiffFunctionTransformer::transformFloat;
+              case DOUBLE -> DiffFunctionTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<NegationTransformer> NEGATION_TRANSFORMER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 -> ArithmeticNegationTransformer::transformInt;
+              case INT64 -> ArithmeticNegationTransformer::transformLong;
+              case FLOAT -> ArithmeticNegationTransformer::transformFloat;
+              case DOUBLE -> ArithmeticNegationTransformer::transformDouble;
+              case BOOLEAN, DATE, TIMESTAMP, TEXT, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (transformer, columns, builder) -> {
+                    throw new QueryProcessException(
+                        DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_2 + type.getTypeEnum());
+                  };
+            };
+
+    public static final TypeService<StateWindowSplitter> STATE_WINDOW_SPLITTER_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordInt(type.getInt(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getInt(values, index) - valueRecorder.getInt()) > delta;
+                    if (split) {
+                      valueRecorder.recordInt(type.getInt(values, index));
+                    }
+                    return split;
+                  };
+              case INT64 ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordLong(type.getLong(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getLong(values, index) - valueRecorder.getLong()) > delta;
+                    if (split) {
+                      valueRecorder.recordLong(type.getLong(values, index));
+                    }
+                    return split;
+                  };
+              case FLOAT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordFloat(type.getFloat(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getFloat(values, index) - valueRecorder.getFloat()) > delta;
+                    if (split) {
+                      valueRecorder.recordFloat(type.getFloat(values, index));
+                    }
+                    return split;
+                  };
+              case DOUBLE ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordDouble(type.getDouble(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        Math.abs(type.getDouble(values, index) - valueRecorder.getDouble()) > delta;
+                    if (split) {
+                      valueRecorder.recordDouble(type.getDouble(values, index));
+                    }
+                    return split;
+                  };
+              case BOOLEAN ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index - 1));
+                      valueRecorder.setRecorded(true);
+                    }
+                    final boolean split =
+                        type.getBoolean(values, index) != valueRecorder.getBoolean();
+                    if (split) {
+                      valueRecorder.recordBoolean(type.getBoolean(values, index));
+                    }
+                    return split;
+                  };
+              case TEXT ->
+                  (valueRecorder, delta, values, index) -> {
+                    if (!valueRecorder.hasRecorded()) {
+                      valueRecorder.recordString(type.getBinary(values, index - 1).toString());
+                      valueRecorder.setRecorded(true);
+                    }
+                    final String value = type.getBinary(values, index).toString();
+                    final boolean split = !value.equals(valueRecorder.getString());
+                    if (split) {
+                      valueRecorder.recordString(value);
+                    }
+                    return split;
+                  };
+              case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  (valueRecorder, delta, values, index) -> {
+                    throw new UnsupportedOperationException(
+                        DataNodeQueryMessages.INVALID_DATA_TYPE_FOR_STATE_WINDOW_STRATEGY);
+                  };
+            };
+
+    public static final TypeService<InTransformerSetInitializer>
+        IN_TRANSFORMER_SET_INITIALIZER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::initIntSet;
+                  case INT64, TIMESTAMP -> InTransformer::initLongSet;
+                  case FLOAT -> InTransformer::initFloatSet;
+                  case DOUBLE -> InTransformer::initDoubleSet;
+                  case BOOLEAN -> InTransformer::initBooleanSet;
+                  case TEXT, STRING -> InTransformer::initStringSet;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, values) -> {
+                        throw new UnsupportedOperationException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<InTransformerColumnTransformer>
+        IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE -> InTransformer::transformInt;
+                  case INT64, TIMESTAMP -> InTransformer::transformLong;
+                  case FLOAT -> InTransformer::transformFloat;
+                  case DOUBLE -> InTransformer::transformDouble;
+                  case BOOLEAN -> InTransformer::transformBoolean;
+                  case TEXT, STRING -> InTransformer::transformBinary;
+                  case BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      (transformer, columns, builder) -> {
+                        throw new QueryProcessException(
+                            DataNodeQueryMessages.UNSUPPORTED_DATA_TYPE_3 + type.getTypeEnum());
+                      };
+                };
+
+    public static final TypeService<TypeService<CastColumnStrategy>> CAST_COLUMN_SERVICE =
+        type ->
+            switch (type.getTypeEnum()) {
+              case INT32 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(builder, type.getInt(column, index)));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getInt(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getInt(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getInt(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getInt(column, index) != 0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getInt(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case INT64 ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castLongToInt(
+                                            type.getLong(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(builder, type.getLong(column, index)));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getLong(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getLong(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getLong(column, index) != 0L));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getLong(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case FLOAT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castFloatToInt(
+                                            type.getFloat(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castFloatToLong(
+                                            type.getFloat(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(builder, type.getFloat(column, index)));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getFloat(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getFloat(column, index) != 0.0f));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getFloat(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DOUBLE ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToInt(
+                                            type.getDouble(column, index))));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToLong(
+                                            type.getDouble(column, index))));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder,
+                                        CastFunctionUtils.castDoubleToFloat(
+                                            type.getDouble(column, index))));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(builder, type.getDouble(column, index)));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getDouble(column, index) != 0.0));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getDouble(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case BOOLEAN ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeInt(
+                                        builder, type.getBoolean(column, index) ? 1 : 0));
+                        case INT64 ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeLong(
+                                        builder, type.getBoolean(column, index) ? 1L : 0L));
+                        case FLOAT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeFloat(
+                                        builder, type.getBoolean(column, index) ? 1.0f : 0.0f));
+                        case DOUBLE ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeDouble(
+                                        builder, type.getBoolean(column, index) ? 1.0 : 0.0));
+                        case BOOLEAN ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, type.getBoolean(column, index)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(
+                                        builder,
+                                        BytesUtils.valueOf(
+                                            String.valueOf(type.getBoolean(column, index)))));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case TEXT ->
+                  targetType ->
+                      switch (targetType.getTypeEnum()) {
+                        case INT32 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeInt(builder, Integer.parseInt(value)));
+                        case INT64 ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeLong(builder, Long.parseLong(value)));
+                        case FLOAT ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeFloat(
+                                        builder, CastFunctionUtils.castTextToFloat(value)));
+                        case DOUBLE ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeDouble(
+                                        builder, CastFunctionUtils.castTextToDouble(value)));
+                        case BOOLEAN ->
+                            castBinaryColumnStrategy(
+                                type,
+                                targetType,
+                                (value, builder) ->
+                                    targetType.writeBoolean(
+                                        builder, CastFunctionUtils.castTextToBoolean(value)));
+                        case TEXT ->
+                            castColumnStrategy(
+                                targetType,
+                                (column, index, builder) ->
+                                    targetType.writeBinary(builder, type.getBinary(column, index)));
+                        case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                            unsupportedTargetCastStrategy(type);
+                      };
+              case DATE, TIMESTAMP, STRING, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                  targetType -> unsupportedSourceCastStrategy(type);
+            };
+
+    private static CastColumnStrategy castColumnStrategy(
+        final Type targetType, final CastColumnWriter writer) {
+      return new CastColumnStrategy(() -> {}, targetType::createColumnBuilder, writer);
+    }
+
+    private static CastColumnStrategy castBinaryColumnStrategy(
+        final Type sourceType, final Type targetType, final BinaryStringCastWriter writer) {
+      return castColumnStrategy(
+          targetType,
+          (column, index, builder) ->
+              writer.write(
+                  sourceType.getBinary(column, index).getStringValue(TSFileConfig.STRING_CHARSET),
+                  builder));
+    }
+
+    private static CastColumnStrategy unsupportedSourceCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported source dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedTargetCastStrategy(final Type sourceType) {
+      return unsupportedCastStrategy(
+          String.format("Unsupported target dataType: %s", sourceType.getTypeEnum()));
+    }
+
+    private static CastColumnStrategy unsupportedCastStrategy(final String message) {
+      return new CastColumnStrategy(
+          () -> {
+            throw new UnsupportedOperationException(message);
+          },
+          ignored -> {
+            throw new UnsupportedOperationException(message);
+          },
+          (column, index, builder) -> {
+            throw new UnsupportedOperationException(message);
+          });
+    }
+
+    public static final class CastColumnStrategy {
+      private final Runnable validator;
+      private final IntFunction<ColumnBuilder> builderFactory;
+      private final CastColumnWriter writer;
+
+      private CastColumnStrategy(
+          final Runnable validator,
+          final IntFunction<ColumnBuilder> builderFactory,
+          final CastColumnWriter writer) {
+        this.validator = validator;
+        this.builderFactory = builderFactory;
+        this.writer = writer;
+      }
+
+      public void validate() {
+        validator.run();
+      }
+
+      public ColumnBuilder createBuilder(final int expectedEntries) {
+        return builderFactory.apply(expectedEntries);
+      }
+
+      public void cast(final Column column, final int index, final ColumnBuilder builder) {
+        writer.write(column, index, builder);
+      }
+    }
+
+    @FunctionalInterface
+    private interface CastColumnWriter {
+      void write(Column column, int index, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    private interface BinaryStringCastWriter {
+      void write(String value, ColumnBuilder builder);
+    }
+
+    @FunctionalInterface
+    public interface ColumnToDoubleConverter {
+      double convert(Column column, int index) throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface ColumnValueWriter {
+      void write(ColumnBuilder builder, Column column, int index);
+    }
+
+    @FunctionalInterface
+    public interface AlteredDataTypeColumnTransformer {
+      Column transform(Column source, int positionCount);
+    }
+
+    @FunctionalInterface
+    public interface RoundTransformer {
+      void transform(RoundFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface DiffTransformer {
+      void transform(DiffFunctionTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    @FunctionalInterface
+    public interface NegationTransformer {
+      void transform(
+          ArithmeticNegationTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException, IOException;
+    }
+
+    @FunctionalInterface
+    public interface StateWindowSplitter {
+      boolean split(ValueRecorder valueRecorder, double delta, Column values, int index);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerSetInitializer {
+      void initialize(InTransformer transformer, Set<String> values);
+    }
+
+    @FunctionalInterface
+    public interface InTransformerColumnTransformer {
+      void transform(InTransformer transformer, Column[] columns, ColumnBuilder builder)
+          throws QueryProcessException;
+    }
+
+    static {
+      CONSTANT_COLUMN_BUILDER_SERVICE.check();
+      CONSTANT_FILL_SERVICE.check();
+      COLUMN_BUILDER_SERVICE.check();
+      VALUE_TO_DOUBLE_SERVICE.check();
+      TRANSFORM_COLUMN_VALUE_WRITER_SERVICE.check();
+      ALTERED_DATA_TYPE_COLUMN_TRANSFORMER_SERVICE.check();
+      ROUND_TRANSFORMER_SERVICE.check();
+      DIFF_TRANSFORMER_SERVICE.check();
+      NEGATION_TRANSFORMER_SERVICE.check();
+      STATE_WINDOW_SPLITTER_SERVICE.check();
+      IN_TRANSFORMER_SET_INITIALIZER_SERVICE.check();
+      IN_TRANSFORMER_COLUMN_TRANSFORMER_SERVICE.check();
+      CAST_COLUMN_SERVICE.check();
+    }
+
+    private Transformation() {
+      // Utility class
+    }
+  }
+
+  public static final class Aggregation {
+
+    public static final TypeService<ExtremeValueAccumulatorStrategy>
+        EXTREME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateIntResult(column.getInt(index)),
+                          (accumulator, value) ->
+                              accumulator.updateIntResult(((Number) value).intValue()),
+                          (accumulator, column) -> accumulator.getResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateLongResult(column.getLong(index)),
+                          (accumulator, value) ->
+                              accumulator.updateLongResult(((Number) value).longValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateFloatResult(column.getFloat(index)),
+                          (accumulator, value) ->
+                              accumulator.updateFloatResult(((Number) value).floatValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateDoubleResult(column.getDouble(index)),
+                          (accumulator, value) ->
+                              accumulator.updateDoubleResult(((Number) value).doubleValue()),
+                          (accumulator, column) ->
+                              accumulator.getResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case STRING ->
+                      extremeValueAccumulatorStrategy(
+                          (accumulator, column, index) ->
+                              accumulator.updateBinaryResult(column.getBinary(index)),
+                          (accumulator, value) -> accumulator.updateBinaryResult((Binary) value),
+                          (accumulator, column) ->
+                              accumulator.getResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN, TEXT, BLOB, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      ExtremeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<TimeValueAccumulatorStrategy>
+        TIME_VALUE_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateIntResult(column.getInt(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateIntResult(
+                                  ((Number) getStatisticsValue(statistics, first)).intValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setInt(column.getInt(0)),
+                          (builder, result) -> builder.writeInt(result.getInt()));
+                  case INT64, TIMESTAMP ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateLongResult(column.getLong(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateLongResult(
+                                  ((Number) getStatisticsValue(statistics, first)).longValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setLong(column.getLong(0)),
+                          (builder, result) -> builder.writeLong(result.getLong()));
+                  case FLOAT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateFloatResult(column.getFloat(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateFloatResult(
+                                  ((Number) getStatisticsValue(statistics, first)).floatValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setFloat(column.getFloat(0)),
+                          (builder, result) -> builder.writeFloat(result.getFloat()));
+                  case DOUBLE ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateDoubleResult(column.getDouble(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateDoubleResult(
+                                  ((Number) getStatisticsValue(statistics, first)).doubleValue(),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setDouble(column.getDouble(0)),
+                          (builder, result) -> builder.writeDouble(result.getDouble()));
+                  case TEXT, BLOB, STRING, OBJECT ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBinaryResult(column.getBinary(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBinaryResult(
+                                  getBinaryStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBinary(column.getBinary(0)),
+                          (builder, result) -> builder.writeBinary(result.getBinary()));
+                  case BOOLEAN ->
+                      timeValueAccumulatorStrategy(
+                          (accumulator, column, index, time) ->
+                              accumulator.updateBooleanResult(column.getBoolean(index), time),
+                          (accumulator, statistics, first) ->
+                              accumulator.updateBooleanResult(
+                                  (boolean) getStatisticsValue(statistics, first),
+                                  getStatisticsTime(statistics, first)),
+                          (accumulator, column) ->
+                              accumulator.getTimeValueResult().setBoolean(column.getBoolean(0)),
+                          (builder, result) -> builder.writeBoolean(result.getBoolean()));
+                  case ROW, UNKNOWN, VECTOR -> TimeValueAccumulatorStrategy.unsupported();
+                };
+
+    public static final TypeService<MaxMinByAccumulatorStrategy>
+        MAX_MIN_BY_ACCUMULATOR_STRATEGY_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32, DATE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateIntResult(
+                                  time, yColumn.getInt(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateIntResult(
+                                  time,
+                                  BytesUtils.bytesToInt(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Integer.BYTES),
+                                  0));
+                  case INT64, TIMESTAMP ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateLongResult(
+                                  time, yColumn.getLong(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateLongResult(
+                                  time,
+                                  BytesUtils.bytesToLongFromOffset(bytes, Long.BYTES, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Long.BYTES),
+                                  0));
+                  case FLOAT ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateFloatResult(
+                                  time, yColumn.getFloat(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateFloatResult(
+                                  time,
+                                  BytesUtils.bytesToFloat(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Float.BYTES),
+                                  0));
+                  case DOUBLE ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateDoubleResult(
+                                  time, yColumn.getDouble(yIndex), xColumn, xIndex),
+                          (accumulator, time, bytes, offset) ->
+                              accumulator.updateDoubleResult(
+                                  time,
+                                  BytesUtils.bytesToDouble(bytes, offset),
+                                  accumulator.readXFromBytesIntermediateInput(
+                                      bytes, offset + Double.BYTES),
+                                  0));
+                  case STRING ->
+                      maxMinByAccumulatorStrategy(
+                          type,
+                          (accumulator, time, yColumn, yIndex, xColumn, xIndex) ->
+                              accumulator.updateBinaryResult(
+                                  time, yColumn.getBinary(yIndex), xColumn, xIndex),
+                          TypeServices.Aggregation::updateBinaryIntermediate);
+                  case TEXT, BLOB, OBJECT -> maxMinByAccumulatorStrategy(type, null, null);
+                  case BOOLEAN -> maxMinByAccumulatorStrategy(type, null, null);
+                  case ROW, UNKNOWN, VECTOR -> MaxMinByAccumulatorStrategy.unsupported(type);
+                };
+
+    public static final TypeService<EventWindowManagerProvider>
+        EVENT_WINDOW_MANAGER_PROVIDER_SERVICE =
+            type ->
+                switch (type.getTypeEnum()) {
+                  case INT32 ->
+                      eventWindowManagerProvider(
+                          EqualIntWindowManager::new, VariationIntWindowManager::new);
+                  case INT64 ->
+                      eventWindowManagerProvider(
+                          EqualLongWindowManager::new, VariationLongWindowManager::new);
+                  case FLOAT ->
+                      eventWindowManagerProvider(
+                          EqualFloatWindowManager::new, VariationFloatWindowManager::new);
+                  case DOUBLE ->
+                      eventWindowManagerProvider(
+                          EqualDoubleWindowManager::new, VariationDoubleWindowManager::new);
+                  case TEXT -> eventWindowManagerProvider(EqualBinaryWindowManager::new, null);
+                  case BOOLEAN -> eventWindowManagerProvider(EqualBooleanWindowManager::new, null);
+                  case DATE, TIMESTAMP, BLOB, STRING, OBJECT, ROW, UNKNOWN, VECTOR ->
+                      EventWindowManagerProvider.unsupported();
+                };
+
+    private static EventWindowManagerProvider eventWindowManagerProvider(
+        final EventWindowManagerFactory equalFactory,
+        final EventWindowManagerFactory variationFactory) {
+      return new EventWindowManagerProvider(equalFactory, variationFactory);
+    }
+
+    private static void updateBinaryIntermediate(
+        final MaxMinByAccumulator accumulator,
+        final long time,
+        final byte[] bytes,
+        final int offset) {
+      final int length = BytesUtils.bytesToInt(bytes, offset);
+      final int valueOffset = offset + Integer.BYTES;
+      accumulator.updateBinaryResult(
+          time,
+          new Binary(BytesUtils.subBytes(bytes, valueOffset, length)),
+          accumulator.readXFromBytesIntermediateInput(bytes, valueOffset + length),
+          0);
+    }
+
+    private static MaxMinByAccumulatorStrategy maxMinByAccumulatorStrategy(
+        final Type type,
+        final MaxMinByYColumnUpdater yColumnUpdater,
+        final MaxMinByYBytesUpdater yBytesUpdater) {
+      return new MaxMinByAccumulatorStrategy(type, true, yColumnUpdater, yBytesUpdater);
+    }
+
+    private static TimeValueAccumulatorStrategy timeValueAccumulatorStrategy(
+        final TimeValueColumnUpdater columnUpdater,
+        final TimeValueStatisticsUpdater statisticsUpdater,
+        final TimeValueFinalSetter finalSetter,
+        final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+      return new TimeValueAccumulatorStrategy(
+          columnUpdater, statisticsUpdater, finalSetter, resultWriter);
+    }
+
+    private static Object getStatisticsValue(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getFirstValue() : statistics.getLastValue();
+    }
+
+    private static long getStatisticsTime(final Statistics<?> statistics, final boolean first) {
+      return first ? statistics.getStartTime() : statistics.getEndTime();
+    }
+
+    private static Binary getBinaryStatisticsValue(
+        final Statistics<?> statistics, final boolean first) {
+      final Object value = getStatisticsValue(statistics, first);
+      if (statistics instanceof DateStatistics) {
+        return new Binary(TSDataType.getDateStringValue((Integer) value), StandardCharsets.UTF_8);
+      }
+      return value instanceof Binary
+          ? (Binary) value
+          : new Binary(String.valueOf(value), StandardCharsets.UTF_8);
+    }
+
+    public static final class TimeValueAccumulatorStrategy {
+      private final TimeValueColumnUpdater columnUpdater;
+      private final TimeValueStatisticsUpdater statisticsUpdater;
+      private final TimeValueFinalSetter finalSetter;
+      private final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter;
+
+      private TimeValueAccumulatorStrategy(
+          final TimeValueColumnUpdater columnUpdater,
+          final TimeValueStatisticsUpdater statisticsUpdater,
+          final TimeValueFinalSetter finalSetter,
+          final BiConsumer<ColumnBuilder, TsPrimitiveType> resultWriter) {
+        this.columnUpdater = columnUpdater;
+        this.statisticsUpdater = statisticsUpdater;
+        this.finalSetter = finalSetter;
+        this.resultWriter = resultWriter;
+      }
+
+      private static TimeValueAccumulatorStrategy unsupported() {
+        return new TimeValueAccumulatorStrategy(null, null, null, null);
+      }
+
+      public boolean isSupported() {
+        return columnUpdater != null;
+      }
+
+      public void addInput(
+          final TimeValueAccumulator accumulator,
+          final Column[] columns,
+          final BitMap bitMap,
+          final boolean stopAfterFirstValue,
+          final boolean bitmapMarksSelected) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && bitmapMarksSelected != bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[1].isNull(i)) {
+            columnUpdater.update(accumulator, columns[1], i, columns[0].getLong(i));
+            if (stopAfterFirstValue) {
+              return;
+            }
+          }
+        }
+      }
+
+      public void addIntermediate(
+          final TimeValueAccumulator accumulator,
+          final Column valueColumn,
+          final Column timeColumn) {
+        columnUpdater.update(accumulator, valueColumn, 0, timeColumn.getLong(0));
+      }
+
+      public void addStatistics(
+          final TimeValueAccumulator accumulator,
+          final Statistics<?> statistics,
+          final boolean first) {
+        statisticsUpdater.update(accumulator, statistics, first);
+      }
+
+      public void setFinal(final TimeValueAccumulator accumulator, final Column column) {
+        finalSetter.set(accumulator, column);
+      }
+
+      public void writeResult(final ColumnBuilder builder, final TsPrimitiveType result) {
+        resultWriter.accept(builder, result);
+      }
+    }
+
+    public static final class MaxMinByAccumulatorStrategy {
+      private final Type type;
+      private final boolean xSupported;
+      private final MaxMinByYColumnUpdater yColumnUpdater;
+      private final MaxMinByYBytesUpdater yBytesUpdater;
+
+      private MaxMinByAccumulatorStrategy(
+          final Type type,
+          final boolean xSupported,
+          final MaxMinByYColumnUpdater yColumnUpdater,
+          final MaxMinByYBytesUpdater yBytesUpdater) {
+        this.type = type;
+        this.xSupported = xSupported;
+        this.yColumnUpdater = yColumnUpdater;
+        this.yBytesUpdater = yBytesUpdater;
+      }
+
+      private static MaxMinByAccumulatorStrategy unsupported(final Type type) {
+        return new MaxMinByAccumulatorStrategy(type, false, null, null);
+      }
+
+      public boolean isXSupported() {
+        return xSupported;
+      }
+
+      public boolean isYSupported() {
+        return yColumnUpdater != null;
+      }
+
+      public void addInput(
+          final MaxMinByAccumulator accumulator, final Column[] columns, final BitMap bitMap) {
+        final int count = columns[0].getPositionCount();
+        for (int i = 0; i < count; i++) {
+          if (bitMap != null && !bitMap.isMarked(i)) {
+            continue;
+          }
+          if (!columns[2].isNull(i)) {
+            yColumnUpdater.update(accumulator, columns[0].getLong(i), columns[2], i, columns[1], i);
+          }
+        }
+      }
+
+      public void setXResult(final TsPrimitiveType result, final Column column, final int index) {
+        type.setTo(result, column, index);

Review Comment:
   Fixed in the updated branch: setXResult now uses the column-to-primitive setter to copy the selected input into the result, without writing into the source column. The testMaxMinByReadsXWithoutModifyingInput regression verifies both result replacement and input preservation; the DataNode TypeServicesTest suite passes.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java:
##########
@@ -792,108 +749,12 @@ private void writeValues(DataOutputStream stream) throws IOException {
   }
 
   private void serializeColumn(TSDataType dataType, Object column, ByteBuffer buffer) {
-    switch (dataType) {
-      case INT32:
-      case DATE:
-        int[] intValues = (int[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(intValues[j], buffer);
-        }
-        break;
-      case INT64:
-      case TIMESTAMP:
-        long[] longValues = (long[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(longValues[j], buffer);
-        }
-        break;
-      case FLOAT:
-        float[] floatValues = (float[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(floatValues[j], buffer);
-        }
-        break;
-      case DOUBLE:
-        double[] doubleValues = (double[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(doubleValues[j], buffer);
-        }
-        break;
-      case BOOLEAN:
-        boolean[] boolValues = (boolean[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          ReadWriteIOUtils.write(BytesUtils.boolToByte(boolValues[j]), buffer);
-        }
-        break;
-      case TEXT:
-      case BLOB:
-      case STRING:
-      case OBJECT:
-        Binary[] binaryValues = (Binary[]) column;
-        for (int j = 0; j < rowCount; j++) {
-          if (binaryValues[j] != null && binaryValues[j].getValues() != null) {
-            ReadWriteIOUtils.write(binaryValues[j], buffer);
-          } else {
-            ReadWriteIOUtils.write(0, buffer);
-          }
-        }
-        break;
-      default:
-        throw new UnSupportedDataTypeException(String.format(DATATYPE_UNSUPPORTED, dataType));
-    }
+    Type.fromTsDataType(dataType).serializeArray(column, rowCount, buffer);

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). Both ByteBuffer and DataOutputStream Tablet writers now use dedicated TypeService serializers that preserve the legacy length-plus-payload format. Null binary values retain a zero-length placeholder and use the existing separate bitmap; no TsFile presence byte is added. The new regression checks exact bytes for TEXT, STRING, BLOB and OBJECT, including nulls, empty values and inactive rows. InsertTabletNodeSerdeTest and InsertMultiTabletsNodeSerdeTest pass.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java:
##########
@@ -1032,36 +893,7 @@ private int getRowNumInRange(List<int[]> rangeList) {
   }
 
   private int getColumnSize(TSDataType dataType, Object column, int start, int end) {
-    int size = 0;
-    switch (dataType) {
-      case INT32:
-      case DATE:
-        size += Integer.BYTES * (end - start);
-        break;
-      case INT64:
-      case TIMESTAMP:
-        size += Long.BYTES * (end - start);
-        break;
-      case FLOAT:
-        size += Float.BYTES * (end - start);
-        break;
-      case DOUBLE:
-        size += Double.BYTES * (end - start);
-        break;
-      case BOOLEAN:
-        size += Byte.BYTES * (end - start);
-        break;
-      case TEXT:
-      case BLOB:
-      case STRING:
-      case OBJECT:
-        Binary[] binaryValues = (Binary[]) column;
-        for (int j = start; j < end; j++) {
-          size += ReadWriteIOUtils.sizeToWrite(binaryValues[j]);
-        }
-        break;
-    }
-    return size;
+    return Type.fromTsDataType(dataType).serializedSize(column, start, end);

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). Tablet and WAL size calculation now share a range-aware calculator that counts exactly the bytes written by the legacy WAL writer: length plus payload, including null placeholders, over [start, end). A regression compares the calculated size with the actual bytes written for a non-zero-start binary slice. All 5 WALFileTest cases pass; the targeted DataNode serialization/WAL run passed 31 tests.



##########
iotdb-client/isession/src/main/java/org/apache/iotdb/isession/TypeServices.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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.iotdb.isession;
+
+import org.apache.iotdb.rpc.IoTDBRpcDataSet;
+import org.apache.iotdb.rpc.StatementExecutionException;
+
+import org.apache.tsfile.read.common.Field;
+import org.apache.tsfile.read.common.type.service.TypeService;
+import org.apache.tsfile.write.UnSupportedDataTypeException;
+
+/** Type-specific RPC result readers that preserve primitive access without intermediate boxing. */
+final class TypeServices {
+
+  static final TypeService<FieldValueReader> FIELD_VALUE_READER_SERVICE =
+      type ->
+          switch (type.getTypeEnum()) {
+            case BOOLEAN ->
+                (dataSet, columnIndex, field) -> field.setBoolV(dataSet.getBoolean(columnIndex));
+            case INT32, DATE ->
+                (dataSet, columnIndex, field) -> field.setIntV(dataSet.getInt(columnIndex));
+            case INT64, TIMESTAMP ->
+                (dataSet, columnIndex, field) -> field.setLongV(dataSet.getLong(columnIndex));
+            case FLOAT ->
+                (dataSet, columnIndex, field) -> field.setFloatV(dataSet.getFloat(columnIndex));
+            case DOUBLE ->
+                (dataSet, columnIndex, field) -> field.setDoubleV(dataSet.getDouble(columnIndex));
+            case TEXT, BLOB, STRING, OBJECT ->
+                (dataSet, columnIndex, field) -> field.setBinaryV(dataSet.getBinary(columnIndex));
+            case ROW, UNKNOWN, VECTOR ->
+                (dataSet, columnIndex, field) -> {
+                  throw new UnSupportedDataTypeException(
+                      String.format("Data type %s is not supported.", type.getTypeEnum()));

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9) by reusing ISessionMessages.EXCEPTION_DATA_TYPE_ARG_NOT_SUPPORTED_31213160, which already exists in both locale files. The exception no longer embeds an English literal. English and Chinese source reactor builds pass (excluding the distribution packaging module).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Refactor TSDataType switches to use TypeService [iotdb]

Posted by "jt2594838 (via GitHub)" <gi...@apache.org>.
jt2594838 commented on code in PR #18606:
URL: https://github.com/apache/iotdb/pull/18606#discussion_r3977849693


##########
iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/TSDataTypeSwitchArchitectureTest.java:
##########
@@ -0,0 +1,39 @@
+/*
+ * 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.iotdb.db.utils;
+
+import com.tngtech.archunit.core.importer.ClassFileImporter;
+import com.tngtech.archunit.core.importer.ImportOption;
+import org.junit.Test;
+
+public class TSDataTypeSwitchArchitectureTest {
+
+  @Test
+  public void productionCodeMustUseTypeService() {
+    // Scan IoTDB production classes on this module's classpath, including its dependencies.
+    // Do not freeze violations or swallow failures: existing violations must fail this test too.
+    TSDataTypeSwitchRule.RULE.check(
+        new ClassFileImporter()
+            .withImportOption(new ImportOption.DoNotIncludeTests())
+            // Avoid building the entire server dependency graph: only switch owners need checking.
+            .withImportOption(location -> TSDataTypeSwitchRule.hasSwitch(location.asURI()))
+            .importPackages("org.apache.iotdb"));

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). Added architecture-test to the default reactor with an aggregate production classpath covering the Java modules, including library-udf, JDBC and examples. Its ArchUnit/ASM check scans org.apache.iotdb without a violation baseline; the existing DataNode check remains explicitly scoped to org.apache.iotdb.db. The aggregate module includes the rule regression tests for ordinary switches, lambdas, anonymous classes, valid TypeService implementations and unrelated methods. Both the aggregate and DataNode architecture suites pass (7 tests each). Remaining client/example/REST type dispatches were migrated to TypeService.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -60,6 +60,9 @@ public final class LibraryUdfMessages {
   public static final String ALL_VALUES_ARE_NAN = "All values are NaN";
 
   // UDFEnvelopeAnalysis
+  public static final String FREQUENCY_MUST_BE_POSITIVE = "The param 'frequency' must > 0.";
+  public static final String AMPLIFICATION_MUST_BE_AT_LEAST_1 =
+      "The param 'amplification' must >= 1.";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). The English messages now say "must be greater than 0" and "must be greater than or equal to 1". The corresponding Chinese messages and validation behavior are preserved.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -60,6 +60,9 @@ public final class LibraryUdfMessages {
   public static final String ALL_VALUES_ARE_NAN = "All values are NaN";
 
   // UDFEnvelopeAnalysis
+  public static final String FREQUENCY_MUST_BE_POSITIVE = "The param 'frequency' must > 0.";
+  public static final String AMPLIFICATION_MUST_BE_AT_LEAST_1 =
+      "The param 'amplification' must >= 1.";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). The frequency and amplification keys now use EXCEPTION_THE_PARAM_FREQUENCY_MUST_BE_GREATER_THAN_0_45820CF9 and EXCEPTION_THE_PARAM_AMPLIFICATION_MUST_BE_GREATER_THAN_OR_EQUAL_TO_1_D64050EB, derived from the corrected English messages. Both locale files and UDFEnvelopeAnalysis call sites match.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -100,6 +103,16 @@ public final class LibraryUdfMessages {
   // UDAFPatternMatch, UDAFDTWMatch
   public static final String UNSUPPORTED_DATATYPE = "Unsupported datatype %s";
 
+  // ExactOrderStatistics
+  public static final String UNSUPPORTED_DATA_TYPE = "Unsupported data type: %s";
+
+  // UDAFQuantile
+  public static final String UNSUPPORTED_DATA_TYPE_IN_QUANTILE = "Unsupported data type";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). Both locale files now use EXCEPTION_UNSUPPORTED_DATA_TYPE_ARG_B411C29E and EXCEPTION_UNSUPPORTED_DATA_TYPE_A8CA7BE7, with ExactOrderStatistics and UDAFQuantile updated accordingly. English and Chinese source reactor builds pass.



##########
library-udf/src/main/i18n/en/org/apache/iotdb/library/i18n/LibraryUdfMessages.java:
##########
@@ -100,6 +103,16 @@ public final class LibraryUdfMessages {
   // UDAFPatternMatch, UDAFDTWMatch
   public static final String UNSUPPORTED_DATATYPE = "Unsupported datatype %s";
 
+  // ExactOrderStatistics
+  public static final String UNSUPPORTED_DATA_TYPE = "Unsupported data type: %s";
+
+  // UDAFQuantile
+  public static final String UNSUPPORTED_DATA_TYPE_IN_QUANTILE = "Unsupported data type";
+  public static final String QUANTILE_K_MUST_BE_AT_LEAST_100 =
+      "Size K has to be greater than or equal to 100.";
+  public static final String QUANTILE_RANK_MUST_BE_IN_RANGE =
+      "rank has to be greater than 0 and less than or equal to 1.";

Review Comment:
   Fixed in [5eb7694245c](https://github.com/apache/iotdb/commit/5eb7694245c85771eccebdfcf68a0bfb1123a3f9). The size/rank validation keys now use EXCEPTION_SIZE_K_HAS_TO_BE_GREATER_THAN_OR_EQUAL_TO_100_C514D1C3 and EXCEPTION_RANK_HAS_TO_BE_GREATER_THAN_0_AND_LESS_THAN_OR_EQUAL_TO_1_0F16AF94 in both locale files and UDAFQuantile. The validation boundaries are unchanged; English and Chinese source reactor builds pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org