lianetm commented on code in PR #23483:
URL: https://github.com/apache/kafka/pull/23483#discussion_r4530984043
##########
clients/src/main/java/org/apache/kafka/clients/producer/internals/ChunkedProducerBatch.java:
##########
@@ -64,27 +71,52 @@ int extensionBytesNeeded(long timestamp, byte[] key, byte[]
value, Header[] head
}
/**
- * Appends the record. This batch never acquires memory itself: the
capacity is arranged before
- * the append, by the accumulator attaching chunks (see {@link
#extensionBytesNeeded} and
- * {@link #addBuffers}).
+ * Appends the record. Its capacity is pre-sized by the accumulator before
the append: the batch is
+ * created with chunks for its first record (a blocking acquire), and each
later record gets extension
+ * chunks for the shortfall reported by {@link #extensionBytesNeeded} (see
{@link #addBuffers}) through a
+ * non-blocking acquire; if the pool cannot supply them, the accumulator
closes this batch and retries the
+ * record on a new one. Pre-sizing is an exact upper bound for an
uncompressed batch. For a compressed batch
+ * it scales with the topic's compression ratio estimate, which is only a
heuristic and can change between
+ * pre-sizing and batch creation, so the backing {@link
ChunkedByteBufferOutputStream} also grows during the
+ * write, attaching all the chunks the write still needs: from the pool
without blocking, the rest from the
+ * heap. The check here therefore covers only an uncompressed batch's
first record, the one append no caller
+ * checks ({@code RecordAccumulator.appendNewBatch} appends straight into
the new batch); every later append
+ * comes through {@code ChunkedRecordAccumulator.tryAppend}, which has
already evaluated
+ * {@link #extensionBytesNeeded}.
* <p>
- * The capacity is verified here only for the batch's first record, which
is the one append no
- * caller checks: {@code RecordAccumulator.appendNewBatch} creates the
batch and appends straight
- * into it, relying on the stream having been pre-sized. Every later
append arrives through
- * {@code ChunkedRecordAccumulator.tryAppend}, which evaluates {@link
#extensionBytesNeeded}
- * itself and attaches chunks before retrying, so repeating the check for
those would size the
- * record a second time on every append for no added safety.
+ * If the growth fell back to the heap, the record is still appended but
the batch is then closed for
+ * record appends, so it is sent early rather than growing further on the
heap past buffer.memory.
*
* @return the record's future, or null if the batch is at its batch-size
limit
- * @throws IllegalStateException if the stream was not pre-sized to hold
the batch's first record
+ * @throws IllegalStateException if the uncompressed stream was not
pre-sized to hold the batch's first record
*/
@Override
public FutureRecordMetadata tryAppend(long timestamp, byte[] key, byte[]
value, Header[] headers, Callback callback, long now) {
- if (recordCount == 0 && extensionBytesNeeded(timestamp, key, value,
headers) != 0)
+ if (recordCount == 0 && !isCompressed() &&
extensionBytesNeeded(timestamp, key, value, headers) != 0)
throw new IllegalStateException(
"Unexpected append to a chunked batch whose chunks lack
capacity for the record; " +
"the stream should have been pre-sized for the
batch's first record");
- return super.tryAppend(timestamp, key, value, headers, callback, now);
+ FutureRecordMetadata future = super.tryAppend(timestamp, key, value,
headers, callback, now);
+ if (future != null && stream().fallbackAllocations() > 0) {
+ // The stream grew on the heap mid-record: the pool is exhausted,
and the builder's fullness checks
Review Comment:
"the pool is exhausted"
related to the comment above, couldn't we have the case where the pool is
not exhaused, but we grew above the limit (batch.size), so should close for
appends here too?
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/ChunkedRecordAccumulatorTest.java:
##########
@@ -169,25 +184,776 @@ public void testMidBatchExtensionGrowsExistingBatch()
throws Exception {
}
/**
- * Pool that adds one append right after a chunk allocation returns,
mocking a concurrent
- * appender racing the same batch.
+ * End-to-end compression on the incremental path: records appended with
each codec build a valid
+ * compressed batch (the flatten-close writes the header and CRC over the
compressed buffer) that
+ * declares the codec on the wire and decodes back to exactly the bytes
appended.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"none", "gzip", "snappy", "lz4", "zstd"})
+ public void testCompressedRecordsRoundTripThroughChunkedBatch(String
codec) throws Exception {
+ int chunkSize = 256;
+ Compression compression =
Compression.of(CompressionType.forName(codec)).build();
+ ChunkedRecordAccumulator accum = newAccumulator(8192, chunkSize, 64L *
chunkSize, compression);
+
+ // Enough sizeable records that the batch spans several chunks, so the
compressor writes
+ // across chunk boundaries rather than fitting in the first chunk.
+ int recordCount = 20;
+ List<byte[]> values = new ArrayList<>();
+ for (int i = 0; i < recordCount; i++) {
+ byte[] value = new byte[300];
+ Arrays.fill(value, (byte) i);
+ values.add(value);
+ accum.append(topic, partition1, i, key, value,
Record.EMPTY_HEADERS, null,
+ maxBlockTimeMs, time.milliseconds(), cluster);
+ }
+
+ Deque<ProducerBatch> dq = batchesFor(accum, tp1);
+ assertEquals(1, dq.size());
+ ProducerBatch batch = dq.peekFirst();
+ assertNotNull(batch);
+ assertEquals(recordCount, batch.recordCount);
+
+ // Finalize the batch: the flatten-close path writes the header + CRC
over the (compressed)
+ // contiguous buffer.
+ batch.close();
+ MemoryRecords records = batch.records();
+
+ // The built batch must declare the configured codec on the wire.
+ for (RecordBatch rb : records.batches())
+ assertEquals(compression.type(), rb.compressionType());
+
+ // Every record must decode back to exactly the bytes appended, in
order.
+ int i = 0;
+ for (Record r : records.records()) {
+ assertArrayEquals(key, readBytes(r.key()));
+ assertArrayEquals(values.get(i), readBytes(r.value()));
+ i++;
+ }
+ assertEquals(recordCount, i, "all appended records must be present");
+
+ accum.deallocate(batch);
+ accum.close();
+ }
+
+ /**
+ * A topic whose data doesn't compress drives its compression ratio
estimate above 1.0 (from the
+ * initial 1.0, a single such batch, whose observed ratio is just above
1.0 once the batch header is
+ * counted, raises it by at least COMPRESSION_RATIO_DETERIORATE_STEP). The
first record of a new batch
+ * must still append: its chunks are pre-sized by the compression ratio
estimate (here 1.3 times the
+ * uncompressed upper bound, padded by the 1.05 estimation factor). That
pre-size exceeds what the
+ * compressor writes, so the stream is asserted not to grow. The estimate
here is
+ * set straight to 1.3, above the ~1.0 this batch then observes, so
closing the batch lowers it by
+ * COMPRESSION_RATIO_IMPROVING_STEP to exactly 1.295 rather than raising
it.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"gzip", "snappy", "lz4", "zstd"})
+ public void
testLargeFirstRecordAppendsWhenCompressionRatioEstimateAboveOne(String codec)
throws Exception {
+ int chunkSize = 256;
+ Compression compression =
Compression.of(CompressionType.forName(codec)).build();
+ ChunkedRecordAccumulator accum = newAccumulator(8192, chunkSize, 1024L
* chunkSize, compression);
+ CompressionRatioEstimator.setEstimation(topic, compression.type(),
1.3f);
+ try {
+ // Random bytes don't compress, and the record spans many chunks
so the estimate's
+ // inflation isn't absorbed by rounding up to a whole chunk.
+ byte[] value = new byte[20_000];
+ new Random(42).nextBytes(value);
+ accum.append(topic, partition1, 0L, key, value,
Record.EMPTY_HEADERS, null,
+ maxBlockTimeMs, time.milliseconds(), cluster);
+
+ Deque<ProducerBatch> dq = batchesFor(accum, tp1);
+ assertEquals(1, dq.size());
+ ProducerBatch batch = dq.peekFirst();
+ assertNotNull(batch);
+ assertEquals(1, batch.recordCount);
+ // Checked before close(), which releases the unused chunks.
+ int upperBound =
AbstractRecords.estimateSizeInBytesUpperBound(RecordBatch.CURRENT_MAGIC_VALUE,
+ compression.type(), key, value, Record.EMPTY_HEADERS);
+ int expected =
MemoryRecordsBuilder.estimatedCompressedSizeInBytes(DefaultRecordBatch.RECORD_BATCH_OVERHEAD,
+ upperBound - DefaultRecordBatch.RECORD_BATCH_OVERHEAD,
1.3f);
+ int expectedChunkAligned = (expected + chunkSize - 1) / chunkSize
* chunkSize;
+ ChunkedByteBufferOutputStream stream =
(ChunkedByteBufferOutputStream) batch.recordsBuilder.bufferStream();
+ assertEquals(0, stream.fallbackAllocations());
+ assertEquals(expectedChunkAligned, stream.attachedCapacity());
+
+ batch.close();
+ // Compressors flush on close, so only now is the whole compressed
output known to fit the pre-size.
+ assertTrue(batch.records().sizeInBytes() <= expectedChunkAligned);
+ Record record = batch.records().records().iterator().next();
+ assertArrayEquals(value, readBytes(record.value()));
+
+ // The observed ratio (about 1.0) is well below the 1.3 estimate,
so the estimator lowers the
+ // estimate by one COMPRESSION_RATIO_IMPROVING_STEP (0.005) to
1.295.
+ float observed = (float) batch.compressionRatio();
+ assertTrue(observed < 1.295f, "random data should not inflate by
29.5%, but the observed ratio was " + observed);
+ assertEquals(1.295f, CompressionRatioEstimator.estimation(topic,
compression.type()), 1e-6f);
+
+ accum.deallocate(batch);
+ } finally {
+ accum.close();
+ }
+ }
+
+ /**
+ * Per KIP-1332, a compressed batch's first record is sized by the topic's
compression ratio estimate
+ * times the 1.05 estimation factor, not by its uncompressed upper bound
(a rejected alternative, because
+ * it over-reserves pool memory for data that compresses). An estimate of
0.5 reserves about half the
+ * upper bound, and one of 1.3 (an incompressible topic) reserves more
than it. The record spans many
+ * chunks so the difference is not absorbed by rounding up to a whole
chunk.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"gzip", "snappy", "lz4", "zstd"})
+ public void
testCompressedFirstRecordIsSizedByCompressionRatioEstimate(String codec) throws
Exception {
+ int chunkSize = 256;
+ long totalMemory = 1024L * chunkSize;
+ Compression compression =
Compression.of(CompressionType.forName(codec)).build();
+ BufferPool pool = new BufferPool(totalMemory, chunkSize, metrics,
time, "producer-metrics",
+ BufferPool.AllocationMode.INCREMENTAL);
+ ChunkedRecordAccumulator accum = newAccumulator(8192, compression,
pool);
+ byte[] value = new byte[20_000];
+ int upperBound =
AbstractRecords.estimateSizeInBytesUpperBound(RecordBatch.CURRENT_MAGIC_VALUE,
+ compression.type(), key, value, Record.EMPTY_HEADERS);
+ long upperBoundChunkAligned = ((long) upperBound + chunkSize - 1) /
chunkSize * chunkSize;
+ try {
+ for (float estimate : new float[] {0.5f, 1.3f}) {
+ // Read when the first record is sized, so it must be set
before the append.
+ CompressionRatioEstimator.setEstimation(topic,
compression.type(), estimate);
+ int expected =
MemoryRecordsBuilder.estimatedCompressedSizeInBytes(DefaultRecordBatch.RECORD_BATCH_OVERHEAD,
+ upperBound - DefaultRecordBatch.RECORD_BATCH_OVERHEAD,
estimate);
+ long expectedChunkAligned = ((long) expected + chunkSize - 1)
/ chunkSize * chunkSize;
+ if (estimate < 1.0f)
+ assertTrue(expectedChunkAligned < upperBoundChunkAligned,
"an estimate of " + estimate + " must reserve "
+ + expectedChunkAligned + " bytes, less than the
upper bound's " + upperBoundChunkAligned);
+ else
+ assertTrue(expectedChunkAligned > upperBoundChunkAligned,
"an estimate of " + estimate + " must reserve "
+ + expectedChunkAligned + " bytes, more than the
upper bound's " + upperBoundChunkAligned);
+
+ accum.append(topic, partition1, 0L, key, value,
Record.EMPTY_HEADERS, null,
+ maxBlockTimeMs, time.milliseconds(), cluster);
+ Deque<ProducerBatch> dq = batchesFor(accum, tp1);
+ assertEquals(1, dq.size());
+ ProducerBatch batch = dq.peekFirst();
+ assertNotNull(batch);
+ assertEquals(1, batch.recordCount);
+ // Zero-filled data compresses well, so the write stays within
the reserved chunks.
+ assertEquals(totalMemory - expectedChunkAligned,
pool.availableMemory(),
+ "an estimate of " + estimate + " must reserve " +
expectedChunkAligned + " bytes");
+
+ // Drain, so the next estimate starts a new batch from an
untouched pool.
+ Map<Integer, List<ProducerBatch>> drained =
+ accum.drain(metadataCache, Set.of(node1),
Integer.MAX_VALUE, time.milliseconds());
+ assertEquals(List.of(batch), drained.get(node1.id()));
+ assertArrayEquals(value,
readBytes(batch.records().records().iterator().next().value()));
+ accum.deallocate(batch);
+ assertEquals(totalMemory, pool.availableMemory());
+ }
+ } finally {
+ accum.close();
+ }
+ }
+
+ /**
+ * {@code KafkaProducer.ensureValidRecordSize} bounds only a record's
uncompressed upper bound by
+ * buffer.memory, so a compression ratio estimate above about 0.95 can
size a valid record past the
+ * whole pool. Its first-record allocation must be capped at the pool's
total memory rather than be
+ * rejected by {@link BufferPool#allocateChunks}.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"gzip", "snappy", "lz4", "zstd"})
+ public void testCompressedFirstRecordSizeIsCappedAtPoolSize(String codec)
throws Exception {
+ int chunkSize = 256;
+ int batchSize = 16384;
+ long totalMemory = batchSize;
+ Compression compression =
Compression.of(CompressionType.forName(codec)).build();
+ BufferPool pool = new BufferPool(totalMemory, chunkSize, metrics,
time, "producer-metrics",
+ BufferPool.AllocationMode.INCREMENTAL);
+ ChunkedRecordAccumulator accum = newAccumulator(batchSize,
compression, pool);
+ CompressionRatioEstimator.setEstimation(topic, compression.type(),
1.3f);
+ try {
+ // Preconditions: the record passes ensureValidRecordSize, but its
ratio-based size exceeds the pool.
+ byte[] value = new byte[16000];
+ int upperBound =
AbstractRecords.estimateSizeInBytesUpperBound(RecordBatch.CURRENT_MAGIC_VALUE,
+ compression.type(), key, value, Record.EMPTY_HEADERS);
+ assertTrue(upperBound <= totalMemory);
+ int estimated =
MemoryRecordsBuilder.estimatedCompressedSizeInBytes(DefaultRecordBatch.RECORD_BATCH_OVERHEAD,
+ upperBound - DefaultRecordBatch.RECORD_BATCH_OVERHEAD,
1.3f);
+ assertTrue(estimated > totalMemory, "the estimate of " + estimated
+ " bytes must exceed the pool");
+
+ accum.append(topic, partition1, 0L, key, value,
Record.EMPTY_HEADERS, null,
+ maxBlockTimeMs, time.milliseconds(), cluster);
+
+ // The whole pool backs the batch.
+ Deque<ProducerBatch> dq = batchesFor(accum, tp1);
+ assertEquals(1, dq.size());
+ ProducerBatch batch = dq.peekFirst();
+ assertNotNull(batch);
+ assertEquals(1, batch.recordCount);
+ assertEquals(0, pool.availableMemory());
+
+ batch.close();
+ assertArrayEquals(value,
readBytes(batch.records().records().iterator().next().value()));
+ accum.deallocate(batch);
+ assertEquals(totalMemory, pool.availableMemory());
+ } finally {
+ accum.close();
+ }
+ }
+
+ /**
+ * The opposite of an estimate above 1.0: a topic whose compression ratio
estimate is far below 1.0
+ * but whose data doesn't compress. The batch's fullness checks trust the
estimate, so the batch admits
+ * many times batch.size of uncompressed data, and the compressor then
writes roughly all of it. With
+ * ample pool memory that overshoot is absorbed by mid-write growth from
the pool (mostly as the
+ * compressor flushes on close), so the batch stays open for every record
and never touches the heap.
+ * The batch must decode back to every record appended, every chunk must
go back to the pool, and the
+ * stream is asserted to have grown past its pre-size. Closing the batch
must also feed its observed ratio
+ * (about 1.0) back to the estimator, which is far more than one
COMPRESSION_RATIO_DETERIORATE_STEP above
+ * 0.05, so the estimate jumps straight to it.
+ * {@link #testMidRecordHeapFallbackClosesBatchForAppends} covers the same
growth past an exhausted pool.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"gzip", "snappy", "lz4", "zstd"})
+ public void
testIncompressibleDataWithLowCompressionRatioEstimateGrowsPastBatchSize(String
codec) throws Exception {
+ int chunkSize = 256;
+ int batchSize = 8192;
+ long totalMemory = 1024L * chunkSize;
+ Compression compression =
Compression.of(CompressionType.forName(codec)).build();
+ BufferPool pool = new BufferPool(totalMemory, chunkSize, metrics,
time, "producer-metrics",
+ BufferPool.AllocationMode.INCREMENTAL);
+ ChunkedRecordAccumulator accum = newAccumulator(batchSize,
compression, pool);
+ // Read by the batch on construction, so it must be set before the
first append.
+ CompressionRatioEstimator.setEstimation(topic, compression.type(),
0.05f);
+ try {
+ // Random bytes don't compress, totalling several times batch.size.
+ int recordCount = 100;
+ Random random = new Random(42);
+ List<byte[]> values = new ArrayList<>();
+ int presized = 0;
+ for (int i = 0; i < recordCount; i++) {
+ byte[] value = new byte[500];
+ random.nextBytes(value);
+ values.add(value);
+ accum.append(topic, partition1, i, key, value,
Record.EMPTY_HEADERS, null,
+ maxBlockTimeMs, time.milliseconds(), cluster);
+ if (i == 0)
+ presized = ((ChunkedByteBufferOutputStream)
batchesFor(accum, tp1).peekFirst().recordsBuilder
+ .bufferStream()).attachedCapacity();
+ }
+
+ // The estimate let every record into the one batch.
+ Deque<ProducerBatch> dq = batchesFor(accum, tp1);
+ assertEquals(1, dq.size());
+ ProducerBatch batch = dq.peekFirst();
+ assertNotNull(batch);
+ assertEquals(recordCount, batch.recordCount);
+
+ // Compressors buffer internally, so much of the growth happens as
they flush on close.
+ batch.close();
+ MemoryRecords records = batch.records();
+ assertTrue(records.sizeInBytes() > 4 * batchSize,
+ "the compressed batch should be several times batch.size,
but was " + records.sizeInBytes());
Review Comment:
"the compressed batch should be several times batch.size"...this is expected
if the estimation was really bad/small, but we should ensure the batch is
closed for appends (so we don't continue accepting records that may have a
small estimate but then grow with available pool?)
##########
clients/src/main/java/org/apache/kafka/clients/producer/internals/ChunkedByteBufferOutputStream.java:
##########
@@ -144,6 +174,40 @@ private void ensureNotDeallocated() {
throw new IllegalStateException("operation not allowed after the
stream has been deallocated");
}
+ /**
+ * Makes sure the attached chunks have room for a write of {@code len}
bytes before any of it is written.
+ * A growable stream that is short attaches all the chunks the write still
needs in one step: as many as
+ * the pool can hand out without blocking, the rest from the heap (counted
in {@link #fallbackAllocations()}).
Review Comment:
do we take from the pool with or without a cap in this case? (seems without
a cap on "pool.tryAllocateChunksUpTo(shortfall)"??)
This would be problematic when records end up being bigger than the estimate
(wouldn't we be growing with chunks from the pool over the batch.size and not
closing it for appends?)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]