/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.paimon.format.vortex;

import org.apache.paimon.arrow.ArrowBundleRecords;
import org.apache.paimon.arrow.vector.ArrowFormatWriter;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.data.InternalRow;
import org.apache.paimon.data.serializer.InternalRowSerializer;
import org.apache.paimon.format.BundleFormatWriter;
import org.apache.paimon.format.FileFormatFactory;
import org.apache.paimon.format.FormatReaderContext;
import org.apache.paimon.format.FormatReaderFactory;
import org.apache.paimon.format.FormatWriter;
import org.apache.paimon.format.SupportsDirectWrite;
import org.apache.paimon.fs.FileIO;
import org.apache.paimon.fs.Path;
import org.apache.paimon.fs.local.LocalFileIO;
import org.apache.paimon.options.Options;
import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder;
import org.apache.paimon.reader.FileRecordIterator;
import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.reader.RecordReaderIterator;
import org.apache.paimon.table.SpecialFields;
import org.apache.paimon.types.DataTypes;
import org.apache.paimon.types.RowType;
import org.apache.paimon.utils.RoaringBitmap32;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/** Test read write for Vortex file format. */
public class VortexReaderWriterTest {

    @Test
    public void testWriteAndRead(@TempDir java.nio.file.Path tempDir) throws Exception {
        RowType rowType = RowType.of(DataTypes.INT(), DataTypes.STRING());
        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_data_" + UUID.randomUUID());

        // Write data
        List<InternalRow> expectedRows = new ArrayList<>();
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            expectedRows.add(GenericRow.of(1, BinaryString.fromString("hello")));
            writer.addElement(expectedRows.get(0));
            expectedRows.add(GenericRow.of(2, BinaryString.fromString("world")));
            writer.addElement(expectedRows.get(1));
        }

        InternalRowSerializer internalRowSerializer = new InternalRowSerializer(rowType);
        // Read data and check
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {
            assertNotNull(reader);

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(internalRowSerializer.copy(iterator.next()));
            }

            assertEquals(expectedRows.size(), actualRows.size());
            for (int i = 0; i < expectedRows.size(); i++) {
                assertEquals(expectedRows.get(i).getInt(0), actualRows.get(i).getInt(0));
                assertEquals(expectedRows.get(i).getString(1), actualRows.get(i).getString(1));
            }
        }
    }

    @Test
    public void testReadWithColumnProjection(@TempDir java.nio.file.Path tempDir) throws Exception {
        RowType fullRowType =
                RowType.builder()
                        .field("f_int", DataTypes.INT())
                        .field("f_string", DataTypes.STRING())
                        .field("f_double", DataTypes.DOUBLE())
                        .build();

        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_projection_" + UUID.randomUUID());

        // Write 3 columns
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(fullRowType))
                        .create(fileIO, testFile, "")) {
            writer.addElement(GenericRow.of(1, BinaryString.fromString("hello"), 1.5D));
            writer.addElement(GenericRow.of(2, BinaryString.fromString("world"), 2.5D));
        }

        InternalRowSerializer serializer;

        // Read only f_string column
        RowType projectedRowType = RowType.builder().field("f_string", DataTypes.STRING()).build();
        serializer = new InternalRowSerializer(projectedRowType);
        FormatReaderFactory readerFactory =
                format.createReaderFactory(fullRowType, projectedRowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(serializer.copy(iterator.next()));
            }

            assertEquals(2, actualRows.size());
            assertEquals(1, actualRows.get(0).getFieldCount());
            assertEquals(BinaryString.fromString("hello"), actualRows.get(0).getString(0));
            assertEquals(BinaryString.fromString("world"), actualRows.get(1).getString(0));
        }
    }

    @Test
    public void testWriteAndReadMultipleTypes(@TempDir java.nio.file.Path tempDir)
            throws Exception {
        RowType rowType =
                RowType.builder()
                        .field("f_int", DataTypes.INT())
                        .field("f_bigint", DataTypes.BIGINT())
                        .field("f_double", DataTypes.DOUBLE())
                        .field("f_boolean", DataTypes.BOOLEAN())
                        .field("f_string", DataTypes.STRING())
                        .build();

        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_multi_" + UUID.randomUUID());

        // Write data
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            writer.addElement(GenericRow.of(1, 100L, 1.5D, true, BinaryString.fromString("row1")));
            writer.addElement(GenericRow.of(2, 200L, 2.5D, false, BinaryString.fromString("row2")));
            writer.addElement(GenericRow.of(3, 300L, 3.5D, true, BinaryString.fromString("row3")));
        }

        InternalRowSerializer serializer = new InternalRowSerializer(rowType);
        // Read data and check
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(serializer.copy(iterator.next()));
            }

            assertEquals(3, actualRows.size());
            assertEquals(1, actualRows.get(0).getInt(0));
            assertEquals(100L, actualRows.get(0).getLong(1));
            assertEquals(1.5D, actualRows.get(0).getDouble(2));
            assertEquals(true, actualRows.get(0).getBoolean(3));
            assertEquals(BinaryString.fromString("row1"), actualRows.get(0).getString(4));

            assertEquals(3, actualRows.get(2).getInt(0));
            assertEquals(300L, actualRows.get(2).getLong(1));
        }
    }

    @Test
    public void testWriteDoesNotLeakArrowMemoryOnClose(@TempDir java.nio.file.Path tempDir)
            throws Exception {
        RowType rowType =
                RowType.builder()
                        .field("f_int", DataTypes.INT())
                        .field("f_string", DataTypes.STRING())
                        .build();

        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile =
                new Path(new Path(tempDir.toUri()), "test_ffi_no_leak_" + UUID.randomUUID());

        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            writer.addElement(GenericRow.of(1, BinaryString.fromString("hello")));
            writer.addElement(GenericRow.of(2, BinaryString.fromString("world")));
            writer.addElement(GenericRow.of(3, BinaryString.fromString("vortex")));
        }

        assertTrue(fileIO.getFileSize(testFile) > 0);

        InternalRowSerializer serializer = new InternalRowSerializer(rowType);
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(serializer.copy(iterator.next()));
            }

            assertEquals(3, actualRows.size());
            assertEquals(1, actualRows.get(0).getInt(0));
            assertEquals(BinaryString.fromString("hello"), actualRows.get(0).getString(1));
            assertEquals(2, actualRows.get(1).getInt(0));
            assertEquals(BinaryString.fromString("world"), actualRows.get(1).getString(1));
            assertEquals(3, actualRows.get(2).getInt(0));
            assertEquals(BinaryString.fromString("vortex"), actualRows.get(2).getString(1));
        }
    }

    @Test
    public void testArrowBundleRecordsWriteDoesNotBorrowCallerBuffers(
            @TempDir java.nio.file.Path tempDir) throws Exception {
        RowType rowType =
                RowType.builder()
                        .field("f_int", DataTypes.INT())
                        .field("f_string", DataTypes.STRING())
                        .build();

        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile =
                new Path(new Path(tempDir.toUri()), "test_arrow_bundle_copy_" + UUID.randomUUID());

        try (FormatWriter writer =
                        ((SupportsDirectWrite) format.createWriterFactory(rowType))
                                .create(fileIO, testFile, "");
                ArrowFormatWriter arrowWriter = new ArrowFormatWriter(rowType, 1024, true)) {
            arrowWriter.write(GenericRow.of(1, BinaryString.fromString("hello")));
            arrowWriter.write(GenericRow.of(2, BinaryString.fromString("world")));
            arrowWriter.flush();

            ((BundleFormatWriter) writer)
                    .writeBundle(
                            new ArrowBundleRecords(
                                    arrowWriter.getVectorSchemaRoot(), rowType, true));

            arrowWriter.reset();
            arrowWriter.write(GenericRow.of(100, BinaryString.fromString("mutated")));
            arrowWriter.flush();
        }

        InternalRowSerializer serializer = new InternalRowSerializer(rowType);
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(serializer.copy(iterator.next()));
            }

            assertEquals(2, actualRows.size());
            assertEquals(1, actualRows.get(0).getInt(0));
            assertEquals(BinaryString.fromString("hello"), actualRows.get(0).getString(1));
            assertEquals(2, actualRows.get(1).getInt(0));
            assertEquals(BinaryString.fromString("world"), actualRows.get(1).getString(1));
        }
    }

    @Test
    public void testReadWithSelection(@TempDir java.nio.file.Path tempDir) throws Exception {
        RowType rowType = RowType.of(DataTypes.INT(), DataTypes.STRING());
        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_selection_" + UUID.randomUUID());

        // Write 5 rows
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            for (int i = 0; i < 5; i++) {
                writer.addElement(GenericRow.of(i, BinaryString.fromString("row" + i)));
            }
        }

        InternalRowSerializer serializer = new InternalRowSerializer(rowType);

        // Read with selection: only rows 1 and 3
        RoaringBitmap32 selection = RoaringBitmap32.bitmapOf(1, 3);
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO,
                                        testFile,
                                        fileIO.getFileSize(testFile),
                                        selection));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(serializer.copy(iterator.next()));
            }

            assertEquals(2, actualRows.size());
            assertEquals(1, actualRows.get(0).getInt(0));
            assertEquals(BinaryString.fromString("row1"), actualRows.get(0).getString(1));
            assertEquals(3, actualRows.get(1).getInt(0));
            assertEquals(BinaryString.fromString("row3"), actualRows.get(1).getString(1));
        }
    }

    @Test
    public void testReadWithVirtualRowTrackingField(@TempDir java.nio.file.Path tempDir)
            throws Exception {
        RowType rowType =
                RowType.builder()
                        .field("f_int", DataTypes.INT())
                        .field("f_string", DataTypes.STRING())
                        .build();
        RowType projectedRowType =
                SpecialFields.rowTypeWithRowId(rowType)
                        .project(Arrays.asList("f_string", SpecialFields.ROW_ID.name()));

        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile =
                new Path(new Path(tempDir.toUri()), "test_virtual_row_id_" + UUID.randomUUID());

        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            writer.addElement(GenericRow.of(1, BinaryString.fromString("hello")));
            writer.addElement(GenericRow.of(2, BinaryString.fromString("world")));
        }

        FormatReaderFactory readerFactory =
                format.createReaderFactory(rowType, projectedRowType, null);
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {
            InternalRow row = iterator.next();
            assertEquals(2, row.getFieldCount());
            assertEquals(BinaryString.fromString("hello"), row.getString(0));
            assertEquals(true, row.isNullAt(1));

            row = iterator.next();
            assertEquals(BinaryString.fromString("world"), row.getString(0));
            assertEquals(true, row.isNullAt(1));
        }
    }

    @Test
    public void testReadWithPredicate(@TempDir java.nio.file.Path tempDir) throws Exception {
        RowType rowType =
                RowType.builder()
                        .field("f_int", DataTypes.INT())
                        .field("f_string", DataTypes.STRING())
                        .build();

        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_predicate_" + UUID.randomUUID());

        // Write 5 rows: (0, "row0"), (1, "row1"), ..., (4, "row4")
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            for (int i = 0; i < 5; i++) {
                writer.addElement(GenericRow.of(i, BinaryString.fromString("row" + i)));
            }
        }

        InternalRowSerializer serializer = new InternalRowSerializer(rowType);

        // Read with predicate: f_int > 2 (should return rows 3 and 4)
        PredicateBuilder builder = new PredicateBuilder(rowType);
        Predicate predicate = builder.greaterThan(0, 2);
        FormatReaderFactory readerFactory =
                format.createReaderFactory(rowType, rowType, Collections.singletonList(predicate));
        try (RecordReader<InternalRow> reader =
                        readerFactory.createReader(
                                new FormatReaderContext(
                                        fileIO, testFile, fileIO.getFileSize(testFile), null));
                RecordReaderIterator<InternalRow> iterator = new RecordReaderIterator<>(reader)) {

            List<InternalRow> actualRows = new ArrayList<>();
            while (iterator.hasNext()) {
                actualRows.add(serializer.copy(iterator.next()));
            }

            assertEquals(2, actualRows.size());
            assertEquals(3, actualRows.get(0).getInt(0));
            assertEquals(BinaryString.fromString("row3"), actualRows.get(0).getString(1));
            assertEquals(4, actualRows.get(1).getInt(0));
            assertEquals(BinaryString.fromString("row4"), actualRows.get(1).getString(1));
        }
    }

    @Test
    public void testReturnedPositionWithRowIndices(@TempDir java.nio.file.Path tempDir)
            throws Exception {
        RowType rowType = RowType.of(DataTypes.INT(), DataTypes.STRING());
        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_position_" + UUID.randomUUID());

        // Write 10 rows: (0, "row0"), ..., (9, "row9")
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            for (int i = 0; i < 10; i++) {
                writer.addElement(GenericRow.of(i, BinaryString.fromString("row" + i)));
            }
        }

        // Read with selection: rows at indices 2, 5, 8
        RoaringBitmap32 selection = RoaringBitmap32.bitmapOf(2, 5, 8);
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                readerFactory.createReader(
                        new FormatReaderContext(
                                fileIO, testFile, fileIO.getFileSize(testFile), selection))) {

            long[] expectedPositions = new long[] {2, 5, 8};
            int idx = 0;
            RecordReader.RecordIterator<InternalRow> batch;
            while ((batch = reader.readBatch()) != null) {
                FileRecordIterator<InternalRow> fileIter = (FileRecordIterator<InternalRow>) batch;
                InternalRow row;
                while ((row = fileIter.next()) != null) {
                    assertEquals(
                            expectedPositions[idx],
                            fileIter.returnedPosition(),
                            "returnedPosition mismatch at index " + idx);
                    assertEquals((int) expectedPositions[idx], row.getInt(0));
                    idx++;
                }
                batch.releaseBatch();
            }
            assertEquals(3, idx, "Should have read exactly 3 rows");
        }
    }

    @Test
    public void testReachTargetSize(@TempDir java.nio.file.Path tempDir) throws Exception {
        RowType rowType = RowType.of(DataTypes.INT(), DataTypes.STRING());
        Options options = new Options();
        // Use small batch size to trigger flush frequently
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 2, 1));

        FileIO fileIO = new LocalFileIO();
        Path testFile =
                new Path(new Path(tempDir.toUri()), "test_target_size_" + UUID.randomUUID());

        FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "");
        try {
            // Before any write, should not reach target size
            assertFalse(writer.reachTargetSize(true, 1));

            // Write rows to fill the batch (batchSize=2), triggering a flush
            writer.addElement(GenericRow.of(1, BinaryString.fromString("hello")));
            writer.addElement(GenericRow.of(2, BinaryString.fromString("world")));
            // batch is full, next addElement triggers flush
            writer.addElement(GenericRow.of(3, BinaryString.fromString("vortex")));

            // After flush, ipcBytes > 0. With a very small target, should reach target size
            assertTrue(writer.reachTargetSize(true, 1));

            // suggestedCheck=false should always return false
            assertFalse(writer.reachTargetSize(false, 1));

            // With a very large target, should not reach target size
            assertFalse(writer.reachTargetSize(true, Long.MAX_VALUE));
        } finally {
            writer.close();
        }
    }

    @Test
    public void testReturnedPositionSequential(@TempDir java.nio.file.Path tempDir)
            throws Exception {
        RowType rowType = RowType.of(DataTypes.INT(), DataTypes.STRING());
        Options options = new Options();
        VortexFileFormat format =
                new VortexFileFormatFactory()
                        .create(new FileFormatFactory.FormatContext(options, 1024, 1024));

        FileIO fileIO = new LocalFileIO();
        Path testFile = new Path(new Path(tempDir.toUri()), "test_seq_pos_" + UUID.randomUUID());

        // Write 5 rows
        try (FormatWriter writer =
                ((SupportsDirectWrite) format.createWriterFactory(rowType))
                        .create(fileIO, testFile, "")) {
            for (int i = 0; i < 5; i++) {
                writer.addElement(GenericRow.of(i, BinaryString.fromString("row" + i)));
            }
        }

        // Read without selection — positions should be 0, 1, 2, 3, 4
        FormatReaderFactory readerFactory = format.createReaderFactory(rowType, rowType, null);
        try (RecordReader<InternalRow> reader =
                readerFactory.createReader(
                        new FormatReaderContext(
                                fileIO, testFile, fileIO.getFileSize(testFile), null))) {

            long expectedPos = 0;
            RecordReader.RecordIterator<InternalRow> batch;
            while ((batch = reader.readBatch()) != null) {
                FileRecordIterator<InternalRow> fileIter = (FileRecordIterator<InternalRow>) batch;
                InternalRow row;
                while ((row = fileIter.next()) != null) {
                    assertEquals(
                            expectedPos,
                            fileIter.returnedPosition(),
                            "Sequential position mismatch");
                    assertEquals((int) expectedPos, row.getInt(0));
                    expectedPos++;
                }
                batch.releaseBatch();
            }
            assertEquals(5, expectedPos, "Should have read exactly 5 rows");
        }
    }
}
