hongzhi-gao commented on code in PR #19244:
URL: https://github.com/apache/iotdb/pull/19244#discussion_r4561999448


##########
iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/config/IoTConsensusConfig.java:
##########
@@ -22,6 +22,8 @@
 import 
org.apache.iotdb.commons.client.property.ClientPoolProperty.DefaultProperty;
 import org.apache.iotdb.commons.memory.AtomicLongMemoryBlock;
 import org.apache.iotdb.commons.memory.IMemoryBlock;
+import org.apache.iotdb.consensus.i18n.IoTConsensusMessages;
+import org.apache.iotdb.consensus.iot.thrift.TLogCompressionType;

Review Comment:
   Addressed in 434292b65c5. Internal configuration now uses TsFile 
CompressionType, with NONE mapped to UNCOMPRESSED. The wire enum remains 
separate because its numeric IDs differ from TsFile's; an explicit mapping 
preserves the RPC contract. Unsupported TsFile codecs are rejected by the 
consensus configuration builder, with regression coverage.



##########
iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogCompression.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.consensus.iot.logdispatcher;
+
+import org.apache.iotdb.consensus.i18n.IoTConsensusMessages;
+import org.apache.iotdb.consensus.iot.thrift.TLogBufferCompression;
+import org.apache.iotdb.consensus.iot.thrift.TLogCompressionType;
+import org.apache.iotdb.consensus.iot.thrift.TLogEntry;
+import org.apache.iotdb.consensus.iot.thrift.TSyncLogEntriesReq;
+
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdException;
+import org.apache.tsfile.compress.ICompressor;
+import org.apache.tsfile.compress.IUnCompressor;
+import org.apache.tsfile.file.metadata.enums.CompressionType;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.zip.CRC32C;
+
+/** Wire-only encoding: the original batch and its buffer positions remain 
available for retries. */
+public final class LogCompression {
+  // Conservative allowance for the additional Thrift descriptor and list 
field on the wire.
+  private static final int DESCRIPTOR_BYTES = 32;
+  private static final ICompressor LZ4 = 
ICompressor.getCompressor(CompressionType.LZ4);
+  private static final ICompressor SNAPPY = 
ICompressor.getCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor LZ4_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.LZ4);
+  private static final IUnCompressor SNAPPY_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor ZSTD_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.ZSTD);
+
+  private LogCompression() {}
+
+  /** Accounts for arrays throughout the async attempt, including synchronous 
send failure. */
+  public static final class EncodedRequest implements AutoCloseable {
+    private TSyncLogEntriesReq request;
+    private final AtomicLong reserved;
+    private final long rawBytes;
+    private long encodedBytes;
+    private boolean memoryLimited;
+
+    private EncodedRequest(
+        TSyncLogEntriesReq request, long reserved, long rawBytes, boolean 
memoryLimited) {
+      this.request = request;
+      this.reserved = new AtomicLong(reserved);
+      this.rawBytes = rawBytes;
+      this.encodedBytes = rawBytes;
+      this.memoryLimited = memoryLimited;
+    }
+
+    public long getRawBytes() {
+      return rawBytes;
+    }
+
+    public long getEncodedBytes() {
+      return encodedBytes;
+    }
+
+    public boolean isMemoryLimited() {
+      return memoryLimited;
+    }
+
+    public TSyncLogEntriesReq getRequest() {
+      return request;
+    }
+
+    private void retain(long bytes) {
+      long released = reserved.getAndSet(bytes) - bytes;
+      if (released > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(released);

Review Comment:
   Addressed in 31f35e67b48: expanded the control-flow formatting, split 
declarations, and used clearer variable names. Scoped Spotless checks pass.



##########
iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogCompression.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.consensus.iot.logdispatcher;
+
+import org.apache.iotdb.consensus.i18n.IoTConsensusMessages;
+import org.apache.iotdb.consensus.iot.thrift.TLogBufferCompression;
+import org.apache.iotdb.consensus.iot.thrift.TLogCompressionType;
+import org.apache.iotdb.consensus.iot.thrift.TLogEntry;
+import org.apache.iotdb.consensus.iot.thrift.TSyncLogEntriesReq;
+
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdException;
+import org.apache.tsfile.compress.ICompressor;
+import org.apache.tsfile.compress.IUnCompressor;
+import org.apache.tsfile.file.metadata.enums.CompressionType;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.zip.CRC32C;
+
+/** Wire-only encoding: the original batch and its buffer positions remain 
available for retries. */
+public final class LogCompression {
+  // Conservative allowance for the additional Thrift descriptor and list 
field on the wire.
+  private static final int DESCRIPTOR_BYTES = 32;
+  private static final ICompressor LZ4 = 
ICompressor.getCompressor(CompressionType.LZ4);
+  private static final ICompressor SNAPPY = 
ICompressor.getCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor LZ4_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.LZ4);
+  private static final IUnCompressor SNAPPY_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor ZSTD_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.ZSTD);
+
+  private LogCompression() {}
+
+  /** Accounts for arrays throughout the async attempt, including synchronous 
send failure. */
+  public static final class EncodedRequest implements AutoCloseable {
+    private TSyncLogEntriesReq request;
+    private final AtomicLong reserved;
+    private final long rawBytes;
+    private long encodedBytes;
+    private boolean memoryLimited;
+
+    private EncodedRequest(
+        TSyncLogEntriesReq request, long reserved, long rawBytes, boolean 
memoryLimited) {
+      this.request = request;
+      this.reserved = new AtomicLong(reserved);
+      this.rawBytes = rawBytes;
+      this.encodedBytes = rawBytes;
+      this.memoryLimited = memoryLimited;
+    }
+
+    public long getRawBytes() {
+      return rawBytes;
+    }
+
+    public long getEncodedBytes() {
+      return encodedBytes;
+    }
+
+    public boolean isMemoryLimited() {
+      return memoryLimited;
+    }
+
+    public TSyncLogEntriesReq getRequest() {
+      return request;
+    }
+
+    private void retain(long bytes) {
+      long released = reserved.getAndSet(bytes) - bytes;
+      if (released > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(released);
+    }
+
+    @Override
+    public void close() {
+      long bytes = reserved.getAndSet(0);
+      if (bytes > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(bytes);
+    }
+  }
+
+  public static EncodedRequest compress(
+      TSyncLogEntriesReq original, TLogCompressionType codec, int minSize, int 
maxDecodedBytes)
+      throws IOException {
+    long buffers = 0, rawSize = 0;
+    boolean hasEligibleBuffer = false;
+    for (TLogEntry entry : original.getLogEntries()) {
+      for (ByteBuffer buffer : entry.getData()) {
+        int size = buffer.remaining();
+        rawSize += size;
+        if (size >= minSize && size > 0) {
+          hasEligibleBuffer = true;
+        }
+        buffers++;
+      }
+    }
+    // Preserve the original path for oversized legal entries and when scratch 
memory is scarce.
+    if (codec == TLogCompressionType.NONE || !hasEligibleBuffer || rawSize > 
maxDecodedBytes)
+      return new EncodedRequest(original, 0, rawSize, false);
+    // Charge descriptor/list/entry overhead first, then one block's working 
arrays at a time.
+    // Retain only actual compact outputs between blocks, not a whole-batch 
worst-case estimate.
+    long budget = buffers * 256 + original.getLogEntriesSize() * 128L;
+    if 
(!IoTConsensusMemoryManager.getInstance().reserveLogCompression(budget)) {
+      return new EncodedRequest(original, 0, rawSize, true);
+    }
+    EncodedRequest result = new EncodedRequest(original, budget, rawSize, 
false);
+    try {
+      List<TLogEntry> entries = new ArrayList<>(original.getLogEntriesSize());
+      long retained = 0;
+      boolean changed = false;
+      for (TLogEntry entry : original.getLogEntries()) {
+        List<ByteBuffer> data = new ArrayList<>(entry.getDataSize());
+        List<TLogBufferCompression> info = new 
ArrayList<>(entry.getDataSize());
+        long raw = 0, wire = 0, arrays = 0;
+        boolean compressed = false;
+        for (ByteBuffer buffer : entry.getData()) {
+          int size = buffer.remaining();
+          raw += size;
+          ByteBuffer encoded = buffer;
+          TLogCompressionType actualCodec = TLogCompressionType.NONE;
+          if (size >= minSize && size > 0) {
+            // Includes an optional input copy, codec-bound output and compact 
output, with
+            // allowance for array headers and codec bounds on very small 
buffers.
+            long workspace = 4L * size + 256;
+            long before = result.reserved.get();
+            if 
(IoTConsensusMemoryManager.getInstance().reserveLogCompression(workspace)) {
+              result.reserved.addAndGet(workspace);
+              byte[] input = buffer.hasArray() ? buffer.array() : 
bytes(buffer);
+              int offset = buffer.hasArray() ? buffer.arrayOffset() + 
buffer.position() : 0;
+              int bound =
+                  codec == TLogCompressionType.ZSTD
+                      ? (int) Zstd.compressBound(size)
+                      : compressor(codec).getMaxBytesForCompression(size);

Review Comment:
   The special path originally kept Zstd at level 1 while the available TsFile 
API used its own default level. Removed that special handling in 434292b65c5: 
ZSTD now uses TsFile ICompressor/IUnCompressor and its default level, just like 
the other codecs. The pinned TsFile default is the maximum Zstd level. I am 
rerunning native cluster benchmarks; the existing Zstd-1 numbers are explicitly 
marked as historical and do not represent the new default.



##########
iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogCompression.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.consensus.iot.logdispatcher;
+
+import org.apache.iotdb.consensus.i18n.IoTConsensusMessages;
+import org.apache.iotdb.consensus.iot.thrift.TLogBufferCompression;
+import org.apache.iotdb.consensus.iot.thrift.TLogCompressionType;
+import org.apache.iotdb.consensus.iot.thrift.TLogEntry;
+import org.apache.iotdb.consensus.iot.thrift.TSyncLogEntriesReq;
+
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdException;
+import org.apache.tsfile.compress.ICompressor;
+import org.apache.tsfile.compress.IUnCompressor;
+import org.apache.tsfile.file.metadata.enums.CompressionType;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.zip.CRC32C;
+
+/** Wire-only encoding: the original batch and its buffer positions remain 
available for retries. */
+public final class LogCompression {
+  // Conservative allowance for the additional Thrift descriptor and list 
field on the wire.
+  private static final int DESCRIPTOR_BYTES = 32;
+  private static final ICompressor LZ4 = 
ICompressor.getCompressor(CompressionType.LZ4);
+  private static final ICompressor SNAPPY = 
ICompressor.getCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor LZ4_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.LZ4);
+  private static final IUnCompressor SNAPPY_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.SNAPPY);
+  private static final IUnCompressor ZSTD_DECODER =
+      IUnCompressor.getUnCompressor(CompressionType.ZSTD);
+
+  private LogCompression() {}
+
+  /** Accounts for arrays throughout the async attempt, including synchronous 
send failure. */
+  public static final class EncodedRequest implements AutoCloseable {
+    private TSyncLogEntriesReq request;
+    private final AtomicLong reserved;
+    private final long rawBytes;
+    private long encodedBytes;
+    private boolean memoryLimited;
+
+    private EncodedRequest(
+        TSyncLogEntriesReq request, long reserved, long rawBytes, boolean 
memoryLimited) {
+      this.request = request;
+      this.reserved = new AtomicLong(reserved);
+      this.rawBytes = rawBytes;
+      this.encodedBytes = rawBytes;
+      this.memoryLimited = memoryLimited;
+    }
+
+    public long getRawBytes() {
+      return rawBytes;
+    }
+
+    public long getEncodedBytes() {
+      return encodedBytes;
+    }
+
+    public boolean isMemoryLimited() {
+      return memoryLimited;
+    }
+
+    public TSyncLogEntriesReq getRequest() {
+      return request;
+    }
+
+    private void retain(long bytes) {
+      long released = reserved.getAndSet(bytes) - bytes;
+      if (released > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(released);
+    }
+
+    @Override
+    public void close() {
+      long bytes = reserved.getAndSet(0);
+      if (bytes > 0) 
IoTConsensusMemoryManager.getInstance().freeLogCompression(bytes);
+    }
+  }
+
+  public static EncodedRequest compress(
+      TSyncLogEntriesReq original, TLogCompressionType codec, int minSize, int 
maxDecodedBytes)
+      throws IOException {
+    long buffers = 0, rawSize = 0;
+    boolean hasEligibleBuffer = false;
+    for (TLogEntry entry : original.getLogEntries()) {
+      for (ByteBuffer buffer : entry.getData()) {
+        int size = buffer.remaining();
+        rawSize += size;
+        if (size >= minSize && size > 0) {
+          hasEligibleBuffer = true;
+        }
+        buffers++;
+      }
+    }
+    // Preserve the original path for oversized legal entries and when scratch 
memory is scarce.
+    if (codec == TLogCompressionType.NONE || !hasEligibleBuffer || rawSize > 
maxDecodedBytes)
+      return new EncodedRequest(original, 0, rawSize, false);
+    // Charge descriptor/list/entry overhead first, then one block's working 
arrays at a time.
+    // Retain only actual compact outputs between blocks, not a whole-batch 
worst-case estimate.
+    long budget = buffers * 256 + original.getLogEntriesSize() * 128L;
+    if 
(!IoTConsensusMemoryManager.getInstance().reserveLogCompression(budget)) {
+      return new EncodedRequest(original, 0, rawSize, true);
+    }
+    EncodedRequest result = new EncodedRequest(original, budget, rawSize, 
false);
+    try {
+      List<TLogEntry> entries = new ArrayList<>(original.getLogEntriesSize());
+      long retained = 0;
+      boolean changed = false;
+      for (TLogEntry entry : original.getLogEntries()) {
+        List<ByteBuffer> data = new ArrayList<>(entry.getDataSize());
+        List<TLogBufferCompression> info = new 
ArrayList<>(entry.getDataSize());
+        long raw = 0, wire = 0, arrays = 0;
+        boolean compressed = false;
+        for (ByteBuffer buffer : entry.getData()) {
+          int size = buffer.remaining();
+          raw += size;
+          ByteBuffer encoded = buffer;
+          TLogCompressionType actualCodec = TLogCompressionType.NONE;
+          if (size >= minSize && size > 0) {
+            // Includes an optional input copy, codec-bound output and compact 
output, with
+            // allowance for array headers and codec bounds on very small 
buffers.
+            long workspace = 4L * size + 256;
+            long before = result.reserved.get();
+            if 
(IoTConsensusMemoryManager.getInstance().reserveLogCompression(workspace)) {
+              result.reserved.addAndGet(workspace);
+              byte[] input = buffer.hasArray() ? buffer.array() : 
bytes(buffer);
+              int offset = buffer.hasArray() ? buffer.arrayOffset() + 
buffer.position() : 0;
+              int bound =
+                  codec == TLogCompressionType.ZSTD
+                      ? (int) Zstd.compressBound(size)
+                      : compressor(codec).getMaxBytesForCompression(size);
+              byte[] output = new byte[bound];
+              int length =
+                  codec == TLogCompressionType.ZSTD
+                      ? (int)
+                          Zstd.compressByteArray(output, 0, output.length, 
input, offset, size, 1)
+                      : compressor(codec).compress(input, offset, size, 
output);
+              if (length < 0) throw invalid(Failure.CODEC, size, length);
+              if ((long) length + DESCRIPTOR_BYTES < size) {

Review Comment:
   Renamed the variables to compressedLength/uncompressedLength in 31f35e67b48. 
The existing internal 4 KiB cutoff is a pre-compression eligibility check, 
separate from the post-compression benefit rule. Currently a buffer must save 
space including its descriptor, and the entry must also save space including 
all descriptors; a fixed 5% minimum-savings rule has not been added. I am 
rerunning performance tests on the current implementation and will inspect 
near-break-even payloads before choosing an additional benefit cutoff. Leaving 
this part open rather than claiming the size cutoff addresses decoding cost.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to