maedhroz commented on code in PR #2267:
URL: https://github.com/apache/cassandra/pull/2267#discussion_r1185539060


##########
test/unit/org/apache/cassandra/io/sstable/format/bti/PartitionIndexTest.java:
##########
@@ -0,0 +1,934 @@
+/*
+ * 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.cassandra.io.sstable.format.bti;
+
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.Random;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+
+import com.google.common.collect.HashMultiset;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Multiset;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.Util;
+import org.apache.cassandra.cache.ChunkCache;
+import org.apache.cassandra.config.Config;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.dht.ByteOrderedPartitioner;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.RandomPartitioner;
+import org.apache.cassandra.io.tries.TrieNode;
+import org.apache.cassandra.io.tries.Walker;
+import org.apache.cassandra.io.util.File;
+import org.apache.cassandra.io.util.FileHandle;
+import org.apache.cassandra.io.util.FileUtils;
+import org.apache.cassandra.io.util.PageAware;
+import org.apache.cassandra.io.util.Rebufferer;
+import org.apache.cassandra.io.util.SequentialWriter;
+import org.apache.cassandra.io.util.SequentialWriterOption;
+import org.apache.cassandra.io.util.WrappingRebufferer;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.bytecomparable.ByteComparable;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(Parameterized.class)
+public class PartitionIndexTest
+{
+    private final static Logger logger = 
LoggerFactory.getLogger(PartitionIndexTest.class);
+
+    private final static long SEED = System.nanoTime();
+    private final static Random random = new Random(SEED);
+
+    static final ByteComparable.Version VERSION = 
Walker.BYTE_COMPARABLE_VERSION;
+
+    static
+    {
+        DatabaseDescriptor.daemonInitialization();
+    }
+
+    IPartitioner partitioner = Util.testPartitioner();
+    //Lower the size of the indexes when running without the chunk cache, 
otherwise the test times out on Jenkins
+    static final int COUNT = ChunkCache.instance != null ? 245256 : 24525;
+
+    @Parameterized.Parameters()
+    public static Collection<Object[]> generateData()
+    {
+        return Arrays.asList(new Object[]{ Config.DiskAccessMode.standard },
+                             new Object[]{ Config.DiskAccessMode.mmap });
+    }
+
+    @Parameterized.Parameter(value = 0)
+    public static Config.DiskAccessMode accessMode = 
Config.DiskAccessMode.standard;
+
+    public static void beforeClass()
+    {
+        logger.info("Using random seed: {}", SEED);
+    }
+
+    /**
+     * Tests last-nodes-sizing failure uncovered during code review.
+     */
+    @Test
+    public void testSizingBug() throws IOException, InterruptedException
+    {
+        for (int i = 1; i < COUNT; i *= 10)
+        {
+            testGetEq(generateRandomIndex(i));
+            testGetEq(generateSequentialIndex(i));
+        }
+    }
+
+    @Test
+    public void testGetEq() throws IOException, InterruptedException
+    {
+        testGetEq(generateRandomIndex(COUNT));
+        testGetEq(generateSequentialIndex(COUNT));
+    }
+
+    @Test
+    public void testBrokenFile() throws IOException, InterruptedException
+    {
+        // put some garbage in the file
+        final Pair<List<DecoratedKey>, PartitionIndex> data = 
generateRandomIndex(COUNT);
+        File f = new File(data.right.getFileHandle().path());
+        try (FileChannel ch = FileChannel.open(f.toPath(), 
StandardOpenOption.WRITE))
+        {
+            ch.write(generateRandomKey().getKey(), f.length() * 2 / 3);
+        }
+
+        boolean thrown = false;
+        try
+        {
+            testGetEq(data);
+        }
+        catch (Throwable e)
+        {
+            thrown = true;
+        }
+        assertTrue(thrown);
+    }
+
+    @Test
+    public void testLongKeys() throws IOException, InterruptedException
+    {
+        testGetEq(generateLongKeysIndex(COUNT / 10));
+    }
+
+    void testGetEq(Pair<List<DecoratedKey>, PartitionIndex> data)
+    {
+        List<DecoratedKey> keys = data.left;
+        try (PartitionIndex summary = data.right;
+             PartitionIndex.Reader reader = summary.openReader())
+        {
+            for (int i = 0; i < data.left.size(); i++)
+            {
+                assertEquals(i, reader.exactCandidate(keys.get(i)));
+                DecoratedKey key = generateRandomKey();
+                assertEquals(eq(keys, key), eq(keys, key, 
reader.exactCandidate(key)));
+            }
+        }
+    }
+
+    @Test
+    public void testGetGt() throws IOException
+    {
+        testGetGt(generateRandomIndex(COUNT));
+        testGetGt(generateSequentialIndex(COUNT));
+    }
+
+    private void testGetGt(Pair<List<DecoratedKey>, PartitionIndex> data) 
throws IOException
+    {
+        List<DecoratedKey> keys = data.left;
+        try (PartitionIndex summary = data.right;
+             PartitionIndex.Reader reader = summary.openReader())
+        {
+            for (int i = 0; i < data.left.size(); i++)
+            {
+                assertEquals(i < data.left.size() - 1 ? i + 1 : -1, gt(keys, 
keys.get(i), reader));
+                DecoratedKey key = generateRandomKey();
+                assertEquals(gt(keys, key), gt(keys, key, reader));
+            }
+        }
+    }
+
+    @Test
+    public void testGetGe() throws IOException
+    {
+        testGetGe(generateRandomIndex(COUNT));
+        testGetGe(generateSequentialIndex(COUNT));
+    }
+
+    public void testGetGe(Pair<List<DecoratedKey>, PartitionIndex> data) 
throws IOException
+    {
+        List<DecoratedKey> keys = data.left;
+        try (PartitionIndex summary = data.right;
+             PartitionIndex.Reader reader = summary.openReader())
+        {
+            for (int i = 0; i < data.left.size(); i++)
+            {
+                assertEquals(i, ge(keys, keys.get(i), reader));
+                DecoratedKey key = generateRandomKey();
+                assertEquals(ge(keys, key), ge(keys, key, reader));
+            }
+        }
+    }
+
+
+    @Test
+    public void testGetLt() throws IOException
+    {
+        testGetLt(generateRandomIndex(COUNT));
+        testGetLt(generateSequentialIndex(COUNT));
+    }
+
+    public void testGetLt(Pair<List<DecoratedKey>, PartitionIndex> data) 
throws IOException
+    {
+        List<DecoratedKey> keys = data.left;
+        try (PartitionIndex summary = data.right;
+             PartitionIndex.Reader reader = summary.openReader())
+        {
+            for (int i = 0; i < data.left.size(); i++)
+            {
+                assertEquals(i - 1, lt(keys, keys.get(i), reader));
+                DecoratedKey key = generateRandomKey();
+                assertEquals(lt(keys, key), lt(keys, key, reader));
+            }
+        }
+    }
+
+    private long gt(List<DecoratedKey> keys, DecoratedKey key, 
PartitionIndex.Reader summary) throws IOException
+    {
+        return Optional.ofNullable(summary.ceiling(key, (pos, assumeNoMatch, 
sk) -> (assumeNoMatch || keys.get((int) pos).compareTo(sk) > 0) ? pos : 
null)).orElse(-1L);
+    }
+
+    private long ge(List<DecoratedKey> keys, DecoratedKey key, 
PartitionIndex.Reader summary) throws IOException
+    {
+        return Optional.ofNullable(summary.ceiling(key, (pos, assumeNoMatch, 
sk) -> (assumeNoMatch || keys.get((int) pos).compareTo(sk) >= 0) ? pos : 
null)).orElse(-1L);
+    }
+
+
+    private long lt(List<DecoratedKey> keys, DecoratedKey key, 
PartitionIndex.Reader summary) throws IOException
+    {
+        return Optional.ofNullable(summary.floor(key, (pos, assumeNoMatch, sk) 
-> (assumeNoMatch || keys.get((int) pos).compareTo(sk) < 0) ? pos : 
null)).orElse(-1L);
+    }
+
+    private long eq(List<DecoratedKey> keys, DecoratedKey key, long 
exactCandidate)
+    {
+        int idx = (int) exactCandidate;
+        if (exactCandidate == PartitionIndex.NOT_FOUND)
+            return -1;
+        return (keys.get(idx).equals(key)) ? idx : -1;
+    }
+
+    private long gt(List<DecoratedKey> keys, DecoratedKey key)
+    {
+        int index = Collections.binarySearch(keys, key);
+        if (index < 0)
+            index = -1 - index;
+        else
+            ++index;
+        return index < keys.size() ? index : -1;
+    }
+
+    private long lt(List<DecoratedKey> keys, DecoratedKey key)
+    {
+        int index = Collections.binarySearch(keys, key);
+
+        if (index < 0)
+            index = -index - 2;
+
+        return index >= 0 ? index : -1;
+    }
+
+    private long ge(List<DecoratedKey> keys, DecoratedKey key)
+    {
+        int index = Collections.binarySearch(keys, key);
+        if (index < 0)
+            index = -1 - index;
+        return index < keys.size() ? index : -1;
+    }
+
+    private long eq(List<DecoratedKey> keys, DecoratedKey key)
+    {
+        int index = Collections.binarySearch(keys, key);
+        return index >= 0 ? index : -1;
+    }
+
+    @Test
+    public void testAddEmptyKey() throws Exception
+    {
+        IPartitioner p = new RandomPartitioner();
+        File file = FileUtils.createTempFile("ColumnTrieReaderTest", "");
+
+        FileHandle.Builder fhBuilder = makeHandle(file);
+        try (SequentialWriter writer = makeWriter(file);
+             PartitionIndexBuilder builder = new PartitionIndexBuilder(writer, 
fhBuilder)
+        )
+        {
+            DecoratedKey key = p.decorateKey(ByteBufferUtil.EMPTY_BYTE_BUFFER);
+            builder.addEntry(key, 42);
+            builder.complete();
+            try (PartitionIndex summary = loadPartitionIndex(fhBuilder, 
writer);
+                 PartitionIndex.Reader reader = summary.openReader())
+            {
+                assertEquals(1, summary.size());
+                assertEquals(42, reader.getLastIndexPosition());
+                assertEquals(42, reader.exactCandidate(key));
+            }
+        }
+    }
+
+    @Test
+    public void testIteration() throws IOException
+    {
+//        assertEquals(0, ChunkReader.bufferPool.usedMemoryBytes());
+        Pair<List<DecoratedKey>, PartitionIndex> random = 
generateRandomIndex(COUNT);
+        checkIteration(random.left, random.left.size(), random.right);
+        random.right.close();
+//        assertEquals(0, ChunkReader.bufferPool.usedMemoryBytes());
+    }
+
+    @Test
+    public void testZeroCopyOffsets() throws IOException
+    {
+        Pair<List<DecoratedKey>, PartitionIndex> random = 
generateRandomIndexWithZeroCopy(COUNT, 1, COUNT - 2);
+        List<DecoratedKey> keys = random.left;
+        try (PartitionIndex index = random.right)
+        {
+            assertEquals(COUNT - 2, index.size());
+            assertEquals(keys.get(1), index.firstKey());
+            assertEquals(keys.get(COUNT - 2), index.lastKey());
+        }
+    }
+
+    public void checkIteration(List<DecoratedKey> keys, int keysSize, 
PartitionIndex index)

Review Comment:
   nit: `keys` unused



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to