From 10ebfed73d2d179fd167db6647ae49d9550a40e1 Mon Sep 17 00:00:00 2001 From: Volodymyr Babak Date: Thu, 17 Sep 2026 18:52:53 +0300 Subject: [PATCH 1/3] fix: address review - same-node replacement, disconnect side effects, zombie removal Follow-ups from review of the activity-state guard: 1. The guard only covered a reconnect landing on a different node. If the replacement lands on this node while the stale callback is still tearing its own session down, isOwnedByAnotherNode sees this node's own service id and the stale active=false is written anyway - the exact state the guard exists to prevent. Add the local-session check, matching the eviction guard which already tests for a newer local session. 2. LAST_DISCONNECT_TIME and the DISCONNECT_EVENT push ran unconditionally. The timestamp would contradict the live session's lastConnectTime, and the event payload is {"active": false, ...} with SERVER_SCOPE in its metadata - exactly what a Save Attributes node persists, so a rule chain wiring Disconnect Event to Save Attributes writes active=false straight back and re-creates the dropped-event behaviour through the rule engine. Both now sit inside the same guard. scheduleDisconnectNotification stays outside: it re-verifies liveness itself before firing. 3. The eviction guard only checked cache ownership, so a replacement on this node would have its claim evicted by the stale callback. It now also requires that no live session holds the edge. 4. cleanupZombieSessions removed by edge id unconditionally after destroy(), which is not instantaneous. If the edge reconnected in that gap the live session was dropped from 'sessions' while remaining in 'sessionsById', so it was never torn down but every downlink lookup silently no-opped. Use a compare-and-remove. removeFunc becomes a Consumer, since its return value was already discarded. 5. Document that the guard narrows rather than closes the race - the attribute is last-writer-wins across nodes - and that the dead-owner fallback does not cover a node restarting under the same service id. Tests: cover the same-node replacement, the DISCONNECT_EVENT suppression and its positive counterpart, and pin the onEdgeConnect ownership publish order with an InOrder assertion, which nothing held before. The rule-engine stubs in the suppression tests are lenient on purpose: without them the push could never fire and the never() assertions would pass vacuously. --- .../service/edge/rpc/EdgeGrpcService.java | 45 ++++--- .../service/edge/rpc/EdgeGrpcServiceTest.java | 115 ++++++++++++++++++ 2 files changed, 144 insertions(+), 16 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 0c9a4fa21d..e650bc5f42 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -76,7 +76,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; -import java.util.function.Function; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; @@ -545,16 +544,22 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i destroySession(toRemove); sessionsById.remove(sessionId); TenantId tenantId = toRemove.getEdge().getTenantId(); - // A newer session on another node may have already claimed this edge and set active=true. - // Clearing the flag here would leave the edge marked inactive while it is in fact connected, - // which silently drops every downlink event that is not queued for offline edges. - // When ownership is unknown (no cache entry) fall through and persist the inactive state. - if (!isOwnedByAnotherNode(edgeId)) { + // The edge may already have been claimed by a newer session - on this node (a replacement that + // landed while this stale callback was tearing its own session down) or on another live node. + // Either way the edge is connected, so none of the disconnect side effects apply: + // - clearing the flag makes saveEdgeEvent drop assignment events until a full sync; + // - a newer lastDisconnectTime would contradict the live session's lastConnectTime; + // - the DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE in the metadata, + // so a rule chain wiring Disconnect Event -> Save Attributes writes active=false straight + // back, re-creating the dropped-event behaviour through the rule engine. + // Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline + // edge is always marked inactive. + if (!sessions.containsKey(edgeId) && !isOwnedByAnotherNode(edgeId)) { save(tenantId, edgeId, ACTIVITY_STATE, false); + long lastDisconnectTs = System.currentTimeMillis(); + save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); + pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); } - long lastDisconnectTs = System.currentTimeMillis(); - save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); cancelScheduleEdgeEventsCheck(edgeId); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -570,10 +575,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - // Only evict if the cache still points at this node. If the edge already reconnected to another - // TB-Core node, that node has overwritten the entry and owns it - evicting here would wipe the live - // owner's claim and defeat the activity-state guard above. - if (isOwnedByThisNode(edgeId)) { + // Only evict if no live session holds this edge on this node any more and the cache still points + // here. If the edge already reconnected - to this node or to another one - that session owns the + // entry, and evicting it would wipe the live owner's claim and defeat the activity-state guard above. + if (!sessions.containsKey(edgeId) && isOwnedByThisNode(edgeId)) { edgeIdServiceIdCache.evict(edgeId); } } @@ -585,6 +590,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // - entry naming a node that is no longer in the cluster: the edge sessions cache has no TTL by default // (CACHE_SPECS_EDGE_SESSIONS_TTL=0) and is only ever evicted by the owning node, so a node that died // without evicting would otherwise keep the edge marked active forever, with no reconciler to correct it. + // Note this covers a node that is gone, not one that restarted under the same service id - that claim + // still resolves as live, leaving the edge marked active until something reconnects. That errs towards + // queueing edge events rather than dropping them, which is the safe direction. + // This narrows the race rather than closing it: the attribute is plain last-writer-wins, and two nodes can + // still issue their async writes in an order this read cannot see. private boolean isOwnedByAnotherNode(EdgeId edgeId) { TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); if (wrapper == null) { @@ -722,7 +732,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); + // Compare-and-remove: destroy() above is not instantaneous, so the edge may have reconnected and + // put a live session under this id in the meantime. Removing it unconditionally would leave a + // connected edge with no entry in 'sessions', silently no-opping every downlink lookup. + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { @@ -751,11 +764,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return result; } - private void tryToDestroyZombieSessions(List sessionsToRemove, Function removeFunc) { + private void tryToDestroyZombieSessions(List sessionsToRemove, Consumer removeFunc) { for (EdgeGrpcSession toRemove : sessionsToRemove) { log.info("[{}] Destroying session for edge because edge is not connected", toRemove.getEdge().getId()); if (toRemove.destroy()) { - removeFunc.apply(toRemove); + removeFunc.accept(toRemove); } } } diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 7b71c65c9f..512e5cf283 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatcher; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -29,19 +30,31 @@ import org.thingsboard.server.cache.TbTransactionalCache; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import java.util.Set; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -73,6 +86,15 @@ public class EdgeGrpcServiceTest { @Mock private EdgeContextComponent ctx; + @Mock + private NotificationRuleProcessor ruleProcessor; + + @Mock + private EdgeEventStorageSettings edgeEventStorageSettings; + + @Mock + private ScheduledExecutorService edgeEventProcessingExecutorService; + @InjectMocks private EdgeGrpcService edgeGrpcService; @@ -165,6 +187,82 @@ public class EdgeGrpcServiceTest { verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); } + @Test + public void givenSessionReplacedOnThisNodeAfterRemoval_whenStaleCallbackRuns_thenNoDisconnectSideEffects() { + // The stale callback wins the compare-and-remove, then tearing its own session down takes a while + // (for the Kafka session this stops a consumer). The edge reconnects to THIS node in that gap, so the + // ownership cache legitimately names us and isOwnedByAnotherNode cannot help. None of the disconnect + // side effects may run: not the flag, not the timestamp, not the DISCONNECT_EVENT push. + UUID sessionId = UUID.randomUUID(); + EdgeGrpcSession stale = mock(EdgeGrpcSession.class); + when(stale.getSessionId()).thenReturn(sessionId); + when(stale.getEdge()).thenReturn(edge); + when(stale.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, mock(EdgeGrpcSession.class)); + return true; + }); + lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + sessions().put(edgeId, stale); + + onEdgeDisconnect(sessionId); + + verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); + verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenDisconnectEventNotPushed() { + // The DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE, so a rule chain wiring + // Disconnect Event -> Save Attributes would persist active=false back and re-create the bug. + EdgeSessionStub stub = registerSession(); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); + when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE)); + lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + + onEdgeDisconnect(stub.sessionId()); + + verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); + } + + @Test + public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenDisconnectEventPushed() { + // Also proves the never() assertions above are not vacuous: the push does happen on this path. + EdgeSessionStub stub = registerSession(); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + + onEdgeDisconnect(stub.sessionId()); + + verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); + } + + // --- onEdgeConnect ownership publish order --- + + @Test + public void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() { + // Load-bearing ordering: the previous node's onEdgeDisconnect reads this cache entry to decide whether + // to clear the flag, so the claim must be visible before active=true is written. Nothing else pins the + // order, and a tidy-up that groups the save(...) calls together would silently restore the race. + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + when(session.getSessionId()).thenReturn(UUID.randomUUID()); + when(session.getEdge()).thenReturn(edge); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + when(ctx.getEdgeEventStorageSettings()).thenReturn(edgeEventStorageSettings); + ReflectionTestUtils.setField(edgeGrpcService, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); + when(edgeEventProcessingExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) + .thenAnswer(invocation -> mock(ScheduledFuture.class)); + + ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, session); + + InOrder inOrder = inOrder(edgeIdServiceIdCache, tsSubService); + inOrder.verify(edgeIdServiceIdCache).put(edgeId, THIS_NODE); + inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite())); + } + // --- service-id cache eviction guard --- @Test @@ -198,6 +296,23 @@ public class EdgeGrpcServiceTest { ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId); } + private EdgeSessionStub registerSession() { + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + return new EdgeSessionStub(sessionId); + } + + private record EdgeSessionStub(UUID sessionId) { + } + + private ArgumentMatcher activeStateWrite() { + return request -> request != null + && edgeId.equals(request.getEntityId()) + && request.getEntries().stream().anyMatch(entry -> + ACTIVITY_STATE.equals(entry.getKey()) + && Boolean.TRUE.equals(entry.getBooleanValue().orElse(null))); + } + private EdgeGrpcSession sessionFor(UUID sessionId) { EdgeGrpcSession session = mock(EdgeGrpcSession.class); when(session.getSessionId()).thenReturn(sessionId); From 13f3a197b6691a079d68cdec8c3654581f29b2a5 Mon Sep 17 00:00:00 2001 From: Volodymyr Babak Date: Thu, 24 Sep 2026 17:08:27 +0300 Subject: [PATCH 2/3] fix: do not cancel a replacement session's edge event check on stale disconnect Addresses review feedback on the activity-state guard: - sessionEdgeEventChecks is keyed by edgeId, so a stale disconnect callback cancelled the check scheduled by the session that replaced it. The loop only reschedules from inside the task, so the connected edge stopped receiving downlinks with nothing to restart it. Cancel only when no live session holds the edge on this node. - Document that the EDGE_CONNECTION notification is raised from inside pushRuleEngineMessage on this branch and is therefore suppressed together with the DISCONNECT_EVENT. - Pin the LAST_DISCONNECT_TIME write and the zombie compare-and-remove with tests, both of which were previously unguarded by the suite. --- .../service/edge/rpc/EdgeGrpcService.java | 19 +++- .../service/edge/rpc/EdgeGrpcServiceTest.java | 107 ++++++++++++++++++ 2 files changed, 123 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index e650bc5f42..440c4f4106 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -551,16 +551,29 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // - a newer lastDisconnectTime would contradict the live session's lastConnectTime; // - the DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE in the metadata, // so a rule chain wiring Disconnect Event -> Save Attributes writes active=false straight - // back, re-creating the dropped-event behaviour through the rule engine. + // back, re-creating the dropped-event behaviour through the rule engine; + // - on this branch the EDGE_CONNECTION (disconnected) notification is raised from inside + // pushRuleEngineMessage, so it is suppressed together with the event. That is the point: a + // connected edge must not produce a 'disconnected' notification, and this branch has no + // delayed re-verify to withdraw one after the fact. // Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline // edge is always marked inactive. - if (!sessions.containsKey(edgeId) && !isOwnedByAnotherNode(edgeId)) { + boolean replacedOnThisNode = sessions.containsKey(edgeId); + if (!replacedOnThisNode && !isOwnedByAnotherNode(edgeId)) { save(tenantId, edgeId, ACTIVITY_STATE, false); long lastDisconnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); } - cancelScheduleEdgeEventsCheck(edgeId); + // sessionEdgeEventChecks is keyed by edgeId, not by session, so a replacement that landed on this + // node while this stale callback was running has already scheduled its check under the same key. + // Cancelling it here would leave the live session with no check loop - the loop only reschedules + // itself from inside the task, so a cancelled task never runs again - and downlinks would stall + // silently until the edge reconnects. When the edge is owned by another node there is nothing live + // to protect: the check is node-local and belongs to the session we just tore down. + if (!replacedOnThisNode) { + cancelScheduleEdgeEventsCheck(edgeId); + } } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); EdgeGrpcSession stale = sessionsById.remove(sessionId); diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 512e5cf283..154112ab55 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -35,6 +35,10 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; +import org.thingsboard.server.queue.TbQueueConsumer; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.edge.EdgeContextComponent; @@ -50,6 +54,7 @@ import java.util.concurrent.ConcurrentMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.argThat; @@ -61,6 +66,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; +import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_DISCONNECT_TIME; @ExtendWith(MockitoExtension.class) public class EdgeGrpcServiceTest { @@ -125,6 +131,7 @@ public class EdgeGrpcServiceTest { onEdgeDisconnect(sessionId); verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); + verify(tsSubService, never()).saveAttributes(argThat(lastDisconnectTimeWrite())); } @Test @@ -137,6 +144,7 @@ public class EdgeGrpcServiceTest { onEdgeDisconnect(sessionId); verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); + verify(tsSubService, times(1)).saveAttributes(argThat(lastDisconnectTimeWrite())); } @Test @@ -207,6 +215,7 @@ public class EdgeGrpcServiceTest { onEdgeDisconnect(sessionId); verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); + verify(tsSubService, never()).saveAttributes(argThat(lastDisconnectTimeWrite())); verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); verify(edgeIdServiceIdCache, never()).evict(edgeId); } @@ -239,6 +248,93 @@ public class EdgeGrpcServiceTest { verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); } + @Test + public void givenSessionReplacedOnThisNode_whenStaleCallbackRuns_thenReplacementEdgeEventsCheckNotCancelled() { + // sessionEdgeEventChecks is keyed by edgeId, not by session, so the replacement's check sits under the + // same key as the one this callback is tearing down. The check loop only reschedules itself from inside + // the task, so cancelling it here would leave a connected edge with nothing to restart downlink + // delivery - the same silent stall this guard exists to prevent. + UUID sessionId = UUID.randomUUID(); + EdgeGrpcSession stale = mock(EdgeGrpcSession.class); + when(stale.getSessionId()).thenReturn(sessionId); + when(stale.getEdge()).thenReturn(edge); + ScheduledFuture replacementCheck = mock(ScheduledFuture.class); + when(stale.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, mock(EdgeGrpcSession.class)); + sessionEdgeEventChecks().put(edgeId, replacementCheck); + return true; + }); + sessions().put(edgeId, stale); + + onEdgeDisconnect(sessionId); + + verify(replacementCheck, never()).cancel(anyBoolean()); + assertThat(sessionEdgeEventChecks()).containsEntry(edgeId, replacementCheck); + } + + @Test + public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenEdgeEventsCheckCancelled() { + // Counterpart to the test above: proves the cancel still runs on a real disconnect, so the guard is + // not simply disabling it. + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + ScheduledFuture check = mock(ScheduledFuture.class); + sessionEdgeEventChecks().put(edgeId, check); + + onEdgeDisconnect(sessionId); + + verify(check, times(1)).cancel(anyBoolean()); + assertThat(sessionEdgeEventChecks()).doesNotContainKey(edgeId); + } + + // --- zombie session cleanup --- + + @Test + @SuppressWarnings("unchecked") + public void givenZombieSessionReplacedDuringDestroy_whenCleanupRuns_thenReplacementKept() { + // destroy() stops a Kafka consumer and is not instantaneous. If the edge reconnects in that gap, an + // unconditional sessions.remove(edgeId) would drop the live session, leaving a connected edge with no + // map entry - every downlink lookup then silently no-ops. + KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class); + when(zombie.getEdge()).thenReturn(edge); + when(zombie.isConnected()).thenReturn(false); + QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); + TbQueueConsumer> consumer = mock(TbQueueConsumer.class); + when(consumer.isStopped()).thenReturn(false); + when(consumerManager.getConsumer()).thenReturn(consumer); + when(zombie.getConsumer()).thenReturn(consumerManager); + EdgeGrpcSession replacement = mock(EdgeGrpcSession.class); + when(zombie.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, replacement); + return true; + }); + sessions().put(edgeId, zombie); + + ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions"); + + assertThat(sessions()).containsEntry(edgeId, replacement); + } + + @Test + @SuppressWarnings("unchecked") + public void givenZombieSessionStillCurrent_whenCleanupRuns_thenItIsRemoved() { + // Counterpart: with no replacement, the compare-and-remove must still drop the zombie. + KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class); + when(zombie.getEdge()).thenReturn(edge); + when(zombie.isConnected()).thenReturn(false); + QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); + TbQueueConsumer> consumer = mock(TbQueueConsumer.class); + when(consumer.isStopped()).thenReturn(false); + when(consumerManager.getConsumer()).thenReturn(consumer); + when(zombie.getConsumer()).thenReturn(consumerManager); + when(zombie.destroy()).thenReturn(true); + sessions().put(edgeId, zombie); + + ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions"); + + assertThat(sessions()).doesNotContainKey(edgeId); + } + // --- onEdgeConnect ownership publish order --- @Test @@ -325,6 +421,11 @@ public class EdgeGrpcServiceTest { return (ConcurrentMap) ReflectionTestUtils.getField(edgeGrpcService, "sessions"); } + @SuppressWarnings("unchecked") + private ConcurrentMap> sessionEdgeEventChecks() { + return (ConcurrentMap>) ReflectionTestUtils.getField(edgeGrpcService, "sessionEdgeEventChecks"); + } + private ArgumentMatcher inactiveStateWrite() { return request -> request != null && edgeId.equals(request.getEntityId()) @@ -333,4 +434,10 @@ public class EdgeGrpcServiceTest { && Boolean.FALSE.equals(entry.getBooleanValue().orElse(null))); } + private ArgumentMatcher lastDisconnectTimeWrite() { + return request -> request != null + && edgeId.equals(request.getEntityId()) + && request.getEntries().stream().anyMatch(entry -> LAST_DISCONNECT_TIME.equals(entry.getKey())); + } + } From 8fb852c04d852026be00568ec5fd786305ee11a0 Mon Sep 17 00:00:00 2001 From: Volodymyr Babak Date: Fri, 25 Sep 2026 09:22:07 +0300 Subject: [PATCH 3/3] chore: use SPDX license header in EdgeGrpcServiceTest --- .../service/edge/rpc/EdgeGrpcServiceTest.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 154112ab55..9ee8632f45 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed 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. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc; import org.junit.jupiter.api.BeforeEach;