You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@phoenix.apache.org by GitBox <gi...@apache.org> on 2020/06/01 05:13:50 UTC

[GitHub] [phoenix] kadirozde opened a new pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

kadirozde opened a new pull request #794:
URL: https://github.com/apache/phoenix/pull/794


   This PR eliminates data tables in the rebuild write path by letting UngroupedAggregateRegionObserver directly write to index tables without going through IndexRegionObserver.  By doing so, this PR eliminates going through data table update path and its overhead (its interaction with flushes, row locking etc). This PR also applies the index table updates in the index table row key order. It is expected that this will reduce the number of RPC calls compared to the existing implementation which generates index table updates in the data table row key order. Finally, the PR makes index rebuild from a given table region multi-threaded. Thus, this PR improves the rebuild performance and efficiency. 


----------------------------------------------------------------
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] [phoenix] gokceni commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
gokceni commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433413504



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -197,4 +230,17 @@ protected static long getMaxTimestamp(Pair<Put, Delete> pair) {
         }
         return (ts1 > ts2) ? ts1 : ts2;
     }
+
+    protected boolean isColumnIncluded(Cell cell) {

Review comment:
       Perhaps move to a utility class? CellUtil or some other?




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440534372



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -952,111 +890,89 @@ private void parallelizeIndexVerify(IndexToolVerificationResult.PhaseResult veri
             }
             index++;
         }
-        for (IndexToolVerificationResult.PhaseResult result : verificationPhaseResultList) {
-            verificationPhaseResult.add(result);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            Map<byte[], Pair<Put, Delete>> newDataKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
-            for (List<KeyRange> keyRangeList : listOfKeyRangeList) {
-                for (KeyRange keyRange : keyRangeList) {
-                    byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                    newDataKeyToMutationMap.put(dataKey, dataKeyToMutationMap.get(dataKey));
-                }
+    }
+
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            Map<byte[], List<Mutation>> indexKeyToMutationMap, int splitSize) {
+        int splitCount = (indexKeyToMutationMap.size() + splitSize - 1) / splitSize;
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>(splitCount);
+        Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+        mapList.add(perTaskIndexKeyToMutationMap);
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            if (perTaskIndexKeyToMutationMap.size() == splitSize) {
+                perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+                mapList.add(perTaskIndexKeyToMutationMap);
             }
-            dataKeyToMutationMap.clear();
-            dataKeyToMutationMap = newDataKeyToMutationMap;
+            perTaskIndexKeyToMutationMap.put(entry.getKey(), entry.getValue());
         }
+        return mapList;
     }
 
-    private void rebuildIndexRows(UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
-        byte[] uuidValue = ServerCacheClient.generateId();
-        UngroupedAggregateRegionObserver.MutationList currentMutationList =
-                new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        Put put = null;
-        for (Mutation mutation : mutationList) {
-            if (mutation instanceof Put) {
-                if (put != null) {
-                    // back to back put, i.e., no delete in between. we can commit the previous put
-                    uuidValue = commitIfReady(uuidValue, currentMutationList);
-                }
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                put = (Put)mutation;
-            } else {
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                uuidValue = commitIfReady(uuidValue, currentMutationList);
-                put = null;
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            TreeMap<byte[], List<Mutation>> indexKeyToMutationMap, byte[][] endKeys, int maxMapSize) {
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>();
+        int regionCount = endKeys.length;
+        int regionIndex = 0;
+        byte[] indexKey = indexKeyToMutationMap.firstKey();
+        while (regionIndex < regionCount) {
+            Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap;
+            // Find the region including indexKey
+            while (regionIndex < regionCount - 1 && Bytes.compareTo(indexKey, endKeys[regionIndex]) != 1) {
+                regionIndex++;
             }
+            if (regionIndex == regionCount - 1) {
+                perTaskIndexKeyToMutationMap = indexKeyToMutationMap.subMap(indexKey,
+                        true, indexKeyToMutationMap.lastKey(), true);
+            }
+            else {
+                perTaskIndexKeyToMutationMap = indexKeyToMutationMap.subMap(indexKey,
+                        true, endKeys[regionIndex], true);
+            }
+            if (perTaskIndexKeyToMutationMap.size() > maxMapSize) {
+                // Further partition this map
+                mapList.addAll(getPerTaskIndexKeyToMutationMaps(perTaskIndexKeyToMutationMap, maxMapSize));
+            }
+            else {
+                mapList.add(perTaskIndexKeyToMutationMap);
+            }
+            if (regionIndex == regionCount - 1) {
+                break;
+            }
+            indexKey = indexKeyToMutationMap.higherKey(endKeys[regionIndex]);
+            regionIndex++;
         }
-        if (!currentMutationList.isEmpty()) {
-            ungroupedAggregateRegionObserver.checkForRegionClosing();
-            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, currentMutationList, blockingMemstoreSize);
-        }
+        return mapList;
     }
 
-    private void verifyAndOrRebuildIndex() throws IOException {
-        isBeforeRebuilt = true;
-        IndexToolVerificationResult nextVerificationResult = new IndexToolVerificationResult(scan);
-        nextVerificationResult.setScannedDataRowCount(dataKeyToMutationMap.size());
-        if (verifyType == IndexTool.IndexVerifyType.AFTER || verifyType == IndexTool.IndexVerifyType.NONE) {
-            // For these options we start with rebuilding index rows
-            rebuildIndexRows(mutations);
-            nextVerificationResult.setRebuiltIndexRowCount(dataKeyToMutationMap.size());
-            isBeforeRebuilt = false;
-        }
-        if (verifyType == IndexTool.IndexVerifyType.NONE) {
+    private void verifyAndOrRebuildIndex(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                         Set<byte[]> mostRecentIndexRowKeys) throws IOException {
+        if (indexKeyToMutationMap.size() == 0) {
             return;
         }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH ||
-                verifyType == IndexTool.IndexVerifyType.ONLY) {
-            IndexToolVerificationResult.PhaseResult verificationPhaseResult = new IndexToolVerificationResult.PhaseResult();
-            // For these options we start with verifying index rows
-            parallelizeIndexVerify(verificationPhaseResult);
-            nextVerificationResult.getBefore().add(verificationPhaseResult);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            // For these options, we have identified the rows to be rebuilt and now need to rebuild them
-            // At this point, dataKeyToDataPutMap includes mapping only for the rows to be rebuilt
-            mutations.clear();
-
-            for (Map.Entry<byte[], Pair<Put, Delete>> entry: dataKeyToMutationMap.entrySet()) {
-                if (entry.getValue().getFirst() != null) {
-                    mutations.add(entry.getValue().getFirst());
-                }
-                if (entry.getValue().getSecond() != null) {
-                    mutations.add(entry.getValue().getSecond());
-                }
+        if (verifyType != IndexTool.IndexVerifyType.ONLY) {
+            // Since we are building the index table, the region boundaries may change while we are building. Thus,
+            // we should update endKeys
+            try (org.apache.hadoop.hbase.client.Connection connection =

Review comment:
       As I mentioned above, I will fix this, i.e., I  will use one connection per table region.  I will also look into sharing the same connection within a region server or within a cluster. I think there is a way to do this. @abhishek-chouhan, let me know if you know already there is a way to do 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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433663207



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -241,6 +243,16 @@ public void start(CoprocessorEnvironment e) throws IOException {
             e.getConfiguration().getInt(QueryServices.INDEX_REBUILD_RPC_RETRIES_COUNTER,
                 QueryServicesOptions.DEFAULT_INDEX_REBUILD_RPC_RETRIES_COUNTER));
         indexWriteProps = new ReadOnlyProps(indexWriteConfig.iterator());
+        final RegionCoprocessorEnvironment env = (RegionCoprocessorEnvironment) e;
+        String serverName = env.getRegionServerServices().getServerName().getServerName();
+        DelegateRegionCoprocessorEnvironment indexWriterEnv = new
+                DelegateRegionCoprocessorEnvironment(env, ConnectionType.INDEX_WRITER_CONNECTION);
+        // setup the global index writer
+        this.globalIndexRebuildWriter = new IndexWriter(indexWriterEnv, serverName + "-globalIndexRebuildWriter", false);
+    }
+
+    public IndexWriter getGlobalIndexRebuildWriter() {

Review comment:
       We have to already pass the UARO coproc object directly. Are suggesting passing the writer directly too?




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433479066



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -1088,9 +1100,17 @@ private RegionScanner rebuildIndices(final RegionScanner innerScanner, final Reg
             }
             innerScanner.close();
             RegionScanner scanner = region.getScanner(rawScan);
-            return new IndexRebuildRegionScanner(scanner, region, scan, env, this);
+            if (oldCoproc) {
+                return new IndexerRegionScanner(scanner, region, scan, env, this);

Review comment:
       For the old indexing design, the verification other than ONLY is not supported. This was a problem before this PR too. This should be fixed in IndexTool. I will add the fix.




----------------------------------------------------------------
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] [phoenix] gjacoby126 commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
gjacoby126 commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433371850



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;

Review comment:
       This superclass does not appear to use the ungroupedAggregateRegionObserver pointer, so it should belong to appropriate subclasses. (Also, we shouldn't be passing coprocs around -- see comments below.) 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();

Review comment:
       Should this also go in a util class along with the get blocking store size method?

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;
+    protected Map<byte[], NavigableSet<byte[]>> familyMap;
+    protected IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
+    protected boolean verify = false;
 
     public GlobalIndexRegionScanner(RegionScanner innerScanner, final Region region, final Scan scan,
-            final RegionCoprocessorEnvironment env) throws IOException {
+                                    final RegionCoprocessorEnvironment env,
+                                    UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver) throws IOException {
         super(innerScanner);
         final Configuration config = env.getConfiguration();
         if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) != null) {
             pageSizeInRows = config.getLong(INDEX_REBUILD_PAGE_SIZE_IN_ROWS,
                     QueryServicesOptions.DEFAULT_INDEX_REBUILD_PAGE_SIZE_IN_ROWS);
         }
         maxBatchSize = config.getInt(MUTATE_BATCH_SIZE_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE);
+        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
+                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
+        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);

Review comment:
       If this method is needed outside UARO, perhaps it should be in a static Util class somewhere. 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();
+            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, mutationList, blockingMemstoreSize);
+            uuidValue = ServerCacheClient.generateId();
+            mutationList.clear();
+        }
+        return uuidValue;
+    }
+
     @Override
     public boolean next(List<Cell> results) throws IOException {
         Cell lastCell = null;
         int rowCount = 0;
         region.startRegionOperation();
         try {
             synchronized (innerScanner) {
+                byte[] uuidValue = ServerCacheClient.generateId();
                 do {
                     List<Cell> row = new ArrayList<>();
                     hasMore = innerScanner.nextRaw(row);
                     if (!row.isEmpty()) {
-                        lastCell = row.get(0);
+                        lastCell = row.get(0); // lastCell is any cell from the last visited row
                         Put put = null;
+                        Delete del = null;
                         for (Cell cell : row) {
                             if (KeyValue.Type.codeToType(cell.getTypeByte()) == KeyValue.Type.Put) {
+                                if (!partialRebuild && familyMap != null && !isColumnIncluded(cell)) {
+                                    continue;
+                                }
                                 if (put == null) {
                                     put = new Put(CellUtil.cloneRow(cell));
                                 }
                                 put.add(cell);
                             } else {
-                                throw new DoNotRetryIOException("Scan without raw found a deleted cell");
+                                if (del == null) {
+                                    del = new Delete(CellUtil.cloneRow(cell));
+                                }
+                                del.addDeleteMarker(cell);
+                            }
+                        }
+                        if (put == null && del == null) {
+                            continue;
+                        }
+                        if (!verify) {
+                            if (put != null) {
+                                setMutationAttributes(put, uuidValue);
+                                mutations.add(put);
                             }
+                            if (del != null) {
+                                setMutationAttributes(del, uuidValue);
+                                mutations.add(del);
+                            }
+                            uuidValue = commitIfReady(uuidValue, mutations);
+                        } else {
+                            indexKeyToDataPutMap
+                                    .put(getIndexRowKey(indexMaintainer, put), put);
                         }
                         rowCount++;
-                        indexKeyToDataPutMap
-                                .put(getIndexRowKey(indexMaintainer, put), put);
+
                     }
                 } while (hasMore && rowCount < pageSizeInRows);
-                verifyIndex();
+                if (verify) {
+                    verifyIndex();
+                } else if (!mutations.isEmpty()) {
+                    ungroupedAggregateRegionObserver.checkForRegionClosing();

Review comment:
       I'm a bit confused -- I thought IndexerRegionScanner was only used for old-style indexes when doing ONLY-mode index verifications so we got the new correct verify features on the old indexes -- why are we committing things?

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();
+            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, mutationList, blockingMemstoreSize);

Review comment:
       Seems like it would be pretty straightforward to factor out the UARO.commitWith* functions into a dedicated Committer class that takes in a Region in the constructor and can be called from either UARO or here, to avoid the need for passing the UARO itself around. More in keeping with Single Responsibility Principle. 
   
   Over time, we ideally should whittle UARO down to where it's just a dispatcher, catching Scan events and then calling appropriate objects to serve them based on the Scan attribute. That's out of scope here, but we can get a good start. 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/mapreduce/index/IndexVerificationResultRepository.java
##########
@@ -83,7 +83,7 @@
             "BeforeRebuildUnknownIndexRowCount";
     public final static byte[] BEFORE_REBUILD_UNKNOWN_INDEX_ROW_COUNT_BYTES = Bytes.toBytes(BEFORE_REBUILD_UNKNOWN_INDEX_ROW_COUNT);
     public final static String AFTER_REBUILD_VALID_INDEX_ROW_COUNT =
-        "AfterValidExpiredIndexRowCount";
+        "AfterRebuildValidIndexRowCount";

Review comment:
       Oops, thanks for the fix. 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -241,6 +243,16 @@ public void start(CoprocessorEnvironment e) throws IOException {
             e.getConfiguration().getInt(QueryServices.INDEX_REBUILD_RPC_RETRIES_COUNTER,
                 QueryServicesOptions.DEFAULT_INDEX_REBUILD_RPC_RETRIES_COUNTER));
         indexWriteProps = new ReadOnlyProps(indexWriteConfig.iterator());
+        final RegionCoprocessorEnvironment env = (RegionCoprocessorEnvironment) e;
+        String serverName = env.getRegionServerServices().getServerName().getServerName();
+        DelegateRegionCoprocessorEnvironment indexWriterEnv = new
+                DelegateRegionCoprocessorEnvironment(env, ConnectionType.INDEX_WRITER_CONNECTION);
+        // setup the global index writer
+        this.globalIndexRebuildWriter = new IndexWriter(indexWriterEnv, serverName + "-globalIndexRebuildWriter", false);
+    }
+
+    public IndexWriter getGlobalIndexRebuildWriter() {

Review comment:
       if other classes need access to this, better to pass it to them directly rather than pass an UARO and make them call this getter. 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();
+            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, mutationList, blockingMemstoreSize);
+            uuidValue = ServerCacheClient.generateId();
+            mutationList.clear();
+        }
+        return uuidValue;
+    }
+
     @Override
     public boolean next(List<Cell> results) throws IOException {
         Cell lastCell = null;
         int rowCount = 0;
         region.startRegionOperation();
         try {
             synchronized (innerScanner) {
+                byte[] uuidValue = ServerCacheClient.generateId();
                 do {
                     List<Cell> row = new ArrayList<>();
                     hasMore = innerScanner.nextRaw(row);
                     if (!row.isEmpty()) {
-                        lastCell = row.get(0);
+                        lastCell = row.get(0); // lastCell is any cell from the last visited row
                         Put put = null;
+                        Delete del = null;
                         for (Cell cell : row) {
                             if (KeyValue.Type.codeToType(cell.getTypeByte()) == KeyValue.Type.Put) {
+                                if (!partialRebuild && familyMap != null && !isColumnIncluded(cell)) {
+                                    continue;
+                                }
                                 if (put == null) {
                                     put = new Put(CellUtil.cloneRow(cell));
                                 }
                                 put.add(cell);
                             } else {
-                                throw new DoNotRetryIOException("Scan without raw found a deleted cell");
+                                if (del == null) {
+                                    del = new Delete(CellUtil.cloneRow(cell));
+                                }
+                                del.addDeleteMarker(cell);
+                            }
+                        }
+                        if (put == null && del == null) {
+                            continue;
+                        }
+                        if (!verify) {
+                            if (put != null) {
+                                setMutationAttributes(put, uuidValue);
+                                mutations.add(put);
                             }
+                            if (del != null) {
+                                setMutationAttributes(del, uuidValue);
+                                mutations.add(del);
+                            }
+                            uuidValue = commitIfReady(uuidValue, mutations);
+                        } else {
+                            indexKeyToDataPutMap
+                                    .put(getIndexRowKey(indexMaintainer, put), put);
                         }
                         rowCount++;
-                        indexKeyToDataPutMap
-                                .put(getIndexRowKey(indexMaintainer, put), put);
+
                     }
                 } while (hasMore && rowCount < pageSizeInRows);
-                verifyIndex();
+                if (verify) {
+                    verifyIndex();
+                } else if (!mutations.isEmpty()) {
+                    ungroupedAggregateRegionObserver.checkForRegionClosing();

Review comment:
       OK, I see below that we're now using IndexerRegionScanner more broadly. Is this necessary -- just curious if it's worth doing a lot of refactoring and requisite testing on an index framework we know we want to deprecate soon. If it's actually harder to avoid the refactoring while touching UARO and the new indexing classes, that's fine. 




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440527690



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -91,90 +83,51 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Throwables;
 import com.google.common.collect.Maps;
 
 public class IndexRebuildRegionScanner extends GlobalIndexRegionScanner {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(IndexRebuildRegionScanner.class);
 
-    private final long maxBatchSizeBytes;
-    private final long blockingMemstoreSize;
-    private final byte[] clientVersionBytes;
-    private boolean useProto = true;
+    private static boolean ignoreIndexRebuildForTesting  = false;
+    public static void setIgnoreIndexRebuildForTesting(boolean ignore) { ignoreIndexRebuildForTesting = ignore; }
     private byte[] indexRowKey;
-    private IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
     private IndexTool.IndexDisableLoggingType disableLoggingVerifyType = IndexTool.IndexDisableLoggingType.NONE;
-    private boolean verify = false;
-    private Map<byte[], List<Mutation>> indexKeyToMutationMap;
-    private Map<byte[], Pair<Put, Delete>> dataKeyToMutationMap;
-    private UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;
-    protected UngroupedAggregateRegionObserver.MutationList mutations;
-    private boolean isBeforeRebuilt = true;
-    private boolean partialRebuild = false;
     private int singleRowRebuildReturnCode;
-    private Map<byte[], NavigableSet<byte[]>> familyMap;
     private byte[][] viewConstants;
-    private IndexVerificationOutputRepository verificationOutputRepository;
+    private IndexVerificationOutputRepository verificationOutputRepository = null;
     private boolean skipped = false;
     private boolean shouldVerifyCheckDone = false;
-
+    final private RegionCoprocessorEnvironment env;
+    byte[][] endKeys;
     @VisibleForTesting
     public IndexRebuildRegionScanner(final RegionScanner innerScanner, final Region region, final Scan scan,
-                              final RegionCoprocessorEnvironment env,
-                              UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver) throws IOException {
+                              final RegionCoprocessorEnvironment env) throws IOException {
         super(innerScanner, region, scan, env);
-        final Configuration config = env.getConfiguration();
-        if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) == null) {
-            partialRebuild = true;
-        }
-        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
-                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
-        mutations = new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);
-        clientVersionBytes = scan.getAttribute(BaseScannerRegionObserver.CLIENT_VERSION);
-        indexMetaData = scan.getAttribute(PhoenixIndexCodec.INDEX_PROTO_MD);
-        if (indexMetaData == null) {
-            useProto = false;
-        }
-        familyMap = scan.getFamilyMap();
-        if (familyMap.isEmpty()) {
-            familyMap = null;
-        }
-        this.ungroupedAggregateRegionObserver = ungroupedAggregateRegionObserver;
+        this.env = env;
+        try (org.apache.hadoop.hbase.client.Connection connection =
+                     HBaseFactoryProvider.getHConnectionFactory().createConnection(env.getConfiguration())) {
+            endKeys = connection.getRegionLocator(indexHTable.getName()).getEndKeys();

Review comment:
       For ONLY verifications, we do this once a table region so it should not be a concern. For the other types of index tool runs, we do this per page per table region as we rebuild index tables. The default size of the page is 32K index rows. So for every 32K index rows, we do this. Assuming creating a connection is expensive as you pointed out, I will use one connection for the table region instead of creating one for every page.




----------------------------------------------------------------
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] [phoenix] swaroopak commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
swaroopak commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433394479



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -1088,9 +1100,17 @@ private RegionScanner rebuildIndices(final RegionScanner innerScanner, final Reg
             }
             innerScanner.close();
             RegionScanner scanner = region.getScanner(rawScan);
-            return new IndexRebuildRegionScanner(scanner, region, scan, env, this);
+            if (oldCoproc) {
+                return new IndexerRegionScanner(scanner, region, scan, env, this);

Review comment:
       Also, what happens to the specific check for ONLY?




----------------------------------------------------------------
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] [phoenix] gjacoby126 commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
gjacoby126 commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440499149



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -91,90 +83,51 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Throwables;
 import com.google.common.collect.Maps;
 
 public class IndexRebuildRegionScanner extends GlobalIndexRegionScanner {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(IndexRebuildRegionScanner.class);
 
-    private final long maxBatchSizeBytes;
-    private final long blockingMemstoreSize;
-    private final byte[] clientVersionBytes;
-    private boolean useProto = true;
+    private static boolean ignoreIndexRebuildForTesting  = false;
+    public static void setIgnoreIndexRebuildForTesting(boolean ignore) { ignoreIndexRebuildForTesting = ignore; }
     private byte[] indexRowKey;
-    private IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
     private IndexTool.IndexDisableLoggingType disableLoggingVerifyType = IndexTool.IndexDisableLoggingType.NONE;
-    private boolean verify = false;
-    private Map<byte[], List<Mutation>> indexKeyToMutationMap;
-    private Map<byte[], Pair<Put, Delete>> dataKeyToMutationMap;
-    private UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;
-    protected UngroupedAggregateRegionObserver.MutationList mutations;
-    private boolean isBeforeRebuilt = true;
-    private boolean partialRebuild = false;
     private int singleRowRebuildReturnCode;
-    private Map<byte[], NavigableSet<byte[]>> familyMap;
     private byte[][] viewConstants;
-    private IndexVerificationOutputRepository verificationOutputRepository;
+    private IndexVerificationOutputRepository verificationOutputRepository = null;
     private boolean skipped = false;
     private boolean shouldVerifyCheckDone = false;
-
+    final private RegionCoprocessorEnvironment env;
+    byte[][] endKeys;
     @VisibleForTesting
     public IndexRebuildRegionScanner(final RegionScanner innerScanner, final Region region, final Scan scan,
-                              final RegionCoprocessorEnvironment env,
-                              UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver) throws IOException {
+                              final RegionCoprocessorEnvironment env) throws IOException {
         super(innerScanner, region, scan, env);
-        final Configuration config = env.getConfiguration();
-        if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) == null) {
-            partialRebuild = true;
-        }
-        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
-                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
-        mutations = new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);
-        clientVersionBytes = scan.getAttribute(BaseScannerRegionObserver.CLIENT_VERSION);
-        indexMetaData = scan.getAttribute(PhoenixIndexCodec.INDEX_PROTO_MD);
-        if (indexMetaData == null) {
-            useProto = false;
-        }
-        familyMap = scan.getFamilyMap();
-        if (familyMap.isEmpty()) {
-            familyMap = null;
-        }
-        this.ungroupedAggregateRegionObserver = ungroupedAggregateRegionObserver;
+        this.env = env;
+        try (org.apache.hadoop.hbase.client.Connection connection =
+                     HBaseFactoryProvider.getHConnectionFactory().createConnection(env.getConfiguration())) {
+            endKeys = connection.getRegionLocator(indexHTable.getName()).getEndKeys();

Review comment:
       (I've been assuming that we'd get a different region rebuild scanner per mapper task (and hence usually per region), but parts of the logic elsewhere seem like they're trying to do the whole table. Is that just to account for splits? 




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433658492



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();

Review comment:
       This is only used currently by the old index design. I would not want to invest on it. Also, because of ungroupedAggregateRegionObserver.checkForRegionClosing(), it cannot go into a util call.




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440352734



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -68,30 +75,44 @@
     protected int rowCountPerTask;
     protected boolean hasMore;
     protected int maxBatchSize;
+    protected final long maxBatchSizeBytes;
+    protected final long blockingMemstoreSize;
+    protected final byte[] clientVersionBytes;
+    protected boolean useProto = true;
     protected byte[] indexMetaData;
     protected Scan scan;
     protected RegionScanner innerScanner;
     protected Region region;
     protected IndexMaintainer indexMaintainer;
     protected Table indexHTable;
     protected TaskRunner pool;
-    protected TaskBatch<Boolean> tasks;
     protected String exceptionMessage;
     protected HTableFactory hTableFactory;
     protected int indexTableTTL;
     protected long maxLookBackInMills;
-    protected IndexToolVerificationResult verificationResult;
-    protected IndexVerificationResultRepository verificationResultRepository;
+    protected IndexToolVerificationResult verificationResult = null;
+    protected IndexVerificationResultRepository verificationResultRepository = null;
+    protected Map<byte[], NavigableSet<byte[]>> familyMap;
+    protected IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
+    protected boolean verify = false;
 
     public GlobalIndexRegionScanner(RegionScanner innerScanner, final Region region, final Scan scan,
-            final RegionCoprocessorEnvironment env) throws IOException {
+                                    final RegionCoprocessorEnvironment env) throws IOException {
         super(innerScanner);
         final Configuration config = env.getConfiguration();
         if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) != null) {
             pageSizeInRows = config.getLong(INDEX_REBUILD_PAGE_SIZE_IN_ROWS,
                     QueryServicesOptions.DEFAULT_INDEX_REBUILD_PAGE_SIZE_IN_ROWS);
         }
         maxBatchSize = config.getInt(MUTATE_BATCH_SIZE_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE);
+        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
+                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
+        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);
+        clientVersionBytes = scan.getAttribute(BaseScannerRegionObserver.CLIENT_VERSION);
+        familyMap = scan.getFamilyMap();
+        if (familyMap.isEmpty()) {
+            familyMap = null;

Review comment:
       It is just a little optimization for run-time checking by mapping the empty map case to the null map case so we do not check both. This check is done for every cell scanned. This code is not introduced in this PR is just moved to 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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433662176



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();
+            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, mutationList, blockingMemstoreSize);
+            uuidValue = ServerCacheClient.generateId();
+            mutationList.clear();
+        }
+        return uuidValue;
+    }
+
     @Override
     public boolean next(List<Cell> results) throws IOException {
         Cell lastCell = null;
         int rowCount = 0;
         region.startRegionOperation();
         try {
             synchronized (innerScanner) {
+                byte[] uuidValue = ServerCacheClient.generateId();
                 do {
                     List<Cell> row = new ArrayList<>();
                     hasMore = innerScanner.nextRaw(row);
                     if (!row.isEmpty()) {
-                        lastCell = row.get(0);
+                        lastCell = row.get(0); // lastCell is any cell from the last visited row
                         Put put = null;
+                        Delete del = null;
                         for (Cell cell : row) {
                             if (KeyValue.Type.codeToType(cell.getTypeByte()) == KeyValue.Type.Put) {
+                                if (!partialRebuild && familyMap != null && !isColumnIncluded(cell)) {
+                                    continue;
+                                }
                                 if (put == null) {
                                     put = new Put(CellUtil.cloneRow(cell));
                                 }
                                 put.add(cell);
                             } else {
-                                throw new DoNotRetryIOException("Scan without raw found a deleted cell");
+                                if (del == null) {
+                                    del = new Delete(CellUtil.cloneRow(cell));
+                                }
+                                del.addDeleteMarker(cell);
+                            }
+                        }
+                        if (put == null && del == null) {
+                            continue;
+                        }
+                        if (!verify) {
+                            if (put != null) {
+                                setMutationAttributes(put, uuidValue);
+                                mutations.add(put);
                             }
+                            if (del != null) {
+                                setMutationAttributes(del, uuidValue);
+                                mutations.add(del);
+                            }
+                            uuidValue = commitIfReady(uuidValue, mutations);
+                        } else {
+                            indexKeyToDataPutMap
+                                    .put(getIndexRowKey(indexMaintainer, put), put);
                         }
                         rowCount++;
-                        indexKeyToDataPutMap
-                                .put(getIndexRowKey(indexMaintainer, put), put);
+
                     }
                 } while (hasMore && rowCount < pageSizeInRows);
-                verifyIndex();
+                if (verify) {
+                    verifyIndex();
+                } else if (!mutations.isEmpty()) {
+                    ungroupedAggregateRegionObserver.checkForRegionClosing();

Review comment:
       This PR moved the rebuild path from IndexRegionObserver into UARO, more specifically IndexRebuildRegionObserver. This means that we cannot use IndexRebuildRegionObserver for building old indexes anymore. So I needed to move the responsibility of building old indexes to IndexerRegionObserver in order to continue using the index rebuild code in Indexer for old indexes.




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r437015814



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -197,4 +230,17 @@ protected static long getMaxTimestamp(Pair<Put, Delete> pair) {
         }
         return (ts1 > ts2) ? ts1 : ts2;
     }
+
+    protected boolean isColumnIncluded(Cell cell) {

Review comment:
       I agree with you on this. There are several other such methods that should be moved to utility classes. I suggest opening a Jira for this and doing it there as I want to control the size of the changes here. It is already getting large

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;

Review comment:
       You are right that it is not used anymore here in this abstract class but both the classes that expand this class access this attribute. So it is a common attribute.




----------------------------------------------------------------
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] [phoenix] gjacoby126 commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
gjacoby126 commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r437041844



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;

Review comment:
       Could you please point out where? I just expanded the file and I don't see 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] [phoenix] swaroopak commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
swaroopak commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433393583



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -1088,9 +1100,17 @@ private RegionScanner rebuildIndices(final RegionScanner innerScanner, final Reg
             }
             innerScanner.close();
             RegionScanner scanner = region.getScanner(rawScan);
-            return new IndexRebuildRegionScanner(scanner, region, scan, env, this);
+            if (oldCoproc) {
+                return new IndexerRegionScanner(scanner, region, scan, env, this);

Review comment:
       For old coproc, we wanted to do only one version verification. Moving this inside not-raw block, wouldn't it change the strategy? 




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440534782



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -952,111 +890,89 @@ private void parallelizeIndexVerify(IndexToolVerificationResult.PhaseResult veri
             }
             index++;
         }
-        for (IndexToolVerificationResult.PhaseResult result : verificationPhaseResultList) {
-            verificationPhaseResult.add(result);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            Map<byte[], Pair<Put, Delete>> newDataKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
-            for (List<KeyRange> keyRangeList : listOfKeyRangeList) {
-                for (KeyRange keyRange : keyRangeList) {
-                    byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                    newDataKeyToMutationMap.put(dataKey, dataKeyToMutationMap.get(dataKey));
-                }
+    }
+
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            Map<byte[], List<Mutation>> indexKeyToMutationMap, int splitSize) {
+        int splitCount = (indexKeyToMutationMap.size() + splitSize - 1) / splitSize;
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>(splitCount);
+        Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+        mapList.add(perTaskIndexKeyToMutationMap);
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            if (perTaskIndexKeyToMutationMap.size() == splitSize) {
+                perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+                mapList.add(perTaskIndexKeyToMutationMap);
             }
-            dataKeyToMutationMap.clear();
-            dataKeyToMutationMap = newDataKeyToMutationMap;
+            perTaskIndexKeyToMutationMap.put(entry.getKey(), entry.getValue());
         }
+        return mapList;
     }
 
-    private void rebuildIndexRows(UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
-        byte[] uuidValue = ServerCacheClient.generateId();
-        UngroupedAggregateRegionObserver.MutationList currentMutationList =
-                new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        Put put = null;
-        for (Mutation mutation : mutationList) {
-            if (mutation instanceof Put) {
-                if (put != null) {
-                    // back to back put, i.e., no delete in between. we can commit the previous put
-                    uuidValue = commitIfReady(uuidValue, currentMutationList);
-                }
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                put = (Put)mutation;
-            } else {
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                uuidValue = commitIfReady(uuidValue, currentMutationList);
-                put = null;
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            TreeMap<byte[], List<Mutation>> indexKeyToMutationMap, byte[][] endKeys, int maxMapSize) {
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>();
+        int regionCount = endKeys.length;
+        int regionIndex = 0;
+        byte[] indexKey = indexKeyToMutationMap.firstKey();
+        while (regionIndex < regionCount) {
+            Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap;
+            // Find the region including indexKey
+            while (regionIndex < regionCount - 1 && Bytes.compareTo(indexKey, endKeys[regionIndex]) != 1) {

Review comment:
       As I described before, we get the end keys at the beginning of a page (every 32K index row verification/rebuild).  Our scans misses small number of rows when they operate on multiple table regions occasionally. Let me see if I can improve this further
   




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433693943



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;

Review comment:
       It is used below.




----------------------------------------------------------------
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] [phoenix] kadirozde closed pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde closed pull request #794:
URL: https://github.com/apache/phoenix/pull/794


   


----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433663207



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -241,6 +243,16 @@ public void start(CoprocessorEnvironment e) throws IOException {
             e.getConfiguration().getInt(QueryServices.INDEX_REBUILD_RPC_RETRIES_COUNTER,
                 QueryServicesOptions.DEFAULT_INDEX_REBUILD_RPC_RETRIES_COUNTER));
         indexWriteProps = new ReadOnlyProps(indexWriteConfig.iterator());
+        final RegionCoprocessorEnvironment env = (RegionCoprocessorEnvironment) e;
+        String serverName = env.getRegionServerServices().getServerName().getServerName();
+        DelegateRegionCoprocessorEnvironment indexWriterEnv = new
+                DelegateRegionCoprocessorEnvironment(env, ConnectionType.INDEX_WRITER_CONNECTION);
+        // setup the global index writer
+        this.globalIndexRebuildWriter = new IndexWriter(indexWriterEnv, serverName + "-globalIndexRebuildWriter", false);
+    }
+
+    public IndexWriter getGlobalIndexRebuildWriter() {

Review comment:
       We have to already pass the UARO coproc object directly. Are you suggesting passing the writer directly too?




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433693943



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;

Review comment:
       It is using 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] [phoenix] swaroopak commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
swaroopak commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433499825



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
##########
@@ -1088,9 +1100,17 @@ private RegionScanner rebuildIndices(final RegionScanner innerScanner, final Reg
             }
             innerScanner.close();
             RegionScanner scanner = region.getScanner(rawScan);
-            return new IndexRebuildRegionScanner(scanner, region, scan, env, this);
+            if (oldCoproc) {
+                return new IndexerRegionScanner(scanner, region, scan, env, this);

Review comment:
       Okay, thanks! I think I misread the change at line 1088. 




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433472807



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;
+    protected Map<byte[], NavigableSet<byte[]>> familyMap;
+    protected IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
+    protected boolean verify = false;
 
     public GlobalIndexRegionScanner(RegionScanner innerScanner, final Region region, final Scan scan,
-            final RegionCoprocessorEnvironment env) throws IOException {
+                                    final RegionCoprocessorEnvironment env,
+                                    UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver) throws IOException {
         super(innerScanner);
         final Configuration config = env.getConfiguration();
         if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) != null) {
             pageSizeInRows = config.getLong(INDEX_REBUILD_PAGE_SIZE_IN_ROWS,
                     QueryServicesOptions.DEFAULT_INDEX_REBUILD_PAGE_SIZE_IN_ROWS);
         }
         maxBatchSize = config.getInt(MUTATE_BATCH_SIZE_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE);
+        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
+                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
+        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);

Review comment:
       Not currently




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r433663826



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
##########
@@ -305,42 +320,96 @@ private void verifyIndex() throws IOException {
         verificationResult.add(nextVerificationResult);
     }
 
+    private void setMutationAttributes(Mutation m, byte[] uuidValue) {
+        m.setAttribute(useProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMetaData);
+        m.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
+        m.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES,
+                BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES);
+        m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes);
+        // Since we're replaying existing mutations, it makes no sense to write them to the wal
+        m.setDurability(Durability.SKIP_WAL);
+    }
+
+    private byte[] commitIfReady(byte[] uuidValue, UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
+        if (ServerUtil.readyToCommit(mutationList.size(), mutationList.byteSize(), maxBatchSize, maxBatchSizeBytes)) {
+            ungroupedAggregateRegionObserver.checkForRegionClosing();
+            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, mutationList, blockingMemstoreSize);

Review comment:
       Please see my related comments.




----------------------------------------------------------------
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] [phoenix] gjacoby126 commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
gjacoby126 commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440447653



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -197,4 +230,17 @@ protected static long getMaxTimestamp(Pair<Put, Delete> pair) {
         }
         return (ts1 > ts2) ? ts1 : ts2;
     }
+
+    protected boolean isColumnIncluded(Cell cell) {

Review comment:
       Agree this should probably move to a util class. That won't increase the size of the patch too much

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -836,74 +747,122 @@ private void verifyIndexRows(List<KeyRange> keys,
         indexScan.setCacheBlocks(false);
         try (ResultScanner resultScanner = indexHTable.getScanner(indexScan)) {
             for (Result result = resultScanner.next(); (result != null); result = resultScanner.next()) {
-                KeyRange keyRange = PVarbinary.INSTANCE.getKeyRange(result.getRow());
-                if (!keys.contains(keyRange)) {
-                    continue;
+                if (!verifySingleIndexRow(result, indexKeyToMutationMap, mostRecentIndexRowKeys,
+                        verificationPhaseResult, isBeforeRebuild)) {
+                    invalidIndexRows.put(result.getRow(), indexKeyToMutationMap.get(result.getRow()));
                 }
-                if (!verifySingleIndexRow(result, verificationPhaseResult)) {
-                    invalidKeys.add(keyRange);
-                }
-                keys.remove(keyRange);
+                indexKeyToMutationMap.remove(result.getRow());
             }
         } catch (Throwable t) {
             ServerUtil.throwIOException(indexHTable.getName().toString(), t);
         }
+        List<byte[]> expiredIndexRows = new ArrayList<>();
         // Check if any expected rows from index(which we didn't get) are already expired due to TTL
         // TODO: metrics for expired rows
-        if (!keys.isEmpty()) {
-            Iterator<KeyRange> itr = keys.iterator();
-            long currentTime = EnvironmentEdgeManager.currentTimeMillis();
-            while(itr.hasNext()) {
-                KeyRange keyRange = itr.next();
-                byte[] key = keyRange.getLowerRange();
-                List<Mutation> mutationList = indexKeyToMutationMap.get(key);
-                if (isTimestampBeforeTTL(indexTableTTL, currentTime, getTimestamp(mutationList.get(mutationList.size() - 1)))) {
-                    itr.remove();
-                    verificationPhaseResult.setExpiredIndexRowCount(verificationPhaseResult.getExpiredIndexRowCount() + 1);
-                }
+        long currentTime = EnvironmentEdgeManager.currentTimeMillis();
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            List<Mutation> mutationList = entry.getValue();
+            if (isTimestampBeforeTTL(indexTableTTL, currentTime, getTimestamp(mutationList.get(mutationList.size() - 1)))) {
+                verificationPhaseResult.setExpiredIndexRowCount(verificationPhaseResult.getExpiredIndexRowCount() + 1);
+                expiredIndexRows.add(entry.getKey());
             }
         }
-        if (keys.size() > 0) {
-            for (KeyRange keyRange : keys) {
-                byte[] key = keyRange.getLowerRange();
-                List<Mutation> mutationList = indexKeyToMutationMap.get(key);
-                Mutation mutation = mutationList.get(mutationList.size() - 1);
-                if (mutation instanceof Delete) {
-                    continue;
-                }
-                long currentTime = EnvironmentEdgeManager.currentTimeMillis();
-                String errorMsg;
-                if (isTimestampBeyondMaxLookBack(maxLookBackInMills, currentTime, getTimestamp(mutation))){
-                    errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW_BEYOND_MAX_LOOKBACK;
-                    verificationPhaseResult.
-                            setBeyondMaxLookBackMissingIndexRowCount(verificationPhaseResult.getBeyondMaxLookBackMissingIndexRowCount() + 1);
-                }
-                else {
-                    errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW;
-                    verificationPhaseResult.setMissingIndexRowCount(verificationPhaseResult.getMissingIndexRowCount() + 1);
+        // Remove the expired rows from indexKeyToMutationMap
+        for (byte[] indexKey : expiredIndexRows) {
+            indexKeyToMutationMap.remove(indexKey);
+        }
+        // Count and log missing rows
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            byte[] indexKey = entry.getKey();
+            List<Mutation> mutationList = entry.getValue();
+            Mutation mutation = mutationList.get(mutationList.size() - 1);
+            if (mutation instanceof Delete) {
+                continue;
+            }
+            currentTime = EnvironmentEdgeManager.currentTimeMillis();
+            String errorMsg;
+            if (isTimestampBeyondMaxLookBack(maxLookBackInMills, currentTime, getTimestamp(mutation))){
+                errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW_BEYOND_MAX_LOOKBACK;
+                verificationPhaseResult.
+                        setBeyondMaxLookBackMissingIndexRowCount(verificationPhaseResult.getBeyondMaxLookBackMissingIndexRowCount() + 1);
+            }
+            else {
+                errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW;
+                verificationPhaseResult.setMissingIndexRowCount(verificationPhaseResult.getMissingIndexRowCount() + 1);
+            }
+            byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(indexKey), viewConstants);
+            logToIndexToolOutputTable(dataKey, indexKey, getTimestamp(mutation), 0, errorMsg, isBeforeRebuild);
+        }
+        // Leave the invalid and missing rows in indexKeyToMutationMap
+        indexKeyToMutationMap.putAll(invalidIndexRows);
+    }
+
+    private void rebuildIndexRows(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                  IndexToolVerificationResult verificationResult) throws IOException {
+        if (ignoreIndexRebuildForTesting) {
+            return;
+        }
+        try {
+            int batchSize = 0;
+            List<Mutation> indexUpdates = new ArrayList<Mutation>(maxBatchSize);
+            for (List<Mutation> mutationList : indexKeyToMutationMap.values()) {
+                indexUpdates.addAll(mutationList);
+                batchSize += mutationList.size();
+                if (batchSize >= maxBatchSize) {
+                    indexHTable.batch(indexUpdates);
+                    batchSize = 0;
+                    indexUpdates = new ArrayList<Mutation>(maxBatchSize);
                 }
-                byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                logToIndexToolOutputTable(dataKey,
-                        keyRange.getLowerRange(),
-                        getMaxTimestamp(dataKeyToMutationMap.get(dataKey)),
-                        getTimestamp(mutation), errorMsg);
             }
+            if (batchSize > 0) {
+                indexHTable.batch(indexUpdates);
+            }
+            if (verify) {
+                verificationResult.setRebuiltIndexRowCount(verificationResult.getRebuiltIndexRowCount() + indexKeyToMutationMap.size());
+            }
+        } catch (Throwable t) {
+            ServerUtil.throwIOException(indexHTable.getName().toString(), t);
         }
+    }
 
-        keys.addAll(invalidKeys);
+    private void rebuildAndOrVerifyIndexRows(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                             Set<byte[]> mostRecentIndexRowKeys,
+                                             IndexToolVerificationResult verificationResult) throws IOException {
+        if (verifyType == IndexTool.IndexVerifyType.NONE) {
+            rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+        } else if (verifyType == IndexTool.IndexVerifyType.ONLY) {

Review comment:
       very nice, clear simplification of the verify type logic

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -952,111 +890,89 @@ private void parallelizeIndexVerify(IndexToolVerificationResult.PhaseResult veri
             }
             index++;
         }
-        for (IndexToolVerificationResult.PhaseResult result : verificationPhaseResultList) {
-            verificationPhaseResult.add(result);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            Map<byte[], Pair<Put, Delete>> newDataKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
-            for (List<KeyRange> keyRangeList : listOfKeyRangeList) {
-                for (KeyRange keyRange : keyRangeList) {
-                    byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                    newDataKeyToMutationMap.put(dataKey, dataKeyToMutationMap.get(dataKey));
-                }
+    }
+
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            Map<byte[], List<Mutation>> indexKeyToMutationMap, int splitSize) {
+        int splitCount = (indexKeyToMutationMap.size() + splitSize - 1) / splitSize;
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>(splitCount);
+        Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+        mapList.add(perTaskIndexKeyToMutationMap);
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            if (perTaskIndexKeyToMutationMap.size() == splitSize) {
+                perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+                mapList.add(perTaskIndexKeyToMutationMap);
             }
-            dataKeyToMutationMap.clear();
-            dataKeyToMutationMap = newDataKeyToMutationMap;
+            perTaskIndexKeyToMutationMap.put(entry.getKey(), entry.getValue());
         }
+        return mapList;
     }
 
-    private void rebuildIndexRows(UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
-        byte[] uuidValue = ServerCacheClient.generateId();
-        UngroupedAggregateRegionObserver.MutationList currentMutationList =
-                new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        Put put = null;
-        for (Mutation mutation : mutationList) {
-            if (mutation instanceof Put) {
-                if (put != null) {
-                    // back to back put, i.e., no delete in between. we can commit the previous put
-                    uuidValue = commitIfReady(uuidValue, currentMutationList);
-                }
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                put = (Put)mutation;
-            } else {
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                uuidValue = commitIfReady(uuidValue, currentMutationList);
-                put = null;
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            TreeMap<byte[], List<Mutation>> indexKeyToMutationMap, byte[][] endKeys, int maxMapSize) {
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>();
+        int regionCount = endKeys.length;
+        int regionIndex = 0;
+        byte[] indexKey = indexKeyToMutationMap.firstKey();
+        while (regionIndex < regionCount) {
+            Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap;
+            // Find the region including indexKey
+            while (regionIndex < regionCount - 1 && Bytes.compareTo(indexKey, endKeys[regionIndex]) != 1) {

Review comment:
       What happens if regions splits (or if regions merge) between us grabbing endKeys and farming out the work? Still OK because we're using Table.batch in the end? 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -91,90 +83,51 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Throwables;
 import com.google.common.collect.Maps;
 
 public class IndexRebuildRegionScanner extends GlobalIndexRegionScanner {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(IndexRebuildRegionScanner.class);
 
-    private final long maxBatchSizeBytes;
-    private final long blockingMemstoreSize;
-    private final byte[] clientVersionBytes;
-    private boolean useProto = true;
+    private static boolean ignoreIndexRebuildForTesting  = false;
+    public static void setIgnoreIndexRebuildForTesting(boolean ignore) { ignoreIndexRebuildForTesting = ignore; }
     private byte[] indexRowKey;
-    private IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
     private IndexTool.IndexDisableLoggingType disableLoggingVerifyType = IndexTool.IndexDisableLoggingType.NONE;
-    private boolean verify = false;
-    private Map<byte[], List<Mutation>> indexKeyToMutationMap;
-    private Map<byte[], Pair<Put, Delete>> dataKeyToMutationMap;
-    private UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;
-    protected UngroupedAggregateRegionObserver.MutationList mutations;
-    private boolean isBeforeRebuilt = true;
-    private boolean partialRebuild = false;
     private int singleRowRebuildReturnCode;
-    private Map<byte[], NavigableSet<byte[]>> familyMap;
     private byte[][] viewConstants;
-    private IndexVerificationOutputRepository verificationOutputRepository;
+    private IndexVerificationOutputRepository verificationOutputRepository = null;
     private boolean skipped = false;
     private boolean shouldVerifyCheckDone = false;
-
+    final private RegionCoprocessorEnvironment env;
+    byte[][] endKeys;
     @VisibleForTesting
     public IndexRebuildRegionScanner(final RegionScanner innerScanner, final Region region, final Scan scan,
-                              final RegionCoprocessorEnvironment env,
-                              UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver) throws IOException {
+                              final RegionCoprocessorEnvironment env) throws IOException {
         super(innerScanner, region, scan, env);
-        final Configuration config = env.getConfiguration();
-        if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) == null) {
-            partialRebuild = true;
-        }
-        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
-                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
-        mutations = new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);
-        clientVersionBytes = scan.getAttribute(BaseScannerRegionObserver.CLIENT_VERSION);
-        indexMetaData = scan.getAttribute(PhoenixIndexCodec.INDEX_PROTO_MD);
-        if (indexMetaData == null) {
-            useProto = false;
-        }
-        familyMap = scan.getFamilyMap();
-        if (familyMap.isEmpty()) {
-            familyMap = null;
-        }
-        this.ungroupedAggregateRegionObserver = ungroupedAggregateRegionObserver;
+        this.env = env;
+        try (org.apache.hadoop.hbase.client.Connection connection =
+                     HBaseFactoryProvider.getHConnectionFactory().createConnection(env.getConfiguration())) {
+            endKeys = connection.getRegionLocator(indexHTable.getName()).getEndKeys();

Review comment:
       Could this add too much pressure on meta on a large table with many regions? (Creating connections are a bit heavyweight, and doesn't populating the region locator require reading from meta?)
   
   Since the keys are going to be the same across all regions of a single table, is there a way to share between regions of the same data table on the same RS, since all regions of a data table share the same indexes?

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -836,74 +747,122 @@ private void verifyIndexRows(List<KeyRange> keys,
         indexScan.setCacheBlocks(false);
         try (ResultScanner resultScanner = indexHTable.getScanner(indexScan)) {
             for (Result result = resultScanner.next(); (result != null); result = resultScanner.next()) {
-                KeyRange keyRange = PVarbinary.INSTANCE.getKeyRange(result.getRow());
-                if (!keys.contains(keyRange)) {
-                    continue;
+                if (!verifySingleIndexRow(result, indexKeyToMutationMap, mostRecentIndexRowKeys,
+                        verificationPhaseResult, isBeforeRebuild)) {
+                    invalidIndexRows.put(result.getRow(), indexKeyToMutationMap.get(result.getRow()));
                 }
-                if (!verifySingleIndexRow(result, verificationPhaseResult)) {
-                    invalidKeys.add(keyRange);
-                }
-                keys.remove(keyRange);
+                indexKeyToMutationMap.remove(result.getRow());
             }
         } catch (Throwable t) {
             ServerUtil.throwIOException(indexHTable.getName().toString(), t);
         }
+        List<byte[]> expiredIndexRows = new ArrayList<>();
         // Check if any expected rows from index(which we didn't get) are already expired due to TTL
         // TODO: metrics for expired rows
-        if (!keys.isEmpty()) {
-            Iterator<KeyRange> itr = keys.iterator();
-            long currentTime = EnvironmentEdgeManager.currentTimeMillis();
-            while(itr.hasNext()) {
-                KeyRange keyRange = itr.next();
-                byte[] key = keyRange.getLowerRange();
-                List<Mutation> mutationList = indexKeyToMutationMap.get(key);
-                if (isTimestampBeforeTTL(indexTableTTL, currentTime, getTimestamp(mutationList.get(mutationList.size() - 1)))) {
-                    itr.remove();
-                    verificationPhaseResult.setExpiredIndexRowCount(verificationPhaseResult.getExpiredIndexRowCount() + 1);
-                }
+        long currentTime = EnvironmentEdgeManager.currentTimeMillis();
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            List<Mutation> mutationList = entry.getValue();
+            if (isTimestampBeforeTTL(indexTableTTL, currentTime, getTimestamp(mutationList.get(mutationList.size() - 1)))) {
+                verificationPhaseResult.setExpiredIndexRowCount(verificationPhaseResult.getExpiredIndexRowCount() + 1);
+                expiredIndexRows.add(entry.getKey());
             }
         }
-        if (keys.size() > 0) {
-            for (KeyRange keyRange : keys) {
-                byte[] key = keyRange.getLowerRange();
-                List<Mutation> mutationList = indexKeyToMutationMap.get(key);
-                Mutation mutation = mutationList.get(mutationList.size() - 1);
-                if (mutation instanceof Delete) {
-                    continue;
-                }
-                long currentTime = EnvironmentEdgeManager.currentTimeMillis();
-                String errorMsg;
-                if (isTimestampBeyondMaxLookBack(maxLookBackInMills, currentTime, getTimestamp(mutation))){
-                    errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW_BEYOND_MAX_LOOKBACK;
-                    verificationPhaseResult.
-                            setBeyondMaxLookBackMissingIndexRowCount(verificationPhaseResult.getBeyondMaxLookBackMissingIndexRowCount() + 1);
-                }
-                else {
-                    errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW;
-                    verificationPhaseResult.setMissingIndexRowCount(verificationPhaseResult.getMissingIndexRowCount() + 1);
+        // Remove the expired rows from indexKeyToMutationMap
+        for (byte[] indexKey : expiredIndexRows) {
+            indexKeyToMutationMap.remove(indexKey);
+        }
+        // Count and log missing rows
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            byte[] indexKey = entry.getKey();
+            List<Mutation> mutationList = entry.getValue();
+            Mutation mutation = mutationList.get(mutationList.size() - 1);
+            if (mutation instanceof Delete) {
+                continue;
+            }
+            currentTime = EnvironmentEdgeManager.currentTimeMillis();
+            String errorMsg;
+            if (isTimestampBeyondMaxLookBack(maxLookBackInMills, currentTime, getTimestamp(mutation))){
+                errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW_BEYOND_MAX_LOOKBACK;
+                verificationPhaseResult.
+                        setBeyondMaxLookBackMissingIndexRowCount(verificationPhaseResult.getBeyondMaxLookBackMissingIndexRowCount() + 1);
+            }
+            else {
+                errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW;
+                verificationPhaseResult.setMissingIndexRowCount(verificationPhaseResult.getMissingIndexRowCount() + 1);
+            }
+            byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(indexKey), viewConstants);
+            logToIndexToolOutputTable(dataKey, indexKey, getTimestamp(mutation), 0, errorMsg, isBeforeRebuild);
+        }
+        // Leave the invalid and missing rows in indexKeyToMutationMap
+        indexKeyToMutationMap.putAll(invalidIndexRows);
+    }
+
+    private void rebuildIndexRows(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                  IndexToolVerificationResult verificationResult) throws IOException {
+        if (ignoreIndexRebuildForTesting) {
+            return;
+        }
+        try {
+            int batchSize = 0;
+            List<Mutation> indexUpdates = new ArrayList<Mutation>(maxBatchSize);
+            for (List<Mutation> mutationList : indexKeyToMutationMap.values()) {
+                indexUpdates.addAll(mutationList);
+                batchSize += mutationList.size();
+                if (batchSize >= maxBatchSize) {
+                    indexHTable.batch(indexUpdates);
+                    batchSize = 0;
+                    indexUpdates = new ArrayList<Mutation>(maxBatchSize);
                 }
-                byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                logToIndexToolOutputTable(dataKey,
-                        keyRange.getLowerRange(),
-                        getMaxTimestamp(dataKeyToMutationMap.get(dataKey)),
-                        getTimestamp(mutation), errorMsg);
             }
+            if (batchSize > 0) {
+                indexHTable.batch(indexUpdates);
+            }
+            if (verify) {
+                verificationResult.setRebuiltIndexRowCount(verificationResult.getRebuiltIndexRowCount() + indexKeyToMutationMap.size());
+            }
+        } catch (Throwable t) {
+            ServerUtil.throwIOException(indexHTable.getName().toString(), t);
         }
+    }
 
-        keys.addAll(invalidKeys);
+    private void rebuildAndOrVerifyIndexRows(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                             Set<byte[]> mostRecentIndexRowKeys,
+                                             IndexToolVerificationResult verificationResult) throws IOException {
+        if (verifyType == IndexTool.IndexVerifyType.NONE) {
+            rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+        } else if (verifyType == IndexTool.IndexVerifyType.ONLY) {
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getBefore(), true);
+        } else if (verifyType == IndexTool.IndexVerifyType.BEFORE) {
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getBefore(), true);
+            if (!indexKeyToMutationMap.isEmpty()) {
+                rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+            }
+        } else if (verifyType == IndexTool.IndexVerifyType.AFTER) {
+            rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getAfter(), false);
+        } else { // verifyType == IndexTool.IndexVerifyType.BOTH
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getBefore(), true);
+            if (!indexKeyToMutationMap.isEmpty()) {
+                rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+                verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getAfter(), false);
+            }
+        }
     }
 
-    private void addVerifyTask(final List<KeyRange> keys,
-            final IndexToolVerificationResult.PhaseResult verificationPhaseResult) {
+    private void addRebuildAndOrVerifyTask(TaskBatch<Boolean> tasks,
+                                           final Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                           final Set<byte[]> mostRecentIndexRowKeys,
+                                           final IndexToolVerificationResult verificationResult) {
         tasks.add(new Task<Boolean>() {
             @Override
             public Boolean call() throws Exception {
                 try {
-                    if (Thread.currentThread().isInterrupted()) {
-                        exceptionMessage = "Pool closed, not attempting to verify index rows! " + indexHTable.getName();
+                    if (Thread.currentThread().isInterrupted() || env.getRegionServerServices().isAborted() ||

Review comment:
       Note that in HBase 2.x coprocs don't have access to RegionServerServices through the env, so this will only work for 4.x / HBase 1.x. 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -952,111 +890,89 @@ private void parallelizeIndexVerify(IndexToolVerificationResult.PhaseResult veri
             }
             index++;
         }
-        for (IndexToolVerificationResult.PhaseResult result : verificationPhaseResultList) {
-            verificationPhaseResult.add(result);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            Map<byte[], Pair<Put, Delete>> newDataKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
-            for (List<KeyRange> keyRangeList : listOfKeyRangeList) {
-                for (KeyRange keyRange : keyRangeList) {
-                    byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                    newDataKeyToMutationMap.put(dataKey, dataKeyToMutationMap.get(dataKey));
-                }
+    }
+
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            Map<byte[], List<Mutation>> indexKeyToMutationMap, int splitSize) {
+        int splitCount = (indexKeyToMutationMap.size() + splitSize - 1) / splitSize;
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>(splitCount);
+        Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+        mapList.add(perTaskIndexKeyToMutationMap);
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            if (perTaskIndexKeyToMutationMap.size() == splitSize) {
+                perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+                mapList.add(perTaskIndexKeyToMutationMap);
             }
-            dataKeyToMutationMap.clear();
-            dataKeyToMutationMap = newDataKeyToMutationMap;
+            perTaskIndexKeyToMutationMap.put(entry.getKey(), entry.getValue());
         }
+        return mapList;
     }
 
-    private void rebuildIndexRows(UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
-        byte[] uuidValue = ServerCacheClient.generateId();
-        UngroupedAggregateRegionObserver.MutationList currentMutationList =
-                new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        Put put = null;
-        for (Mutation mutation : mutationList) {
-            if (mutation instanceof Put) {
-                if (put != null) {
-                    // back to back put, i.e., no delete in between. we can commit the previous put
-                    uuidValue = commitIfReady(uuidValue, currentMutationList);
-                }
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                put = (Put)mutation;
-            } else {
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                uuidValue = commitIfReady(uuidValue, currentMutationList);
-                put = null;
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            TreeMap<byte[], List<Mutation>> indexKeyToMutationMap, byte[][] endKeys, int maxMapSize) {
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>();
+        int regionCount = endKeys.length;
+        int regionIndex = 0;
+        byte[] indexKey = indexKeyToMutationMap.firstKey();
+        while (regionIndex < regionCount) {
+            Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap;
+            // Find the region including indexKey
+            while (regionIndex < regionCount - 1 && Bytes.compareTo(indexKey, endKeys[regionIndex]) != 1) {
+                regionIndex++;
             }
+            if (regionIndex == regionCount - 1) {
+                perTaskIndexKeyToMutationMap = indexKeyToMutationMap.subMap(indexKey,
+                        true, indexKeyToMutationMap.lastKey(), true);
+            }
+            else {
+                perTaskIndexKeyToMutationMap = indexKeyToMutationMap.subMap(indexKey,
+                        true, endKeys[regionIndex], true);
+            }
+            if (perTaskIndexKeyToMutationMap.size() > maxMapSize) {
+                // Further partition this map
+                mapList.addAll(getPerTaskIndexKeyToMutationMaps(perTaskIndexKeyToMutationMap, maxMapSize));
+            }
+            else {
+                mapList.add(perTaskIndexKeyToMutationMap);
+            }
+            if (regionIndex == regionCount - 1) {
+                break;
+            }
+            indexKey = indexKeyToMutationMap.higherKey(endKeys[regionIndex]);
+            regionIndex++;
         }
-        if (!currentMutationList.isEmpty()) {
-            ungroupedAggregateRegionObserver.checkForRegionClosing();
-            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, currentMutationList, blockingMemstoreSize);
-        }
+        return mapList;
     }
 
-    private void verifyAndOrRebuildIndex() throws IOException {
-        isBeforeRebuilt = true;
-        IndexToolVerificationResult nextVerificationResult = new IndexToolVerificationResult(scan);
-        nextVerificationResult.setScannedDataRowCount(dataKeyToMutationMap.size());
-        if (verifyType == IndexTool.IndexVerifyType.AFTER || verifyType == IndexTool.IndexVerifyType.NONE) {
-            // For these options we start with rebuilding index rows
-            rebuildIndexRows(mutations);
-            nextVerificationResult.setRebuiltIndexRowCount(dataKeyToMutationMap.size());
-            isBeforeRebuilt = false;
-        }
-        if (verifyType == IndexTool.IndexVerifyType.NONE) {
+    private void verifyAndOrRebuildIndex(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                         Set<byte[]> mostRecentIndexRowKeys) throws IOException {
+        if (indexKeyToMutationMap.size() == 0) {
             return;
         }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH ||
-                verifyType == IndexTool.IndexVerifyType.ONLY) {
-            IndexToolVerificationResult.PhaseResult verificationPhaseResult = new IndexToolVerificationResult.PhaseResult();
-            // For these options we start with verifying index rows
-            parallelizeIndexVerify(verificationPhaseResult);
-            nextVerificationResult.getBefore().add(verificationPhaseResult);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            // For these options, we have identified the rows to be rebuilt and now need to rebuild them
-            // At this point, dataKeyToDataPutMap includes mapping only for the rows to be rebuilt
-            mutations.clear();
-
-            for (Map.Entry<byte[], Pair<Put, Delete>> entry: dataKeyToMutationMap.entrySet()) {
-                if (entry.getValue().getFirst() != null) {
-                    mutations.add(entry.getValue().getFirst());
-                }
-                if (entry.getValue().getSecond() != null) {
-                    mutations.add(entry.getValue().getSecond());
-                }
+        if (verifyType != IndexTool.IndexVerifyType.ONLY) {
+            // Since we are building the index table, the region boundaries may change while we are building. Thus,
+            // we should update endKeys
+            try (org.apache.hadoop.hbase.client.Connection connection =

Review comment:
       What are the implications of endKeys being out-of-date? Is it a correctness problem, or a perf problem (as tasks would be crossing region boundaries)

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -952,111 +890,89 @@ private void parallelizeIndexVerify(IndexToolVerificationResult.PhaseResult veri
             }
             index++;
         }
-        for (IndexToolVerificationResult.PhaseResult result : verificationPhaseResultList) {
-            verificationPhaseResult.add(result);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            Map<byte[], Pair<Put, Delete>> newDataKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
-            for (List<KeyRange> keyRangeList : listOfKeyRangeList) {
-                for (KeyRange keyRange : keyRangeList) {
-                    byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                    newDataKeyToMutationMap.put(dataKey, dataKeyToMutationMap.get(dataKey));
-                }
+    }
+
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            Map<byte[], List<Mutation>> indexKeyToMutationMap, int splitSize) {
+        int splitCount = (indexKeyToMutationMap.size() + splitSize - 1) / splitSize;
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>(splitCount);
+        Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+        mapList.add(perTaskIndexKeyToMutationMap);
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            if (perTaskIndexKeyToMutationMap.size() == splitSize) {
+                perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+                mapList.add(perTaskIndexKeyToMutationMap);
             }
-            dataKeyToMutationMap.clear();
-            dataKeyToMutationMap = newDataKeyToMutationMap;
+            perTaskIndexKeyToMutationMap.put(entry.getKey(), entry.getValue());
         }
+        return mapList;
     }
 
-    private void rebuildIndexRows(UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
-        byte[] uuidValue = ServerCacheClient.generateId();
-        UngroupedAggregateRegionObserver.MutationList currentMutationList =
-                new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        Put put = null;
-        for (Mutation mutation : mutationList) {
-            if (mutation instanceof Put) {
-                if (put != null) {
-                    // back to back put, i.e., no delete in between. we can commit the previous put
-                    uuidValue = commitIfReady(uuidValue, currentMutationList);
-                }
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                put = (Put)mutation;
-            } else {
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                uuidValue = commitIfReady(uuidValue, currentMutationList);
-                put = null;
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            TreeMap<byte[], List<Mutation>> indexKeyToMutationMap, byte[][] endKeys, int maxMapSize) {
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>();
+        int regionCount = endKeys.length;
+        int regionIndex = 0;
+        byte[] indexKey = indexKeyToMutationMap.firstKey();
+        while (regionIndex < regionCount) {
+            Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap;
+            // Find the region including indexKey
+            while (regionIndex < regionCount - 1 && Bytes.compareTo(indexKey, endKeys[regionIndex]) != 1) {
+                regionIndex++;
             }
+            if (regionIndex == regionCount - 1) {
+                perTaskIndexKeyToMutationMap = indexKeyToMutationMap.subMap(indexKey,
+                        true, indexKeyToMutationMap.lastKey(), true);
+            }
+            else {
+                perTaskIndexKeyToMutationMap = indexKeyToMutationMap.subMap(indexKey,
+                        true, endKeys[regionIndex], true);
+            }
+            if (perTaskIndexKeyToMutationMap.size() > maxMapSize) {
+                // Further partition this map
+                mapList.addAll(getPerTaskIndexKeyToMutationMaps(perTaskIndexKeyToMutationMap, maxMapSize));
+            }
+            else {
+                mapList.add(perTaskIndexKeyToMutationMap);
+            }
+            if (regionIndex == regionCount - 1) {
+                break;
+            }
+            indexKey = indexKeyToMutationMap.higherKey(endKeys[regionIndex]);
+            regionIndex++;
         }
-        if (!currentMutationList.isEmpty()) {
-            ungroupedAggregateRegionObserver.checkForRegionClosing();
-            ungroupedAggregateRegionObserver.commitBatchWithRetries(region, currentMutationList, blockingMemstoreSize);
-        }
+        return mapList;
     }
 
-    private void verifyAndOrRebuildIndex() throws IOException {
-        isBeforeRebuilt = true;
-        IndexToolVerificationResult nextVerificationResult = new IndexToolVerificationResult(scan);
-        nextVerificationResult.setScannedDataRowCount(dataKeyToMutationMap.size());
-        if (verifyType == IndexTool.IndexVerifyType.AFTER || verifyType == IndexTool.IndexVerifyType.NONE) {
-            // For these options we start with rebuilding index rows
-            rebuildIndexRows(mutations);
-            nextVerificationResult.setRebuiltIndexRowCount(dataKeyToMutationMap.size());
-            isBeforeRebuilt = false;
-        }
-        if (verifyType == IndexTool.IndexVerifyType.NONE) {
+    private void verifyAndOrRebuildIndex(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                         Set<byte[]> mostRecentIndexRowKeys) throws IOException {
+        if (indexKeyToMutationMap.size() == 0) {
             return;
         }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH ||
-                verifyType == IndexTool.IndexVerifyType.ONLY) {
-            IndexToolVerificationResult.PhaseResult verificationPhaseResult = new IndexToolVerificationResult.PhaseResult();
-            // For these options we start with verifying index rows
-            parallelizeIndexVerify(verificationPhaseResult);
-            nextVerificationResult.getBefore().add(verificationPhaseResult);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            // For these options, we have identified the rows to be rebuilt and now need to rebuild them
-            // At this point, dataKeyToDataPutMap includes mapping only for the rows to be rebuilt
-            mutations.clear();
-
-            for (Map.Entry<byte[], Pair<Put, Delete>> entry: dataKeyToMutationMap.entrySet()) {
-                if (entry.getValue().getFirst() != null) {
-                    mutations.add(entry.getValue().getFirst());
-                }
-                if (entry.getValue().getSecond() != null) {
-                    mutations.add(entry.getValue().getSecond());
-                }
+        if (verifyType != IndexTool.IndexVerifyType.ONLY) {
+            // Since we are building the index table, the region boundaries may change while we are building. Thus,
+            // we should update endKeys
+            try (org.apache.hadoop.hbase.client.Connection connection =

Review comment:
       Creating HBase connections is heavy-weight. Can we re-use one from somewhere, such as a Phoenix connection?
   
   Also, since this code is duplicated in the constructor, can we factor out into a small helper function? 

##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -952,111 +890,89 @@ private void parallelizeIndexVerify(IndexToolVerificationResult.PhaseResult veri
             }
             index++;
         }
-        for (IndexToolVerificationResult.PhaseResult result : verificationPhaseResultList) {
-            verificationPhaseResult.add(result);
-        }
-        if (verifyType == IndexTool.IndexVerifyType.BEFORE || verifyType == IndexTool.IndexVerifyType.BOTH) {
-            Map<byte[], Pair<Put, Delete>> newDataKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
-            for (List<KeyRange> keyRangeList : listOfKeyRangeList) {
-                for (KeyRange keyRange : keyRangeList) {
-                    byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                    newDataKeyToMutationMap.put(dataKey, dataKeyToMutationMap.get(dataKey));
-                }
+    }
+
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            Map<byte[], List<Mutation>> indexKeyToMutationMap, int splitSize) {
+        int splitCount = (indexKeyToMutationMap.size() + splitSize - 1) / splitSize;
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>(splitCount);
+        Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+        mapList.add(perTaskIndexKeyToMutationMap);
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            if (perTaskIndexKeyToMutationMap.size() == splitSize) {
+                perTaskIndexKeyToMutationMap = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
+                mapList.add(perTaskIndexKeyToMutationMap);
             }
-            dataKeyToMutationMap.clear();
-            dataKeyToMutationMap = newDataKeyToMutationMap;
+            perTaskIndexKeyToMutationMap.put(entry.getKey(), entry.getValue());
         }
+        return mapList;
     }
 
-    private void rebuildIndexRows(UngroupedAggregateRegionObserver.MutationList mutationList) throws IOException {
-        byte[] uuidValue = ServerCacheClient.generateId();
-        UngroupedAggregateRegionObserver.MutationList currentMutationList =
-                new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        Put put = null;
-        for (Mutation mutation : mutationList) {
-            if (mutation instanceof Put) {
-                if (put != null) {
-                    // back to back put, i.e., no delete in between. we can commit the previous put
-                    uuidValue = commitIfReady(uuidValue, currentMutationList);
-                }
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                put = (Put)mutation;
-            } else {
-                currentMutationList.add(mutation);
-                setMutationAttributes(mutation, uuidValue);
-                uuidValue = commitIfReady(uuidValue, currentMutationList);
-                put = null;
+    public static List<Map<byte[], List<Mutation>>> getPerTaskIndexKeyToMutationMaps(
+            TreeMap<byte[], List<Mutation>> indexKeyToMutationMap, byte[][] endKeys, int maxMapSize) {
+        List<Map<byte[], List<Mutation>>> mapList = new ArrayList<>();
+        int regionCount = endKeys.length;
+        int regionIndex = 0;
+        byte[] indexKey = indexKeyToMutationMap.firstKey();
+        while (regionIndex < regionCount) {
+            Map<byte[], List<Mutation>> perTaskIndexKeyToMutationMap;
+            // Find the region including indexKey
+            while (regionIndex < regionCount - 1 && Bytes.compareTo(indexKey, endKeys[regionIndex]) != 1) {

Review comment:
       (I'm a little confused that you seem to be taking great care to keep endKeys up to date in other places but not here where it's being relied on.) 




----------------------------------------------------------------
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] [phoenix] gokceni commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
gokceni commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440312372



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -68,30 +75,44 @@
     protected int rowCountPerTask;
     protected boolean hasMore;
     protected int maxBatchSize;
+    protected final long maxBatchSizeBytes;
+    protected final long blockingMemstoreSize;
+    protected final byte[] clientVersionBytes;
+    protected boolean useProto = true;
     protected byte[] indexMetaData;
     protected Scan scan;
     protected RegionScanner innerScanner;
     protected Region region;
     protected IndexMaintainer indexMaintainer;
     protected Table indexHTable;
     protected TaskRunner pool;
-    protected TaskBatch<Boolean> tasks;
     protected String exceptionMessage;
     protected HTableFactory hTableFactory;
     protected int indexTableTTL;
     protected long maxLookBackInMills;
-    protected IndexToolVerificationResult verificationResult;
-    protected IndexVerificationResultRepository verificationResultRepository;
+    protected IndexToolVerificationResult verificationResult = null;
+    protected IndexVerificationResultRepository verificationResultRepository = null;
+    protected Map<byte[], NavigableSet<byte[]>> familyMap;
+    protected IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
+    protected boolean verify = false;
 
     public GlobalIndexRegionScanner(RegionScanner innerScanner, final Region region, final Scan scan,
-            final RegionCoprocessorEnvironment env) throws IOException {
+                                    final RegionCoprocessorEnvironment env) throws IOException {
         super(innerScanner);
         final Configuration config = env.getConfiguration();
         if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) != null) {
             pageSizeInRows = config.getLong(INDEX_REBUILD_PAGE_SIZE_IN_ROWS,
                     QueryServicesOptions.DEFAULT_INDEX_REBUILD_PAGE_SIZE_IN_ROWS);
         }
         maxBatchSize = config.getInt(MUTATE_BATCH_SIZE_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE);
+        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
+                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
+        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);
+        clientVersionBytes = scan.getAttribute(BaseScannerRegionObserver.CLIENT_VERSION);
+        familyMap = scan.getFamilyMap();
+        if (familyMap.isEmpty()) {
+            familyMap = null;

Review comment:
       Any reason why we set this to null? isColumnIncluded should work if it is not null but empty right?




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440528102



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -836,74 +747,122 @@ private void verifyIndexRows(List<KeyRange> keys,
         indexScan.setCacheBlocks(false);
         try (ResultScanner resultScanner = indexHTable.getScanner(indexScan)) {
             for (Result result = resultScanner.next(); (result != null); result = resultScanner.next()) {
-                KeyRange keyRange = PVarbinary.INSTANCE.getKeyRange(result.getRow());
-                if (!keys.contains(keyRange)) {
-                    continue;
+                if (!verifySingleIndexRow(result, indexKeyToMutationMap, mostRecentIndexRowKeys,
+                        verificationPhaseResult, isBeforeRebuild)) {
+                    invalidIndexRows.put(result.getRow(), indexKeyToMutationMap.get(result.getRow()));
                 }
-                if (!verifySingleIndexRow(result, verificationPhaseResult)) {
-                    invalidKeys.add(keyRange);
-                }
-                keys.remove(keyRange);
+                indexKeyToMutationMap.remove(result.getRow());
             }
         } catch (Throwable t) {
             ServerUtil.throwIOException(indexHTable.getName().toString(), t);
         }
+        List<byte[]> expiredIndexRows = new ArrayList<>();
         // Check if any expected rows from index(which we didn't get) are already expired due to TTL
         // TODO: metrics for expired rows
-        if (!keys.isEmpty()) {
-            Iterator<KeyRange> itr = keys.iterator();
-            long currentTime = EnvironmentEdgeManager.currentTimeMillis();
-            while(itr.hasNext()) {
-                KeyRange keyRange = itr.next();
-                byte[] key = keyRange.getLowerRange();
-                List<Mutation> mutationList = indexKeyToMutationMap.get(key);
-                if (isTimestampBeforeTTL(indexTableTTL, currentTime, getTimestamp(mutationList.get(mutationList.size() - 1)))) {
-                    itr.remove();
-                    verificationPhaseResult.setExpiredIndexRowCount(verificationPhaseResult.getExpiredIndexRowCount() + 1);
-                }
+        long currentTime = EnvironmentEdgeManager.currentTimeMillis();
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            List<Mutation> mutationList = entry.getValue();
+            if (isTimestampBeforeTTL(indexTableTTL, currentTime, getTimestamp(mutationList.get(mutationList.size() - 1)))) {
+                verificationPhaseResult.setExpiredIndexRowCount(verificationPhaseResult.getExpiredIndexRowCount() + 1);
+                expiredIndexRows.add(entry.getKey());
             }
         }
-        if (keys.size() > 0) {
-            for (KeyRange keyRange : keys) {
-                byte[] key = keyRange.getLowerRange();
-                List<Mutation> mutationList = indexKeyToMutationMap.get(key);
-                Mutation mutation = mutationList.get(mutationList.size() - 1);
-                if (mutation instanceof Delete) {
-                    continue;
-                }
-                long currentTime = EnvironmentEdgeManager.currentTimeMillis();
-                String errorMsg;
-                if (isTimestampBeyondMaxLookBack(maxLookBackInMills, currentTime, getTimestamp(mutation))){
-                    errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW_BEYOND_MAX_LOOKBACK;
-                    verificationPhaseResult.
-                            setBeyondMaxLookBackMissingIndexRowCount(verificationPhaseResult.getBeyondMaxLookBackMissingIndexRowCount() + 1);
-                }
-                else {
-                    errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW;
-                    verificationPhaseResult.setMissingIndexRowCount(verificationPhaseResult.getMissingIndexRowCount() + 1);
+        // Remove the expired rows from indexKeyToMutationMap
+        for (byte[] indexKey : expiredIndexRows) {
+            indexKeyToMutationMap.remove(indexKey);
+        }
+        // Count and log missing rows
+        for (Map.Entry<byte[], List<Mutation>> entry: indexKeyToMutationMap.entrySet()) {
+            byte[] indexKey = entry.getKey();
+            List<Mutation> mutationList = entry.getValue();
+            Mutation mutation = mutationList.get(mutationList.size() - 1);
+            if (mutation instanceof Delete) {
+                continue;
+            }
+            currentTime = EnvironmentEdgeManager.currentTimeMillis();
+            String errorMsg;
+            if (isTimestampBeyondMaxLookBack(maxLookBackInMills, currentTime, getTimestamp(mutation))){
+                errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW_BEYOND_MAX_LOOKBACK;
+                verificationPhaseResult.
+                        setBeyondMaxLookBackMissingIndexRowCount(verificationPhaseResult.getBeyondMaxLookBackMissingIndexRowCount() + 1);
+            }
+            else {
+                errorMsg = ERROR_MESSAGE_MISSING_INDEX_ROW;
+                verificationPhaseResult.setMissingIndexRowCount(verificationPhaseResult.getMissingIndexRowCount() + 1);
+            }
+            byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(indexKey), viewConstants);
+            logToIndexToolOutputTable(dataKey, indexKey, getTimestamp(mutation), 0, errorMsg, isBeforeRebuild);
+        }
+        // Leave the invalid and missing rows in indexKeyToMutationMap
+        indexKeyToMutationMap.putAll(invalidIndexRows);
+    }
+
+    private void rebuildIndexRows(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                  IndexToolVerificationResult verificationResult) throws IOException {
+        if (ignoreIndexRebuildForTesting) {
+            return;
+        }
+        try {
+            int batchSize = 0;
+            List<Mutation> indexUpdates = new ArrayList<Mutation>(maxBatchSize);
+            for (List<Mutation> mutationList : indexKeyToMutationMap.values()) {
+                indexUpdates.addAll(mutationList);
+                batchSize += mutationList.size();
+                if (batchSize >= maxBatchSize) {
+                    indexHTable.batch(indexUpdates);
+                    batchSize = 0;
+                    indexUpdates = new ArrayList<Mutation>(maxBatchSize);
                 }
-                byte[] dataKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(keyRange.getLowerRange()), viewConstants);
-                logToIndexToolOutputTable(dataKey,
-                        keyRange.getLowerRange(),
-                        getMaxTimestamp(dataKeyToMutationMap.get(dataKey)),
-                        getTimestamp(mutation), errorMsg);
             }
+            if (batchSize > 0) {
+                indexHTable.batch(indexUpdates);
+            }
+            if (verify) {
+                verificationResult.setRebuiltIndexRowCount(verificationResult.getRebuiltIndexRowCount() + indexKeyToMutationMap.size());
+            }
+        } catch (Throwable t) {
+            ServerUtil.throwIOException(indexHTable.getName().toString(), t);
         }
+    }
 
-        keys.addAll(invalidKeys);
+    private void rebuildAndOrVerifyIndexRows(Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                             Set<byte[]> mostRecentIndexRowKeys,
+                                             IndexToolVerificationResult verificationResult) throws IOException {
+        if (verifyType == IndexTool.IndexVerifyType.NONE) {
+            rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+        } else if (verifyType == IndexTool.IndexVerifyType.ONLY) {
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getBefore(), true);
+        } else if (verifyType == IndexTool.IndexVerifyType.BEFORE) {
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getBefore(), true);
+            if (!indexKeyToMutationMap.isEmpty()) {
+                rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+            }
+        } else if (verifyType == IndexTool.IndexVerifyType.AFTER) {
+            rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getAfter(), false);
+        } else { // verifyType == IndexTool.IndexVerifyType.BOTH
+            verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getBefore(), true);
+            if (!indexKeyToMutationMap.isEmpty()) {
+                rebuildIndexRows(indexKeyToMutationMap, verificationResult);
+                verifyIndexRows(indexKeyToMutationMap, mostRecentIndexRowKeys, verificationResult.getAfter(), false);
+            }
+        }
     }
 
-    private void addVerifyTask(final List<KeyRange> keys,
-            final IndexToolVerificationResult.PhaseResult verificationPhaseResult) {
+    private void addRebuildAndOrVerifyTask(TaskBatch<Boolean> tasks,
+                                           final Map<byte[], List<Mutation>> indexKeyToMutationMap,
+                                           final Set<byte[]> mostRecentIndexRowKeys,
+                                           final IndexToolVerificationResult verificationResult) {
         tasks.add(new Task<Boolean>() {
             @Override
             public Boolean call() throws Exception {
                 try {
-                    if (Thread.currentThread().isInterrupted()) {
-                        exceptionMessage = "Pool closed, not attempting to verify index rows! " + indexHTable.getName();
+                    if (Thread.currentThread().isInterrupted() || env.getRegionServerServices().isAborted() ||

Review comment:
       Indexers do the same. We need to change all then later. 




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440567731



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
##########
@@ -91,90 +83,51 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Throwables;
 import com.google.common.collect.Maps;
 
 public class IndexRebuildRegionScanner extends GlobalIndexRegionScanner {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(IndexRebuildRegionScanner.class);
 
-    private final long maxBatchSizeBytes;
-    private final long blockingMemstoreSize;
-    private final byte[] clientVersionBytes;
-    private boolean useProto = true;
+    private static boolean ignoreIndexRebuildForTesting  = false;
+    public static void setIgnoreIndexRebuildForTesting(boolean ignore) { ignoreIndexRebuildForTesting = ignore; }
     private byte[] indexRowKey;
-    private IndexTool.IndexVerifyType verifyType = IndexTool.IndexVerifyType.NONE;
     private IndexTool.IndexDisableLoggingType disableLoggingVerifyType = IndexTool.IndexDisableLoggingType.NONE;
-    private boolean verify = false;
-    private Map<byte[], List<Mutation>> indexKeyToMutationMap;
-    private Map<byte[], Pair<Put, Delete>> dataKeyToMutationMap;
-    private UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;
-    protected UngroupedAggregateRegionObserver.MutationList mutations;
-    private boolean isBeforeRebuilt = true;
-    private boolean partialRebuild = false;
     private int singleRowRebuildReturnCode;
-    private Map<byte[], NavigableSet<byte[]>> familyMap;
     private byte[][] viewConstants;
-    private IndexVerificationOutputRepository verificationOutputRepository;
+    private IndexVerificationOutputRepository verificationOutputRepository = null;
     private boolean skipped = false;
     private boolean shouldVerifyCheckDone = false;
-
+    final private RegionCoprocessorEnvironment env;
+    byte[][] endKeys;
     @VisibleForTesting
     public IndexRebuildRegionScanner(final RegionScanner innerScanner, final Region region, final Scan scan,
-                              final RegionCoprocessorEnvironment env,
-                              UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver) throws IOException {
+                              final RegionCoprocessorEnvironment env) throws IOException {
         super(innerScanner, region, scan, env);
-        final Configuration config = env.getConfiguration();
-        if (scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_PAGING) == null) {
-            partialRebuild = true;
-        }
-        maxBatchSizeBytes = config.getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
-                QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
-        mutations = new UngroupedAggregateRegionObserver.MutationList(maxBatchSize);
-        blockingMemstoreSize = UngroupedAggregateRegionObserver.getBlockingMemstoreSize(region, config);
-        clientVersionBytes = scan.getAttribute(BaseScannerRegionObserver.CLIENT_VERSION);
-        indexMetaData = scan.getAttribute(PhoenixIndexCodec.INDEX_PROTO_MD);
-        if (indexMetaData == null) {
-            useProto = false;
-        }
-        familyMap = scan.getFamilyMap();
-        if (familyMap.isEmpty()) {
-            familyMap = null;
-        }
-        this.ungroupedAggregateRegionObserver = ungroupedAggregateRegionObserver;
+        this.env = env;
+        try (org.apache.hadoop.hbase.client.Connection connection =
+                     HBaseFactoryProvider.getHConnectionFactory().createConnection(env.getConfiguration())) {
+            endKeys = connection.getRegionLocator(indexHTable.getName()).getEndKeys();

Review comment:
       We have a different data table region per mapper.  Mappers initiate a separate IndexRebuildRegionScanner object on their data table regions. Then in parallel these objects scan their data table regions and rebuild index table rows.  A object may rebuild rows from any index table region. 




----------------------------------------------------------------
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] [phoenix] kadirozde commented on a change in pull request #794: PHOENIX-5928 Index rebuilds without replaying data table mutations

Posted by GitBox <gi...@apache.org>.
kadirozde commented on a change in pull request #794:
URL: https://github.com/apache/phoenix/pull/794#discussion_r440642914



##########
File path: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/GlobalIndexRegionScanner.java
##########
@@ -82,16 +94,30 @@
     protected long maxLookBackInMills;
     protected IndexToolVerificationResult verificationResult;
     protected IndexVerificationResultRepository verificationResultRepository;
+    protected UngroupedAggregateRegionObserver ungroupedAggregateRegionObserver;

Review comment:
       The attribute ungroupedAggregateRegionObserver has been removed from this class




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