You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@phoenix.apache.org by "tkhurana (via GitHub)" <gi...@apache.org> on 2026/06/22 20:50:04 UTC

[PR] PHOENIX-7931 Coalesce per-batch replication appends into a single record [phoenix]

tkhurana opened a new pull request, #2540:
URL: https://github.com/apache/phoenix/pull/2540

   ## PHOENIX-7931: Coalesce per-batch replication appends into a single record
   
   Targets the `PHOENIX-7562-feature-new` feature branch (not master).
   
   ### What changed
   On the write path, a server-side batch's mutations for a given table are now coalesced into a **single** replication log record carrying a flat cell stream, rather than one record per mutation. On the replay path, `MutationCellGrouper` reconstructs Put/Delete mutations from that cell stream on the row + put-vs-delete boundary, mirroring the algorithm HBase's `ReplicationSink` uses for WALEdits.
   
   This cuts ring-buffer pressure substantially (≈5× fewer Disruptor events at high batch sizes) without changing the fsync floor — coalescing already minimized inner syncs. The on-disk record format changes accordingly (per-cell row/family/qualifier/timestamp/type/value, with a per-record table name + commitId + attributes header).
   
   ### Key files
   - `IndexRegionObserver` — per-(table, batch) cell aggregation before a single `append`
   - `MutationCellGrouper` (new) — replay-side cell-stream → mutation regrouping
   - `LogFileCodec` / `LogFileRecord` / `LogFile` — new coalesced record format
   - `ReplicationLogGroup` / `ReplicationLog` — cell-oriented append API
   
   ### Testing
   - New `MutationCellGrouperTest` (10 cases): empty input, single Put/Delete, contiguous same-row/type coalescing, row-change splits, Put→Delete same-row type-boundary split, three-row Put/Delete/Put, adjacent DeleteColumn/DeleteFamily subtype split, non-consecutive same-row partitioning, and cell preservation.
   - New `testAppendAndSyncSingleBatchRecordCount` IT pins the coalesced record-count contract with cross-cluster cell-level equality.
   - New `testSyncMetricsEmitted` unit test — deterministic replacement for the flaky IT metrics assertion (injects an fsync delay to clear ms-truncation; reads metrics only after a graceful close that joins the consumer).
   - Expanded `LogFileCodecTest` round-trip coverage for the new format (multi-family ordering, empty-record rejection, all cell types).
   - `testReplicationSyncPathSimulator` (opt-in) for sync-coalescing measurement under contention.
   
   ### Verification
   - `phoenix-core-server` compiles clean; `MutationCellGrouperTest`, `LogFileCodecTest`, and the replication unit tests pass.
   - `mvn spotless:check` passes on both `phoenix-core-server` and `phoenix-core`.
   


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

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "tkhurana (via GitHub)" <gi...@apache.org>.
tkhurana merged PR #2540:
URL: https://github.com/apache/phoenix/pull/2540


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

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "apurtell (via GitHub)" <gi...@apache.org>.
apurtell commented on code in PR #2540:
URL: https://github.com/apache/phoenix/pull/2540#discussion_r3500554618


##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/reader/ReplicationLogProcessor.java:
##########
@@ -246,21 +246,19 @@ public void processLogFile(FileSystem fs, Path filePath) throws IOException {
 
       for (LogFile.Record record : logFileReader) {
         final TableName tableName = TableName.valueOf(record.getHBaseTableName());
-        final Mutation mutation = record.getMutation();
-
-        tableToMutationsMap.computeIfAbsent(tableName, k -> new ArrayList<>()).add(mutation);
-
-        // Increment current batch size and current batch size bytes
-        currentBatchSize++;
-        currentBatchSizeBytes += mutation.heapSize();
-
-        // Process when we reach either the batch count or size limit
-        if (currentBatchSize >= getBatchSize() || currentBatchSizeBytes >= getBatchSizeBytes()) {
-          processReplicationLogBatch(tableToMutationsMap);
-          totalProcessed += currentBatchSize;
-          tableToMutationsMap.clear();
-          currentBatchSize = 0;
-          currentBatchSizeBytes = 0;
+        for (Mutation mutation : record.getMutations()) {
+          tableToMutationsMap.computeIfAbsent(tableName, k -> new ArrayList<>()).add(mutation);
+          currentBatchSize++;
+          currentBatchSizeBytes += mutation.heapSize();
+
+          // Process when we reach either the batch count or size limit

Review Comment:
   Before this change a record was always a single Mutation, so batches always split between records. Now a single record's mutations can be split across two processReplicationLogBatch invocations. I think it's fine but future maintainers cannot assume a certain atomicity here.



##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/log/LogFileCodec.java:
##########
@@ -26,55 +26,56 @@
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import org.apache.hadoop.hbase.Cell;
 import org.apache.hadoop.hbase.KeyValue;
-import org.apache.hadoop.hbase.client.Delete;
-import org.apache.hadoop.hbase.client.Mutation;
-import org.apache.hadoop.hbase.client.Put;
 import org.apache.hadoop.hbase.io.ByteBuffInputStream;
 import org.apache.hadoop.hbase.nio.ByteBuff;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.io.WritableUtils;
 
 /**
- * Default Codec for encoding and decoding ReplicationLog Records within a block buffer. This
- * implementation uses standard Java DataInput/DataOutput for serialization. Record Format within a
- * block:
+ * Default Codec for encoding and decoding ReplicationLog Records within a block buffer. The on-disk

Review Comment:
   This is the most interesting change (to me). I suppose it's of a piece with the evolution of HBase WAL with WALEdit to group cells and on the RPC side "cell blocks" instead of individually described cells in the IDL. 
   
   We may want to restructure the ascii art here further
   
   ```text
   RECORD LENGTH (vint)
   RECORD HEADER
     Table name length (vint)
     Table name bytes
     Commit id (vlong)
   ATTRIBUTES COUNT (vint)            -- NEW: record-level attribute map
   PER-ATTRIBUTE (repeated):
     Key length (vint)
     Key bytes (UTF-8)
     Value length (vint)
     Value bytes
   CELL COUNT (vint)
   PER-CELL (repeated):
     Row length (vint)                -- row written on EVERY cell
     Row bytes
     Family length (vint)             -- family written on EVERY cell
     Family bytes
     Qualifier length (vint)
     Qualifier bytes
     Cell timestamp (long, 8 bytes)
     Cell type byte (1 byte)
     Value length (vint)
     Value bytes
   ```



##########
phoenix-core/src/test/java/org/apache/phoenix/replication/ReplicationLogGroupTest.java:
##########
@@ -1429,59 +1456,15 @@ public void testRetryPicksUpStagedWriter() throws Exception {
     assertTrue("Should be using new writer", newWriter != initialWriter);
 
     // Old writer: received the append only
-    verify(initialWriter, times(1)).append(eq(tableName), eq(commitId), eq(put));
+    verify(initialWriter, times(1)).append(eq(tableName), eq(commitId),
+      eq(LogFileTestUtil.cellsOf(put)));
 
     // New writer: received replayed append + successful sync
-    verify(newWriter, times(1)).append(eq(tableName), eq(commitId), eq(put));
+    verify(newWriter, times(1)).append(eq(tableName), eq(commitId),
+      eq(LogFileTestUtil.cellsOf(put)));
     verify(newWriter, times(1)).sync();
   }
 
-  /**
-   * Tests the idle-then-lease-recovery scenario: after a sync clears currentBatch, the system goes
-   * idle. A rotation tick stages a pending writer. The reader performs HDFS lease recovery,
-   * breaking the old writer's stream. When events resume, apply() drains the healthy staged writer
-   * before the action — the broken writer is never touched. No replay needed (empty batch).
-   */
-  @Test
-  public void testIdleLeaseRecoveryDrainsStagedWriter() throws Exception {

Review Comment:
   I think this test is a real concurrency concern. After a sync clears `currentBatch`, the system goes idle, a rotation tick stages a pending writer, and the reader performs HDFS lease recovery, invalidating the old writer's outputstream. When events resume we need to ensure `apply()` drains to the new and healthy writer before the action and should ensure the broken writer is never touched.
   
   The body of this test only needs some simple updates (any(Mutation.class) → any(List.class), eq(put) → eq(LogFileTestUtil.cellsOf(put))) Let's restore and migrate 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.

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "apurtell (via GitHub)" <gi...@apache.org>.
apurtell commented on code in PR #2540:
URL: https://github.com/apache/phoenix/pull/2540#discussion_r3500554618


##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/reader/ReplicationLogProcessor.java:
##########
@@ -246,21 +246,19 @@ public void processLogFile(FileSystem fs, Path filePath) throws IOException {
 
       for (LogFile.Record record : logFileReader) {
         final TableName tableName = TableName.valueOf(record.getHBaseTableName());
-        final Mutation mutation = record.getMutation();
-
-        tableToMutationsMap.computeIfAbsent(tableName, k -> new ArrayList<>()).add(mutation);
-
-        // Increment current batch size and current batch size bytes
-        currentBatchSize++;
-        currentBatchSizeBytes += mutation.heapSize();
-
-        // Process when we reach either the batch count or size limit
-        if (currentBatchSize >= getBatchSize() || currentBatchSizeBytes >= getBatchSizeBytes()) {
-          processReplicationLogBatch(tableToMutationsMap);
-          totalProcessed += currentBatchSize;
-          tableToMutationsMap.clear();
-          currentBatchSize = 0;
-          currentBatchSizeBytes = 0;
+        for (Mutation mutation : record.getMutations()) {
+          tableToMutationsMap.computeIfAbsent(tableName, k -> new ArrayList<>()).add(mutation);
+          currentBatchSize++;
+          currentBatchSizeBytes += mutation.heapSize();
+
+          // Process when we reach either the batch count or size limit

Review Comment:
   Before this change a record was always a single Mutation, so batches always split between records. Now a single record's mutations can be split across two `processReplicationLogBatch` invocations. I think it's fine but future maintainers cannot assume a certain atomicity here.



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

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "apurtell (via GitHub)" <gi...@apache.org>.
apurtell commented on code in PR #2540:
URL: https://github.com/apache/phoenix/pull/2540#discussion_r3500567968


##########
phoenix-core/src/test/java/org/apache/phoenix/replication/ReplicationLogGroupTest.java:
##########
@@ -1429,59 +1456,15 @@ public void testRetryPicksUpStagedWriter() throws Exception {
     assertTrue("Should be using new writer", newWriter != initialWriter);
 
     // Old writer: received the append only
-    verify(initialWriter, times(1)).append(eq(tableName), eq(commitId), eq(put));
+    verify(initialWriter, times(1)).append(eq(tableName), eq(commitId),
+      eq(LogFileTestUtil.cellsOf(put)));
 
     // New writer: received replayed append + successful sync
-    verify(newWriter, times(1)).append(eq(tableName), eq(commitId), eq(put));
+    verify(newWriter, times(1)).append(eq(tableName), eq(commitId),
+      eq(LogFileTestUtil.cellsOf(put)));
     verify(newWriter, times(1)).sync();
   }
 
-  /**
-   * Tests the idle-then-lease-recovery scenario: after a sync clears currentBatch, the system goes
-   * idle. A rotation tick stages a pending writer. The reader performs HDFS lease recovery,
-   * breaking the old writer's stream. When events resume, apply() drains the healthy staged writer
-   * before the action — the broken writer is never touched. No replay needed (empty batch).
-   */
-  @Test
-  public void testIdleLeaseRecoveryDrainsStagedWriter() throws Exception {

Review Comment:
   I think this test is a real concurrency concern. After a sync clears `currentBatch`, the system goes idle, a rotation tick stages a pending writer, invalidating the old writer. When events resume we need to ensure `apply()` drains to the new and healthy writer before the action and should ensure the dead writer is never touched.
   
   The body of this test only needs some simple updates (any(Mutation.class) → any(List.class), eq(put) → eq(LogFileTestUtil.cellsOf(put))) Let's restore and migrate 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.

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "apurtell (via GitHub)" <gi...@apache.org>.
apurtell commented on code in PR #2540:
URL: https://github.com/apache/phoenix/pull/2540#discussion_r3500567968


##########
phoenix-core/src/test/java/org/apache/phoenix/replication/ReplicationLogGroupTest.java:
##########
@@ -1429,59 +1456,15 @@ public void testRetryPicksUpStagedWriter() throws Exception {
     assertTrue("Should be using new writer", newWriter != initialWriter);
 
     // Old writer: received the append only
-    verify(initialWriter, times(1)).append(eq(tableName), eq(commitId), eq(put));
+    verify(initialWriter, times(1)).append(eq(tableName), eq(commitId),
+      eq(LogFileTestUtil.cellsOf(put)));
 
     // New writer: received replayed append + successful sync
-    verify(newWriter, times(1)).append(eq(tableName), eq(commitId), eq(put));
+    verify(newWriter, times(1)).append(eq(tableName), eq(commitId),
+      eq(LogFileTestUtil.cellsOf(put)));
     verify(newWriter, times(1)).sync();
   }
 
-  /**
-   * Tests the idle-then-lease-recovery scenario: after a sync clears currentBatch, the system goes
-   * idle. A rotation tick stages a pending writer. The reader performs HDFS lease recovery,
-   * breaking the old writer's stream. When events resume, apply() drains the healthy staged writer
-   * before the action — the broken writer is never touched. No replay needed (empty batch).
-   */
-  @Test
-  public void testIdleLeaseRecoveryDrainsStagedWriter() throws Exception {

Review Comment:
   I think this test is a real concurrency concern. After a sync clears `currentBatch`, the system goes idle, a rotation tick stages a pending writer, invalidating the old writer. When events resume we need to ensure `apply()` drains to the new and healthy writer before the action and should ensure the broken writer is never touched.
   
   The body of this test only needs some simple updates (any(Mutation.class) → any(List.class), eq(put) → eq(LogFileTestUtil.cellsOf(put))) Let's restore and migrate 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.

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2540:
URL: https://github.com/apache/phoenix/pull/2540#discussion_r3500644902


##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/ReplicationLogGroup.java:
##########
@@ -551,6 +556,31 @@ public void append(String tableName, long commitId, Mutation mutation) throws IO
     if (LOG.isTraceEnabled()) {
       LOG.trace("Append: table={}, commitId={}, mutation={}", tableName, commitId, mutation);
     }
+    List<Cell> cells = new ArrayList<>();
+    for (List<Cell> familyCells : mutation.getFamilyCellMap().values()) {
+      cells.addAll(familyCells);
+    }
+    publishDataEvent(new Record(tableName, commitId, cells));
+  }

Review Comment:
   append(String,long,Mutation) now flattens the mutation into a cell list and publishes it asynchronously, but it doesn't guard against empty mutations. If a Put/Delete has no cells, the consumer will later fail when encoding (LogFileCodec rejects empty records), potentially triggering fail-stop. Validate and fail fast on empty input before publishing.



##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/ReplicationLogGroup.java:
##########
@@ -551,6 +556,31 @@ public void append(String tableName, long commitId, Mutation mutation) throws IO
     if (LOG.isTraceEnabled()) {
       LOG.trace("Append: table={}, commitId={}, mutation={}", tableName, commitId, mutation);
     }
+    List<Cell> cells = new ArrayList<>();
+    for (List<Cell> familyCells : mutation.getFamilyCellMap().values()) {
+      cells.addAll(familyCells);
+    }
+    publishDataEvent(new Record(tableName, commitId, cells));
+  }
+
+  /**
+   * Append a coalesced batch of cells as a single record on the log. The cells must already be
+   * grouped by row+type so consumers can reconstruct Put/Delete mutations on the row+type boundary
+   * (see {@link MutationCellGrouper}). Behaves identically to
+   * {@link #append(String, long, Mutation)} with respect to backpressure and fail-stop.
+   * @param tableName The HBase table name shared by every cell in {@code cells}.
+   * @param commitId  The commit identifier (e.g., SCN) for the batch.
+   * @param cells     The flat ordered cell stream for one batch on one table.
+   * @throws IOException If the writer is closed or the ring buffer is full.
+   */
+  public void append(String tableName, long commitId, List<Cell> cells) throws IOException {
+    if (LOG.isTraceEnabled()) {
+      LOG.trace("Append: table={}, commitId={}, cells={}", tableName, commitId, cells.size());
+    }
+    publishDataEvent(new Record(tableName, commitId, cells));
+  }

Review Comment:
   append(String,long,List<Cell>) will throw a NullPointerException when trace logging is enabled if callers pass a null cell list (cells.size()). Since the record body is also required to be non-empty (LogFileCodec rejects empty records), validate inputs before publishing so the failure is synchronous and doesn't poison the consumer thread later.



##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/MutationCellGrouper.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.replication;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.CellUtil;
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Mutation;
+import org.apache.hadoop.hbase.client.Put;
+
+/**
+ * Groups a flat cell stream into Put/Delete mutations, mirroring the algorithm HBase's
+ * ReplicationSink uses to reconstruct mutations from a WALEdit. A new mutation is started whenever
+ * the row key or the put-vs-delete disposition differs from the immediately preceding cell;
+ * consecutive cells sharing both are collected into one mutation. There is no precondition on the
+ * input ordering: any cell stream produces valid mutations. Ordering only affects how the cells are

Review Comment:
   The class-level Javadoc says the boundary is "put-vs-delete disposition", but the implementation actually starts a new mutation whenever the *cell type* changes (previousCell.getType() != cell.getType()), which intentionally splits distinct delete subtypes. Please align the documentation with the actual row+cell-type boundary so readers don't misinterpret the contract.



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

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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


Re: [PR] PHOENIX-7931 Coalesce per-batch mutations into a single record [phoenix]

Posted by "apurtell (via GitHub)" <gi...@apache.org>.
apurtell commented on code in PR #2540:
URL: https://github.com/apache/phoenix/pull/2540#discussion_r3500529683


##########
phoenix-core-server/src/main/java/org/apache/phoenix/replication/log/LogFileCodec.java:
##########
@@ -26,55 +26,56 @@
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import org.apache.hadoop.hbase.Cell;
 import org.apache.hadoop.hbase.KeyValue;
-import org.apache.hadoop.hbase.client.Delete;
-import org.apache.hadoop.hbase.client.Mutation;
-import org.apache.hadoop.hbase.client.Put;
 import org.apache.hadoop.hbase.io.ByteBuffInputStream;
 import org.apache.hadoop.hbase.nio.ByteBuff;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.io.WritableUtils;
 
 /**
- * Default Codec for encoding and decoding ReplicationLog Records within a block buffer. This
- * implementation uses standard Java DataInput/DataOutput for serialization. Record Format within a
- * block:
+ * Default Codec for encoding and decoding ReplicationLog Records within a block buffer. The on-disk

Review Comment:
   This is the most interesting change (to me). I suppose it's of a piece with the evolution of HBase WAL with WALEdit to group cells and on the RPC side "cell blocks" instead of individually described cells in the IDL. 
   
   It was probably inevitable that this grouping was necessary to bring down overheads but I wanted to go with simple and atomic first if we could get away with it. 
   
   We may want to restructure the ascii art here further
   
   ```text
   RECORD LENGTH (vint)
   RECORD HEADER
     Table name length (vint)
     Table name bytes
     Commit id (vlong)
   ATTRIBUTES COUNT (vint)            -- NEW: record-level attribute map
   PER-ATTRIBUTE (repeated):
     Key length (vint)
     Key bytes (UTF-8)
     Value length (vint)
     Value bytes
   CELL COUNT (vint)
   PER-CELL (repeated):
     Row length (vint)                -- row written on EVERY cell
     Row bytes
     Family length (vint)             -- family written on EVERY cell
     Family bytes
     Qualifier length (vint)
     Qualifier bytes
     Cell timestamp (long, 8 bytes)
     Cell type byte (1 byte)
     Value length (vint)
     Value bytes
   ```



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

To unsubscribe, e-mail: issues-unsubscribe@phoenix.apache.org

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