mike-tr-adamson commented on code in PR #2409:
URL: https://github.com/apache/cassandra/pull/2409#discussion_r1246435889


##########
src/java/org/apache/cassandra/index/sai/disk/v1/bbtree/BlockBalancedTreeWriter.java:
##########
@@ -0,0 +1,767 @@
+/*
+ * 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.index.sai.disk.v1.bbtree;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import com.google.common.base.MoreObjects;
+
+import org.apache.cassandra.config.CassandraRelevantProperties;
+import org.apache.cassandra.index.sai.disk.io.RAMIndexOutput;
+import org.apache.cassandra.index.sai.disk.v1.SAICodecUtils;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.store.GrowableByteArrayDataOutput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.FutureArrays;
+import org.apache.lucene.util.IntroSorter;
+import org.apache.lucene.util.Sorter;
+import org.apache.lucene.util.bkd.BKDWriter;
+import org.apache.lucene.util.bkd.MutablePointsReaderUtils;
+
+/**
+ * This is a specialisation of the Lucene {@link BKDWriter} that only writes a 
single dimension
+ * balanced tree.
+ * <p>
+ * Recursively builds a block balanced tree to assign all incoming points to 
smaller
+ * and smaller rectangles (cells) until the number of points in a given
+ * rectangle is &lt;= <code>maxPointsInLeafNode</code>.  The tree is
+ * fully balanced, which means the leaf nodes will have between 50% and 100% of
+ * the requested <code>maxPointsInLeafNode</code>.  Values that fall exactly
+ * on a cell boundary may be in either cell.
+ * <p>
+ * Visual representation of the disk format:
+ * <pre>
+ *
+ * 
+========+=======================================+==================+========+
+ * | HEADER | LEAF BLOCK LIST                       | BALANCED TREE    | 
FOOTER |
+ * 
+========+================+=====+================+==================+========+
+ *          | LEAF BLOCK (0) | ... | LEAF BLOCK (N) | VALUES PER LEAF  |
+ *          +----------------+-----+----------------+------------------|
+ *          | ORDER INDEX    |                      | BYTES PER VALUE  |
+ *          +----------------+                      +------------------+
+ *          | PREFIX         |                      | NUMBER OF LEAVES |
+ *          +----------------+                      +------------------+
+ *          | VALUES         |                      | MINIMUM VALUE    |
+ *          +----------------+                      +------------------+
+ *                                                  | MAXIMUM VALUE    |
+ *                                                  +------------------+
+ *                                                  | TOTAL VALUES     |
+ *                                                  +------------------+
+ *                                                  | INDEX TREE       |
+ *                                                  +--------+---------+
+ *                                                  | LENGTH | BYTES   |
+ *                                                  +--------+---------+
+ *  </pre>
+ *
+ * <p>
+ * <b>NOTE</b>: This can write at most Integer.MAX_VALUE * 
<code>maxPointsInLeafNode</code> total points.
+ * <p>
+ * @see BKDWriter
+ */
+@NotThreadSafe
+public class BlockBalancedTreeWriter
+{
+    // Enable to check that values are added to the tree in correct order and 
within bounds
+    public static final boolean DEBUG = 
CassandraRelevantProperties.SAI_TEST_BALANCED_TREE_DEBUG_ENABLED.getBoolean();
+
+    // Default maximum number of point in each leaf block
+    public static final int DEFAULT_MAX_POINTS_IN_LEAF_NODE = 1024;
+
+    private final int bytesPerValue;
+    private final int maxPointsInLeafNode;
+    private final byte[] minPackedValue;
+    private final byte[] maxPackedValue;
+    private long valueCount;
+    private final long maxRows;
+
+    public BlockBalancedTreeWriter(long maxRows, int bytesPerValue, int 
maxPointsInLeafNode)
+    {
+        if (maxPointsInLeafNode <= 0)
+            throw new IllegalArgumentException("maxPointsInLeafNode must be > 
0; got " + maxPointsInLeafNode);
+        if (maxPointsInLeafNode > ArrayUtil.MAX_ARRAY_LENGTH)
+            throw new IllegalArgumentException("maxPointsInLeafNode must be <= 
ArrayUtil.MAX_ARRAY_LENGTH (= " +
+                                               ArrayUtil.MAX_ARRAY_LENGTH + 
"); got " + maxPointsInLeafNode);
+
+        this.maxPointsInLeafNode = maxPointsInLeafNode;
+        this.bytesPerValue = bytesPerValue;
+        this.maxRows = maxRows;
+
+        minPackedValue = new byte[bytesPerValue];
+        maxPackedValue = new byte[bytesPerValue];
+    }
+
+    public long getValueCount()
+    {
+        return valueCount;
+    }
+
+    public int getBytesPerValue()
+    {
+        return bytesPerValue;
+    }
+
+    public int getMaxPointsInLeafNode()
+    {
+        return maxPointsInLeafNode;
+    }
+
+    /**
+     * Write the point values from a {@link IntersectingPointValues}. The 
points can be reordered before writing
+     * to disk and does not use transient disk for reordering.
+     * <p>
+     *
+     * @param treeOutput The {@link IndexOutput} to write the balanced tree to
+     * @param reader The {@link IntersectingPointValues} containing the values 
and rowIDs to be written
+     * @param callback The {@link Callback} used to record the leaf postings 
for each leaf
+     *
+     * @return The file pointer to the beginning of the balanced tree
+     */
+    public long write(IndexOutput treeOutput, IntersectingPointValues reader,
+                      final Callback callback) throws IOException
+    {
+        SAICodecUtils.writeHeader(treeOutput);
+
+        // We are only ever dealing with one dimension, so we can sort the 
points in ascending order
+        // and write out the values
+        if (reader.needsSorting())
+            MutablePointsReaderUtils.sort(Math.toIntExact(maxRows), 
bytesPerValue, reader, 0, Math.toIntExact(reader.size()));
+
+        LeafWriter leafWriter = new LeafWriter(treeOutput, callback);
+
+        reader.intersect((rowID, packedValue) -> leafWriter.add(packedValue, 
rowID));
+
+        valueCount = leafWriter.finish();
+
+        long treeFilePointer = valueCount == 0 ? -1 : 
treeOutput.getFilePointer();
+
+        // There is only any point in writing the balanced tree if any values 
were added
+        if (treeFilePointer >= 0)
+            writeBalancedTree(treeOutput, maxPointsInLeafNode, 
leafWriter.leafBlockStartValues, leafWriter.leafBlockFilePointers);
+
+        SAICodecUtils.writeFooter(treeOutput);
+
+        return treeFilePointer;
+    }
+
+    private void writeBalancedTree(IndexOutput out, int countPerLeaf, 
List<byte[]> leafBlockStartValues, List<Long> leafBlockFilePointer) throws 
IOException
+    {
+        int numInnerNodes = leafBlockStartValues.size();
+        byte[] splitValues = new byte[(1 + numInnerNodes) * bytesPerValue];
+        int depth = recurseBalanceTree(1, 0, numInnerNodes, 1, splitValues, 
leafBlockStartValues);
+        long[] leafBlockFPs = leafBlockFilePointer.stream().mapToLong(l -> 
l).toArray();
+        byte[] packedIndex = packIndex(leafBlockFPs, splitValues);
+
+        out.writeVInt(countPerLeaf);
+        out.writeVInt(bytesPerValue);
+
+        out.writeVInt(leafBlockFPs.length);
+        out.writeVInt(Math.min(depth, leafBlockFPs.length));
+
+        out.writeBytes(minPackedValue, 0, bytesPerValue);
+        out.writeBytes(maxPackedValue, 0, bytesPerValue);
+
+        out.writeVLong(valueCount);
+
+        out.writeVInt(packedIndex.length);
+        out.writeBytes(packedIndex, 0, packedIndex.length);
+    }
+
+    /**
+     * This can, potentially, be removed in the future by CASSANDRA-18597
+     */
+    private int recurseBalanceTree(int nodeID, int offset, int count, int 
treeDepth, byte[] splitValues, List<byte[]> leafBlockStartValues)
+    {
+        treeDepth++;
+        if (count == 1)
+        {
+            // Leaf index node
+            System.arraycopy(leafBlockStartValues.get(offset), 0, splitValues, 
nodeID * bytesPerValue, bytesPerValue);
+        }
+        else if (count > 1)
+        {
+            // Internal index node: binary partition of count
+            int countAtLevel = 1;
+            int totalCount = 0;
+            while (true)
+            {
+                int countLeft = count - totalCount;
+                if (countLeft <= countAtLevel)
+                {
+                    // This is the last level, possibly partially filled:
+                    int lastLeftCount = Math.min(countAtLevel / 2, countLeft);
+                    assert lastLeftCount >= 0;
+                    int leftHalf = (totalCount - 1) / 2 + lastLeftCount;
+
+                    int rootOffset = offset + leftHalf;
+
+                    System.arraycopy(leafBlockStartValues.get(rootOffset), 0, 
splitValues, nodeID * bytesPerValue, bytesPerValue);
+
+                    // TODO: we could optimize/specialize, when we know it's 
simply fully balanced binary tree
+                    // under here, to save this while loop on each recursion
+
+                    // Recurse left
+                    int leftTreeDepth = recurseBalanceTree(2 * nodeID, offset, 
leftHalf, treeDepth, splitValues, leafBlockStartValues);
+
+                    // Recurse right
+                    int rightTreeDepth = recurseBalanceTree(2 * nodeID + 1, 
rootOffset + 1, count - leftHalf - 1, treeDepth, splitValues, 
leafBlockStartValues);
+                    return Math.max(leftTreeDepth, rightTreeDepth);
+                }
+                totalCount += countAtLevel;
+                countAtLevel *= 2;
+            }
+        }
+        else
+        {
+            assert count == 0;

Review Comment:
   Answering this and below here.
   
   I have refined this calculation to be more accurate and have added testing 
to test that the tree depth is correct. I have moved the increment to only 
increment for tree nodes and leaf nodes. The tree depth starts at one to 
account for the root node.



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