You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "mimaison (via GitHub)" <gi...@apache.org> on 2024/03/11 18:40:19 UTC
[PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
mimaison opened a new pull request, #15516:
URL: https://github.com/apache/kafka/pull/15516
Based on https://github.com/apache/kafka/pull/5927
### Committer Checklist (excluded from commit message)
- [ ] Verify design and implementation
- [ ] Verify test coverage and CI build status
- [ ] Verify documentation (including upgrade notes)
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "stanislavkozlovski (via GitHub)" <gi...@apache.org>.
stanislavkozlovski commented on PR #15516:
URL: https://github.com/apache/kafka/pull/15516#issuecomment-2250176172
Has anybody noticed that the Linear Write test in KIP-390 is inaccurate?
1. It suggests that the write speed on a broker is 22GB/s. I wasn't able to find an SSD on the market in 2024 (6 years later) that supports this throughput
2. The reason for this, I think, is that it inaccurately sets the benchmark test to write just 8192 bytes `--bytes 8192` and the size to write is 8192 itself, so the test seems to just be comparing the nanoseconds it takes for the very first write and then extrapolating further to a full second.
- https://cwiki.apache.org/confluence/display/KAFKA/KIP-390%3A+Support+Compression+Level

--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1601283629
##########
clients/src/test/java/org/apache/kafka/common/compress/GzipCompressionTest.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class GzipCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ GzipCompression.Builder builder = Compression.gzip();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ for (int level : Arrays.asList(GzipCompression.MIN_LEVEL, GzipCompression.DEFAULT_LEVEL, GzipCompression.MAX_LEVEL)) {
+ GzipCompression compression = builder.level(level).build();
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
+ out.write(data);
+ out.flush();
+ }
+ bufferStream.buffer().flip();
+
+ try (InputStream inputStream = compression.wrapForInput(bufferStream.buffer(), magic, BufferSupplier.create())) {
+ byte[] result = new byte[data.length];
+ int read = inputStream.read(result);
+ assertEquals(data.length, read);
+ assertArrayEquals(data, result);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testCompressionLevels() {
+ GzipCompression.Builder builder = Compression.gzip();
+
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MIN_LEVEL - 1));
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MAX_LEVEL + 1));
+
+ builder.level(GzipCompression.MIN_LEVEL);
+ builder.level(GzipCompression.MAX_LEVEL);
+ }
+
+ @Test
+ public void testLevelValidator() {
+ GzipCompression.LevelValidator validator = new GzipCompression.LevelValidator();
+ for (int level = GzipCompression.MIN_LEVEL; level <= GzipCompression.MAX_LEVEL; level++) {
+ validator.ensureValid("", level);
+ }
+ validator.ensureValid("", GzipCompression.DEFAULT_LEVEL);
+ assertThrows(ConfigException.class, () -> validator.ensureValid("", 0));
Review Comment:
Yes this can be removed
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2380478649
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
@chia7712 : Previously, we considered using the topic level compression type instead of the one in the original batch. There is one subtle issue on batch size. During compaction, we group a set of segments so that the total size doesn't exceed 2GB. If we use a different compression type, the compacted data could be exceeding the max segment limit and failing the index append.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison merged PR #15516:
URL: https://github.com/apache/kafka/pull/15516
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2314325244
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
> Right, here we could use the level if specified. I expect most topics to use compression.type=producer but in case a specific compression type and level is set, that would make sense to use them.
@Yunyung Could you please file a minor patch for it?
> Do you think there are scenarios where the gains of picking a different level for older data would be significant enough to motivate such a feature?
The key point is the compression type rather than level. I received a request to compress old data during compaction. The change should be straightforward, so it seems acceptable.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "showuon (via GitHub)" <gi...@apache.org>.
showuon commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1607919763
##########
storage/src/main/java/org/apache/kafka/storage/internals/log/LogValidator.java:
##########
@@ -331,12 +332,12 @@ public ValidationResult assignOffsetsNonCompressed(LongRef offsetCounter,
public ValidationResult validateMessagesAndAssignOffsetsCompressed(LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
- if (targetCompression == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
+ if (targetCompression.type() == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
throw new UnsupportedCompressionTypeException("Produce requests to inter.broker.protocol.version < 2.1 broker " +
"are not allowed to use ZStandard compression");
// No in place assignment situation 1
- boolean inPlaceAssignment = sourceCompression == targetCompression;
+ boolean inPlaceAssignment = sourceCompressionType == targetCompression.type();
Review Comment:
I agree. But I think we should mention this in the KIP-390 at least.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15516:
URL: https://github.com/apache/kafka/pull/15516#issuecomment-2122361920
Thanks for the reviews!
I had to rebase again so I'll wait for the CI to complete.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1601337698
##########
clients/src/test/java/org/apache/kafka/common/compress/GzipCompressionTest.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class GzipCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ GzipCompression.Builder builder = Compression.gzip();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
Review Comment:
Good idea, I increased the input data to 1024 bytes
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2661185848
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
open https://issues.apache.org/jira/browse/KAFKA-20036
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "showuon (via GitHub)" <gi...@apache.org>.
showuon commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1607924069
##########
clients/src/main/java/org/apache/kafka/common/config/TopicConfig.java:
##########
@@ -173,6 +173,14 @@ public class TopicConfig {
"accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the " +
"original compression codec set by the producer.";
+
+ public static final String COMPRESSION_GZIP_LEVEL_CONFIG = "compression.gzip.level";
+ public static final String COMPRESSION_GZIP_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>gzip</code>.";
+ public static final String COMPRESSION_LZ4_LEVEL_CONFIG = "compression.lz4.level";
+ public static final String COMPRESSION_LZ4_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>lz4</code>.";
+ public static final String COMPRESSION_ZSTD_LEVEL_CONFIG = "compression.zstd.level";
+ public static final String COMPRESSION_ZSTD_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>zstd</code>.";
Review Comment:
I was thinking we added in the config description. Or maybe added in KIP-390 is good enough.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1601222613
##########
clients/src/test/java/org/apache/kafka/common/compress/NoCompressionTest.java:
##########
@@ -0,0 +1,57 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class NoCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ NoCompression compression = Compression.NONE;
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
Review Comment:
Yes, good catch!
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1605313096
##########
core/src/test/scala/unit/kafka/log/LogValidatorTest.scala:
##########
@@ -1538,7 +1563,80 @@ class LogValidatorTest {
assertEquals(e.recordErrors.size, 3)
}
- private def testBatchWithoutRecordsNotAllowed(sourceCompression: CompressionType, targetCompression: CompressionType): Unit = {
+ @Test
+ def testDifferentLevelDoesNotCauseRecompression(): Unit = {
+ val records = List(
+ List.fill(256)("some").mkString("").getBytes,
+ List.fill(256)("data").mkString("").getBytes
+ )
+ // Records from the producer were created with gzip max level
+ val gzipMax: Compression = Compression.gzip().level(GzipCompression.MAX_LEVEL).build()
+ val recordsGzipMax = createRecords(records, RecordBatch.MAGIC_VALUE_V2, RecordBatch.NO_TIMESTAMP, gzipMax)
+
+ // The topic is configured with gzip min level
+ val gzipMin: Compression = Compression.gzip().level(GzipCompression.MIN_LEVEL).build()
+ val recordsGzipMin = createRecords(records, RecordBatch.MAGIC_VALUE_V2, RecordBatch.NO_TIMESTAMP, gzipMin)
+
+ // ensure data compressed with gzip max and min is different
+ assertNotEquals(recordsGzipMax, recordsGzipMin)
+ val validator = new LogValidator(recordsGzipMax,
+ topicPartition,
+ time,
+ gzipMax.`type`(),
+ gzipMin,
+ false,
+ RecordBatch.CURRENT_MAGIC_VALUE,
Review Comment:
Earlier, we use RecordBatch.MAGIC_VALUE_V2. Should we be consistent here? Ditto in the next test.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2312529139
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
1) I'm not sure whether there has been any discussion about the compression level used during compaction. The current implementation just applies the default level, but perhaps it should respect the topic's configured compression level
2) Another brainstorm is to introduce a flag that allows compaction to use different compression. This would give users option to choose a different compression algorithm for older data.
@mimaison @junrao @showuon WDYT?
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "showuon (via GitHub)" <gi...@apache.org>.
showuon commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1579334152
##########
clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java:
##########
@@ -189,7 +189,7 @@ public RecordAccumulator(LogContext logContext,
BufferPool bufferPool) {
this(logContext,
batchSize,
- compression,
+ compression,
Review Comment:
nit: wrong indent
##########
clients/src/main/java/org/apache/kafka/common/compress/Compression.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+public interface Compression {
+
+ /**
+ * The compression type for this compression codec
+ */
+ CompressionType type();
+
+ /**
+ * Wrap bufferStream with an OutputStream that will compress data with this CompressionType.
+ * Note: Unlike {@link #wrapForInput}, this cannot take {@link ByteBuffer}s directly.
+ * Currently, MemoryRecordsBuilder writes to the underlying buffer in the given {@link ByteBufferOutputStream} after the compressed data has been written.
+ * In the event that the buffer needs to be expanded while writing the data, access to the underlying buffer needs to be preserved.
+ */
+ OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion);
+
+ /**
+ * Wrap buffer with an InputStream that will decompress data with this CompressionType.
+ *
+ * @param buffer The {@link ByteBuffer} instance holding the data to decompress.
+ * @param messageVersion The record format version to use.
+ * @param decompressionBufferSupplier The supplier of ByteBuffer(s) used for decompression if supported.
+ * For small record batches, allocating a potentially large buffer (64 KB for LZ4)
Review Comment:
miss `@return`
##########
clients/src/test/java/org/apache/kafka/common/compress/GzipCompressionTest.java:
##########
@@ -0,0 +1,82 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class GzipCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ GzipCompression.Builder builder = Compression.gzip();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ for (int level : Arrays.asList(GzipCompression.MIN_LEVEL, GzipCompression.DEFAULT_LEVEL, GzipCompression.MAX_LEVEL)) {
+ GzipCompression compression = builder.level(level).build();
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
+ out.write(data);
+ out.flush();
+ }
+ bufferStream.buffer().flip();
+
+ try (InputStream inputStream = compression.wrapForInput(bufferStream.buffer(), magic, BufferSupplier.create())) {
+ byte[] result = new byte[data.length];
+ inputStream.read(result);
+ assertArrayEquals(data, result);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testCompressionLevels() {
+ GzipCompression.Builder builder = new GzipCompression.Builder();
+
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MIN_LEVEL - 1));
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MAX_LEVEL + 1));
+
+ builder.level(GzipCompression.MIN_LEVEL);
+ builder.level(GzipCompression.MAX_LEVEL);
Review Comment:
nit: `assertDoesNotThrow`
##########
clients/src/main/java/org/apache/kafka/common/compress/Lz4BlockOutputStream.java:
##########
@@ -33,18 +33,14 @@
*
* This class is not thread-safe.
*/
-public final class KafkaLZ4BlockOutputStream extends OutputStream {
+public final class Lz4BlockOutputStream extends OutputStream {
public static final int MAGIC = 0x184D2204;
- public static final int LZ4_MAX_HEADER_LENGTH = 19;
public static final int LZ4_FRAME_INCOMPRESSIBLE_MASK = 0x80000000;
public static final String CLOSED_STREAM = "The stream is already closed";
public static final int BLOCKSIZE_64KB = 4;
- public static final int BLOCKSIZE_256KB = 5;
- public static final int BLOCKSIZE_1MB = 6;
- public static final int BLOCKSIZE_4MB = 7;
Review Comment:
They can be removed because we have another KIP to address them. Fine.
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/RecordAccumulatorTest.java:
##########
@@ -1600,7 +1601,7 @@ public void testDrainWithANodeThatDoesntHostAnyPartitions() {
int lingerMs = 10;
long totalSize = 10 * 1024;
RecordAccumulator accum = createTestRecordAccumulator(batchSize, totalSize,
- CompressionType.NONE, lingerMs);
+ Compression.NONE, lingerMs);
Review Comment:
wrong indent.
##########
clients/src/main/java/org/apache/kafka/common/compress/Compression.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+public interface Compression {
+
+ /**
+ * The compression type for this compression codec
+ */
+ CompressionType type();
+
+ /**
+ * Wrap bufferStream with an OutputStream that will compress data with this CompressionType.
+ * Note: Unlike {@link #wrapForInput}, this cannot take {@link ByteBuffer}s directly.
+ * Currently, MemoryRecordsBuilder writes to the underlying buffer in the given {@link ByteBufferOutputStream} after the compressed data has been written.
+ * In the event that the buffer needs to be expanded while writing the data, access to the underlying buffer needs to be preserved.
+ */
Review Comment:
Please add `@param` `@return` .
##########
clients/src/main/java/org/apache/kafka/common/compress/Lz4BlockOutputStream.java:
##########
@@ -64,15 +60,22 @@ public final class KafkaLZ4BlockOutputStream extends OutputStream {
* @param out The output stream to compress
* @param blockSize Default: 4. The block size used during compression. 4=64kb, 5=256kb, 6=1mb, 7=4mb. All other
* values will generate an exception
+ * @param level The compression level to use
* @param blockChecksum Default: false. When true, a XXHash32 checksum is computed and appended to the stream for
* every block of data
* @param useBrokenFlagDescriptorChecksum Default: false. When true, writes an incorrect FrameDescriptor checksum
* compatible with older kafka clients.
* @throws IOException
*/
- public KafkaLZ4BlockOutputStream(OutputStream out, int blockSize, boolean blockChecksum, boolean useBrokenFlagDescriptorChecksum) throws IOException {
+ public Lz4BlockOutputStream(OutputStream out, int blockSize, int level, boolean blockChecksum, boolean useBrokenFlagDescriptorChecksum) throws IOException {
this.out = out;
- compressor = LZ4Factory.fastestInstance().fastCompressor();
+ /*
+ * lz4-java provides two types of compressors; fastCompressor, which requires less memory but fast compression speed (with default compression level only),
+ * and highCompressor which requires more memory and slower speed but compresses more efficiently (with various compression level).
+ *
+ * For backward compatibility, Lz4BlockOutputStream uses fastCompressor with default compression level but, with the other level, it uses highCompressor.
+ */
+ compressor = level == Lz4Compression.DEFAULT_LEVEL ? LZ4Factory.fastestInstance().fastCompressor() : LZ4Factory.fastestInstance().highCompressor(level);
Review Comment:
Should we add this comment in the `lz4.level` config description? I think users also need to know it.
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/RecordAccumulatorTest.java:
##########
@@ -458,7 +459,7 @@ public void testRetryBackoff() throws Exception {
String metricGrpName = "producer-metrics";
final RecordAccumulator accum = new RecordAccumulator(logContext, batchSize,
- CompressionType.NONE, lingerMs, retryBackoffMs, retryBackoffMaxMs,
+ Compression.NONE, lingerMs, retryBackoffMs, retryBackoffMaxMs,
Review Comment:
wrong indent
##########
storage/src/main/java/org/apache/kafka/storage/internals/log/LogValidator.java:
##########
@@ -331,12 +332,12 @@ public ValidationResult assignOffsetsNonCompressed(LongRef offsetCounter,
public ValidationResult validateMessagesAndAssignOffsetsCompressed(LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
- if (targetCompression == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
+ if (targetCompression.type() == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
throw new UnsupportedCompressionTypeException("Produce requests to inter.broker.protocol.version < 2.1 broker " +
"are not allowed to use ZStandard compression");
// No in place assignment situation 1
- boolean inPlaceAssignment = sourceCompression == targetCompression;
+ boolean inPlaceAssignment = sourceCompressionType == targetCompression.type();
Review Comment:
So we won't do re-compression if only level is different? I didn't see this in KIP. Maybe we should add it?
##########
clients/src/test/java/org/apache/kafka/common/compress/Lz4CompressionTest.java:
##########
@@ -27,25 +31,92 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
-import static org.apache.kafka.common.compress.KafkaLZ4BlockOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK;
+import static org.apache.kafka.common.compress.Lz4BlockOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-public class KafkaLZ4Test {
+public class Lz4CompressionTest {
private final static Random RANDOM = new Random(0);
+ @Test
+ public void testLz4FramingMagicV0() {
+ ByteBuffer buffer = ByteBuffer.allocate(256);
+ Lz4Compression compression = new Lz4Compression.Builder().build();
+ Lz4BlockOutputStream out = (Lz4BlockOutputStream) compression.wrapForOutput(
+ new ByteBufferOutputStream(buffer), RecordBatch.MAGIC_VALUE_V0);
+ assertTrue(out.useBrokenFlagDescriptorChecksum());
+
+ buffer.rewind();
+
+ ChunkedBytesStream in = (ChunkedBytesStream) compression.wrapForInput(buffer, RecordBatch.MAGIC_VALUE_V0, BufferSupplier.NO_CACHING);
+ assertTrue(((Lz4BlockInputStream) in.sourceStream()).ignoreFlagDescriptorChecksum());
+ }
+
+ @Test
+ public void testLz4FramingMagicV1() {
+ ByteBuffer buffer = ByteBuffer.allocate(256);
+ Lz4Compression compression = new Lz4Compression.Builder().build();
+ Lz4BlockOutputStream out = (Lz4BlockOutputStream) compression.wrapForOutput(
+ new ByteBufferOutputStream(buffer), RecordBatch.MAGIC_VALUE_V1);
+ assertFalse(out.useBrokenFlagDescriptorChecksum());
+
+ buffer.rewind();
+
+ ChunkedBytesStream in = (ChunkedBytesStream) compression.wrapForInput(buffer, RecordBatch.MAGIC_VALUE_V1, BufferSupplier.create());
+ assertFalse(((Lz4BlockInputStream) in.sourceStream()).ignoreFlagDescriptorChecksum());
+ }
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ Lz4Compression.Builder builder = Compression.lz4();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ for (int level : Arrays.asList(Lz4Compression.MIN_LEVEL, Lz4Compression.DEFAULT_LEVEL, Lz4Compression.MAX_LEVEL)) {
+ Lz4Compression compression = builder.level(level).build();
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
+ out.write(data);
+ out.flush();
+ }
+ bufferStream.buffer().flip();
+
+ try (InputStream inputStream = compression.wrapForInput(bufferStream.buffer(), magic, BufferSupplier.create())) {
+ byte[] result = new byte[data.length];
+ inputStream.read(result);
+ assertArrayEquals(data, result);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testCompressionLevels() {
+ Lz4Compression.Builder builder = new Lz4Compression.Builder();
+
+ assertThrows(IllegalArgumentException.class, () -> builder.level(Lz4Compression.MIN_LEVEL - 1));
+ assertThrows(IllegalArgumentException.class, () -> builder.level(Lz4Compression.MAX_LEVEL + 1));
+
+ builder.level(Lz4Compression.MIN_LEVEL);
+ builder.level(Lz4Compression.MAX_LEVEL);
Review Comment:
nit: assertDoesNotThrow
##########
clients/src/test/java/org/apache/kafka/common/record/DefaultRecordBatchTest.java:
##########
@@ -500,27 +501,24 @@ private static Stream<Arguments> testBufferReuseInSkipKeyValueIterator() {
@MethodSource
public void testZstdJniForSkipKeyValueIterator(int expectedJniCalls, byte[] recordValue) throws IOException {
MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L,
- CompressionType.ZSTD, TimestampType.CREATE_TIME,
+ Compression.zstd().build(), TimestampType.CREATE_TIME,
new SimpleRecord(9L, "hakuna-matata".getBytes(), recordValue)
);
// Buffer containing compressed data
final ByteBuffer compressedBuf = records.buffer();
// Create a RecordBatch object
final DefaultRecordBatch batch = spy(new DefaultRecordBatch(compressedBuf.duplicate()));
- final CompressionType mockCompression = mock(CompressionType.ZSTD.getClass());
- doReturn(mockCompression).when(batch).compressionType();
-
+ final ZstdCompression compression = Compression.zstd().build();
// Buffer containing compressed records to be used for creating zstd-jni stream
- ByteBuffer recordsBuffer = compressedBuf.duplicate();
+ ByteBuffer recordsBuffer = spy(compressedBuf.duplicate());
Review Comment:
Why should we spy this?
##########
clients/src/main/java/org/apache/kafka/common/config/TopicConfig.java:
##########
@@ -173,6 +173,14 @@ public class TopicConfig {
"accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the " +
"original compression codec set by the producer.";
+
+ public static final String COMPRESSION_GZIP_LEVEL_CONFIG = "compression.gzip.level";
+ public static final String COMPRESSION_GZIP_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>gzip</code>.";
+ public static final String COMPRESSION_LZ4_LEVEL_CONFIG = "compression.lz4.level";
+ public static final String COMPRESSION_LZ4_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>lz4</code>.";
+ public static final String COMPRESSION_ZSTD_LEVEL_CONFIG = "compression.zstd.level";
+ public static final String COMPRESSION_ZSTD_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>zstd</code>.";
Review Comment:
nit: Should we provide the doc link for each compression type? It's hard to know which level means what.
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/RecordAccumulatorTest.java:
##########
@@ -1750,7 +1751,7 @@ private RecordAccumulator createTestRecordAccumulator(
return new RecordAccumulator(
logContext,
batchSize,
- type,
+ compression,
Review Comment:
wrong indent.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1586920863
##########
clients/src/main/java/org/apache/kafka/common/compress/NoCompression.java:
##########
@@ -14,37 +14,48 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.kafka.common.compress;
-import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
import org.apache.kafka.common.utils.ByteBufferInputStream;
import org.apache.kafka.common.utils.ByteBufferOutputStream;
-import org.xerial.snappy.SnappyInputStream;
-import org.xerial.snappy.SnappyOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
-public class SnappyFactory {
+public class NoCompression implements Compression {
- private SnappyFactory() { }
+ @Override
+ public CompressionType type() {
+ return CompressionType.NONE;
+ }
- public static OutputStream wrapForOutput(ByteBufferOutputStream buffer) {
- try {
- return new SnappyOutputStream(buffer);
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) {
+ return bufferStream;
}
- public static InputStream wrapForInput(ByteBuffer buffer) {
- try {
- return new SnappyInputStream(new ByteBufferInputStream(buffer));
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
+ return new ByteBufferInputStream(buffer);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof NoCompression;
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
Review Comment:
Hmm, we redefine `equals()` such that all objects of type NoCompression are equal, yet they have different hashcode?
##########
clients/src/main/java/org/apache/kafka/common/telemetry/internals/ClientTelemetryUtils.java:
##########
@@ -201,8 +203,10 @@ public static byte[] compress(byte[] raw, CompressionType compressionType) throw
public static ByteBuffer decompress(byte[] metrics, CompressionType compressionType) {
ByteBuffer data = ByteBuffer.wrap(metrics);
- try (InputStream in = compressionType.wrapForInput(data, RecordBatch.CURRENT_MAGIC_VALUE, BufferSupplier.create());
+ Compression compression = Compression.of(compressionType).build();
+ try (InputStream in = compression.wrapForInput(data, RecordBatch.CURRENT_MAGIC_VALUE, BufferSupplier.create());
ByteBufferOutputStream out = new ByteBufferOutputStream(512)) {
+
Review Comment:
extra new line
##########
clients/src/main/java/org/apache/kafka/common/compress/Lz4Compression.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.apache.kafka.common.utils.ChunkedBytesStream;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Objects;
+
+public class Lz4Compression implements Compression {
+
+ public static final int MIN_LEVEL = 1;
+ public static final int MAX_LEVEL = 17;
+ public static final int DEFAULT_LEVEL = 9;
Review Comment:
So, every time we update the Lz4 library, we may need to update the above values? We probably want to add a note here.
##########
clients/src/main/java/org/apache/kafka/common/compress/Compression.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+public interface Compression {
+
+ /**
+ * The compression type for this compression codec
+ */
+ CompressionType type();
+
+ /**
+ * Wrap bufferStream with an OutputStream that will compress data with this CompressionType.
Review Comment:
Could we add the javadoc for messageVersion?
##########
clients/src/main/java/org/apache/kafka/common/compress/GzipCompression.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.config.ConfigDef;
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferInputStream;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.apache.kafka.common.utils.ChunkedBytesStream;
+
+import java.io.BufferedOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Objects;
+import java.util.zip.Deflater;
+import java.util.zip.GZIPInputStream;
+
+public class GzipCompression implements Compression {
+
+ public static final int MIN_LEVEL = Deflater.BEST_SPEED;
+ public static final int MAX_LEVEL = Deflater.BEST_COMPRESSION;
+ public static final int DEFAULT_LEVEL = Deflater.DEFAULT_COMPRESSION;
+
+ private final int level;
+
+ private GzipCompression(int level) {
+ this.level = level;
+ }
+
+ @Override
+ public CompressionType type() {
+ return CompressionType.GZIP;
+ }
+
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream buffer, byte messageVersion) {
+ try {
+ // Set input buffer (uncompressed) to 16 KB (none by default) and output buffer (compressed) to
+ // 8 KB (0.5 KB by default) to ensure reasonable performance in cases where the caller passes a small
+ // number of bytes to write (potentially a single byte)
+ return new BufferedOutputStream(new GzipOutputStream(buffer, 8 * 1024, this.level), 16 * 1024);
Review Comment:
this.level => level Ditto in a few other classes.
##########
clients/src/main/java/org/apache/kafka/common/compress/NoCompression.java:
##########
@@ -14,37 +14,48 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.kafka.common.compress;
-import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
import org.apache.kafka.common.utils.ByteBufferInputStream;
import org.apache.kafka.common.utils.ByteBufferOutputStream;
-import org.xerial.snappy.SnappyInputStream;
-import org.xerial.snappy.SnappyOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
-public class SnappyFactory {
+public class NoCompression implements Compression {
- private SnappyFactory() { }
+ @Override
+ public CompressionType type() {
+ return CompressionType.NONE;
+ }
- public static OutputStream wrapForOutput(ByteBufferOutputStream buffer) {
- try {
- return new SnappyOutputStream(buffer);
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) {
+ return bufferStream;
}
- public static InputStream wrapForInput(ByteBuffer buffer) {
- try {
- return new SnappyInputStream(new ByteBufferInputStream(buffer));
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
+ return new ByteBufferInputStream(buffer);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof NoCompression;
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
}
+ public static class Builder implements Compression.Builder<NoCompression> {
Review Comment:
Should we make the constructor of NoCompression private so that only the builder can be used? Ditto for other compression classes.
##########
storage/src/main/java/org/apache/kafka/storage/internals/log/LogConfig.java:
##########
@@ -388,6 +402,32 @@ public LogConfig(Map<?, ?> props, Set<String> overriddenConfigs) {
remoteLogConfig = new RemoteLogConfig(this);
}
+ private Optional<Compression> getCompression() {
+ BrokerCompressionType brokerCompressionType = BrokerCompressionType.forName(getString(TopicConfig.COMPRESSION_TYPE_CONFIG));
Review Comment:
Could we just use `compressionType`, which is previously set already?
##########
clients/src/main/java/org/apache/kafka/common/compress/ZstdCompression.java:
##########
@@ -0,0 +1,143 @@
+/*
+ * 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.kafka.common.compress;
+
+import com.github.luben.zstd.BufferPool;
+import com.github.luben.zstd.RecyclingBufferPool;
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdInputStreamNoFinalizer;
+import com.github.luben.zstd.ZstdOutputStreamNoFinalizer;
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferInputStream;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.apache.kafka.common.utils.ChunkedBytesStream;
+
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Objects;
+
+public class ZstdCompression implements Compression {
+
+ public static final int MIN_LEVEL = Zstd.minCompressionLevel();
+ public static final int MAX_LEVEL = Zstd.maxCompressionLevel();
+ public static final int DEFAULT_LEVEL = Zstd.defaultCompressionLevel();
+
+ private final int level;
+
+ private ZstdCompression(int level) {
+ this.level = level;
+ }
+
+ @Override
+ public CompressionType type() {
+ return CompressionType.ZSTD;
+ }
+
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) {
+ try {
+ // Set input buffer (uncompressed) to 16 KB (none by default) to ensure reasonable performance
+ // in cases where the caller passes a small number of bytes to write (potentially a single byte).
+ return new BufferedOutputStream(new ZstdOutputStreamNoFinalizer(bufferStream, RecyclingBufferPool.INSTANCE, level), 16 * 1024);
+ } catch (Throwable e) {
+ throw new KafkaException(e);
+ }
+ }
+
+ @Override
+ public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
+ try {
+ return new ChunkedBytesStream(wrapForZstdInput(buffer, decompressionBufferSupplier),
+ decompressionBufferSupplier,
+ decompressionOutputSize(),
+ false);
+ } catch (Throwable e) {
+ throw new KafkaException(e);
+ }
+ }
+
+ // visible for testing
+ public ZstdInputStreamNoFinalizer wrapForZstdInput(ByteBuffer buffer, BufferSupplier decompressionBufferSupplier) throws IOException {
Review Comment:
Should we make this static?
##########
clients/src/main/java/org/apache/kafka/common/compress/Compression.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+public interface Compression {
+
+ /**
+ * The compression type for this compression codec
+ */
+ CompressionType type();
+
+ /**
+ * Wrap bufferStream with an OutputStream that will compress data with this CompressionType.
+ * Note: Unlike {@link #wrapForInput}, this cannot take {@link ByteBuffer}s directly.
+ * Currently, MemoryRecordsBuilder writes to the underlying buffer in the given {@link ByteBufferOutputStream} after the compressed data has been written.
+ * In the event that the buffer needs to be expanded while writing the data, access to the underlying buffer needs to be preserved.
+ */
+ OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion);
+
+ /**
+ * Wrap buffer with an InputStream that will decompress data with this CompressionType.
+ *
+ * @param buffer The {@link ByteBuffer} instance holding the data to decompress.
+ * @param messageVersion The record format version to use.
+ * @param decompressionBufferSupplier The supplier of ByteBuffer(s) used for decompression if supported.
+ * For small record batches, allocating a potentially large buffer (64 KB for LZ4)
Review Comment:
indentation
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600255317
##########
clients/src/main/java/org/apache/kafka/common/compress/NoCompression.java:
##########
@@ -14,37 +14,48 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.kafka.common.compress;
-import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
import org.apache.kafka.common.utils.ByteBufferInputStream;
import org.apache.kafka.common.utils.ByteBufferOutputStream;
-import org.xerial.snappy.SnappyInputStream;
-import org.xerial.snappy.SnappyOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
-public class SnappyFactory {
+public class NoCompression implements Compression {
- private SnappyFactory() { }
+ @Override
+ public CompressionType type() {
+ return CompressionType.NONE;
+ }
- public static OutputStream wrapForOutput(ByteBufferOutputStream buffer) {
- try {
- return new SnappyOutputStream(buffer);
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) {
+ return bufferStream;
}
- public static InputStream wrapForInput(ByteBuffer buffer) {
- try {
- return new SnappyInputStream(new ByteBufferInputStream(buffer));
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
+ return new ByteBufferInputStream(buffer);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof NoCompression;
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
}
+ public static class Builder implements Compression.Builder<NoCompression> {
Review Comment:
Yes, I made all of them private.
I also considered making the Builders private too as I expect them to be retrieved via the getters in Compression, but I decided to keep them public.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1598609324
##########
clients/src/test/java/org/apache/kafka/common/compress/GzipCompressionTest.java:
##########
@@ -0,0 +1,82 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class GzipCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ GzipCompression.Builder builder = Compression.gzip();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ for (int level : Arrays.asList(GzipCompression.MIN_LEVEL, GzipCompression.DEFAULT_LEVEL, GzipCompression.MAX_LEVEL)) {
+ GzipCompression compression = builder.level(level).build();
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
+ out.write(data);
+ out.flush();
+ }
+ bufferStream.buffer().flip();
+
+ try (InputStream inputStream = compression.wrapForInput(bufferStream.buffer(), magic, BufferSupplier.create())) {
+ byte[] result = new byte[data.length];
+ inputStream.read(result);
+ assertArrayEquals(data, result);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testCompressionLevels() {
+ GzipCompression.Builder builder = new GzipCompression.Builder();
+
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MIN_LEVEL - 1));
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MAX_LEVEL + 1));
+
+ builder.level(GzipCompression.MIN_LEVEL);
+ builder.level(GzipCompression.MAX_LEVEL);
Review Comment:
It's not needed, if `level()` throws, it automatically fails the test.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2313866487
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
1. Right, here we could use the level if specified. I expect most topics to use `compression.type=producer` but in case a specific compression type and level is set, that would make sense to use them.
2. It's not something I thought about before. Do you think there are scenarios where the gains of picking a different level for older data would be significant enough to motivate such a feature?
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15516:
URL: https://github.com/apache/kafka/pull/15516#issuecomment-2252950296
Yeah it looks like the numbers are not accurate. To be honest it's a bit of a strange performance test. The Produce Test benchmark should be much more representative. However I did not reproduce that benchmark. It might be worth asking @dongjinleekr if he has any data points to share.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600267022
##########
clients/src/main/java/org/apache/kafka/common/compress/ZstdCompression.java:
##########
@@ -0,0 +1,143 @@
+/*
+ * 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.kafka.common.compress;
+
+import com.github.luben.zstd.BufferPool;
+import com.github.luben.zstd.RecyclingBufferPool;
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdInputStreamNoFinalizer;
+import com.github.luben.zstd.ZstdOutputStreamNoFinalizer;
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferInputStream;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.apache.kafka.common.utils.ChunkedBytesStream;
+
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Objects;
+
+public class ZstdCompression implements Compression {
+
+ public static final int MIN_LEVEL = Zstd.minCompressionLevel();
+ public static final int MAX_LEVEL = Zstd.maxCompressionLevel();
+ public static final int DEFAULT_LEVEL = Zstd.defaultCompressionLevel();
+
+ private final int level;
+
+ private ZstdCompression(int level) {
+ this.level = level;
+ }
+
+ @Override
+ public CompressionType type() {
+ return CompressionType.ZSTD;
+ }
+
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) {
+ try {
+ // Set input buffer (uncompressed) to 16 KB (none by default) to ensure reasonable performance
+ // in cases where the caller passes a small number of bytes to write (potentially a single byte).
+ return new BufferedOutputStream(new ZstdOutputStreamNoFinalizer(bufferStream, RecyclingBufferPool.INSTANCE, level), 16 * 1024);
+ } catch (Throwable e) {
+ throw new KafkaException(e);
+ }
+ }
+
+ @Override
+ public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
+ try {
+ return new ChunkedBytesStream(wrapForZstdInput(buffer, decompressionBufferSupplier),
+ decompressionBufferSupplier,
+ decompressionOutputSize(),
+ false);
+ } catch (Throwable e) {
+ throw new KafkaException(e);
+ }
+ }
+
+ // visible for testing
+ public ZstdInputStreamNoFinalizer wrapForZstdInput(ByteBuffer buffer, BufferSupplier decompressionBufferSupplier) throws IOException {
Review Comment:
I considered inlining this method as it's only used in a test which kind of test in `DefaultRecordBatchTest` the internal behavior of `ZstdInputStreamNoFinalizer`.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600263287
##########
clients/src/main/java/org/apache/kafka/common/compress/Lz4Compression.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.apache.kafka.common.utils.ChunkedBytesStream;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Objects;
+
+public class Lz4Compression implements Compression {
+
+ public static final int MIN_LEVEL = 1;
+ public static final int MAX_LEVEL = 17;
+ public static final int DEFAULT_LEVEL = 9;
Review Comment:
I hesitated defining these constants for this reason but these levels have not changed over 10 years [0], so hopefully this won't require a lot of maintenance.
0: https://github.com/lz4/lz4-java/blame/master/src/java/net/jpountz/lz4/LZ4Constants.java#L23-L24
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1603325731
##########
server-common/src/test/java/org/apache/kafka/server/record/BrokerCompressionTypeTest.java:
##########
@@ -16,23 +16,38 @@
*/
package org.apache.kafka.server.record;
+import org.apache.kafka.common.compress.Compression;
+import org.apache.kafka.common.compress.GzipCompression;
+import org.apache.kafka.common.compress.Lz4Compression;
+import org.apache.kafka.common.compress.SnappyCompression;
+import org.apache.kafka.common.compress.ZstdCompression;
import org.apache.kafka.common.record.CompressionType;
import org.junit.jupiter.api.Test;
+import java.util.Optional;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BrokerCompressionTypeTest {
@Test
public void testTargetCompressionType() {
- assertEquals(CompressionType.GZIP, BrokerCompressionType.GZIP.targetCompressionType(CompressionType.ZSTD));
- assertEquals(CompressionType.SNAPPY, BrokerCompressionType.SNAPPY.targetCompressionType(CompressionType.LZ4));
- assertEquals(CompressionType.LZ4, BrokerCompressionType.LZ4.targetCompressionType(CompressionType.ZSTD));
- assertEquals(CompressionType.ZSTD, BrokerCompressionType.ZSTD.targetCompressionType(CompressionType.GZIP));
-
- assertEquals(CompressionType.LZ4, BrokerCompressionType.PRODUCER.targetCompressionType(CompressionType.LZ4));
- assertEquals(CompressionType.ZSTD, BrokerCompressionType.PRODUCER.targetCompressionType(CompressionType.ZSTD));
+ GzipCompression gzipWithLevel = Compression.gzip().level(GzipCompression.MAX_LEVEL).build();
+ assertEquals(gzipWithLevel, BrokerCompressionType.GZIP.targetCompression(Optional.of(gzipWithLevel), CompressionType.ZSTD));
Review Comment:
Fixed!
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2649600413
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
> If we use a different compression type, the compacted data could be
exceeding the max segment limit and failing the index append.
It appears that using a high compression level during ingestion can indeed trigger overflow issue during compaction. This is because the cleaner's size estimation becomes inaccurate when it rebuilds batches using the default compression level instead of the origin one
```
[2025-12-28 08:25:42,915] WARN [kafka-log-cleaner-thread-0]: Unexpected exception thrown when cleaning log Log(dir=/tmp/log-folder-0/chia-0, topicId=5vKt56jQQ_S3QRuqrNmrTw, topic=chia, partition=0, highWatermark=66028296, lastStableOffset=66028296, logStartOffset=0, logEndOffset=66028296). Marking its partition (chia-0) as uncleanable (org.apache.kafka.storage.internals.log.LogCleaner$CleanerThread)
org.apache.kafka.storage.internals.log.LogCleaningException: Append of size 258080 bytes is too large for segment with current file position at 2147262463
at org.apache.kafka.storage.internals.log.LogCleaner$CleanerThread.cleanFilthiestLog(LogCleaner.java:570)
at org.apache.kafka.storage.internals.log.LogCleaner$CleanerThread.tryCleanFilthiestLog(LogCleaner.java:544)
at org.apache.kafka.storage.internals.log.LogCleaner$CleanerThread.doWork(LogCleaner.java:513)
at org.apache.kafka.server.util.ShutdownableThread.run(ShutdownableThread.java:136)
Caused by: java.lang.IllegalArgumentException: Append of size 258080 bytes is too large for segment with current file position at 2147262463
at org.apache.kafka.common.record.FileRecords.append(FileRecords.java:196)
at org.apache.kafka.storage.internals.log.LogSegment.append(LogSegment.java:260)
at org.apache.kafka.storage.internals.log.Cleaner.cleanInto(Cleaner.java:405)
at org.apache.kafka.storage.internals.log.Cleaner.cleanSegments(Cleaner.java:243)
at org.apache.kafka.storage.internals.log.Cleaner.doClean(Cleaner.java:180)
at org.apache.kafka.storage.internals.log.Cleaner.clean(Cleaner.java:127)
at org.apache.kafka.storage.internals.log.LogCleaner$CleanerThread.cleanLog(LogCleaner.java:596)
at org.apache.kafka.storage.internals.log.LogCleaner$CleanerThread.cleanFilthiestLog(LogCleaner.java:565)
... 3 more
```
To mitigate this, I propose introducing a safety margin specifically for partitions that fail to compact due to overflows.
@mimaison @junrao @Yunyung WDYT?
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15516:
URL: https://github.com/apache/kafka/pull/15516#issuecomment-2122934859
None of the test failures seem related, merging to trunk
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600483273
##########
clients/src/test/java/org/apache/kafka/common/compress/GzipCompressionTest.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class GzipCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ GzipCompression.Builder builder = Compression.gzip();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
Review Comment:
Should we test sth bigger like more than 512 bytes so that it covers the out.flush() logic?
##########
clients/src/test/java/org/apache/kafka/common/compress/GzipCompressionTest.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class GzipCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ GzipCompression.Builder builder = Compression.gzip();
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ for (int level : Arrays.asList(GzipCompression.MIN_LEVEL, GzipCompression.DEFAULT_LEVEL, GzipCompression.MAX_LEVEL)) {
+ GzipCompression compression = builder.level(level).build();
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
+ out.write(data);
+ out.flush();
+ }
+ bufferStream.buffer().flip();
+
+ try (InputStream inputStream = compression.wrapForInput(bufferStream.buffer(), magic, BufferSupplier.create())) {
+ byte[] result = new byte[data.length];
+ int read = inputStream.read(result);
+ assertEquals(data.length, read);
+ assertArrayEquals(data, result);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testCompressionLevels() {
+ GzipCompression.Builder builder = Compression.gzip();
+
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MIN_LEVEL - 1));
+ assertThrows(IllegalArgumentException.class, () -> builder.level(GzipCompression.MAX_LEVEL + 1));
+
+ builder.level(GzipCompression.MIN_LEVEL);
+ builder.level(GzipCompression.MAX_LEVEL);
+ }
+
+ @Test
+ public void testLevelValidator() {
+ GzipCompression.LevelValidator validator = new GzipCompression.LevelValidator();
+ for (int level = GzipCompression.MIN_LEVEL; level <= GzipCompression.MAX_LEVEL; level++) {
+ validator.ensureValid("", level);
+ }
+ validator.ensureValid("", GzipCompression.DEFAULT_LEVEL);
+ assertThrows(ConfigException.class, () -> validator.ensureValid("", 0));
Review Comment:
This is the same as GzipCompression.MIN_LEVEL - 1, right?
##########
core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala:
##########
@@ -711,6 +710,30 @@ class KafkaConfigTest {
assertThrows(classOf[ConfigException], () => KafkaConfig.fromProps(props))
}
+ @Test
+ def testInvalidGzipCompressionLevel(): Unit = {
+ val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181)
+ props.setProperty(KafkaConfig.CompressionTypeProp, "gzip")
+ props.setProperty(KafkaConfig.CompressionGzipLevelProp, (GzipCompression.MAX_LEVEL+1).toString)
Review Comment:
space before and after +
##########
core/src/test/scala/unit/kafka/log/LogValidatorTest.scala:
##########
@@ -1587,7 +1612,7 @@ class LogValidatorTest {
private def createTwoBatchedRecords(magicValue: Byte,
timestamp: Long,
- codec: CompressionType): MemoryRecords = {
+ codec: Compression): MemoryRecords = {
Review Comment:
This is an existing issue, but timestamp seems unused.
##########
core/src/main/scala/kafka/log/UnifiedLog.scala:
##########
@@ -791,7 +790,7 @@ class UnifiedLog(@volatile var logStartOffset: Long,
val offset = PrimitiveRef.ofLong(localLog.logEndOffset)
appendInfo.setFirstOffset(offset.value)
val validateAndOffsetAssignResult = try {
- val targetCompression = BrokerCompressionType.forName(config.compressionType).targetCompressionType(appendInfo.sourceCompression)
+ val targetCompression = config.compressionType.targetCompression(config.compression, appendInfo.sourceCompression())
Review Comment:
`config.compressionType` is not really being used. Could we make `targetCompression` a static method and independent of compressionType?
##########
core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala:
##########
@@ -917,6 +940,10 @@ class KafkaConfigTest {
case MetricConfigs.METRIC_SAMPLE_WINDOW_MS_CONFIG => assertPropertyInvalid(baseProperties, name, "not_a_number", "-1", "0")
case MetricConfigs.METRIC_REPORTER_CLASSES_CONFIG => // ignore string
case MetricConfigs.METRIC_RECORDING_LEVEL_CONFIG => // ignore string
+
+ case KafkaConfig.CompressionGzipLevelProp => assertPropertyInvalid(baseProperties, name, "not_a_number", "0")
Review Comment:
Should we test LZ4 too?
##########
clients/src/test/java/org/apache/kafka/common/record/MemoryRecordsBuilderTest.java:
##########
@@ -60,20 +61,20 @@ public class MemoryRecordsBuilderTest {
private static class Args {
final int bufferOffset;
- final CompressionType compressionType;
+ final Compression compression;
final byte magic;
- public Args(int bufferOffset, CompressionType compressionType, byte magic) {
+ public Args(int bufferOffset, Compression compression, byte magic) {
this.bufferOffset = bufferOffset;
- this.compressionType = compressionType;
+ this.compression = compression;
this.magic = magic;
}
@Override
public String toString() {
return "magic=" + magic +
", bufferOffset=" + bufferOffset +
- ", compressionType=" + compressionType;
+ ", compressionType=" + compression;
Review Comment:
compressionType => compression?
##########
clients/src/test/java/org/apache/kafka/common/compress/NoCompressionTest.java:
##########
@@ -0,0 +1,57 @@
+/*
+ * 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.kafka.common.compress;
+
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.ByteBufferOutputStream;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class NoCompressionTest {
+
+ @Test
+ public void testCompressionDecompression() throws IOException {
+ NoCompression compression = Compression.NONE;
+ byte[] data = "data".getBytes(StandardCharsets.UTF_8);
+
+ for (byte magic : Arrays.asList(RecordBatch.MAGIC_VALUE_V0, RecordBatch.MAGIC_VALUE_V1, RecordBatch.MAGIC_VALUE_V2)) {
+ ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(4);
+ try (OutputStream out = compression.wrapForOutput(bufferStream, RecordBatch.CURRENT_MAGIC_VALUE)) {
Review Comment:
`RecordBatch.CURRENT_MAGIC_VALUE` should be `magic`, right? Ditto in SnappyCompressionTest, GzipCompressionTest and ZstdCompressionTest.
##########
core/src/test/scala/unit/kafka/log/LogConfigTest.scala:
##########
@@ -95,6 +95,8 @@ class LogConfigTest {
case TopicConfig.REMOTE_LOG_STORAGE_ENABLE_CONFIG => assertPropertyInvalid(name, "not_a_boolean")
case TopicConfig.LOCAL_LOG_RETENTION_MS_CONFIG => assertPropertyInvalid(name, "not_a_number", "-3")
case TopicConfig.LOCAL_LOG_RETENTION_BYTES_CONFIG => assertPropertyInvalid(name, "not_a_number", "-3")
+ case TopicConfig.COMPRESSION_GZIP_LEVEL_CONFIG => assertPropertyInvalid(name, "not_a_number", "-2")
+ case TopicConfig.COMPRESSION_ZSTD_LEVEL_CONFIG => assertPropertyInvalid(name, "not_a_number", "-0.1")
Review Comment:
Should we test LZ4 too?
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600235959
##########
storage/src/main/java/org/apache/kafka/storage/internals/log/LogValidator.java:
##########
@@ -331,12 +332,12 @@ public ValidationResult assignOffsetsNonCompressed(LongRef offsetCounter,
public ValidationResult validateMessagesAndAssignOffsetsCompressed(LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
- if (targetCompression == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
+ if (targetCompression.type() == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
throw new UnsupportedCompressionTypeException("Produce requests to inter.broker.protocol.version < 2.1 broker " +
"are not allowed to use ZStandard compression");
// No in place assignment situation 1
- boolean inPlaceAssignment = sourceCompression == targetCompression;
+ boolean inPlaceAssignment = sourceCompressionType == targetCompression.type();
Review Comment:
The broker has no easy way of retrieving the level that the producer used when compressing the records. So if the compression codec matches, I decided to keep the compressed bytes instead of decompressing and compressing everything again as this would be wasteful, especially as the producer could have already used the same compression level.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2655222766
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
Theoretically, having the cleaner produce multiple segments is the superior design. However, the current implementation strictly pre-groups the segments. Simply splitting an overflowing group would result in fragmented, undersized segments. To handle this gracefully would require major architectural surgery on the grouping logic.
Given that this overflow is a rare edge case, requiring a specific combination of large segments, significant compression drop, and low deletion rates, the adaptive safety margin is a much more pragmatic win.
@junrao wdyt ?
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "Yunyung (via GitHub)" <gi...@apache.org>.
Yunyung commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2314007436
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
That’s an interesting topic.
For 1., it would be intuitive and reasonable to use the compression level that is set. I’ll create a minor for it.
For 2., I’m not entirely sure, but one possible case is that users may prefer tighter compression for cold data to save space, especially if storage is cost-sensitive
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1605420401
##########
core/src/test/scala/unit/kafka/log/LogValidatorTest.scala:
##########
@@ -1538,7 +1563,80 @@ class LogValidatorTest {
assertEquals(e.recordErrors.size, 3)
}
- private def testBatchWithoutRecordsNotAllowed(sourceCompression: CompressionType, targetCompression: CompressionType): Unit = {
+ @Test
+ def testDifferentLevelDoesNotCauseRecompression(): Unit = {
+ val records = List(
+ List.fill(256)("some").mkString("").getBytes,
+ List.fill(256)("data").mkString("").getBytes
+ )
+ // Records from the producer were created with gzip max level
+ val gzipMax: Compression = Compression.gzip().level(GzipCompression.MAX_LEVEL).build()
+ val recordsGzipMax = createRecords(records, RecordBatch.MAGIC_VALUE_V2, RecordBatch.NO_TIMESTAMP, gzipMax)
+
+ // The topic is configured with gzip min level
+ val gzipMin: Compression = Compression.gzip().level(GzipCompression.MIN_LEVEL).build()
+ val recordsGzipMin = createRecords(records, RecordBatch.MAGIC_VALUE_V2, RecordBatch.NO_TIMESTAMP, gzipMin)
+
+ // ensure data compressed with gzip max and min is different
+ assertNotEquals(recordsGzipMax, recordsGzipMin)
+ val validator = new LogValidator(recordsGzipMax,
+ topicPartition,
+ time,
+ gzipMax.`type`(),
+ gzipMin,
+ false,
+ RecordBatch.CURRENT_MAGIC_VALUE,
Review Comment:
Yes, let's keep it consistent. Done
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1602012880
##########
server-common/src/test/java/org/apache/kafka/server/record/BrokerCompressionTypeTest.java:
##########
@@ -16,23 +16,38 @@
*/
package org.apache.kafka.server.record;
+import org.apache.kafka.common.compress.Compression;
+import org.apache.kafka.common.compress.GzipCompression;
+import org.apache.kafka.common.compress.Lz4Compression;
+import org.apache.kafka.common.compress.SnappyCompression;
+import org.apache.kafka.common.compress.ZstdCompression;
import org.apache.kafka.common.record.CompressionType;
import org.junit.jupiter.api.Test;
+import java.util.Optional;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BrokerCompressionTypeTest {
@Test
public void testTargetCompressionType() {
- assertEquals(CompressionType.GZIP, BrokerCompressionType.GZIP.targetCompressionType(CompressionType.ZSTD));
- assertEquals(CompressionType.SNAPPY, BrokerCompressionType.SNAPPY.targetCompressionType(CompressionType.LZ4));
- assertEquals(CompressionType.LZ4, BrokerCompressionType.LZ4.targetCompressionType(CompressionType.ZSTD));
- assertEquals(CompressionType.ZSTD, BrokerCompressionType.ZSTD.targetCompressionType(CompressionType.GZIP));
-
- assertEquals(CompressionType.LZ4, BrokerCompressionType.PRODUCER.targetCompressionType(CompressionType.LZ4));
- assertEquals(CompressionType.ZSTD, BrokerCompressionType.PRODUCER.targetCompressionType(CompressionType.ZSTD));
+ GzipCompression gzipWithLevel = Compression.gzip().level(GzipCompression.MAX_LEVEL).build();
+ assertEquals(gzipWithLevel, BrokerCompressionType.GZIP.targetCompression(Optional.of(gzipWithLevel), CompressionType.ZSTD));
Review Comment:
`BrokerCompressionType.GZIP.targetCompression` => `BrokerCompressionType.targetCompression`
Ditto below.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600241274
##########
clients/src/main/java/org/apache/kafka/common/compress/NoCompression.java:
##########
@@ -14,37 +14,48 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.kafka.common.compress;
-import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.record.CompressionType;
+import org.apache.kafka.common.utils.BufferSupplier;
import org.apache.kafka.common.utils.ByteBufferInputStream;
import org.apache.kafka.common.utils.ByteBufferOutputStream;
-import org.xerial.snappy.SnappyInputStream;
-import org.xerial.snappy.SnappyOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
-public class SnappyFactory {
+public class NoCompression implements Compression {
- private SnappyFactory() { }
+ @Override
+ public CompressionType type() {
+ return CompressionType.NONE;
+ }
- public static OutputStream wrapForOutput(ByteBufferOutputStream buffer) {
- try {
- return new SnappyOutputStream(buffer);
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) {
+ return bufferStream;
}
- public static InputStream wrapForInput(ByteBuffer buffer) {
- try {
- return new SnappyInputStream(new ByteBufferInputStream(buffer));
- } catch (Throwable e) {
- throw new KafkaException(e);
- }
+ @Override
+ public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) {
+ return new ByteBufferInputStream(buffer);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof NoCompression;
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
Review Comment:
Actually I don't think we need to override the default hashCode/equals methods. Initially I wanted to make this a singleton but I don't think it's necessary.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1598619060
##########
clients/src/test/java/org/apache/kafka/common/record/DefaultRecordBatchTest.java:
##########
@@ -500,27 +501,24 @@ private static Stream<Arguments> testBufferReuseInSkipKeyValueIterator() {
@MethodSource
public void testZstdJniForSkipKeyValueIterator(int expectedJniCalls, byte[] recordValue) throws IOException {
MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L,
- CompressionType.ZSTD, TimestampType.CREATE_TIME,
+ Compression.zstd().build(), TimestampType.CREATE_TIME,
new SimpleRecord(9L, "hakuna-matata".getBytes(), recordValue)
);
// Buffer containing compressed data
final ByteBuffer compressedBuf = records.buffer();
// Create a RecordBatch object
final DefaultRecordBatch batch = spy(new DefaultRecordBatch(compressedBuf.duplicate()));
- final CompressionType mockCompression = mock(CompressionType.ZSTD.getClass());
- doReturn(mockCompression).when(batch).compressionType();
-
+ final ZstdCompression compression = Compression.zstd().build();
// Buffer containing compressed records to be used for creating zstd-jni stream
- ByteBuffer recordsBuffer = compressedBuf.duplicate();
+ ByteBuffer recordsBuffer = spy(compressedBuf.duplicate());
Review Comment:
Right, it's not needed
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1600247977
##########
clients/src/main/java/org/apache/kafka/common/config/TopicConfig.java:
##########
@@ -173,6 +173,14 @@ public class TopicConfig {
"accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the " +
"original compression codec set by the producer.";
+
+ public static final String COMPRESSION_GZIP_LEVEL_CONFIG = "compression.gzip.level";
+ public static final String COMPRESSION_GZIP_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>gzip</code>.";
+ public static final String COMPRESSION_LZ4_LEVEL_CONFIG = "compression.lz4.level";
+ public static final String COMPRESSION_LZ4_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>lz4</code>.";
+ public static final String COMPRESSION_ZSTD_LEVEL_CONFIG = "compression.zstd.level";
+ public static final String COMPRESSION_ZSTD_LEVEL_DOC = "The compression level to use if " + COMPRESSION_TYPE_CONFIG + " is set to <code>zstd</code>.";
Review Comment:
Do you mean a link to the compression library websites?
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15516:
URL: https://github.com/apache/kafka/pull/15516#issuecomment-2048128916
@divijvaidya It seems you've done a bit of work around compression in the past. Can you take a look? Thanks
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1601240696
##########
core/src/test/scala/unit/kafka/log/LogValidatorTest.scala:
##########
@@ -1587,7 +1612,7 @@ class LogValidatorTest {
private def createTwoBatchedRecords(magicValue: Byte,
timestamp: Long,
- codec: CompressionType): MemoryRecords = {
+ codec: Compression): MemoryRecords = {
Review Comment:
Yes, so let's remove it
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15516:
URL: https://github.com/apache/kafka/pull/15516#issuecomment-2115225074
I also added a couple of new tests in LogValidatorTest to check recompression only happens if the compression codec is different between the records from the producer and the topic configuration and does not happen if only the compression levels are different.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r1608274764
##########
storage/src/main/java/org/apache/kafka/storage/internals/log/LogValidator.java:
##########
@@ -331,12 +332,12 @@ public ValidationResult assignOffsetsNonCompressed(LongRef offsetCounter,
public ValidationResult validateMessagesAndAssignOffsetsCompressed(LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
- if (targetCompression == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
+ if (targetCompression.type() == CompressionType.ZSTD && interBrokerProtocolVersion.isLessThan(IBP_2_1_IV0))
throw new UnsupportedCompressionTypeException("Produce requests to inter.broker.protocol.version < 2.1 broker " +
"are not allowed to use ZStandard compression");
// No in place assignment situation 1
- boolean inPlaceAssignment = sourceCompression == targetCompression;
+ boolean inPlaceAssignment = sourceCompressionType == targetCompression.type();
Review Comment:
Right, I updated the KIP.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2661927809
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
Good find!
Thanks for following up
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-7632: Support Compression Levels (KIP-390) [kafka]
Posted by "junrao (via GitHub)" <gi...@apache.org>.
junrao commented on code in PR #15516:
URL: https://github.com/apache/kafka/pull/15516#discussion_r2651437312
##########
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java:
##########
@@ -293,14 +294,15 @@ private static MemoryRecordsBuilder buildRetainedRecordsInto(RecordBatch origina
ByteBufferOutputStream bufferOutputStream,
final long deleteHorizonMs) {
byte magic = originalBatch.magic();
+ Compression compression = Compression.of(originalBatch.compressionType()).build();
Review Comment:
Another option is to make the cleaning logic more generic so that it could produce more than 1 segment during each round of cleaning if the segment size limit is exceeded.
--
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: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org