You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2021/06/18 20:51:25 UTC

[GitHub] [kafka] niket-goel opened a new pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

niket-goel opened a new pull request #10899:
URL: https://github.com/apache/kafka/pull/10899


   Draft commit to add basic wiring for stamping a header into the
   Metadata Snapshot file. This commit does not add a footer to the
   file.
   


-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655550695



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       When `freeze` is called it is possible that the `accumulator` has batches. When freezing the `SnapshotWriter`, it needs to:
   1. Add the footer batch to the accumulator
   2. Drain any pending batches in the accumulator including the control batch appended in 1.
   3. Append those batches to the underlying `RawSnapshotWriter`.




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660032373



##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",
+      "about": "The append time of the highest record contained in this snapshot"}

Review comment:
       How about "The append time of the last record from the log contained in the snapshot"?

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());

Review comment:
       You can use `assertTrue` instead. This comment applies to a few places.

##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",

Review comment:
       Let's call this `LastContainedLogTimestamp` to match Kafka's existing use of "Timestamp"`.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);

Review comment:
       How about moving the buffer allocation to `appendControlMessage`? Not sure we need different messages in the exception since we will have different stacktraces.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -22,25 +22,65 @@
 import java.util.Optional;
 import java.util.OptionalInt;
 import java.util.Random;
+import java.util.Iterator;
 import java.util.Set;
+import org.apache.kafka.common.message.SnapshotFooterRecord;
+import org.apache.kafka.common.message.SnapshotHeaderRecord;
 import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.raft.Batch;
 import org.apache.kafka.raft.OffsetAndEpoch;
 import org.apache.kafka.raft.RaftClientTestContext;
 import org.apache.kafka.raft.internals.StringSerde;
+import org.apache.kafka.common.utils.BufferSupplier.GrowableBufferSupplier;
+import org.apache.kafka.common.record.ControlRecordUtils;
+import org.apache.kafka.common.record.Record;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.Utils;
+
 import org.junit.jupiter.api.Test;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 final public class SnapshotWriterReaderTest {
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        int recordsPerBatch = 1;
+        int batches = 0;
+        int delimiterCount = 2;
+        long lastContainedLogTime = new MockTime().milliseconds();

Review comment:
       I suggest using some known value. `MockTime` could be zero for example. This is okay because this time is an append time which may be unrelated to the mock time.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());
+        RecordBatch batch = recordBatches.next();
+
+        Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+
+        // Verify existence of the header record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+        assertEquals(Boolean.TRUE, records.hasNext());
+        Record record = records.next();
+        countRecords += 1;
+
+        SnapshotHeaderRecord headerRecord = ControlRecordUtils.deserializedSnapshotHeaderRecord(record);
+        assertEquals(headerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+        assertEquals(headerRecord.lastContainedLogTime(), lastContainedLogTime);
+
+        assertEquals(Boolean.FALSE, records.hasNext());

Review comment:
       You can use `assertFalse` instead. This commend applies to a few places.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withLeaderChangeMessage(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    leaderChangeMessage),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the leader change record.");
+        }
+    }
+
+
+    /**
+     * Append a {@link SnapshotHeaderRecord} record to the batch
+     *
+     * @param @SnapshotHeaderRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotHeaderMessage(
+        SnapshotHeaderRecord snapshotHeaderRecord,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+        }
+    }
+
+    /**
+     * Append a {@link SnapshotFooterRecord} record to the batch
+     *
+     * @param @SnapshotFooterRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotFooterMessage(
+        SnapshotFooterRecord snapshotFooterRecord

Review comment:
       In two of this control messages we pass the `currentTimeMs` in this one we don't. It is nice to be consistent. I think that `appendLeaderChangeMessage` passed the `currentTimeMs` because it want to use the same time for the entire `poll` call.

##########
File path: raft/src/main/java/org/apache/kafka/raft/ReplicatedCounter.java
##########
@@ -106,7 +106,7 @@ public synchronized void handleCommit(BatchReader<Integer> reader) {
                     lastCommittedEpoch,
                     lastOffsetSnapshotted
                 );
-                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch);
+                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch, 0/*KAFKA-12997*/);

Review comment:
       Same here. Let's remove the comment referencing a Jira.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -55,13 +95,16 @@ public void testWritingSnapshot() throws Exception {
 
         context.advanceLocalLeaderHighWatermarkToLogEndOffset();
 
-        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch, 0).get()) {

Review comment:
       How about using a non-zero value for all of this cases?

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);

Review comment:
       This is an existing bug but it looks like we never release (`MemoryPool::release`) if there is an exception before adding to `completed`.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());
+        RecordBatch batch = recordBatches.next();
+
+        Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+
+        // Verify existence of the header record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+        assertEquals(Boolean.TRUE, records.hasNext());
+        Record record = records.next();
+        countRecords += 1;
+
+        SnapshotHeaderRecord headerRecord = ControlRecordUtils.deserializedSnapshotHeaderRecord(record);
+        assertEquals(headerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+        assertEquals(headerRecord.lastContainedLogTime(), lastContainedLogTime);
+
+        assertEquals(Boolean.FALSE, records.hasNext());
+
+        // Loop over remaining records
+        while (recordBatches.hasNext()) {
+            batch = recordBatches.next();
+            records = batch.streamingIterator(new GrowableBufferSupplier());
+
+            while (records.hasNext()) {
+                countRecords += 1;
+                record = records.next();
+            }
+        }
+
+        // Verify existence of the footer record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+
+        SnapshotFooterRecord footerRecord = ControlRecordUtils.deserializedSnapshotFooterRecord(record);
+        assertEquals(footerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+
+        // Verify there is nothing past the footer
+        assertEquals(Boolean.FALSE, records.hasNext());
+        assertEquals(Boolean.FALSE, recordBatches.hasNext());

Review comment:
       These two checks will always pass because of the `while` loops above.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -26,19 +28,49 @@
  */
 public class ControlRecordUtils {
 
-    public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short LEADER_CHANGE_SCHEMA_HIGHEST_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short SNAPSHOT_HEADER_HIGHEST_VERSION = new SnapshotHeaderRecord().highestSupportedVersion();
+    public static final short SNAPSHOT_FOOTER_HIGHEST_VERSION = new SnapshotFooterRecord().highestSupportedVersion();
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(Record record) {
         ControlRecordType recordType = ControlRecordType.parse(record.key());
         if (recordType != ControlRecordType.LEADER_CHANGE) {
             throw new IllegalArgumentException(
-                "Expected LEADER_CHANGE control record type(3), but found " + recordType.toString());
+                "Expected LEADER_CHANGE control record type(2), but found " + recordType.toString());
         }
         return deserializeLeaderChangeMessage(record.value().duplicate());
     }
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(ByteBuffer data) {

Review comment:
       Unrelated to this PR but should we file a Jira to change this name to `LeaderChangeRecord` to make it consistent with the rest of the values encoded in the metadata log and snapshot? I think changing the name of this type is backwards compatible. cc @hachikuji 

##########
File path: metadata/src/main/java/org/apache/kafka/controller/QuorumController.java
##########
@@ -345,7 +345,8 @@ void createSnapshotGenerator(long committedOffset, int committedEpoch) {
             }
             Optional<SnapshotWriter<ApiMessageAndVersion>> writer = raftClient.createSnapshot(
                 committedOffset,
-                committedEpoch
+                committedEpoch,
+                0/*KAFKA-12997*/

Review comment:
       We normally don't mention Jira in the code. If I want the reviewer to be aware of a Jira, I link to it through a PR comment.




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655552347



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       Ahh. I was missing point 3. Understood your point. Will make the change.




-- 
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.

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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655618351



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotFooterRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotFooterRecord",

Review comment:
       This is generic to snapshots, rather than metadata snapshots, right? In other words, if we have another snapshotted topic, we'd want to use this record as well.
   
   So I don't think it should have "metadata" in the name




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660032373



##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",
+      "about": "The append time of the highest record contained in this snapshot"}

Review comment:
       How about "The append time of the last record from the log contained in the snapshot"?

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());

Review comment:
       You can use `assertTrue` instead. This comment applies to a few places.

##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",

Review comment:
       Let's call this `LastContainedLogTimestamp` to match Kafka's existing use of "Timestamp"`.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);

Review comment:
       How about moving the buffer allocation to `appendControlMessage`? Not sure we need different messages in the exception since we will have different stacktraces.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -22,25 +22,65 @@
 import java.util.Optional;
 import java.util.OptionalInt;
 import java.util.Random;
+import java.util.Iterator;
 import java.util.Set;
+import org.apache.kafka.common.message.SnapshotFooterRecord;
+import org.apache.kafka.common.message.SnapshotHeaderRecord;
 import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.raft.Batch;
 import org.apache.kafka.raft.OffsetAndEpoch;
 import org.apache.kafka.raft.RaftClientTestContext;
 import org.apache.kafka.raft.internals.StringSerde;
+import org.apache.kafka.common.utils.BufferSupplier.GrowableBufferSupplier;
+import org.apache.kafka.common.record.ControlRecordUtils;
+import org.apache.kafka.common.record.Record;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.Utils;
+
 import org.junit.jupiter.api.Test;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 final public class SnapshotWriterReaderTest {
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        int recordsPerBatch = 1;
+        int batches = 0;
+        int delimiterCount = 2;
+        long lastContainedLogTime = new MockTime().milliseconds();

Review comment:
       I suggest using some known value. `MockTime` could be zero for example. This is okay because this time is an append time which may be unrelated to the mock time.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());
+        RecordBatch batch = recordBatches.next();
+
+        Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+
+        // Verify existence of the header record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+        assertEquals(Boolean.TRUE, records.hasNext());
+        Record record = records.next();
+        countRecords += 1;
+
+        SnapshotHeaderRecord headerRecord = ControlRecordUtils.deserializedSnapshotHeaderRecord(record);
+        assertEquals(headerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+        assertEquals(headerRecord.lastContainedLogTime(), lastContainedLogTime);
+
+        assertEquals(Boolean.FALSE, records.hasNext());

Review comment:
       You can use `assertFalse` instead. This commend applies to a few places.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withLeaderChangeMessage(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    leaderChangeMessage),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the leader change record.");
+        }
+    }
+
+
+    /**
+     * Append a {@link SnapshotHeaderRecord} record to the batch
+     *
+     * @param @SnapshotHeaderRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotHeaderMessage(
+        SnapshotHeaderRecord snapshotHeaderRecord,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+        }
+    }
+
+    /**
+     * Append a {@link SnapshotFooterRecord} record to the batch
+     *
+     * @param @SnapshotFooterRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotFooterMessage(
+        SnapshotFooterRecord snapshotFooterRecord

Review comment:
       In two of this control messages we pass the `currentTimeMs` in this one we don't. It is nice to be consistent. I think that `appendLeaderChangeMessage` passed the `currentTimeMs` because it want to use the same time for the entire `poll` call.

##########
File path: raft/src/main/java/org/apache/kafka/raft/ReplicatedCounter.java
##########
@@ -106,7 +106,7 @@ public synchronized void handleCommit(BatchReader<Integer> reader) {
                     lastCommittedEpoch,
                     lastOffsetSnapshotted
                 );
-                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch);
+                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch, 0/*KAFKA-12997*/);

Review comment:
       Same here. Let's remove the comment referencing a Jira.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -55,13 +95,16 @@ public void testWritingSnapshot() throws Exception {
 
         context.advanceLocalLeaderHighWatermarkToLogEndOffset();
 
-        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch, 0).get()) {

Review comment:
       How about using a non-zero value for all of this cases?

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);

Review comment:
       This is an existing bug but it looks like we never release (`MemoryPool::release`) if there is an exception before adding to `completed`.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());
+        RecordBatch batch = recordBatches.next();
+
+        Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+
+        // Verify existence of the header record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+        assertEquals(Boolean.TRUE, records.hasNext());
+        Record record = records.next();
+        countRecords += 1;
+
+        SnapshotHeaderRecord headerRecord = ControlRecordUtils.deserializedSnapshotHeaderRecord(record);
+        assertEquals(headerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+        assertEquals(headerRecord.lastContainedLogTime(), lastContainedLogTime);
+
+        assertEquals(Boolean.FALSE, records.hasNext());
+
+        // Loop over remaining records
+        while (recordBatches.hasNext()) {
+            batch = recordBatches.next();
+            records = batch.streamingIterator(new GrowableBufferSupplier());
+
+            while (records.hasNext()) {
+                countRecords += 1;
+                record = records.next();
+            }
+        }
+
+        // Verify existence of the footer record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+
+        SnapshotFooterRecord footerRecord = ControlRecordUtils.deserializedSnapshotFooterRecord(record);
+        assertEquals(footerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+
+        // Verify there is nothing past the footer
+        assertEquals(Boolean.FALSE, records.hasNext());
+        assertEquals(Boolean.FALSE, recordBatches.hasNext());

Review comment:
       These two checks will always pass because of the `while` loops above.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -26,19 +28,49 @@
  */
 public class ControlRecordUtils {
 
-    public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short LEADER_CHANGE_SCHEMA_HIGHEST_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short SNAPSHOT_HEADER_HIGHEST_VERSION = new SnapshotHeaderRecord().highestSupportedVersion();
+    public static final short SNAPSHOT_FOOTER_HIGHEST_VERSION = new SnapshotFooterRecord().highestSupportedVersion();
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(Record record) {
         ControlRecordType recordType = ControlRecordType.parse(record.key());
         if (recordType != ControlRecordType.LEADER_CHANGE) {
             throw new IllegalArgumentException(
-                "Expected LEADER_CHANGE control record type(3), but found " + recordType.toString());
+                "Expected LEADER_CHANGE control record type(2), but found " + recordType.toString());
         }
         return deserializeLeaderChangeMessage(record.value().duplicate());
     }
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(ByteBuffer data) {

Review comment:
       Unrelated to this PR but should we file a Jira to change this name to `LeaderChangeRecord` to make it consistent with the rest of the values encoded in the metadata log and snapshot? I think changing the name of this type is backwards compatible. cc @hachikuji 

##########
File path: metadata/src/main/java/org/apache/kafka/controller/QuorumController.java
##########
@@ -345,7 +345,8 @@ void createSnapshotGenerator(long committedOffset, int committedEpoch) {
             }
             Optional<SnapshotWriter<ApiMessageAndVersion>> writer = raftClient.createSnapshot(
                 committedOffset,
-                committedEpoch
+                committedEpoch,
+                0/*KAFKA-12997*/

Review comment:
       We normally don't mention Jira in the code. If I want the reviewer to be aware of a Jira, I link to it through a PR comment.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -654,14 +657,69 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
                                                  long timestamp,
                                                  int leaderEpoch,
                                                  LeaderChangeMessage leaderChangeMessage) {
+        try (MemoryRecordsBuilder builder = new MemoryRecordsBuilder(
+            buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE,
+            TimestampType.CREATE_TIME, initialOffset, timestamp,
+            RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE,
+            false, true, leaderEpoch, buffer.capacity())
+        ) {
+            builder.appendLeaderChangeMessage(timestamp, leaderChangeMessage);
+        }
+    }
+
+    public static MemoryRecords withSnapshotHeaderRecord(
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        ByteBuffer buffer,
+        SnapshotHeaderRecord snapshotHeaderRecord
+    ) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+    }
+
+    private static void writeSnapshotHeaderRecord(ByteBuffer buffer,
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        SnapshotHeaderRecord snapshotHeaderRecord
+    ) {
+        try (MemoryRecordsBuilder builder = new MemoryRecordsBuilder(
+            buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE,
+            TimestampType.CREATE_TIME, initialOffset, timestamp,
+            RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE,
+            false, true, leaderEpoch, buffer.capacity())
+        ) {
+            builder.appendSnapshotHeaderMessage(timestamp, snapshotHeaderRecord);
+        }
+    }
+
+    public static MemoryRecords withSnapshotFooterRecord(
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        ByteBuffer buffer,
+        SnapshotFooterRecord snapshotFooterRecord
+    ) {
+        writeSnapshotFooterRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotFooterRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+    }
+
+    private static void writeSnapshotFooterRecord(ByteBuffer buffer,
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        SnapshotFooterRecord snapshotFooterRecord
+    ) {
         MemoryRecordsBuilder builder = new MemoryRecordsBuilder(
             buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE,
             TimestampType.CREATE_TIME, initialOffset, timestamp,
             RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE,
             false, true, leaderEpoch, buffer.capacity()
         );
-        builder.appendLeaderChangeMessage(timestamp, leaderChangeMessage);
+        builder.appendSnapshotFooterMessage(timestamp, snapshotFooterRecord);
         builder.close();

Review comment:
       We should use Java's try-with-resources here.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotReader.java
##########
@@ -100,4 +116,21 @@ public void close() {
             new RecordsIterator<>(snapshot.records(), serde, bufferSupplier, maxBatchSize)
         );
     }
+
+    /**
+     * Returns the next non-control Batch
+     */
+    private Optional<Batch<T>> nextBatch() {
+        while (iterator.hasNext()) {
+            Batch<T> batch = iterator.next();
+
+            if (batch.records().isEmpty()) {
+                continue;
+            } else {
+                return Optional.of(batch);
+            }

Review comment:
       ```suggestion
               if (!batch.records().isEmpty()) {
                   return Optional.of(batch);
               }
   ```




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655547991



##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       Hmmm. I see your point of not encoding the logic of maintaining the snapshot invariants into the BatchAccumulator, but then there is nothing in code preventing the usage pattern you listed above. Are we ok with that?




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r659060915



##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",

Review comment:
       I am not 100% sure on the type that should be used here to accommodate a long (the json parser was not happy with long as a type). Please let me if the type should be something else.




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r658132063



##########
File path: metadata/src/test/java/org/apache/kafka/metalog/LocalLogManager.java
##########
@@ -541,6 +541,8 @@ public void resign(int epoch) {
     @Override
     public Optional<SnapshotWriter<ApiMessageAndVersion>> createSnapshot(long committedOffset, int committedEpoch) {
         OffsetAndEpoch snapshotId = new OffsetAndEpoch(committedOffset + 1, committedEpoch);
+        return SnapshotWriter.createWithHeader(
+                () -> createNewSnapshot(snapshotId),

Review comment:
       This was a miss. Let me fix 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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655536129



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {

Review comment:
       We have the following document: https://kafka.apache.org/coding-guide




-- 
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.

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



[GitHub] [kafka] cmccabe merged pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe merged pull request #10899:
URL: https://github.com/apache/kafka/pull/10899


   


-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655696253



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+            }
+
+    private static void writeSnapshotHeaderRecord(ByteBuffer buffer,
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        MemoryRecordsBuilder builder = new MemoryRecordsBuilder(

Review comment:
       You are right in that one of the underlying calls throws a few exceptions, but again looking at a similar implementation for the leader change message. Given that implementation (being canonical) does not implement a try/catch, I assumed that the API structure handles exceptions somewhere higher up in the stack. I guess that understanding is not correct. I will make similar changes for the leader change call stack as well then. Will ping offline about what the general exception handling mechanism here. 




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r654014807



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotHeaderRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the metadata snapshot file"}

Review comment:
       Lets add this version field to the `LeaderChangeMessage` schema JSON also.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +81,52 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * FIXME ngoel Improve this comment
+     * Instantiates a SnapshotWriter and stamps the underlying
+     * snapshot with a @MetadataSnapshotHeaderRecord.
+     *
+     * @return {@link Optional}{@link SnapshotWriter}
+     */
+    public static <T> Optional<SnapshotWriter<T>> create(
+            Supplier<Optional<RawSnapshotWriter>> supplier,
+            int maxBatchSize,
+            MemoryPool memoryPool,
+            Time snapshotTime,
+            CompressionType compressionType,
+            RecordSerde<T> serde
+            ){
+        Optional<SnapshotWriter<T>> writer = supplier.get().map(snapshot -> {
+            return new SnapshotWriter<T>(
+                    snapshot,
+                    maxBatchSize,
+                    memoryPool,
+                    snapshotTime,
+                    CompressionType.NONE,
+                    serde
+                    );
+        });
+        if (writer.isPresent()) {
+            //TODO ngoel Append Header
+            // Once the snapshot is intantiated assert that
+            // the snapshot file is 0 bytes and then append a
+            // header
+            SnapshotWriter<T> snapWriter = writer.get();
+            RawSnapshotWriter snapshot = snapWriter.snapshot;
+            if (snapshot.sizeInBytes() != 0){
+                throw new IllegalStateException("Initializing new snapshot with a non-empty file");
+            }
+            // Append the header control record.
+            // FIXME ngoel Where should we define the version?
+            short headerVersion = 0;
+            MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord().setVersion(headerVersion);
+            snapWriter.accumulator.appendSnapshotHeaderMessage(headerRecord);
+            snapWriter.accumulator.forceDrain();
+            snapWriter.close();

Review comment:
       Closing the writer here will abort the snapshot since we are not done and we didn't call.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordType.java
##########
@@ -43,9 +43,13 @@
 public enum ControlRecordType {
     ABORT((short) 0),
     COMMIT((short) 1),
+
     // Raft quorum related control messages.
-    QUORUM_REASSIGNMENT((short) 2),
+    // TODO - ngoel
+    // Burn enum val 2 to prevent
+    // accidental corruption. (Consult with team)

Review comment:
       The change proposed in this PR  already a backward incompatible change. I think we agreed to make `LEADER_CHANGE(2)` and `SNAPSHOT_HEADER(3)`.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +81,52 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * FIXME ngoel Improve this comment
+     * Instantiates a SnapshotWriter and stamps the underlying
+     * snapshot with a @MetadataSnapshotHeaderRecord.
+     *
+     * @return {@link Optional}{@link SnapshotWriter}
+     */
+    public static <T> Optional<SnapshotWriter<T>> create(
+            Supplier<Optional<RawSnapshotWriter>> supplier,
+            int maxBatchSize,
+            MemoryPool memoryPool,
+            Time snapshotTime,
+            CompressionType compressionType,
+            RecordSerde<T> serde
+            ){
+        Optional<SnapshotWriter<T>> writer = supplier.get().map(snapshot -> {
+            return new SnapshotWriter<T>(
+                    snapshot,
+                    maxBatchSize,
+                    memoryPool,
+                    snapshotTime,
+                    CompressionType.NONE,
+                    serde
+                    );
+        });
+        if (writer.isPresent()) {
+            //TODO ngoel Append Header
+            // Once the snapshot is intantiated assert that
+            // the snapshot file is 0 bytes and then append a
+            // header
+            SnapshotWriter<T> snapWriter = writer.get();
+            RawSnapshotWriter snapshot = snapWriter.snapshot;
+            if (snapshot.sizeInBytes() != 0){
+                throw new IllegalStateException("Initializing new snapshot with a non-empty file");
+            }
+            // Append the header control record.
+            // FIXME ngoel Where should we define the version?
+            short headerVersion = 0;
+            MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord().setVersion(headerVersion);
+            snapWriter.accumulator.appendSnapshotHeaderMessage(headerRecord);
+            snapWriter.accumulator.forceDrain();

Review comment:
       I would move all of this functionality as a private instance method of `SnapshotWriter`.

##########
File path: .gitignore
##########
@@ -56,3 +56,8 @@ jmh-benchmarks/src/main/generated
 raft/.jqwik-database
 **/src/generated
 **/src/generated-test
+
+.vim
+.bloop/
+.metals/
+bin/

Review comment:
       I would remove these gitignore patterns from the project. Git allows you to have personal gitignore patterns.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660133212



##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -26,19 +28,49 @@
  */
 public class ControlRecordUtils {
 
-    public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short LEADER_CHANGE_SCHEMA_HIGHEST_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short SNAPSHOT_HEADER_HIGHEST_VERSION = new SnapshotHeaderRecord().highestSupportedVersion();
+    public static final short SNAPSHOT_FOOTER_HIGHEST_VERSION = new SnapshotFooterRecord().highestSupportedVersion();
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(Record record) {
         ControlRecordType recordType = ControlRecordType.parse(record.key());
         if (recordType != ControlRecordType.LEADER_CHANGE) {
             throw new IllegalArgumentException(
-                "Expected LEADER_CHANGE control record type(3), but found " + recordType.toString());
+                "Expected LEADER_CHANGE control record type(2), but found " + recordType.toString());
         }
         return deserializeLeaderChangeMessage(record.value().duplicate());
     }
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(ByteBuffer data) {

Review comment:
       Will cut a JIRA.

##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",
+      "about": "The append time of the highest record contained in this snapshot"}

Review comment:
       That sounds better. Will use this.

##########
File path: metadata/src/main/java/org/apache/kafka/controller/QuorumController.java
##########
@@ -345,7 +345,8 @@ void createSnapshotGenerator(long committedOffset, int committedEpoch) {
             }
             Optional<SnapshotWriter<ApiMessageAndVersion>> writer = raftClient.createSnapshot(
                 committedOffset,
-                committedEpoch
+                committedEpoch,
+                0/*KAFKA-12997*/

Review comment:
       ack.

##########
File path: raft/src/main/java/org/apache/kafka/raft/ReplicatedCounter.java
##########
@@ -106,7 +106,7 @@ public synchronized void handleCommit(BatchReader<Integer> reader) {
                     lastCommittedEpoch,
                     lastOffsetSnapshotted
                 );
-                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch);
+                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch, 0/*KAFKA-12997*/);

Review comment:
       ack

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withLeaderChangeMessage(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    leaderChangeMessage),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the leader change record.");
+        }
+    }
+
+
+    /**
+     * Append a {@link SnapshotHeaderRecord} record to the batch
+     *
+     * @param @SnapshotHeaderRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotHeaderMessage(
+        SnapshotHeaderRecord snapshotHeaderRecord,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+        }
+    }
+
+    /**
+     * Append a {@link SnapshotFooterRecord} record to the batch
+     *
+     * @param @SnapshotFooterRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotFooterMessage(
+        SnapshotFooterRecord snapshotFooterRecord

Review comment:
       Will do

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());

Review comment:
       thanks

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -22,25 +22,65 @@
 import java.util.Optional;
 import java.util.OptionalInt;
 import java.util.Random;
+import java.util.Iterator;
 import java.util.Set;
+import org.apache.kafka.common.message.SnapshotFooterRecord;
+import org.apache.kafka.common.message.SnapshotHeaderRecord;
 import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.raft.Batch;
 import org.apache.kafka.raft.OffsetAndEpoch;
 import org.apache.kafka.raft.RaftClientTestContext;
 import org.apache.kafka.raft.internals.StringSerde;
+import org.apache.kafka.common.utils.BufferSupplier.GrowableBufferSupplier;
+import org.apache.kafka.common.record.ControlRecordUtils;
+import org.apache.kafka.common.record.Record;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.Utils;
+
 import org.junit.jupiter.api.Test;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 final public class SnapshotWriterReaderTest {
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        int recordsPerBatch = 1;
+        int batches = 0;
+        int delimiterCount = 2;
+        long lastContainedLogTime = new MockTime().milliseconds();

Review comment:
       Will use a deafult

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());
+        RecordBatch batch = recordBatches.next();
+
+        Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+
+        // Verify existence of the header record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+        assertEquals(Boolean.TRUE, records.hasNext());
+        Record record = records.next();
+        countRecords += 1;
+
+        SnapshotHeaderRecord headerRecord = ControlRecordUtils.deserializedSnapshotHeaderRecord(record);
+        assertEquals(headerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+        assertEquals(headerRecord.lastContainedLogTime(), lastContainedLogTime);
+
+        assertEquals(Boolean.FALSE, records.hasNext());
+
+        // Loop over remaining records
+        while (recordBatches.hasNext()) {
+            batch = recordBatches.next();
+            records = batch.streamingIterator(new GrowableBufferSupplier());
+
+            while (records.hasNext()) {
+                countRecords += 1;
+                record = records.next();
+            }
+        }
+
+        // Verify existence of the footer record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+
+        SnapshotFooterRecord footerRecord = ControlRecordUtils.deserializedSnapshotFooterRecord(record);
+        assertEquals(footerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+
+        // Verify there is nothing past the footer
+        assertEquals(Boolean.FALSE, records.hasNext());
+        assertEquals(Boolean.FALSE, recordBatches.hasNext());

Review comment:
       Yep. Just an old habit of asserting things to aid readability. Will remove it here.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);

Review comment:
       The code organization gets funny if we do that because the byte buffer is needed for the MemoryRecord API as well. Will sync with you offline on this.




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655542184



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -55,7 +60,7 @@
      * @param compressionType the compression algorithm to use
      * @param serde the record serialization and deserialization implementation
      */

Review comment:
       ack




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655625433



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotFooterRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotFooterRecord",

Review comment:
       Good Point. I had initially made this to be a generic Header and Footer record, but then scoped it to metadata. I did not know we had the intention of expanding the snapshot concept to other topics. (IIUC snapshots would only work on topics that are delta logged, and no other topics work that way today). But if we will do that, then I agree with you.
   
   I guess my only counter question would be that given today the metadata topic is kind of special,  do you envision the metadata snapshot schema evolving different (richer in information) from other snapshot-able topics, such that it might need it's own header/footer?




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660209060



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -654,14 +657,69 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
                                                  long timestamp,
                                                  int leaderEpoch,
                                                  LeaderChangeMessage leaderChangeMessage) {
+        try (MemoryRecordsBuilder builder = new MemoryRecordsBuilder(
+            buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE,
+            TimestampType.CREATE_TIME, initialOffset, timestamp,
+            RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE,
+            false, true, leaderEpoch, buffer.capacity())
+        ) {
+            builder.appendLeaderChangeMessage(timestamp, leaderChangeMessage);
+        }
+    }
+
+    public static MemoryRecords withSnapshotHeaderRecord(
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        ByteBuffer buffer,
+        SnapshotHeaderRecord snapshotHeaderRecord
+    ) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+    }
+
+    private static void writeSnapshotHeaderRecord(ByteBuffer buffer,
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        SnapshotHeaderRecord snapshotHeaderRecord
+    ) {
+        try (MemoryRecordsBuilder builder = new MemoryRecordsBuilder(
+            buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE,
+            TimestampType.CREATE_TIME, initialOffset, timestamp,
+            RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE,
+            false, true, leaderEpoch, buffer.capacity())
+        ) {
+            builder.appendSnapshotHeaderMessage(timestamp, snapshotHeaderRecord);
+        }
+    }
+
+    public static MemoryRecords withSnapshotFooterRecord(
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        ByteBuffer buffer,
+        SnapshotFooterRecord snapshotFooterRecord
+    ) {
+        writeSnapshotFooterRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotFooterRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+    }
+
+    private static void writeSnapshotFooterRecord(ByteBuffer buffer,
+        long initialOffset,
+        long timestamp,
+        int leaderEpoch,
+        SnapshotFooterRecord snapshotFooterRecord
+    ) {
         MemoryRecordsBuilder builder = new MemoryRecordsBuilder(
             buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE,
             TimestampType.CREATE_TIME, initialOffset, timestamp,
             RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE,
             false, true, leaderEpoch, buffer.capacity()
         );
-        builder.appendLeaderChangeMessage(timestamp, leaderChangeMessage);
+        builder.appendSnapshotFooterMessage(timestamp, snapshotFooterRecord);
         builder.close();

Review comment:
       We should use Java's try-with-resources here.




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655537490



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");

Review comment:
       Will do.




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655536129



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {

Review comment:
       We have the following document: https://kafka.apache.org/coding-guide

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       It is a valid/correct check but it doesn't cover all of the cases. For example, in theory `SnapshotWriter` could do the following:
   ```
   accumulator.appendSnapshotHeaderMessage(...);
   snapshot.appendBatches(accumulator.drain());
   accumulator.appendSnapshotHeaderMessage(...);
   ```
   
   This is okay from the `BatchAccumulator`'s point of view because the accumulator doesn't have enough information. I am also not sure if we want to encode the invariant of `SnapshotHeaderMessage` and `SnaspshotFooterMessage` into the `BatchAccumulator`.
   
   I think only the `SnapshotWriter` has enough information to make these invariant checks. What do you think?
   

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       When `freeze` is called it is possible that the `accumulator` has batches. When freezing the `SnapshotWriter`, it needs to:
   1. Add the footer batch to the accumulator
   2. Drain any pending batches in the accumulator including the control batch appended in 1.
   3. Append those batches to the underlying `RawSnapshotWriter`.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       I think that having tests that check this behavior for `SnaphsotWriter` is the best we can do.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660135431



##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);

Review comment:
       The code organization gets funny if we do that because the byte buffer is needed for the MemoryRecord API as well. Will sync with you offline on this.




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r658137972



##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -37,6 +43,52 @@
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        // TODO ngoel
+        // Is this the right way to setup the offset for
+        // an empty snapshot?
+        int recordsPerBatch = 1;
+        int batches = 0;
+        OffsetAndEpoch id = new OffsetAndEpoch(recordsPerBatch * batches, 3);
+
+        RaftClientTestContext.Builder contextBuilder = new RaftClientTestContext.Builder(localId, voters);
+        RaftClientTestContext context = contextBuilder.build();
+
+        context.pollUntil(() -> context.currentLeader().equals(OptionalInt.of(localId)));
+        context.advanceLocalLeaderHighWatermarkToLogEndOffset();
+
+        // Create an empty snapshot and freeze it immediately
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+            assertEquals(id, snapshot.snapshotId());
+            snapshot.freeze();
+        }
+
+        // Verify that an empty snapshot has only the Header and Footer
+        try (SnapshotReader<String> reader = readSnapshot(context, id, Integer.MAX_VALUE)) {
+            RawSnapshotReader snapshot = context.log.readSnapshot(id).get();
+            // TODO ngoel
+            // Is there a way to make this a function of the actual
+            // Control Batch Record size.
+            assertEquals(150, snapshot.sizeInBytes());

Review comment:
       Yeah, I wanted to ask you about this. I think checking to decode it as  a control batch makes sense. Will do that.
   

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -37,6 +43,52 @@
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        // TODO ngoel
+        // Is this the right way to setup the offset for
+        // an empty snapshot?
+        int recordsPerBatch = 1;
+        int batches = 0;
+        OffsetAndEpoch id = new OffsetAndEpoch(recordsPerBatch * batches, 3);
+
+        RaftClientTestContext.Builder contextBuilder = new RaftClientTestContext.Builder(localId, voters);
+        RaftClientTestContext context = contextBuilder.build();
+
+        context.pollUntil(() -> context.currentLeader().equals(OptionalInt.of(localId)));
+        context.advanceLocalLeaderHighWatermarkToLogEndOffset();
+
+        // Create an empty snapshot and freeze it immediately
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+            assertEquals(id, snapshot.snapshotId());
+            snapshot.freeze();
+        }
+
+        // Verify that an empty snapshot has only the Header and Footer
+        try (SnapshotReader<String> reader = readSnapshot(context, id, Integer.MAX_VALUE)) {
+            RawSnapshotReader snapshot = context.log.readSnapshot(id).get();
+            // TODO ngoel
+            // Is there a way to make this a function of the actual
+            // Control Batch Record size.
+            assertEquals(150, snapshot.sizeInBytes());
+            int countBatches = 0;
+            Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+            while (recordBatches.hasNext()) {
+                int countRecords = 0;
+                RecordBatch batch = recordBatches.next();

Review comment:
       Will do




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655542285



##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       It is a valid/correct check but it doesn't cover all of the cases. For example, in theory `SnapshotWriter` could do the following:
   ```
   accumulator.appendSnapshotHeaderMessage(...);
   snapshot.appendBatches(accumulator.drain());
   accumulator.appendSnapshotHeaderMessage(...);
   ```
   
   This is okay from the `BatchAccumulator`'s point of view because the accumulator doesn't have enough information. I am also not sure if we want to encode the invariant of `SnapshotHeaderMessage` and `SnaspshotFooterMessage` into the `BatchAccumulator`.
   
   I think only the `SnapshotWriter` has enough information to make these invariant checks. What do you think?
   




-- 
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.

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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655617821



##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -27,6 +29,8 @@
 public class ControlRecordUtils {
 
     public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_HEADER_VERSION = new MetadataSnapshotHeaderRecord().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_FOOTER_VERSION = new MetadataSnapshotFooterRecord().highestSupportedVersion();

Review comment:
       Same comment for this.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660134385



##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -204,35 +207,103 @@ private void completeCurrentBatch() {
         currentBatch = null;
     }
 
-    public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, long currentTimeMs) {
+    private void appendControlMessage(
+        Supplier<MemoryRecords> supplier,
+        ByteBuffer buffer
+    ) {
         appendLock.lock();
         try {
             forceDrain();
-            ByteBuffer buffer = memoryPool.tryAllocate(256);
-            if (buffer != null) {
-                MemoryRecords data = MemoryRecords.withLeaderChangeMessage(
-                    this.nextOffset, 
-                    currentTimeMs, 
-                    this.epoch, 
-                    buffer, 
-                    leaderChangeMessage
-                );
-                completed.add(new CompletedBatch<>(
-                    nextOffset,
-                    1,
-                    data,
-                    memoryPool,
-                    buffer
-                ));
-                nextOffset += 1;
-            } else {
-                throw new IllegalStateException("Could not allocate buffer for the leader change record.");
-            }
+            completed.add(new CompletedBatch<>(
+                nextOffset,
+                1,
+                supplier.get(),
+                memoryPool,
+                buffer
+            ));
+            nextOffset += 1;
         } finally {
             appendLock.unlock();
         }
     }
 
+    /**
+     * Append a {@link LeaderChangeMessage} record to the batch
+     *
+     * @param @LeaderChangeMessage The message to append
+     * @param @currentTimeMs The timestamp of message generation
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendLeaderChangeMessage(
+        LeaderChangeMessage leaderChangeMessage,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withLeaderChangeMessage(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    leaderChangeMessage),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the leader change record.");
+        }
+    }
+
+
+    /**
+     * Append a {@link SnapshotHeaderRecord} record to the batch
+     *
+     * @param @SnapshotHeaderRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotHeaderMessage(
+        SnapshotHeaderRecord snapshotHeaderRecord,
+        long currentTimeMs
+    ) {
+        ByteBuffer buffer = memoryPool.tryAllocate(256);
+        if (buffer != null) {
+            appendControlMessage(
+                () -> MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord),
+                buffer);
+        } else {
+            throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+        }
+    }
+
+    /**
+     * Append a {@link SnapshotFooterRecord} record to the batch
+     *
+     * @param @SnapshotFooterRecord The message to append
+     * @throws IllegalStateException on failure to allocate a buffer for the record
+     */
+    public void appendSnapshotFooterMessage(
+        SnapshotFooterRecord snapshotFooterRecord

Review comment:
       Will do

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());

Review comment:
       thanks

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -22,25 +22,65 @@
 import java.util.Optional;
 import java.util.OptionalInt;
 import java.util.Random;
+import java.util.Iterator;
 import java.util.Set;
+import org.apache.kafka.common.message.SnapshotFooterRecord;
+import org.apache.kafka.common.message.SnapshotHeaderRecord;
 import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.raft.Batch;
 import org.apache.kafka.raft.OffsetAndEpoch;
 import org.apache.kafka.raft.RaftClientTestContext;
 import org.apache.kafka.raft.internals.StringSerde;
+import org.apache.kafka.common.utils.BufferSupplier.GrowableBufferSupplier;
+import org.apache.kafka.common.record.ControlRecordUtils;
+import org.apache.kafka.common.record.Record;
+import org.apache.kafka.common.record.RecordBatch;
+import org.apache.kafka.common.utils.Utils;
+
 import org.junit.jupiter.api.Test;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 final public class SnapshotWriterReaderTest {
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        int recordsPerBatch = 1;
+        int batches = 0;
+        int delimiterCount = 2;
+        long lastContainedLogTime = new MockTime().milliseconds();

Review comment:
       Will use a deafult

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -151,6 +194,57 @@ public void testAppendToFrozenSnapshot() throws Exception {
         );
     }
 
+    private int validateDelimiters(
+        RawSnapshotReader snapshot,
+        long lastContainedLogTime
+    ) {
+        assertNotEquals(0, snapshot.sizeInBytes());
+
+        int countRecords = 0;
+
+        Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+
+        assertEquals(Boolean.TRUE, recordBatches.hasNext());
+        RecordBatch batch = recordBatches.next();
+
+        Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+
+        // Verify existence of the header record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+        assertEquals(Boolean.TRUE, records.hasNext());
+        Record record = records.next();
+        countRecords += 1;
+
+        SnapshotHeaderRecord headerRecord = ControlRecordUtils.deserializedSnapshotHeaderRecord(record);
+        assertEquals(headerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+        assertEquals(headerRecord.lastContainedLogTime(), lastContainedLogTime);
+
+        assertEquals(Boolean.FALSE, records.hasNext());
+
+        // Loop over remaining records
+        while (recordBatches.hasNext()) {
+            batch = recordBatches.next();
+            records = batch.streamingIterator(new GrowableBufferSupplier());
+
+            while (records.hasNext()) {
+                countRecords += 1;
+                record = records.next();
+            }
+        }
+
+        // Verify existence of the footer record
+        assertEquals(Boolean.TRUE, batch.isControlBatch());
+
+        SnapshotFooterRecord footerRecord = ControlRecordUtils.deserializedSnapshotFooterRecord(record);
+        assertEquals(footerRecord.version(), ControlRecordUtils.SNAPSHOT_HEADER_HIGHEST_VERSION);
+
+        // Verify there is nothing past the footer
+        assertEquals(Boolean.FALSE, records.hasNext());
+        assertEquals(Boolean.FALSE, recordBatches.hasNext());

Review comment:
       Yep. Just an old habit of asserting things to aid readability. Will remove it here.




-- 
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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655616706



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+            }
+
+    private static void writeSnapshotHeaderRecord(ByteBuffer buffer,
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        MemoryRecordsBuilder builder = new MemoryRecordsBuilder(

Review comment:
       Does this need to be wrapped in a try... catch block to avoid leaking something if we throw an exception in `appendSnapshotHeaderMessage` ?




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655546225



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       Would we not want to drain the pipe (here accumulator) before finalizing it (by stamping the footer). I guess your point is that the footer is yet another record which we can append and then just do one final drain?
   PS right now in the code the finalize method is also forcing a drain on the accumulator. We could remove that too then. 
   
   Let me do it that way.




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r654704639



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {

Review comment:
       Apache Kafka doesn't have a style guide but newer code tends to have 4 spaces for argument indentation and the sequence `) {` in its own line. E.g.
   ```
   void functionName(
       Type argument,
       AnotherType anotherArgument
   ) {
       // Code here
   }
   ```
   
   This comment applies to a few places in this PR.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       I think we need to do this before appending the batches above.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");
+        }
+        MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord()
+            .setVersion(ControlRecordUtils.METADATA_SNAPSHOT_HEADER_VERSION);
+        accumulator.appendSnapshotHeaderMessage(headerRecord);
+        accumulator.forceDrain();
+    }
+
+    /**
+     * Add a {@link MetadataSnapshotFooterRecord} to the snapshot
+     *
+     * No more records should be appended to the snapshot after calling this method
+     *
+     * @throws IllegalStateException if the snapshot is empty (no header)
+     */
+    private void finalizeSnapshotWithFooter() {
+        if (snapshot.sizeInBytes() == 0) {

Review comment:
       Hmm. Not sure but I would argue that this check is always false since there is only once "constructor" and that always appends at least one record batch. We can confirm in the tests that this is always true.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+            }

Review comment:
       Extra spaces.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -55,7 +60,7 @@
      * @param compressionType the compression algorithm to use
      * @param serde the record serialization and deserialization implementation
      */

Review comment:
       Let's remove this Java Doc since you moved it to the static method and the constructor is private.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       At this layer I think the best we can do is `forceDrain()`. It should be a noop if there are no records in the current batch.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this
+            long currentTimeMs = time.milliseconds();
+            ByteBuffer buffer = memoryPool.tryAllocate(256);
+            if (buffer != null) {
+                MemoryRecords data = MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord
+                );
+                completed.add(new CompletedBatch<>(
+                    nextOffset,
+                    1,
+                    data,
+                    memoryPool,
+                    buffer
+                ));
+                nextOffset += 1;
+            } else {
+                throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+            }
+        } finally {
+            appendLock.unlock();
+        }
+    }
+
+    public void appendSnapshotFooterMessage(MetadataSnapshotFooterRecord snapshotFooterRecord) {
+        appendLock.lock();
+        try {
+            forceDrain();
+            long currentTimeMs = time.milliseconds();
+            ByteBuffer buffer = memoryPool.tryAllocate(256);
+            if (buffer != null) {
+                MemoryRecords data = MemoryRecords.withSnapshotFooterRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotFooterRecord
+                );
+                completed.add(new CompletedBatch<>(
+                    nextOffset,
+                    1,
+                    data,
+                    memoryPool,
+                    buffer
+                ));
+                nextOffset += 1;
+            } else {
+                throw new IllegalStateException("Could not allocate buffer for the metadata snapshot footer record.");
+            }
+        } finally {
+            appendLock.unlock();
+        }
+    }

Review comment:
       There is code duplication between these 3 methods. Let's figure out a way to remove this duplicate code.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");

Review comment:
       You can rely on `OffsetAndEpoch::toString`. For example, `String.format("Initializing with non-empty snapshot  (%s)", snapshot.snapshotId())`.
   
   Changed the message because it is possible that the `RawSnapshotWriter` is not a file but an in-memory snapshot.
   
   This comment always applies to the footer message.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");
+        }
+        MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord()
+            .setVersion(ControlRecordUtils.METADATA_SNAPSHOT_HEADER_VERSION);
+        accumulator.appendSnapshotHeaderMessage(headerRecord);
+        accumulator.forceDrain();
+    }
+
+    /**
+     * Add a {@link MetadataSnapshotFooterRecord} to the snapshot
+     *
+     * No more records should be appended to the snapshot after calling this method
+     *
+     * @throws IllegalStateException if the snapshot is empty (no header)
+     */
+    private void finalizeSnapshotWithFooter() {
+        if (snapshot.sizeInBytes() == 0) {
+            throw new IllegalStateException("Finalizing snapshot (ID: "
+                + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                + ") without a header");
+        }
+        MetadataSnapshotFooterRecord footerRecord = new MetadataSnapshotFooterRecord()
+            .setVersion(ControlRecordUtils.METADATA_SNAPSHOT_FOOTER_VERSION);
+        accumulator.appendSnapshotFooterMessage(footerRecord);
+        accumulator.forceDrain();
+    }
+
+    /**
+     * Create an instance of this class and initialize
+     * the underlying snapshot with {@link MetadataSnapshotHeaderRecord}
+     *
+     * @param snapshot a lambda to create the low level snapshot writer
+     * @param maxBatchSize the maximum size in byte for a batch
+     * @param memoryPool the memory pool for buffer allocation
+     * @param time the clock implementation
+     * @param compressionType the compression algorithm to use
+     * @param serde the record serialization and deserialization implementation
+     * @return {@link Optional}{@link SnapshotWriter}
+     */
+    public static <T> Optional<SnapshotWriter<T>> createWithHeader(
+            Supplier<Optional<RawSnapshotWriter>> supplier,
+            int maxBatchSize,
+            MemoryPool memoryPool,
+            Time snapshotTime,
+            CompressionType compressionType,
+            RecordSerde<T> serde) {
+        Optional<SnapshotWriter<T>> writer = supplier.get().map(snapshot -> {
+            return new SnapshotWriter<T>(
+                    snapshot,
+                    maxBatchSize,
+                    memoryPool,
+                    snapshotTime,
+                    CompressionType.NONE,
+                    serde);
+        });
+        if (writer.isPresent()) {
+            writer.get().initializeSnapshotWithHeader();
+        }

Review comment:
       I think you can use `ifPresent`. E.g.
   ```
   writer.ifPresent(SnapshotWriter::initializeSnapshotWithHeader)
   ```




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655511645



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {

Review comment:
       Thanks. I was trying to find some info around styling. Will follow this across the PR.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       I am concerned about improper usage in the future which might lead to stamping the header after other records in the file. Is asserting on the fact that the current batch has no records as this time valid? It should be an error if it isn't.
   
   What do you think?




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r658125257



##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -37,6 +43,52 @@
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        // TODO ngoel
+        // Is this the right way to setup the offset for
+        // an empty snapshot?
+        int recordsPerBatch = 1;
+        int batches = 0;
+        OffsetAndEpoch id = new OffsetAndEpoch(recordsPerBatch * batches, 3);
+
+        RaftClientTestContext.Builder contextBuilder = new RaftClientTestContext.Builder(localId, voters);
+        RaftClientTestContext context = contextBuilder.build();
+
+        context.pollUntil(() -> context.currentLeader().equals(OptionalInt.of(localId)));
+        context.advanceLocalLeaderHighWatermarkToLogEndOffset();
+
+        // Create an empty snapshot and freeze it immediately
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+            assertEquals(id, snapshot.snapshotId());
+            snapshot.freeze();
+        }
+
+        // Verify that an empty snapshot has only the Header and Footer
+        try (SnapshotReader<String> reader = readSnapshot(context, id, Integer.MAX_VALUE)) {
+            RawSnapshotReader snapshot = context.log.readSnapshot(id).get();
+            // TODO ngoel
+            // Is there a way to make this a function of the actual
+            // Control Batch Record size.
+            assertEquals(150, snapshot.sizeInBytes());
+            int countBatches = 0;
+            Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+            while (recordBatches.hasNext()) {
+                int countRecords = 0;
+                RecordBatch batch = recordBatches.next();
+                countBatches += 1;
+
+                Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+                while (records.hasNext()) {
+                    Record record = records.next();

Review comment:
       Are you planning to add a check that the record is a control record and that you can decode the key and the value?

##########
File path: metadata/src/test/java/org/apache/kafka/metalog/LocalLogManager.java
##########
@@ -541,6 +541,8 @@ public void resign(int epoch) {
     @Override
     public Optional<SnapshotWriter<ApiMessageAndVersion>> createSnapshot(long committedOffset, int committedEpoch) {
         OffsetAndEpoch snapshotId = new OffsetAndEpoch(committedOffset + 1, committedEpoch);
+        return SnapshotWriter.createWithHeader(
+                () -> createNewSnapshot(snapshotId),

Review comment:
       There are two returns in a row. The second return is never reached.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -37,6 +43,52 @@
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        // TODO ngoel
+        // Is this the right way to setup the offset for
+        // an empty snapshot?
+        int recordsPerBatch = 1;
+        int batches = 0;
+        OffsetAndEpoch id = new OffsetAndEpoch(recordsPerBatch * batches, 3);
+
+        RaftClientTestContext.Builder contextBuilder = new RaftClientTestContext.Builder(localId, voters);
+        RaftClientTestContext context = contextBuilder.build();
+
+        context.pollUntil(() -> context.currentLeader().equals(OptionalInt.of(localId)));
+        context.advanceLocalLeaderHighWatermarkToLogEndOffset();
+
+        // Create an empty snapshot and freeze it immediately
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+            assertEquals(id, snapshot.snapshotId());
+            snapshot.freeze();
+        }
+
+        // Verify that an empty snapshot has only the Header and Footer
+        try (SnapshotReader<String> reader = readSnapshot(context, id, Integer.MAX_VALUE)) {
+            RawSnapshotReader snapshot = context.log.readSnapshot(id).get();
+            // TODO ngoel
+            // Is there a way to make this a function of the actual
+            // Control Batch Record size.
+            assertEquals(150, snapshot.sizeInBytes());

Review comment:
       Yeah. This is probably a brittle check. How about checking that is is non-empty and that you can decode the control batches/records?

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -84,44 +74,36 @@ private SnapshotWriter(
     }
 
     /**
-     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     * Adds a {@link SnapshotHeaderRecord} to snapshot
      *
      * @throws IllegalStateException if the snapshot is not empty
      */
     private void initializeSnapshotWithHeader() {
         if (snapshot.sizeInBytes() != 0) {
-            throw new IllegalStateException("Initializing new snapshot (ID: "
-                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
-                    + ") with a non-empty file");
+            throw new IllegalStateException("Initializing with a non-empty snapshot (%s)"
+                    + snapshot.snapshotId());

Review comment:
       `+` does a string concatenation. You need to use `String.format` if you wan to perform string formatting.

##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -37,6 +43,52 @@
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        // TODO ngoel
+        // Is this the right way to setup the offset for
+        // an empty snapshot?
+        int recordsPerBatch = 1;
+        int batches = 0;
+        OffsetAndEpoch id = new OffsetAndEpoch(recordsPerBatch * batches, 3);
+
+        RaftClientTestContext.Builder contextBuilder = new RaftClientTestContext.Builder(localId, voters);
+        RaftClientTestContext context = contextBuilder.build();
+
+        context.pollUntil(() -> context.currentLeader().equals(OptionalInt.of(localId)));
+        context.advanceLocalLeaderHighWatermarkToLogEndOffset();
+
+        // Create an empty snapshot and freeze it immediately
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+            assertEquals(id, snapshot.snapshotId());
+            snapshot.freeze();
+        }
+
+        // Verify that an empty snapshot has only the Header and Footer
+        try (SnapshotReader<String> reader = readSnapshot(context, id, Integer.MAX_VALUE)) {
+            RawSnapshotReader snapshot = context.log.readSnapshot(id).get();
+            // TODO ngoel
+            // Is there a way to make this a function of the actual
+            // Control Batch Record size.
+            assertEquals(150, snapshot.sizeInBytes());
+            int countBatches = 0;
+            Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+            while (recordBatches.hasNext()) {
+                int countRecords = 0;
+                RecordBatch batch = recordBatches.next();

Review comment:
       We should check that this is a control batch.




-- 
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.

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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660199695



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotFooterRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotFooterRecord",

Review comment:
       Perhaps. However, if we needed a specific metadata header or footer, we'd do that as a metadata record.




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660133212



##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -26,19 +28,49 @@
  */
 public class ControlRecordUtils {
 
-    public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short LEADER_CHANGE_SCHEMA_HIGHEST_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short SNAPSHOT_HEADER_HIGHEST_VERSION = new SnapshotHeaderRecord().highestSupportedVersion();
+    public static final short SNAPSHOT_FOOTER_HIGHEST_VERSION = new SnapshotFooterRecord().highestSupportedVersion();
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(Record record) {
         ControlRecordType recordType = ControlRecordType.parse(record.key());
         if (recordType != ControlRecordType.LEADER_CHANGE) {
             throw new IllegalArgumentException(
-                "Expected LEADER_CHANGE control record type(3), but found " + recordType.toString());
+                "Expected LEADER_CHANGE control record type(2), but found " + recordType.toString());
         }
         return deserializeLeaderChangeMessage(record.value().duplicate());
     }
 
     public static LeaderChangeMessage deserializeLeaderChangeMessage(ByteBuffer data) {

Review comment:
       Will cut a JIRA.

##########
File path: clients/src/main/resources/common/message/SnapshotHeaderRecord.json
##########
@@ -0,0 +1,27 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "SnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the snapshot header record"},
+    {"name": "LastContainedLogTime", "type": "int64", "versions": "0+",
+      "about": "The append time of the highest record contained in this snapshot"}

Review comment:
       That sounds better. Will use this.

##########
File path: metadata/src/main/java/org/apache/kafka/controller/QuorumController.java
##########
@@ -345,7 +345,8 @@ void createSnapshotGenerator(long committedOffset, int committedEpoch) {
             }
             Optional<SnapshotWriter<ApiMessageAndVersion>> writer = raftClient.createSnapshot(
                 committedOffset,
-                committedEpoch
+                committedEpoch,
+                0/*KAFKA-12997*/

Review comment:
       ack.

##########
File path: raft/src/main/java/org/apache/kafka/raft/ReplicatedCounter.java
##########
@@ -106,7 +106,7 @@ public synchronized void handleCommit(BatchReader<Integer> reader) {
                     lastCommittedEpoch,
                     lastOffsetSnapshotted
                 );
-                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch);
+                Optional<SnapshotWriter<Integer>> snapshot = client.createSnapshot(lastCommittedOffset, lastCommittedEpoch, 0/*KAFKA-12997*/);

Review comment:
       ack




-- 
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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655616706



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+            }
+
+    private static void writeSnapshotHeaderRecord(ByteBuffer buffer,
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        MemoryRecordsBuilder builder = new MemoryRecordsBuilder(

Review comment:
       Does this need to be wrapped in a try... catch block to avoid leaking something if we throw an exception in `appendSnapshotHeaderMessage` ?

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -27,6 +29,8 @@
 public class ControlRecordUtils {
 
     public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_HEADER_VERSION = new MetadataSnapshotHeaderRecord().highestSupportedVersion();

Review comment:
       Do we really need this constant? It seems confusing since it implies there is only one version ever, but there may well be more versions later on. If you mean highest supported, why not just say highest supported rather than referring to "the version"?

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -27,6 +29,8 @@
 public class ControlRecordUtils {
 
     public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_HEADER_VERSION = new MetadataSnapshotHeaderRecord().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_FOOTER_VERSION = new MetadataSnapshotFooterRecord().highestSupportedVersion();

Review comment:
       Same comment for this.

##########
File path: clients/src/main/resources/common/message/MetadataSnapshotFooterRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotFooterRecord",

Review comment:
       This is generic to snapshots, rather than metadata snapshots, right? In other words, if we have another snapshotted topic, we'd want to use this record as well.
   
   So I don't think it should have "metadata" in the name

##########
File path: clients/src/main/resources/common/message/MetadataSnapshotHeaderRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotHeaderRecord",

Review comment:
       Same comment about naming here.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655511645



##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {

Review comment:
       Thanks. I was trying to find some info around styling. Will follow this across the PR.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       I am concerned about improper usage in the future which might lead to stamping the header after other records in the file. Is asserting on the fact that the current batch has no records as this time valid? It should be an error if it isn't.
   
   What do you think?

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this
+            long currentTimeMs = time.milliseconds();
+            ByteBuffer buffer = memoryPool.tryAllocate(256);
+            if (buffer != null) {
+                MemoryRecords data = MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord
+                );
+                completed.add(new CompletedBatch<>(
+                    nextOffset,
+                    1,
+                    data,
+                    memoryPool,
+                    buffer
+                ));
+                nextOffset += 1;
+            } else {
+                throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+            }
+        } finally {
+            appendLock.unlock();
+        }
+    }
+
+    public void appendSnapshotFooterMessage(MetadataSnapshotFooterRecord snapshotFooterRecord) {
+        appendLock.lock();
+        try {
+            forceDrain();
+            long currentTimeMs = time.milliseconds();
+            ByteBuffer buffer = memoryPool.tryAllocate(256);
+            if (buffer != null) {
+                MemoryRecords data = MemoryRecords.withSnapshotFooterRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotFooterRecord
+                );
+                completed.add(new CompletedBatch<>(
+                    nextOffset,
+                    1,
+                    data,
+                    memoryPool,
+                    buffer
+                ));
+                nextOffset += 1;
+            } else {
+                throw new IllegalStateException("Could not allocate buffer for the metadata snapshot footer record.");
+            }
+        } finally {
+            appendLock.unlock();
+        }
+    }

Review comment:
       I agree. Let me fix that.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");

Review comment:
       Will do.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -55,7 +60,7 @@
      * @param compressionType the compression algorithm to use
      * @param serde the record serialization and deserialization implementation
      */

Review comment:
       ack

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");
+        }
+        MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord()
+            .setVersion(ControlRecordUtils.METADATA_SNAPSHOT_HEADER_VERSION);
+        accumulator.appendSnapshotHeaderMessage(headerRecord);
+        accumulator.forceDrain();
+    }
+
+    /**
+     * Add a {@link MetadataSnapshotFooterRecord} to the snapshot
+     *
+     * No more records should be appended to the snapshot after calling this method
+     *
+     * @throws IllegalStateException if the snapshot is empty (no header)
+     */
+    private void finalizeSnapshotWithFooter() {
+        if (snapshot.sizeInBytes() == 0) {

Review comment:
       I agree with the argument, and adding a test, but do you think we should remove the code check? For me the code check serves as a runtime fail safe and also a hint to the reader. The check is in no way complete. I do not have a strong opinion here. Just thinking out loud.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       Would we not want to drain the pipe (here accumulator) before finalizing it (by stamping the footer). I guess your point is that the footer is yet another record which we can append and then just do one final drain?
   PS right now in the code the finalize method is also forcing a drain on the accumulator. We could remove that too then. 
   
   Let me do it that way.

##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       Hmmm. I see your point of not encoding the logic of maintaining the snapshot invariants into the BatchAccumulator, but then there is nothing in code preventing the usage pattern you listed above. Are we ok with that?

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -135,9 +210,12 @@ public void append(List<T> records) {
 
     /**
      * Freezes the snapshot by flushing all pending writes and marking it as immutable.
+     *
+     * Also adds a {@link MetadataSnapshotFooterRecord} to the end of the snapshot
      */
     public void freeze() {
         appendBatches(accumulator.drain());
+        finalizeSnapshotWithFooter();

Review comment:
       Ahh. I was missing point 3. Understood your point. Will make the change.

##########
File path: clients/src/main/resources/common/message/MetadataSnapshotFooterRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotFooterRecord",

Review comment:
       Good Point. I had initially made this to be a generic Header and Footer record, but then scoped it to metadata. I did not know we had the intention of expanding the snapshot concept to other topics. (IIUC snapshots would only work on topics that are delta logged, and no other topics work that way today). But if we will do that, then I agree with you.
   
   I guess my only counter question would be that given today the metadata topic is kind of special,  do you envision the metadata snapshot schema evolving different (richer in information) from other snapshot-able topics, such that it might need it's own header/footer?

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -27,6 +29,8 @@
 public class ControlRecordUtils {
 
     public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_HEADER_VERSION = new MetadataSnapshotHeaderRecord().highestSupportedVersion();

Review comment:
       I honestly do not have an opinion here. Was following what was done for the LEADER_CHANGE message (right above it). I think saying highest supported version (or maybe even current version) would make sense. I would then change the leader change message related constants as well to be consistent. Let me do that in the next version.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
##########
@@ -664,4 +666,55 @@ private static void writeLeaderChangeMessage(ByteBuffer buffer,
         builder.close();
     }
 
+    public static MemoryRecords withSnapshotHeaderRecord(
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            ByteBuffer buffer,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        writeSnapshotHeaderRecord(buffer, initialOffset, timestamp, leaderEpoch, snapshotHeaderRecord);
+        buffer.flip();
+        return MemoryRecords.readableRecords(buffer);
+            }
+
+    private static void writeSnapshotHeaderRecord(ByteBuffer buffer,
+            long initialOffset,
+            long timestamp,
+            int leaderEpoch,
+            MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        MemoryRecordsBuilder builder = new MemoryRecordsBuilder(

Review comment:
       You are right in that one of the underlying calls throws a few exceptions, but again looking at a similar implementation for the leader change message. Given that implementation (being canonical) does not implement a try/catch, I assumed that the API structure handles exceptions somewhere higher up in the stack. I guess that understanding is not correct. I will make similar changes for the leader change call stack as well then. Will ping offline about what the general exception handling mechanism here. 




-- 
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.

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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660199695



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotFooterRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotFooterRecord",

Review comment:
       Perhaps. However, if we needed a specific metadata header or footer, we'd do that as a metadata record.




-- 
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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655617424



##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -27,6 +29,8 @@
 public class ControlRecordUtils {
 
     public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_HEADER_VERSION = new MetadataSnapshotHeaderRecord().highestSupportedVersion();

Review comment:
       Do we really need this constant? It seems confusing since it implies there is only one version ever, but there may well be more versions later on. If you mean highest supported, why not just say highest supported rather than referring to "the version"?




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r654552376



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotHeaderRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotHeaderRecord",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    {"name": "Version", "type": "int16", "versions": "0+",
+      "about": "The version of the metadata snapshot file"}

Review comment:
       Yep. Added in the next commit.

##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordType.java
##########
@@ -43,9 +43,13 @@
 public enum ControlRecordType {
     ABORT((short) 0),
     COMMIT((short) 1),
+
     // Raft quorum related control messages.
-    QUORUM_REASSIGNMENT((short) 2),
+    // TODO - ngoel
+    // Burn enum val 2 to prevent
+    // accidental corruption. (Consult with team)

Review comment:
       Makes sense. Made the change in the next revision

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +81,52 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * FIXME ngoel Improve this comment
+     * Instantiates a SnapshotWriter and stamps the underlying
+     * snapshot with a @MetadataSnapshotHeaderRecord.
+     *
+     * @return {@link Optional}{@link SnapshotWriter}
+     */
+    public static <T> Optional<SnapshotWriter<T>> create(
+            Supplier<Optional<RawSnapshotWriter>> supplier,
+            int maxBatchSize,
+            MemoryPool memoryPool,
+            Time snapshotTime,
+            CompressionType compressionType,
+            RecordSerde<T> serde
+            ){
+        Optional<SnapshotWriter<T>> writer = supplier.get().map(snapshot -> {
+            return new SnapshotWriter<T>(
+                    snapshot,
+                    maxBatchSize,
+                    memoryPool,
+                    snapshotTime,
+                    CompressionType.NONE,
+                    serde
+                    );
+        });
+        if (writer.isPresent()) {
+            //TODO ngoel Append Header
+            // Once the snapshot is intantiated assert that
+            // the snapshot file is 0 bytes and then append a
+            // header
+            SnapshotWriter<T> snapWriter = writer.get();
+            RawSnapshotWriter snapshot = snapWriter.snapshot;
+            if (snapshot.sizeInBytes() != 0){
+                throw new IllegalStateException("Initializing new snapshot with a non-empty file");
+            }
+            // Append the header control record.
+            // FIXME ngoel Where should we define the version?
+            short headerVersion = 0;
+            MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord().setVersion(headerVersion);
+            snapWriter.accumulator.appendSnapshotHeaderMessage(headerRecord);
+            snapWriter.accumulator.forceDrain();
+            snapWriter.close();

Review comment:
       Good catch. Fixed in next version.

##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +81,52 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * FIXME ngoel Improve this comment
+     * Instantiates a SnapshotWriter and stamps the underlying
+     * snapshot with a @MetadataSnapshotHeaderRecord.
+     *
+     * @return {@link Optional}{@link SnapshotWriter}
+     */
+    public static <T> Optional<SnapshotWriter<T>> create(
+            Supplier<Optional<RawSnapshotWriter>> supplier,
+            int maxBatchSize,
+            MemoryPool memoryPool,
+            Time snapshotTime,
+            CompressionType compressionType,
+            RecordSerde<T> serde
+            ){
+        Optional<SnapshotWriter<T>> writer = supplier.get().map(snapshot -> {
+            return new SnapshotWriter<T>(
+                    snapshot,
+                    maxBatchSize,
+                    memoryPool,
+                    snapshotTime,
+                    CompressionType.NONE,
+                    serde
+                    );
+        });
+        if (writer.isPresent()) {
+            //TODO ngoel Append Header
+            // Once the snapshot is intantiated assert that
+            // the snapshot file is 0 bytes and then append a
+            // header
+            SnapshotWriter<T> snapWriter = writer.get();
+            RawSnapshotWriter snapshot = snapWriter.snapshot;
+            if (snapshot.sizeInBytes() != 0){
+                throw new IllegalStateException("Initializing new snapshot with a non-empty file");
+            }
+            // Append the header control record.
+            // FIXME ngoel Where should we define the version?
+            short headerVersion = 0;
+            MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord().setVersion(headerVersion);
+            snapWriter.accumulator.appendSnapshotHeaderMessage(headerRecord);
+            snapWriter.accumulator.forceDrain();

Review comment:
       Done

##########
File path: .gitignore
##########
@@ -56,3 +56,8 @@ jmh-benchmarks/src/main/generated
 raft/.jqwik-database
 **/src/generated
 **/src/generated-test
+
+.vim
+.bloop/
+.metals/
+bin/

Review comment:
       Yes. Pushed by mistake. Fixed in next version.




-- 
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.

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



[GitHub] [kafka] cmccabe commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655618509



##########
File path: clients/src/main/resources/common/message/MetadataSnapshotHeaderRecord.json
##########
@@ -0,0 +1,25 @@
+// 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.
+
+{
+  "type": "data",
+  "name": "MetadataSnapshotHeaderRecord",

Review comment:
       Same comment about naming here.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r658138278



##########
File path: raft/src/test/java/org/apache/kafka/snapshot/SnapshotWriterReaderTest.java
##########
@@ -37,6 +43,52 @@
     private final int localId = 0;
     private final Set<Integer> voters = Collections.singleton(localId);
 
+    @Test
+    public void testSnapshotDelimiters() throws Exception {
+        // TODO ngoel
+        // Is this the right way to setup the offset for
+        // an empty snapshot?
+        int recordsPerBatch = 1;
+        int batches = 0;
+        OffsetAndEpoch id = new OffsetAndEpoch(recordsPerBatch * batches, 3);
+
+        RaftClientTestContext.Builder contextBuilder = new RaftClientTestContext.Builder(localId, voters);
+        RaftClientTestContext context = contextBuilder.build();
+
+        context.pollUntil(() -> context.currentLeader().equals(OptionalInt.of(localId)));
+        context.advanceLocalLeaderHighWatermarkToLogEndOffset();
+
+        // Create an empty snapshot and freeze it immediately
+        try (SnapshotWriter<String> snapshot = context.client.createSnapshot(id.offset - 1, id.epoch).get()) {
+            assertEquals(id, snapshot.snapshotId());
+            snapshot.freeze();
+        }
+
+        // Verify that an empty snapshot has only the Header and Footer
+        try (SnapshotReader<String> reader = readSnapshot(context, id, Integer.MAX_VALUE)) {
+            RawSnapshotReader snapshot = context.log.readSnapshot(id).get();
+            // TODO ngoel
+            // Is there a way to make this a function of the actual
+            // Control Batch Record size.
+            assertEquals(150, snapshot.sizeInBytes());
+            int countBatches = 0;
+            Iterator<RecordBatch> recordBatches = Utils.covariantCast(snapshot.records().batchIterator());
+            while (recordBatches.hasNext()) {
+                int countRecords = 0;
+                RecordBatch batch = recordBatches.next();
+                countBatches += 1;
+
+                Iterator<Record> records = batch.streamingIterator(new GrowableBufferSupplier());
+                while (records.hasNext()) {
+                    Record record = records.next();

Review comment:
       yes. will update in the next version.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655627008



##########
File path: clients/src/main/java/org/apache/kafka/common/record/ControlRecordUtils.java
##########
@@ -27,6 +29,8 @@
 public class ControlRecordUtils {
 
     public static final short LEADER_CHANGE_SCHEMA_VERSION = new LeaderChangeMessage().highestSupportedVersion();
+    public static final short METADATA_SNAPSHOT_HEADER_VERSION = new MetadataSnapshotHeaderRecord().highestSupportedVersion();

Review comment:
       I honestly do not have an opinion here. Was following what was done for the LEADER_CHANGE message (right above it). I think saying highest supported version (or maybe even current version) would make sense. I would then change the leader change message related constants as well to be consistent. Let me do that in the next version.




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimiters to Metadata Snapshot

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r660227382



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotReader.java
##########
@@ -100,4 +116,21 @@ public void close() {
             new RecordsIterator<>(snapshot.records(), serde, bufferSupplier, maxBatchSize)
         );
     }
+
+    /**
+     * Returns the next non-control Batch
+     */
+    private Optional<Batch<T>> nextBatch() {
+        while (iterator.hasNext()) {
+            Batch<T> batch = iterator.next();
+
+            if (batch.records().isEmpty()) {
+                continue;
+            } else {
+                return Optional.of(batch);
+            }

Review comment:
       ```suggestion
               if (!batch.records().isEmpty()) {
                   return Optional.of(batch);
               }
   ```




-- 
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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655546062



##########
File path: raft/src/main/java/org/apache/kafka/snapshot/SnapshotWriter.java
##########
@@ -78,6 +83,76 @@ public SnapshotWriter(
         );
     }
 
+    /**
+     * Adds a {@link MetadataSnapshotHeaderRecord} to snapshot
+     *
+     * @throws IllegalStateException if the snapshot is not empty
+     */
+    private void initializeSnapshotWithHeader() {
+        if (snapshot.sizeInBytes() != 0) {
+            throw new IllegalStateException("Initializing new snapshot (ID: "
+                    + snapshot.snapshotId().epoch + ", " + snapshot.snapshotId().offset
+                    + ") with a non-empty file");
+        }
+        MetadataSnapshotHeaderRecord headerRecord = new MetadataSnapshotHeaderRecord()
+            .setVersion(ControlRecordUtils.METADATA_SNAPSHOT_HEADER_VERSION);
+        accumulator.appendSnapshotHeaderMessage(headerRecord);
+        accumulator.forceDrain();
+    }
+
+    /**
+     * Add a {@link MetadataSnapshotFooterRecord} to the snapshot
+     *
+     * No more records should be appended to the snapshot after calling this method
+     *
+     * @throws IllegalStateException if the snapshot is empty (no header)
+     */
+    private void finalizeSnapshotWithFooter() {
+        if (snapshot.sizeInBytes() == 0) {

Review comment:
       I agree with the argument, and adding a test, but do you think we should remove the code check? For me the code check serves as a runtime fail safe and also a hint to the reader. The check is in no way complete. I do not have a strong opinion here. Just thinking out loud.




-- 
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.

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



[GitHub] [kafka] niket-goel commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
niket-goel commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655512248



##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this
+            long currentTimeMs = time.milliseconds();
+            ByteBuffer buffer = memoryPool.tryAllocate(256);
+            if (buffer != null) {
+                MemoryRecords data = MemoryRecords.withSnapshotHeaderRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotHeaderRecord
+                );
+                completed.add(new CompletedBatch<>(
+                    nextOffset,
+                    1,
+                    data,
+                    memoryPool,
+                    buffer
+                ));
+                nextOffset += 1;
+            } else {
+                throw new IllegalStateException("Could not allocate buffer for the metadata snapshot header record.");
+            }
+        } finally {
+            appendLock.unlock();
+        }
+    }
+
+    public void appendSnapshotFooterMessage(MetadataSnapshotFooterRecord snapshotFooterRecord) {
+        appendLock.lock();
+        try {
+            forceDrain();
+            long currentTimeMs = time.milliseconds();
+            ByteBuffer buffer = memoryPool.tryAllocate(256);
+            if (buffer != null) {
+                MemoryRecords data = MemoryRecords.withSnapshotFooterRecord(
+                    this.nextOffset,
+                    currentTimeMs,
+                    this.epoch,
+                    buffer,
+                    snapshotFooterRecord
+                );
+                completed.add(new CompletedBatch<>(
+                    nextOffset,
+                    1,
+                    data,
+                    memoryPool,
+                    buffer
+                ));
+                nextOffset += 1;
+            } else {
+                throw new IllegalStateException("Could not allocate buffer for the metadata snapshot footer record.");
+            }
+        } finally {
+            appendLock.unlock();
+        }
+    }

Review comment:
       I agree. Let me fix that.




-- 
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.

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



[GitHub] [kafka] jsancio commented on a change in pull request #10899: KAFKA-12952 Adding Delimeters to Metadata Snapshot File

Posted by GitBox <gi...@apache.org>.
jsancio commented on a change in pull request #10899:
URL: https://github.com/apache/kafka/pull/10899#discussion_r655553349



##########
File path: raft/src/main/java/org/apache/kafka/raft/internals/BatchAccumulator.java
##########
@@ -233,6 +235,68 @@ public void appendLeaderChangeMessage(LeaderChangeMessage leaderChangeMessage, l
         }
     }
 
+
+    public void appendSnapshotHeaderMessage(MetadataSnapshotHeaderRecord snapshotHeaderRecord) {
+        appendLock.lock();
+        try {
+            // Ideally there should be nothing in the batch here.
+            // TODO verify this

Review comment:
       I think that having tests that check this behavior for `SnaphsotWriter` is the best we can do.




-- 
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.

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