CQC with setPopulate(false) incorrectly configures NonStopPublisherAccumulator [INBOX-1231]
Here is a sample that shows the problem at hand:
class QueryCacheBooleanLatencyReproducerTest {
private static final String CLUSTER_NAME = "boolean-reproducer";
private static final String MAP_NAME = "BOOLEAN_EVENTS";
private static final String CQC_NAME = "BOOLEAN_EVENTS_CQC";
private static final int EVENT_COUNT = 1_000;
private static final int UPDATE_COUNT = 250;
private HazelcastInstance member;
private HazelcastInstance client;
@AfterEach
void tearDown() {
client.shutdown();
member.shutdown();
}
@Test
void measureQueryCacheListenerLatency() throws Exception {
member = Hazelcast.newHazelcastInstance(memberConfig());
client = HazelcastClient.newHazelcastClient(clientConfig(member));
IMap<Long, TestEvent> eventsMap = client.getMap(MAP_NAME);
populateInitialEvents(eventsMap);
ListenerStats listenerStats = new ListenerStats();
QueryCache<Long, TestEvent> queryCache = eventsMap.getQueryCache(
CQC_NAME,
new CountingListener(listenerStats),
equal("enabled", true),
true
);
System.out.printf(
"Initial mapSize=%d queryCacheSize=%d eventCount=%d updateCount=%d%n",
eventsMap.size(),
queryCache.size(),
EVENT_COUNT,
UPDATE_COUNT
);
runMeasuredUpdates(eventsMap, queryCache, listenerStats);
}
private static void runMeasuredUpdates(
IMap<Long, TestEvent> eventsMap,
QueryCache<Long, TestEvent> queryCache,
ListenerStats listenerStats
) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(UPDATE_COUNT);
listenerStats.startPhase(latch);
for (long eventId = 0; eventId < UPDATE_COUNT; eventId++) {
eventsMap.put(eventId, new TestEvent(true, currentTimeMillis()));
}
assertTrue(latch.await(30, SECONDS));
assertEquals(UPDATE_COUNT, queryCache.size());
System.out.printf(
"listenerEvents=%d avg=%d ms%n",
listenerStats.eventCount(),
listenerStats.averageLatencyMillis()
);
}
private static Config memberConfig() {
return new Config()
.setClusterName(CLUSTER_NAME);
}
private static ClientConfig clientConfig(HazelcastInstance member) {
int memberPort = member.getCluster().getLocalMember().getAddress().getPort();
ClientConfig clientConfig = new ClientConfig()
.setClusterName(CLUSTER_NAME);
clientConfig.getNetworkConfig().addAddress("127.0.0.1:" + memberPort);
clientConfig.setQueryCacheConfigs(Map.of(MAP_NAME, Map.of(CQC_NAME, queryCacheConfig())));
return clientConfig;
}
private static QueryCacheConfig queryCacheConfig() {
return new QueryCacheConfig(CQC_NAME)
.setPopulate(true)
.setBatchSize(1)
.setInMemoryFormat(InMemoryFormat.OBJECT)
.setBufferSize(2_048)
.setDelaySeconds(0)
.setEvictionConfig(new EvictionConfig()
.setSize(1_000)
.setMaxSizePolicy(ENTRY_COUNT)
.setEvictionPolicy(LRU));
}
private static void populateInitialEvents(IMap<Long, TestEvent> eventsMap) {
for (long eventId = 0; eventId < EVENT_COUNT; eventId++) {
eventsMap.put(eventId, new TestEvent(false, currentTimeMillis()));
}
}
private record CountingListener(ListenerStats listenerStats) implements
EntryAddedListener<Long, TestEvent>,
EntryUpdatedListener<Long, TestEvent>,
EntryRemovedListener<Long, TestEvent> {
@Override
public void entryAdded(EntryEvent<Long, TestEvent> event) {
listenerStats.record(event);
}
@Override
public void entryUpdated(EntryEvent<Long, TestEvent> event) {
listenerStats.record(event);
}
@Override
public void entryRemoved(EntryEvent<Long, TestEvent> event) {
listenerStats.record(event);
}
}
private static final class ListenerStats {
private final LongAdder eventCount = new LongAdder();
private final LongAdder totalLatencyMillis = new LongAdder();
private CountDownLatch latch;
synchronized void startPhase(CountDownLatch latch) {
this.latch = latch;
eventCount.reset();
totalLatencyMillis.reset();
}
void record(EntryEvent<Long, TestEvent> event) {
TestEvent eventValue = event.getValue() != null ? event.getValue() : event.getOldValue();
totalLatencyMillis.add(currentTimeMillis() - eventValue.updatedAt());
eventCount.increment();
latch.countDown();
}
long eventCount() {
return eventCount.sum();
}
long averageLatencyMillis() {
long count = eventCount();
if (count == 0) {
return 0;
}
return totalLatencyMillis.sum() / count;
}
}
private record TestEvent(boolean enabled, long updatedAt) implements Serializable {}
}
The idea of the test is rather simple:
- something put in an iMap (
TestEventin our case ) - CQC exists on that iMap ( with Predicate that uses
TestEvent::enabledand.setPopulate(false)) - track how much time it takes for the CQC to actually see the event in the CQC listeners.
with setPopulate(false) the results are in the seconds territory, with .setPopulate(true) its in the milliseconds territory.
After a few days of heapdumps / JFRs / profiling, I ended up realizing that this is actually a bug in the codebase. I'll try to explain the issue:
We need to look at : ClientQueryCacheEndToEndConstructor::createPublisherAccumulator:
if (info.isPopulate()) {
madePublishable(info.getMapName(), info.getCacheId(), urgent);
info.setPublishable(true);
}What this means, in plain english:
if populate=true:
create publisher on members
receive initial snapshot
prepopulate client QueryCache
tell members: "now you may publish live eventson the other hand:
if populate=false:
create publisher on members
receive empty/no snapshot
prepopulate nothing
DO NOT tell members: "now you may publish live events"that last line is the issue, it basically leaves: info::publishable to remain false.
On the member side, the request is handled by either:
MapPublisherCreateMessageTask
MapPublisherCreateWithValueMessageTaskBoth reconstruct a fresh AccumulatorInfo :
AccumulatorInfo.toAccumulatorInfo(..., parameters.populate, parameters.coalesce)And inside AccumulatorInfo both factory methods do:
info.publishable = false;So after the client request reaches the member, the member-side state starts as:
AccumulatorInfo.publishable = falseThen the member runs: PublisherCreateOperation.run() :
if (populate) {
info.setPublishable(false);
}
init();For populate=true , this makes sense: keep it non-publishable while the snapshot is being build.
For populate=false , there is no snapshot, but there is also no setPublishable(true). So that member seems that flag as false forever.
The only thing that normally flips it is: MadePublishableOperation which does: info.setPublishable(true);
But the client only sends MadePublishableOperation when:
if (info.isPopulate()) {
madePublishable(...);
}So with populate=false , the member creates the publisher but never makes it publishable.
Next, we have delaySeconds=0, as such we will be using NonStopPublisherAccumulator which does:
super.accumulate(eventData);
AccumulatorInfo info = getInfo();
if (!info.isPublishable()) {
return;
}
poll(handler, 0, TimeUnit.SECONDS);of course that poll is never hit. So:
event is stored
event is not sent to client immediately
client QueryCache does not update
client QueryCache listener does not fireThen every ~5 seconds this background task runs:
DefaultPublisherContext.startBackgroundAccumulatorScanner() with:
SCAN_PERIOD_SECONDS = 5L;
That scanner finds non-empty accumulators and runs: ConsumeAccumulatorOperation which eventually calls:
accumulator.poll(handler, info.getDelaySeconds(), TimeUnit.SECONDS);
This path does not care that publishable=false , so it drains the buffered events, so they all go the to client at once.
delaySeconds = 1 would not fix the root issue. It changes the accumulator implementation from NonStopPublisherAccumulator to BatchPublisherAccumulator / CoalescingPublisherAccumulator , but those classes still do the same gate:
if (!info.isPublishable()) {
return;
}So with client + populate=false , events would still be buffered and not immediately published.
Source: hazelcast/hazelcast