You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "void-ptr974 (via GitHub)" <gi...@apache.org> on 2026/10/23 10:44:33 UTC
[PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
void-ptr974 opened a new pull request, #27064:
URL: https://github.com/apache/pulsar/pull/27064
### Motivation
`InMemoryRedeliveryTracker` can throw `ArrayIndexOutOfBoundsException` while the broker sends messages to a consumer.
The tracker stores counts in two nested fastutil hash maps. `getRedeliveryCount()` reads both maps using a `StampedLock` optimistic read and validates the stamp only after the lookups. An optimistic read does not block a writer. If either map resizes during a lookup, the reader can see a new capacity or index mask together with an old backing array and access an index outside that array. The exception is thrown before stamp validation can retry the lookup under a read lock.
A concurrent case occurs with consumers of the same persistent Shared or Key_Shared subscription:
1. Consumer A's connection event loop reads a redelivery count while sending an entry.
2. Consumer B's connection, running on another event loop, handles a redelivery request and adds tracked positions to the same tracker. Adding entries within an existing ledger can resize the inner map; adding new ledgers can resize the outer map.
3. Consumer A's lookup overlaps the resize and throws, even when the position being read is valid and its count is unchanged.
The sender catches the exception, interrupts the batch, and closes the consumer connection. This disrupts message dispatch and causes reconnection, redelivery, and additional delivery latency.
### Modifications
- Replace `StampedLock` with `ReentrantReadWriteLock`.
- Hold the read lock for the entire lookup across both maps, and the write lock for increments, removals, and clearing the tracker. Release each lock in `finally`.
- Add concurrent regression tests for reads during expansion of both the inner and outer maps. Cover zero and nonzero keys, and keep reading an unchanged position until concurrent insertions finish.
### Verifying this change
- [ ] Make sure that the change passes the CI checks.
The four `InMemoryRedeliveryTrackerTest` cases use two real threads and only normal tracker operations. One reads an existing count while the other inserts different positions and triggers map expansion. The tests do not inject exceptions or modify map internals.
Using the same compiled test class and runtime dependencies, the original tracker produced 16 `ArrayIndexOutOfBoundsException` failures across 48 case executions; the fixed tracker passed all 48. These runs covered default JIT, interpreter, C1 and C2 execution in 12 independent JVMs per implementation. Both inner and outer map lookups produced `Index 64 out of bounds for length 33` with the original tracker. Reproduction depends on thread scheduling and JVM compilation.
The following scoped tests passed:
```bash
./gradlew :pulsar-broker:test \
--tests org.apache.pulsar.broker.service.InMemoryRedeliveryTrackerTest \
--tests org.apache.pulsar.client.api.ExposeMessageRedeliveryCountTest.testRedeliveryCount \
-PtestRetryCount=0
```
The full repository `./gradlew quickCheck` also passed in the isolated worktree.
### Does this pull request potentially affect one of the following parts:
- [ ] Dependencies (add or upgrade a dependency)
- [ ] The public API
- [ ] The schema
- [ ] The default values of configurations
- [ ] The threading model
- [ ] The binary protocol
- [ ] The REST endpoints
- [ ] The admin CLI options
- [ ] The metrics
- [ ] Anything that affects deployment
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
Posted by "void-ptr974 (via GitHub)" <gi...@apache.org>.
void-ptr974 commented on code in PR #27064:
URL: https://github.com/apache/pulsar/pull/27064#discussion_r4365743602
##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/InMemoryRedeliveryTracker.java:
##########
@@ -23,49 +23,44 @@
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.List;
-import java.util.concurrent.locks.StampedLock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.bookkeeper.mledger.Position;
public class InMemoryRedeliveryTracker implements RedeliveryTracker {
// ledgerId -> entryId -> count
private Long2ObjectMap<Long2IntMap> trackerCache = new Long2ObjectOpenHashMap<>();
- private final StampedLock rwLock = new StampedLock();
+ private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
Review Comment:
Thanks for the suggestion. I adopted it in [ab6ff644](https://github.com/void-ptr974/pulsar/commit/ab6ff644bfc1896c1b7843cfb5244582866b01fc): the tracker keeps StampedLock and now holds readLock() across both map lookups. I also included a [JMH benchmark](https://github.com/void-ptr974/pulsar/blob/ab6ff644bfc1896c1b7843cfb5244582866b01fc/microbench/src/main/java/org/apache/pulsar/broker/service/InMemoryRedeliveryTrackerBenchmark.java) and [reproduction commands](https://github.com/void-ptr974/pulsar/blob/ab6ff644bfc1896c1b7843cfb5244582866b01fc/microbench/README.md#redelivery-tracker) in the PR.
I compared the earlier ReentrantReadWriteLock implementation at ffc22043 with the StampedLock read-lock implementation now committed. The benchmark and tracker sources match the measured variants. Runs used JMH 1.37, OpenJDK 21.0.12.1, fastutil 8.5.19, Linux x86_64 / Xeon E5-2673 v4, generational ZGC and a 512 MiB heap. Each configuration used 2 JVM forks, 3 x 1 s warmup and 5 x 1 s measurement iterations, with -prof gc and affinity CPUs 0-7.
Throughput in million operations/s, mean +/- JMH reported 99.9% error:
| Workload | Threads | ReentrantReadWriteLock | StampedLock read lock |
| --- | ---: | ---: | ---: |
| Empty tracker, read only | 1 | 50.72 +/- 0.63 | 49.91 +/- 1.78 |
| Populated tracker, read hits | 1 | 39.97 +/- 0.36 | 45.88 +/- 2.92 |
| Empty tracker, read only | 8 | 3.36 +/- 0.33 | 9.52 +/- 4.80 |
| Populated tracker, read hits | 8 | 4.04 +/- 0.98 | 5.75 +/- 0.14 |
| Existing positions, 1% increments | 8 | 4.35 +/- 0.53 | 11.79 +/- 0.45 |
| Existing positions, 10% increments | 8 | 2.63 +/- 0.11 | 5.39 +/- 0.46 |
| Empty tracker, ACK batch size 1 | 8 | 4.25 +/- 0.09 | 9.07 +/- 1.21 |
| Empty tracker, ACK batch size 100 | 8 | 4.39 +/- 2.02 | 17.75 +/- 1.16 |
The single-thread empty lookup is effectively tied. The six 8-thread configurations favor StampedLock in this run, although some error intervals are wide, particularly the empty-read case.
The allocation results help explain the difference: the 8-thread read-only workloads allocated 78.78 B/op (empty) and 79.22 B/op (hit) with ReentrantReadWriteLock, versus 0.0020 and 0.0031 B/op with StampedLock. A separate JFR allocation run attributed 924 of 929 samples to the tracker read-lock path: 634 ThreadLocalMap.Entry samples and 290 ReentrantReadWriteLock.Sync.HoldCounter samples.
This is consistent with [RRWL read-hold accounting](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java#L392-L528): readers outside the firstReader fast path use per-thread hold counters, and the last release removes the ThreadLocal entry. Later acquisitions can allocate entries and counters again. The [StampedLock read fast path](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/util/concurrent/locks/StampedLock.java#L525-L533) updates shared reader state without that reentrancy bookkeeping; this lookup does not need reentrancy. Both locks can still contend and block. The sampled stacks identify an extra allocation path, but do not establish how much of the throughput difference comes from GC. I did not measure retained bytes per dispatcher.
For correctness, both fixed implementations hold a real read lock across the entire lookup, excluding structural changes made under the write lock. In three fresh JVMs per implementation, the four existing concurrent regression cases passed 12/12 with each fix; the original optimistic implementation failed 7/12 executions with ArrayIndexOutOfBoundsException. Passing these runs supports the fix; the locking relationship is the correctness argument.
All benchmark threads share one tracker. Populated states contain 4,096 positions over 16 ledgers. Mixed writes increment existing positions without resizing. The ACK workload performs N lookups followed by one removeBatch of N preallocated positions on an empty tracker; one measured operation is a lookup or a batch ACK, so comparisons use the same batch size.
CPUs were pinned but not reserved exclusively, and frequency settings were not controlled. These steady-state microbenchmarks do not measure real removals, map resizing, writer wait time/fairness, broker throughput or P99 latency. The benchmark is included so the trade-off can be reproduced; the results above are summaries of the local runs.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
Posted by "void-ptr974 (via GitHub)" <gi...@apache.org>.
void-ptr974 commented on code in PR #27064:
URL: https://github.com/apache/pulsar/pull/27064#discussion_r4365743602
##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/InMemoryRedeliveryTracker.java:
##########
@@ -23,49 +23,44 @@
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.List;
-import java.util.concurrent.locks.StampedLock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.bookkeeper.mledger.Position;
public class InMemoryRedeliveryTracker implements RedeliveryTracker {
// ledgerId -> entryId -> count
private Long2ObjectMap<Long2IntMap> trackerCache = new Long2ObjectOpenHashMap<>();
- private final StampedLock rwLock = new StampedLock();
+ private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
Review Comment:
Thanks, agreed. Updated in [ab6ff644](https://github.com/void-ptr974/pulsar/commit/ab6ff644bfc1896c1b7843cfb5244582866b01fc) to keep `StampedLock` and use `readLock()` for the full lookup. JMH and reproduction instructions are included.
I have added the performance comparison data and analysis to the [PR description](https://github.com/apache/pulsar/pull/27064).
The local results support this choice: single-thread empty reads were essentially tied; across the tested 8-thread workloads, StampedLock's mean throughput was roughly 1.4-4.0x that of RRWL. Read-only allocation fell from ~79 B/op to <0.004 B/op. JFR traced the extra RRWL allocation to per-thread read-hold bookkeeping; reentrancy is not needed here.
Both fixes passed the concurrent regressions. These are local microbenchmark results, not broker throughput estimates.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
Posted by "lhotari (via GitHub) via commits" <co...@pulsar.apache.org>.
lhotari merged PR #27064:
URL: https://github.com/apache/pulsar/pull/27064
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
Posted by "codelipenghui (via GitHub)" <gi...@apache.org>.
codelipenghui commented on code in PR #27064:
URL: https://github.com/apache/pulsar/pull/27064#discussion_r4361913416
##########
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/InMemoryRedeliveryTrackerTest.java:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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.pulsar.broker.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.PositionFactory;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class InMemoryRedeliveryTrackerTest {
+
+ @DataProvider(name = "firstKey")
+ public Object[][] firstKey() {
+ // Cover both fastutil's special zero-key slot and its regular hash lookup path.
+ return new Object[][] {{0L}, {1L}};
+ }
+
+ @Test(dataProvider = "firstKey", timeOut = 30000)
Review Comment:
FYI: I confirmed this test catches the bug. Run against the previous implementation, this case failed on the first run with `java.lang.ArrayIndexOutOfBoundsException: Index 64 out of bounds for length 33` (from `Long2IntOpenHashMap.get` in the optimistic lookup). With this PR, all four cases pass.
##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/InMemoryRedeliveryTracker.java:
##########
@@ -23,49 +23,44 @@
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.List;
-import java.util.concurrent.locks.StampedLock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.bookkeeper.mledger.Position;
public class InMemoryRedeliveryTracker implements RedeliveryTracker {
// ledgerId -> entryId -> count
private Long2ObjectMap<Long2IntMap> trackerCache = new Long2ObjectOpenHashMap<>();
- private final StampedLock rwLock = new StampedLock();
+ private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
Review Comment:
Non-blocking suggestion: the race is only in the optimistic block of `getRedeliveryCount()`; the writers already took `StampedLock.writeLock()`. Could we keep `StampedLock` and change just that method?
```java
public int getRedeliveryCount(long ledgerId, long entryId) {
long stamp = rwLock.readLock();
try {
Long2IntMap entryMap = trackerCache.get(ledgerId);
return entryMap != null ? entryMap.get(entryId) : 0;
} finally {
rwLock.unlockRead(stamp);
}
}
```
That keeps the change to one method. It also matters a little on this path, since it runs once per dispatched entry on the consumer's event loop: `StampedLock.readLock()`/`unlockRead()` is a single CAS each. `ReentrantReadWriteLock` adds per-thread read-hold tracking: overlapping readers go through `readHolds` ThreadLocal set/remove, which allocates. It also keeps the smaller per-dispatcher footprint from #23640. I haven't benchmarked the difference, so feel free to keep the current version.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
Posted by "void-ptr974 (via GitHub)" <gi...@apache.org>.
void-ptr974 commented on code in PR #27064:
URL: https://github.com/apache/pulsar/pull/27064#discussion_r4365743602
##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/InMemoryRedeliveryTracker.java:
##########
@@ -23,49 +23,44 @@
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.List;
-import java.util.concurrent.locks.StampedLock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.bookkeeper.mledger.Position;
public class InMemoryRedeliveryTracker implements RedeliveryTracker {
// ledgerId -> entryId -> count
private Long2ObjectMap<Long2IntMap> trackerCache = new Long2ObjectOpenHashMap<>();
- private final StampedLock rwLock = new StampedLock();
+ private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
Review Comment:
Thanks, agreed. Updated in [ab6ff644](https://github.com/void-ptr974/pulsar/commit/ab6ff644bfc1896c1b7843cfb5244582866b01fc) to keep `StampedLock` and use `readLock()` for the full lookup. JMH and reproduction instructions are included.
The local results support this choice: single-thread empty reads were essentially tied; across the tested 8-thread workloads, StampedLock's mean throughput was roughly 1.4-4.0x that of RRWL. Read-only allocation fell from ~79 B/op to <0.004 B/op. JFR traced the extra RRWL allocation to per-thread read-hold bookkeeping; reentrancy is not needed here.
Both fixes passed the concurrent regressions. These are local microbenchmark results, not broker throughput estimates.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][broker] Fix message dispatch failures caused by ArrayIndexOutOfBoundsException in InMemoryRedeliveryTracker [pulsar]
Posted by "lhotari (via GitHub) via commits" <co...@pulsar.apache.org>.
lhotari commented on PR #27064:
URL: https://github.com/apache/pulsar/pull/27064#issuecomment-6980493568
btw. this particular details was discussed already as part of the review of the PR that introduced the issue: https://github.com/apache/pulsar/pull/23640/changes#r1858986420
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org