From 81c154ca5fd228e478b83148f518d53974a634eb Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 22 Jul 2026 15:06:42 +0200 Subject: [PATCH 1/7] actor: add a filtered, priority-aware broadcastToChildren capability TbActorSystem/TbActorCtx already supported broadcasting to a filtered subset of children, and separately broadcasting to all children at a given priority, but not both together. Expose the existing internal implementation (already used for the priority-only case) as a public filtered + prioritized overload, so callers can target a subset of children without giving up delivery priority. --- .../server/actors/DefaultTbActorSystem.java | 3 ++- .../thingsboard/server/actors/TbActorCtx.java | 2 ++ .../server/actors/TbActorMailbox.java | 5 ++++ .../server/actors/TbActorSystem.java | 2 ++ .../server/actors/ActorSystemTest.java | 26 +++++++++++++++++++ 5 files changed, 37 insertions(+), 1 deletion(-) diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java b/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java index e93b649b24..e03c10ec0f 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/DefaultTbActorSystem.java @@ -155,7 +155,8 @@ public class DefaultTbActorSystem implements TbActorSystem { broadcastToChildren(parent, childFilter, msg, false); } - private void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg, boolean highPriority) { + @Override + public void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg, boolean highPriority) { Set children = parentChildMap.get(parent); if (children != null) { children.stream().filter(childFilter).forEach(id -> { diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java index 7e409a3efc..6d7697d8c7 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorCtx.java @@ -29,5 +29,7 @@ public interface TbActorCtx extends TbActorRef { void broadcastToChildren(TbActorMsg msg, Predicate childFilter); + void broadcastToChildren(TbActorMsg msg, Predicate childFilter, boolean highPriority); + List filterChildren(Predicate childFilter); } diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java index 4699eb6891..55f2c6d962 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorMailbox.java @@ -196,6 +196,11 @@ public final class TbActorMailbox implements TbActorCtx { system.broadcastToChildren(selfId, childFilter, msg); } + @Override + public void broadcastToChildren(TbActorMsg msg, Predicate childFilter, boolean highPriority) { + system.broadcastToChildren(selfId, childFilter, msg, highPriority); + } + @Override public List filterChildren(Predicate childFilter) { return system.filterChildren(selfId, childFilter); diff --git a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java index 2787524379..e9f040720d 100644 --- a/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java +++ b/common/actor/src/main/java/org/thingsboard/server/actors/TbActorSystem.java @@ -39,5 +39,7 @@ public interface TbActorSystem { void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg); + void broadcastToChildren(TbActorId parent, Predicate childFilter, TbActorMsg msg, boolean highPriority); + List filterChildren(TbActorId parent, Predicate childFilter); } diff --git a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java index 9dee47f948..e7a6f83fa2 100644 --- a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java +++ b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java @@ -184,6 +184,32 @@ public class ActorSystemTest { Assertions.assertEquals(2, testCtx.getInvocationCount().get()); } + @Test + public void testBroadcastToChildrenWithFilterAndPriority() throws InterruptedException { + executor = ThingsBoardExecutors.newWorkStealingPool(parallelism, getClass()); + actorSystem.createDispatcher(ROOT_DISPATCHER, executor); + + TbActorId parentId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); + ActorTestCtx parentTestCtx = getActorTestCtx(1); + actorSystem.createRootActor(ROOT_DISPATCHER, new TestRootActor.TestRootActorCreator(parentId, parentTestCtx)); + + TbActorId matchingChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); + ActorTestCtx matchingChildCtx = getActorTestCtx(1); + actorSystem.createChildActor(ROOT_DISPATCHER, + new TestRootActor.TestRootActorCreator(matchingChildId, matchingChildCtx), parentId); + + TbActorId otherChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); + ActorTestCtx otherChildCtx = getActorTestCtx(1); + actorSystem.createChildActor(ROOT_DISPATCHER, + new TestRootActor.TestRootActorCreator(otherChildId, otherChildCtx), parentId); + + actorSystem.broadcastToChildren(parentId, id -> id.equals(matchingChildId), new IntTbActorMsg(7), true); + + Assertions.assertTrue(matchingChildCtx.getLatch().await(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS)); + Assertions.assertEquals(7L, matchingChildCtx.getActual().get()); + Assertions.assertFalse(otherChildCtx.getLatch().await(1, TimeUnit.SECONDS)); + } + @Test public void testFailedInit() throws InterruptedException { executor = ThingsBoardExecutors.newWorkStealingPool(parallelism, getClass()); From 1528864968e10f6c8d25fc7dbdea09d86f4c5341 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 22 Jul 2026 15:06:51 +0200 Subject: [PATCH 2/7] msg: let PartitionChangeMsg optionally target specific tenants PartitionChangeMsg only carried the affected ServiceType, so a consumer had no way to know which specific tenants (if any) a given partition change actually affects versus all of them. Add an optional affectedTenants set: null preserves today's meaning ("could affect anyone, notify everyone"), a non-null set means only those tenants are affected. Existing single-arg construction is unchanged and keeps defaulting to null. --- .../common/msg/queue/PartitionChangeMsg.java | 22 ++++++++- .../msg/queue/PartitionChangeMsgTest.java | 47 +++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java diff --git a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java index f5673c6dcb..72550a48cf 100644 --- a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java +++ b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java @@ -3,19 +3,37 @@ package org.thingsboard.server.common.msg.queue; import lombok.Data; -import lombok.Getter; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.MsgType; import org.thingsboard.server.common.msg.TbActorMsg; +import java.util.Set; + /** * @author Andrew Shvayka */ @Data public final class PartitionChangeMsg implements TbActorMsg { - @Getter private final ServiceType serviceType; + /** + * Tenants whose partition ownership changed. Null means the shared + * (non-isolated) tenant pool itself changed, so every tenant actor must + * re-verify — shared-pool tenants aren't individually tracked as + * queueKeys, so they can't be enumerated here. + */ + private final Set affectedTenants; + + public PartitionChangeMsg(ServiceType serviceType) { + this(serviceType, null); + } + + public PartitionChangeMsg(ServiceType serviceType, Set affectedTenants) { + this.serviceType = serviceType; + this.affectedTenants = affectedTenants; + } + @Override public MsgType getMsgType() { return MsgType.PARTITION_CHANGE_MSG; diff --git a/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java new file mode 100644 index 0000000000..6e01879941 --- /dev/null +++ b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java @@ -0,0 +1,47 @@ +/** + * 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. + */ +package org.thingsboard.server.common.msg.queue; + +import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.MsgType; + +import java.util.Set; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class PartitionChangeMsgTest { + + @Test + public void singleArgConstructor_defaultsAffectedTenantsToNull() { + PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE); + + assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType()); + assertNull(msg.getAffectedTenants()); + assertEquals(MsgType.PARTITION_CHANGE_MSG, msg.getMsgType()); + } + + @Test + public void twoArgConstructor_carriesAffectedTenants() { + TenantId tenant = new TenantId(UUID.randomUUID()); + PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant)); + + assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType()); + assertEquals(Set.of(tenant), msg.getAffectedTenants()); + } +} From 1930624e1a2fd510098a5b8df2edb9dd176bdad2 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 22 Jul 2026 15:07:01 +0200 Subject: [PATCH 3/7] rule-engine: broadcast partition changes only to affected tenant actors AppActor.doProcess unconditionally broadcasts PARTITION_CHANGE_MSG to every live TenantActor at high priority, regardless of whether a given tenant's ownership actually changed. On a shared rule-engine instance hosting many tenants, this means any single tenant's partition change (e.g. moving to an isolated queue) interrupts every other tenant's in-flight message processing, even though only one tenant's ownership changed. DefaultActorService now resolves which tenants are actually affected from the partition-change diff it already has on hand (returning null when the shared/non-isolated pool itself changed, since those tenants aren't individually tracked and everyone must still be notified), and AppActor uses that to broadcast only to the affected tenant actors, reusing the existing TbEntityTypeActorIdPredicate filtering idiom. Falls back to the original broadcast-to-everyone behavior whenever the affected set can't be narrowed down. --- .../server/actors/app/AppActor.java | 20 ++++ .../actors/service/DefaultActorService.java | 32 ++++++- .../server/actors/app/AppActorTest.java | 92 +++++++++++++++++++ .../service/DefaultActorServiceTest.java | 64 +++++++++++++ 4 files changed, 207 insertions(+), 1 deletion(-) create mode 100644 application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java create mode 100644 application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java b/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java index 93b94542a0..1b503a37f2 100644 --- a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java @@ -11,6 +11,7 @@ import org.thingsboard.server.actors.TbActorException; import org.thingsboard.server.actors.TbActorId; import org.thingsboard.server.actors.TbActorRef; import org.thingsboard.server.actors.TbEntityActorId; +import org.thingsboard.server.actors.TbEntityTypeActorIdPredicate; import org.thingsboard.server.actors.device.SessionTimeoutCheckMsg; import org.thingsboard.server.actors.service.ContextAwareActor; import org.thingsboard.server.actors.service.ContextBasedCreator; @@ -18,6 +19,7 @@ import org.thingsboard.server.actors.service.DefaultActorService; import org.thingsboard.server.actors.tenant.TenantActor; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantProfileId; import org.thingsboard.server.common.data.page.PageDataIterable; @@ -27,6 +29,7 @@ import org.thingsboard.server.common.msg.TbActorMsg; import org.thingsboard.server.common.msg.ToCalculatedFieldSystemMsg; import org.thingsboard.server.common.msg.aware.TenantAwareMsg; import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg; +import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg; import org.thingsboard.server.common.msg.queue.RuleEngineException; import org.thingsboard.server.common.msg.queue.ServiceType; @@ -75,6 +78,8 @@ public class AppActor extends ContextAwareActor { case APP_INIT_MSG: break; case PARTITION_CHANGE_MSG: + onPartitionChangeMsg((PartitionChangeMsg) msg); + break; case CF_PARTITIONS_CHANGE_MSG: case CF_STATE_PARTITION_RESTORE_MSG: ctx.broadcastToChildren(msg, true); @@ -202,6 +207,21 @@ public class AppActor extends ContextAwareActor { }); } + private void onPartitionChangeMsg(PartitionChangeMsg msg) { + Set affectedTenants = msg.getAffectedTenants(); + log.info("Partition change for {}: notifying {} affected tenant(s)", msg.getServiceType(), affectedTenants == null ? "ALL" : affectedTenants.size()); + if (affectedTenants == null) { + ctx.broadcastToChildren(msg, true); + } else { + ctx.broadcastToChildren(msg, new TbEntityTypeActorIdPredicate(EntityType.TENANT) { + @Override + protected boolean testEntityId(EntityId entityId) { + return super.testEntityId(entityId) && affectedTenants.contains(entityId); + } + }, true); + } + } + private Optional getOrCreateTenantActor(TenantId tenantId) { if (deletedTenants.contains(tenantId)) { return Optional.empty(); diff --git a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java b/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java index 0c42f4406f..18da74075d 100644 --- a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java +++ b/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java @@ -19,14 +19,18 @@ import org.thingsboard.server.actors.TbActorSystemSettings; import org.thingsboard.server.actors.app.AppActor; import org.thingsboard.server.actors.app.AppInitMsg; import org.thingsboard.server.actors.stats.StatsActor; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.queue.discovery.QueueKey; import org.thingsboard.server.queue.discovery.TbApplicationEventListener; import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; import org.thingsboard.server.queue.util.AfterStartUp; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.stream.Collectors; @Service @Slf4j @@ -120,7 +124,33 @@ public class DefaultActorService extends TbApplicationEventListener + * Despite its name, {@link PartitionChangeEvent#getNewPartitions()} carries only the + * changed subset of queue keys — including removed ones, mapped to an empty partition + * set — never the full current assignment. That invariant is what makes this method correct; + * if it ever carried the full assignment instead, every recalculation would resolve to + * "everyone". + *

+ * Returns {@code null} when any changed queue key belongs to the shared (non-isolated) tenant + * pool (a sys-tenant-keyed queue) — that pool's tenants aren't individually tracked as queue + * keys, so they can't be enumerated, and every tenant actor must be notified. Otherwise + * returns the non-empty set of affected tenant IDs. Callers must treat {@code null} as + * "notify everyone", never as "notify nobody" — an empty set would mean the latter, but this + * method never returns one today, since it is only invoked when the diff is non-empty. + */ + static Set resolveAffectedTenants(PartitionChangeEvent event) { + Set changedQueueKeys = event.getNewPartitions().keySet(); + boolean sharedPoolChanged = changedQueueKeys.stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId()); + if (sharedPoolChanged) { + return null; + } + return changedQueueKeys.stream().map(QueueKey::getTenantId).collect(Collectors.toSet()); } @Override diff --git a/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java b/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java new file mode 100644 index 0000000000..8d6fef3995 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java @@ -0,0 +1,92 @@ +/** + * 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. + */ +package org.thingsboard.server.actors.app; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.thingsboard.server.actors.ActorSystemContext; +import org.thingsboard.server.actors.TbActorCtx; +import org.thingsboard.server.actors.TbActorId; +import org.thingsboard.server.actors.TbEntityActorId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.dao.tenant.TenantService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; + +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class AppActorTest { + + AppActor appActor; + TbActorCtx ctx; + TenantId tenant1 = new TenantId(UUID.fromString("11111111-1111-1111-1111-111111111111")); + TenantId tenant2 = new TenantId(UUID.fromString("22222222-2222-2222-2222-222222222222")); + + @Before + public void setUp() throws Exception { + ActorSystemContext systemContext = mock(ActorSystemContext.class); + TenantService tenantService = mock(TenantService.class); + when(systemContext.getTenantService()).thenReturn(tenantService); + when(systemContext.isTenantComponentsInitEnabled()).thenReturn(false); + when(systemContext.getServiceInfoProvider()).thenReturn(mock(TbServiceInfoProvider.class)); + + appActor = (AppActor) new AppActor.ActorCreator(systemContext).createActor(); + ctx = mock(TbActorCtx.class); + appActor.init(ctx); + appActor.doProcess(new AppInitMsg()); + } + + @Test + public void onPartitionChangeMsgWithAffectedTenants_onlyForwardsToThoseTenants() { + PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant1)); + + appActor.doProcess(msg); + + @SuppressWarnings("unchecked") + ArgumentCaptor> filterCaptor = ArgumentCaptor.forClass(Predicate.class); + verify(ctx).broadcastToChildren(eq(msg), filterCaptor.capture(), eq(true)); + Predicate filter = filterCaptor.getValue(); + + assertTrue(filter.test(new TbEntityActorId(tenant1))); + assertFalse(filter.test(new TbEntityActorId(tenant2))); + assertFalse(filter.test(new TbEntityActorId(new DeviceId(UUID.randomUUID())))); + } + + @Test + public void onPartitionChangeMsgWithNullAffectedTenants_broadcastsToEveryone() { + PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE); + + appActor.doProcess(msg); + + verify(ctx).broadcastToChildren(msg, true); + verify(ctx, never()).broadcastToChildren(any(), any(), anyBoolean()); + } +} diff --git a/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java b/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java new file mode 100644 index 0000000000..d4e747defc --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java @@ -0,0 +1,64 @@ +/** + * 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. + */ +package org.thingsboard.server.actors.service; + +import org.junit.Test; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.queue.discovery.QueueKey; +import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class DefaultActorServiceTest { + + @Test + public void resolveAffectedTenants_onlyTenantSpecificQueueKeysChanged_returnsThoseTenants() { + TenantId tenant1 = new TenantId(UUID.randomUUID()); + TenantId tenant2 = new TenantId(UUID.randomUUID()); + QueueKey mainQueueTenant1 = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", tenant1); + QueueKey highPriorityQueueTenant1 = new QueueKey(ServiceType.TB_RULE_ENGINE, "HighPriority", tenant1); + QueueKey mainQueueTenant2 = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", tenant2); + + Map> newPartitions = Map.of( + mainQueueTenant1, Collections.emptySet(), + highPriorityQueueTenant1, Collections.emptySet(), + mainQueueTenant2, Collections.emptySet()); + PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of()); + + Set affected = DefaultActorService.resolveAffectedTenants(event); + + assertEquals(Set.of(tenant1, tenant2), affected); + } + + @Test + public void resolveAffectedTenants_sysTenantQueueKeyChanged_returnsNull() { + QueueKey sharedMainQueue = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", TenantId.SYS_TENANT_ID); + Map> newPartitions = Map.of(sharedMainQueue, Collections.emptySet()); + PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of()); + + Set affected = DefaultActorService.resolveAffectedTenants(event); + + assertNull(affected); + } +} From 65364922cf2fa07bda32412def24da3cd2c06f04 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 11:26:31 +0200 Subject: [PATCH 4/7] rule-engine: address review of targeted partition change broadcast - Resolve affected tenants in PartitionChangeEvent.getAffectedTenants(), returning null (all tenants) for non rule engine events, empty diffs and shared queue changes. - HashPartitionService adds isolated tenants whose managed status changed without a change of their own queue keys. - PartitionChangeMsg: forAllTenants/forTenants factories instead of a null sentinel; affected tenants excluded from toString(). - Fold the AppActor log line into the existing DefaultActorService one. - Tests: priority ordering in ActorSystemTest, AppActorTest on a real actor system, DefaultActorServiceTest through onTbApplicationEvent, the managed-status scenario in HashPartitionServiceTest. --- .../server/actors/app/AppActor.java | 6 +- .../actors/service/DefaultActorService.java | 36 +---- .../server/actors/app/AppActorTest.java | 151 +++++++++++------- .../service/DefaultActorServiceTest.java | 99 +++++++----- .../discovery/HashPartitionServiceTest.java | 36 +++++ .../server/actors/ActorSystemTest.java | 69 ++++++-- .../common/msg/queue/PartitionChangeMsg.java | 36 +++-- .../msg/queue/PartitionChangeMsgTest.java | 56 +++---- .../queue/discovery/HashPartitionService.java | 33 +++- .../discovery/event/PartitionChangeEvent.java | 30 ++++ .../event/PartitionChangeEventTest.java | 88 ++++++++++ .../engine/action/TbDeviceStateNodeTest.java | 2 +- 12 files changed, 451 insertions(+), 191 deletions(-) create mode 100644 common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java diff --git a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java b/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java index 1b503a37f2..994b5dae60 100644 --- a/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java +++ b/application/src/main/java/org/thingsboard/server/actors/app/AppActor.java @@ -208,15 +208,13 @@ public class AppActor extends ContextAwareActor { } private void onPartitionChangeMsg(PartitionChangeMsg msg) { - Set affectedTenants = msg.getAffectedTenants(); - log.info("Partition change for {}: notifying {} affected tenant(s)", msg.getServiceType(), affectedTenants == null ? "ALL" : affectedTenants.size()); - if (affectedTenants == null) { + if (msg.isForAllTenants()) { ctx.broadcastToChildren(msg, true); } else { ctx.broadcastToChildren(msg, new TbEntityTypeActorIdPredicate(EntityType.TENANT) { @Override protected boolean testEntityId(EntityId entityId) { - return super.testEntityId(entityId) && affectedTenants.contains(entityId); + return super.testEntityId(entityId) && msg.isAffected((TenantId) entityId); } }, true); } diff --git a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java b/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java index 18da74075d..e7919db97c 100644 --- a/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java +++ b/application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java @@ -22,7 +22,6 @@ import org.thingsboard.server.actors.stats.StatsActor; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; import org.thingsboard.server.common.msg.queue.ServiceType; -import org.thingsboard.server.queue.discovery.QueueKey; import org.thingsboard.server.queue.discovery.TbApplicationEventListener; import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; import org.thingsboard.server.queue.util.AfterStartUp; @@ -30,7 +29,6 @@ import org.thingsboard.server.queue.util.AfterStartUp; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.stream.Collectors; @Service @Slf4j @@ -123,34 +121,12 @@ public class DefaultActorService extends TbApplicationEventListener - * Despite its name, {@link PartitionChangeEvent#getNewPartitions()} carries only the - * changed subset of queue keys — including removed ones, mapped to an empty partition - * set — never the full current assignment. That invariant is what makes this method correct; - * if it ever carried the full assignment instead, every recalculation would resolve to - * "everyone". - *

- * Returns {@code null} when any changed queue key belongs to the shared (non-isolated) tenant - * pool (a sys-tenant-keyed queue) — that pool's tenants aren't individually tracked as queue - * keys, so they can't be enumerated, and every tenant actor must be notified. Otherwise - * returns the non-empty set of affected tenant IDs. Callers must treat {@code null} as - * "notify everyone", never as "notify nobody" — an empty set would mean the latter, but this - * method never returns one today, since it is only invoked when the diff is non-empty. - */ - static Set resolveAffectedTenants(PartitionChangeEvent event) { - Set changedQueueKeys = event.getNewPartitions().keySet(); - boolean sharedPoolChanged = changedQueueKeys.stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId()); - if (sharedPoolChanged) { - return null; - } - return changedQueueKeys.stream().map(QueueKey::getTenantId).collect(Collectors.toSet()); + ServiceType serviceType = event.getServiceType(); + Set affectedTenants = event.getAffectedTenants(); + log.info("Received partition change event for {}, affected tenants: {}", serviceType, affectedTenants == null ? "all" : affectedTenants.size()); + appActor.tellWithHighPriority(affectedTenants == null ? + PartitionChangeMsg.forAllTenants(serviceType) : + PartitionChangeMsg.forTenants(serviceType, affectedTenants)); } @Override diff --git a/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java b/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java index 8d6fef3995..6d6d0129de 100644 --- a/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/app/AppActorTest.java @@ -1,92 +1,125 @@ -/** - * 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.actors.app; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.thingsboard.server.actors.AbstractTbActor; import org.thingsboard.server.actors.ActorSystemContext; -import org.thingsboard.server.actors.TbActorCtx; +import org.thingsboard.server.actors.DefaultTbActorSystem; +import org.thingsboard.server.actors.TbActor; +import org.thingsboard.server.actors.TbActorCreator; import org.thingsboard.server.actors.TbActorId; +import org.thingsboard.server.actors.TbActorRef; +import org.thingsboard.server.actors.TbActorSystem; +import org.thingsboard.server.actors.TbActorSystemSettings; import org.thingsboard.server.actors.TbEntityActorId; -import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.actors.TbStringActorId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.TbActorMsg; import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.dao.tenant.TenantService; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import java.util.List; import java.util.Set; import java.util.UUID; -import java.util.function.Predicate; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.eq; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class AppActorTest { +class AppActorTest { - AppActor appActor; - TbActorCtx ctx; - TenantId tenant1 = new TenantId(UUID.fromString("11111111-1111-1111-1111-111111111111")); - TenantId tenant2 = new TenantId(UUID.fromString("22222222-2222-2222-2222-222222222222")); + private static final String DISPATCHER = "app-actor-test-dispatcher"; - @Before - public void setUp() throws Exception { + private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID()); + private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID()); + + private ExecutorService executor; + private TbActorSystem system; + private TbActorRef appActor; + private List tenant1Msgs; + private List tenant2Msgs; + private List otherChildMsgs; + + @BeforeEach + void setUp() { ActorSystemContext systemContext = mock(ActorSystemContext.class); - TenantService tenantService = mock(TenantService.class); - when(systemContext.getTenantService()).thenReturn(tenantService); - when(systemContext.isTenantComponentsInitEnabled()).thenReturn(false); + when(systemContext.getTenantService()).thenReturn(mock(TenantService.class)); when(systemContext.getServiceInfoProvider()).thenReturn(mock(TbServiceInfoProvider.class)); + when(systemContext.isTenantComponentsInitEnabled()).thenReturn(false); - appActor = (AppActor) new AppActor.ActorCreator(systemContext).createActor(); - ctx = mock(TbActorCtx.class); - appActor.init(ctx); - appActor.doProcess(new AppInitMsg()); - } + executor = Executors.newSingleThreadExecutor(); + system = new DefaultTbActorSystem(new TbActorSystemSettings(5, 1, 42)); + system.createDispatcher(DISPATCHER, executor); + appActor = system.createRootActor(DISPATCHER, new AppActor.ActorCreator(systemContext)); + appActor.tellWithHighPriority(new AppInitMsg()); - @Test - public void onPartitionChangeMsgWithAffectedTenants_onlyForwardsToThoseTenants() { - PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant1)); + tenant1Msgs = createRecordingChild(new TbEntityActorId(tenant1)); + tenant2Msgs = createRecordingChild(new TbEntityActorId(tenant2)); + otherChildMsgs = createRecordingChild(new TbStringActorId("other")); + } - appActor.doProcess(msg); + @AfterEach + void tearDown() { + system.stop(); + executor.shutdownNow(); + } - @SuppressWarnings("unchecked") - ArgumentCaptor> filterCaptor = ArgumentCaptor.forClass(Predicate.class); - verify(ctx).broadcastToChildren(eq(msg), filterCaptor.capture(), eq(true)); - Predicate filter = filterCaptor.getValue(); + @Test + void msgForTenants_isDeliveredToAffectedTenantActorsOnly() { + PartitionChangeMsg msg = PartitionChangeMsg.forTenants(ServiceType.TB_RULE_ENGINE, Set.of(tenant1)); + appActor.tellWithHighPriority(msg); + // processed by the app actor after msg, so it reaches every child after msg would have + PartitionChangeMsg marker = PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE); + appActor.tellWithHighPriority(marker); - assertTrue(filter.test(new TbEntityActorId(tenant1))); - assertFalse(filter.test(new TbEntityActorId(tenant2))); - assertFalse(filter.test(new TbEntityActorId(new DeviceId(UUID.randomUUID())))); + await().atMost(10, TimeUnit.SECONDS).until(() -> tenant2Msgs.contains(marker) && otherChildMsgs.contains(marker)); + assertThat(tenant1Msgs).containsExactly(msg, marker); + assertThat(tenant2Msgs).containsExactly(marker); + assertThat(otherChildMsgs).containsExactly(marker); } @Test - public void onPartitionChangeMsgWithNullAffectedTenants_broadcastsToEveryone() { - PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE); + void msgForAllTenants_isDeliveredToEveryChild() { + PartitionChangeMsg msg = PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE); + appActor.tellWithHighPriority(msg); - appActor.doProcess(msg); + await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { + assertThat(tenant1Msgs).containsExactly(msg); + assertThat(tenant2Msgs).containsExactly(msg); + assertThat(otherChildMsgs).containsExactly(msg); + }); + } + + private List createRecordingChild(TbActorId actorId) { + List received = new CopyOnWriteArrayList<>(); + system.createChildActor(DISPATCHER, new TbActorCreator() { + @Override + public TbActorId createActorId() { + return actorId; + } - verify(ctx).broadcastToChildren(msg, true); - verify(ctx, never()).broadcastToChildren(any(), any(), anyBoolean()); + @Override + public TbActor createActor() { + return new AbstractTbActor() { + @Override + public boolean process(TbActorMsg msg) { + received.add(msg); + return true; + } + }; + } + }, appActor.getActorId()); + return received; } + } diff --git a/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java b/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java index d4e747defc..f03f4dccf3 100644 --- a/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/service/DefaultActorServiceTest.java @@ -1,24 +1,16 @@ -/** - * 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.actors.service; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.actors.TbActorRef; +import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; import org.thingsboard.server.common.msg.queue.ServiceType; -import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; import org.thingsboard.server.queue.discovery.QueueKey; import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; @@ -27,38 +19,61 @@ import java.util.Map; import java.util.Set; import java.util.UUID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -public class DefaultActorServiceTest { +class DefaultActorServiceTest { + + private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID()); + private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID()); + + private DefaultActorService actorService; + private TbActorRef appActor; + + @BeforeEach + void setUp() { + actorService = new DefaultActorService(); + appActor = mock(TbActorRef.class); + ReflectionTestUtils.setField(actorService, "appActor", appActor); + } @Test - public void resolveAffectedTenants_onlyTenantSpecificQueueKeysChanged_returnsThoseTenants() { - TenantId tenant1 = new TenantId(UUID.randomUUID()); - TenantId tenant2 = new TenantId(UUID.randomUUID()); - QueueKey mainQueueTenant1 = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", tenant1); - QueueKey highPriorityQueueTenant1 = new QueueKey(ServiceType.TB_RULE_ENGINE, "HighPriority", tenant1); - QueueKey mainQueueTenant2 = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", tenant2); - - Map> newPartitions = Map.of( - mainQueueTenant1, Collections.emptySet(), - highPriorityQueueTenant1, Collections.emptySet(), - mainQueueTenant2, Collections.emptySet()); - PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of()); - - Set affected = DefaultActorService.resolveAffectedTenants(event); - - assertEquals(Set.of(tenant1, tenant2), affected); + void isolatedTenantQueueChanged_sendsMsgForAffectedTenantsOnly() { + actorService.onTbApplicationEvent(event(ServiceType.TB_RULE_ENGINE, tenant1)); + + PartitionChangeMsg msg = captureMsg(); + assertThat(msg.getServiceType()).isEqualTo(ServiceType.TB_RULE_ENGINE); + assertThat(msg.isForAllTenants()).isFalse(); + assertThat(msg.isAffected(tenant1)).isTrue(); + assertThat(msg.isAffected(tenant2)).isFalse(); } @Test - public void resolveAffectedTenants_sysTenantQueueKeyChanged_returnsNull() { - QueueKey sharedMainQueue = new QueueKey(ServiceType.TB_RULE_ENGINE, "Main", TenantId.SYS_TENANT_ID); - Map> newPartitions = Map.of(sharedMainQueue, Collections.emptySet()); - PartitionChangeEvent event = new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Map.of()); + void sharedQueueChanged_sendsMsgForAllTenants() { + actorService.onTbApplicationEvent(event(ServiceType.TB_RULE_ENGINE, TenantId.SYS_TENANT_ID)); - Set affected = DefaultActorService.resolveAffectedTenants(event); + assertThat(captureMsg().isForAllTenants()).isTrue(); + } - assertNull(affected); + @Test + void corePartitionsChanged_sendsMsgForAllTenants() { + actorService.onTbApplicationEvent(event(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID)); + + PartitionChangeMsg msg = captureMsg(); + assertThat(msg.getServiceType()).isEqualTo(ServiceType.TB_CORE); + assertThat(msg.isForAllTenants()).isTrue(); + } + + private PartitionChangeEvent event(ServiceType serviceType, TenantId tenantId) { + QueueKey queueKey = new QueueKey(serviceType, DataConstants.MAIN_QUEUE_NAME, tenantId); + return new PartitionChangeEvent(this, serviceType, Map.of(queueKey, Collections.emptySet()), Collections.emptyMap()); } + + private PartitionChangeMsg captureMsg() { + ArgumentCaptor captor = ArgumentCaptor.forClass(PartitionChangeMsg.class); + verify(appActor).tellWithHighPriority(captor.capture()); + return captor.getValue(); + } + } diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java index 0eeb11c0f4..32059096f4 100644 --- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java @@ -369,6 +369,42 @@ public class HashPartitionServiceTest { }); } + @Test + public void testPartitionChangeEvent_includesIsolatedTenantWithChangedManagedStatus() { + ServiceInfo commonRuleEngine = ServiceInfo.newBuilder() + .setServiceId("tb-rule-engine-1") + .addAllServiceTypes(List.of(ServiceType.TB_RULE_ENGINE.name())) + .build(); + TenantProfileId profileWithoutDedicatedServers = new TenantProfileId(UUID.randomUUID()); + TenantProfileId profileWithDedicatedServer = new TenantProfileId(UUID.randomUUID()); + ServiceInfo dedicatedRuleEngine = ServiceInfo.newBuilder() + .setServiceId("tb-rule-engine-isolated-1") + .addAllServiceTypes(List.of(ServiceType.TB_RULE_ENGINE.name())) + .addAssignedTenantProfiles(profileWithDedicatedServer.toString()) + .build(); + + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + TenantId otherTenantId = TenantId.fromUUID(UUID.randomUUID()); + mockRoutingInfo(tenantId, profileWithoutDedicatedServers, true); + mockRoutingInfo(otherTenantId, profileWithDedicatedServer, true); + mockQueues(List.of(createQueue(TenantId.SYS_TENANT_ID, 10), createQueue(tenantId, 3), createQueue(otherTenantId, 3))); + when(serviceInfoProvider.isService(eq(ServiceType.TB_RULE_ENGINE))).thenReturn(true); + when(serviceInfoProvider.getAssignedTenantProfiles()).thenReturn(Collections.emptySet()); + + HashPartitionService partitionService = createPartitionService(); + partitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList()); + assertThat(partitionService.isManagedByCurrentService(tenantId)).isTrue(); + + Mockito.reset(applicationEventPublisher); + partitionService.recalculatePartitions(commonRuleEngine, List.of(dedicatedRuleEngine)); + + // tenantId's partitions stay on this server, but its managed status changes + assertThat(partitionService.isManagedByCurrentService(tenantId)).isFalse(); + verifyPartitionChangeEvent(event -> event.getServiceType() == ServiceType.TB_RULE_ENGINE && + event.getNewPartitions().keySet().stream().noneMatch(queueKey -> queueKey.getTenantId().equals(tenantId)) && + Set.of(tenantId, otherTenantId).equals(event.getAffectedTenants())); + } + @Test public void testPartitionsDistribution_sameTenantDifferentQueues() { List ruleEngines = new ArrayList<>(); diff --git a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java index e7a6f83fa2..7ff794930f 100644 --- a/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java +++ b/common/actor/src/test/java/org/thingsboard/server/actors/ActorSystemTest.java @@ -11,11 +11,13 @@ import org.junit.jupiter.api.Test; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.msg.TbActorMsg; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -185,29 +187,36 @@ public class ActorSystemTest { } @Test - public void testBroadcastToChildrenWithFilterAndPriority() throws InterruptedException { - executor = ThingsBoardExecutors.newWorkStealingPool(parallelism, getClass()); + public void testBroadcastToChildrenWithFilterAndHighPriority() throws Exception { + executor = Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName(getClass().getSimpleName())); actorSystem.createDispatcher(ROOT_DISPATCHER, executor); TbActorId parentId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); - ActorTestCtx parentTestCtx = getActorTestCtx(1); - actorSystem.createRootActor(ROOT_DISPATCHER, new TestRootActor.TestRootActorCreator(parentId, parentTestCtx)); - + actorSystem.createRootActor(ROOT_DISPATCHER, new RecordingActorCreator(parentId, new CopyOnWriteArrayList<>())); TbActorId matchingChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); - ActorTestCtx matchingChildCtx = getActorTestCtx(1); - actorSystem.createChildActor(ROOT_DISPATCHER, - new TestRootActor.TestRootActorCreator(matchingChildId, matchingChildCtx), parentId); - + List matchingChildValues = new CopyOnWriteArrayList<>(); + actorSystem.createChildActor(ROOT_DISPATCHER, new RecordingActorCreator(matchingChildId, matchingChildValues), parentId); TbActorId otherChildId = new TbEntityActorId(new DeviceId(UUID.randomUUID())); - ActorTestCtx otherChildCtx = getActorTestCtx(1); - actorSystem.createChildActor(ROOT_DISPATCHER, - new TestRootActor.TestRootActorCreator(otherChildId, otherChildCtx), parentId); + List otherChildValues = new CopyOnWriteArrayList<>(); + actorSystem.createChildActor(ROOT_DISPATCHER, new RecordingActorCreator(otherChildId, otherChildValues), parentId); + + // block the only dispatcher thread, so that all messages are enqueued before any is processed + CountDownLatch dispatcherBlocked = new CountDownLatch(1); + executor.submit(() -> { + dispatcherBlocked.await(); + return null; + }); + actorSystem.tell(matchingChildId, new IntTbActorMsg(1)); + actorSystem.tell(matchingChildId, new IntTbActorMsg(2)); + actorSystem.broadcastToChildren(parentId, id -> id.equals(matchingChildId), new IntTbActorMsg(42), true); + dispatcherBlocked.countDown(); - actorSystem.broadcastToChildren(parentId, id -> id.equals(matchingChildId), new IntTbActorMsg(7), true); + Awaitility.await().atMost(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(matchingChildValues).containsExactly(42, 1, 2)); - Assertions.assertTrue(matchingChildCtx.getLatch().await(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS)); - Assertions.assertEquals(7L, matchingChildCtx.getActual().get()); - Assertions.assertFalse(otherChildCtx.getLatch().await(1, TimeUnit.SECONDS)); + actorSystem.tell(otherChildId, new IntTbActorMsg(3)); + Awaitility.await().atMost(TIMEOUT_AWAIT_MAX_SEC, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(otherChildValues).containsExactly(3)); } @Test @@ -284,4 +293,32 @@ public class ActorSystemTest { AtomicInteger invocations = new AtomicInteger(); return new ActorTestCtx(countDownLatch, invocations, i, actual); } + + private static class RecordingActorCreator implements TbActorCreator { + + private final TbActorId actorId; + private final List values; + + RecordingActorCreator(TbActorId actorId, List values) { + this.actorId = actorId; + this.values = values; + } + + @Override + public TbActorId createActorId() { + return actorId; + } + + @Override + public TbActor createActor() { + return new AbstractTbActor() { + @Override + public boolean process(TbActorMsg msg) { + values.add(((IntTbActorMsg) msg).getValue()); + return true; + } + }; + } + } + } diff --git a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java index 72550a48cf..ec7681aea5 100644 --- a/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java +++ b/common/message/src/main/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsg.java @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.common.msg.queue; +import lombok.AccessLevel; import lombok.Data; +import lombok.Getter; +import lombok.ToString; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.MsgType; import org.thingsboard.server.common.msg.TbActorMsg; @@ -17,23 +20,34 @@ public final class PartitionChangeMsg implements TbActorMsg { private final ServiceType serviceType; - /** - * Tenants whose partition ownership changed. Null means the shared - * (non-isolated) tenant pool itself changed, so every tenant actor must - * re-verify — shared-pool tenants aren't individually tracked as - * queueKeys, so they can't be enumerated here. - */ + @Getter(AccessLevel.NONE) + @ToString.Exclude private final Set affectedTenants; - public PartitionChangeMsg(ServiceType serviceType) { - this(serviceType, null); - } - - public PartitionChangeMsg(ServiceType serviceType, Set affectedTenants) { + private PartitionChangeMsg(ServiceType serviceType, Set affectedTenants) { this.serviceType = serviceType; this.affectedTenants = affectedTenants; } + public static PartitionChangeMsg forAllTenants(ServiceType serviceType) { + return new PartitionChangeMsg(serviceType, null); + } + + public static PartitionChangeMsg forTenants(ServiceType serviceType, Set affectedTenants) { + return new PartitionChangeMsg(serviceType, Set.copyOf(affectedTenants)); + } + + /** + * @return {@code true} if every tenant actor must receive this message + */ + public boolean isForAllTenants() { + return affectedTenants == null; + } + + public boolean isAffected(TenantId tenantId) { + return affectedTenants == null || affectedTenants.contains(tenantId); + } + @Override public MsgType getMsgType() { return MsgType.PARTITION_CHANGE_MSG; diff --git a/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java index 6e01879941..9bdc98755d 100644 --- a/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java +++ b/common/message/src/test/java/org/thingsboard/server/common/msg/queue/PartitionChangeMsgTest.java @@ -1,47 +1,49 @@ -/** - * 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.common.msg.queue; import org.junit.jupiter.api.Test; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.MsgType; +import java.util.HashSet; import java.util.Set; import java.util.UUID; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.assertj.core.api.Assertions.assertThat; public class PartitionChangeMsgTest { + private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID()); + private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID()); + @Test - public void singleArgConstructor_defaultsAffectedTenantsToNull() { - PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE); + public void forAllTenants_affectsEveryTenant() { + PartitionChangeMsg msg = PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE); + + assertThat(msg.getServiceType()).isEqualTo(ServiceType.TB_RULE_ENGINE); + assertThat(msg.getMsgType()).isEqualTo(MsgType.PARTITION_CHANGE_MSG); + assertThat(msg.isForAllTenants()).isTrue(); + assertThat(msg.isAffected(tenant1)).isTrue(); + assertThat(msg.isAffected(tenant2)).isTrue(); + } - assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType()); - assertNull(msg.getAffectedTenants()); - assertEquals(MsgType.PARTITION_CHANGE_MSG, msg.getMsgType()); + @Test + public void forTenants_affectsOnlyGivenTenants() { + Set tenants = new HashSet<>(Set.of(tenant1)); + PartitionChangeMsg msg = PartitionChangeMsg.forTenants(ServiceType.TB_RULE_ENGINE, tenants); + tenants.add(tenant2); + + assertThat(msg.isForAllTenants()).isFalse(); + assertThat(msg.isAffected(tenant1)).isTrue(); + assertThat(msg.isAffected(tenant2)).isFalse(); } @Test - public void twoArgConstructor_carriesAffectedTenants() { - TenantId tenant = new TenantId(UUID.randomUUID()); - PartitionChangeMsg msg = new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE, Set.of(tenant)); + public void toString_doesNotListAffectedTenants() { + PartitionChangeMsg msg = PartitionChangeMsg.forTenants(ServiceType.TB_RULE_ENGINE, Set.of(tenant1)); - assertEquals(ServiceType.TB_RULE_ENGINE, msg.getServiceType()); - assertEquals(Set.of(tenant), msg.getAffectedTenants()); + assertThat(msg.toString()).doesNotContain(tenant1.getId().toString()); } + } diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 57a8023548..380d452f5e 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -108,6 +108,8 @@ public class HashPartitionService implements PartitionService { private List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); private volatile Map> responsibleServices = Collections.emptyMap(); + // managed status of isolated tenants, as of the last published rule engine partition change event + private Map isolatedTenantsManagedStatus = Collections.emptyMap(); private HashFunction hashFunction; @@ -538,7 +540,9 @@ public class HashPartitionService implements PartitionService { .map(tpi -> tpi.getPartition().orElse(-1).toString()).sorted() .collect(Collectors.joining(", ")) + "]") .collect(Collectors.joining(System.lineSeparator()))); - PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions); + Set managedStatusChangedTenants = ServiceType.TB_RULE_ENGINE.equals(serviceType) ? + updateIsolatedTenantsManagedStatus() : Collections.emptySet(); + PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions, managedStatusChangedTenants); try { applicationEventPublisher.publishEvent(event); } catch (Exception e) { @@ -546,6 +550,33 @@ public class HashPartitionService implements PartitionService { } } + // An isolated tenant's managed status depends on responsibleServices, which can change + // while the tenant's own queue keys stay out of the partition change event. + // Returns the isolated tenants whose managed status changed since the previous call. + private synchronized Set updateIsolatedTenantsManagedStatus() { + Map managedStatus = new HashMap<>(); + partitionSizesMap.keySet().stream() + .filter(queueKey -> queueKey.getType() == ServiceType.TB_RULE_ENGINE && !queueKey.getTenantId().isSysTenantId()) + .map(QueueKey::getTenantId) + .distinct() + .forEach(tenantId -> { + try { + managedStatus.put(tenantId, isManagedByCurrentService(tenantId)); + } catch (Exception e) { + log.debug("[{}] Failed to check if tenant is managed by current service", tenantId, e); + } + }); + Set changed = managedStatus.entrySet().stream() + .filter(entry -> { + Boolean previous = isolatedTenantsManagedStatus.get(entry.getKey()); + return previous != null && !previous.equals(entry.getValue()); + }) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + isolatedTenantsManagedStatus = managedStatus; + return changed; + } + private Set toTpiList(QueueKey queueKey, List partitions) { if (partitions == null) { return Collections.emptySet(); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java index 4560a2dec1..a089195e98 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java @@ -5,12 +5,15 @@ package org.thingsboard.server.queue.discovery.event; import lombok.Getter; import lombok.ToString; import org.thingsboard.server.common.data.DataConstants; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; import org.thingsboard.server.queue.discovery.QueueKey; import java.io.Serial; import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -27,14 +30,41 @@ public class PartitionChangeEvent extends TbApplicationEvent { private final Map> newPartitions; @Getter private final Map> oldPartitions; + @Getter + @ToString.Exclude + private final Set managedStatusChangedTenants; public PartitionChangeEvent(Object source, ServiceType serviceType, Map> newPartitions, Map> oldPartitions) { + this(source, serviceType, newPartitions, oldPartitions, Collections.emptySet()); + } + + public PartitionChangeEvent(Object source, ServiceType serviceType, + Map> newPartitions, + Map> oldPartitions, + Set managedStatusChangedTenants) { super(source); this.serviceType = serviceType; this.newPartitions = newPartitions; this.oldPartitions = oldPartitions; + this.managedStatusChangedTenants = managedStatusChangedTenants; + } + + /** + * Returns the tenants affected by this rule engine partition change, or {@code null} if every tenant may be affected. + *

+ * {@code newPartitions} holds only the changed queue keys. A system tenant key stands for the shared queues, + * whose tenants can't be enumerated, so the result is {@code null}. It is also {@code null} for other service types. + */ + public Set getAffectedTenants() { + if (serviceType != ServiceType.TB_RULE_ENGINE || newPartitions.isEmpty() || + newPartitions.keySet().stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId())) { + return null; + } + Set affectedTenants = new HashSet<>(managedStatusChangedTenants); + newPartitions.keySet().forEach(queueKey -> affectedTenants.add(queueKey.getTenantId())); + return affectedTenants; } public Set getCorePartitions() { diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java new file mode 100644 index 0000000000..ca1a36e378 --- /dev/null +++ b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.queue.discovery.event; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.thingsboard.server.common.data.DataConstants; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.queue.discovery.QueueKey; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +class PartitionChangeEventTest { + + private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID()); + private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID()); + private final TenantId tenant3 = TenantId.fromUUID(UUID.randomUUID()); + + @Test + void isolatedTenantQueuesChanged_returnsTheirTenants() { + PartitionChangeEvent event = ruleEngineEvent(Set.of( + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1), + queueKey(DataConstants.HP_QUEUE_NAME, tenant1), + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant2)), Collections.emptySet()); + + assertThat(event.getAffectedTenants()).containsExactlyInAnyOrder(tenant1, tenant2); + } + + @Test + void managedStatusChangedTenantsAreIncluded() { + PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1)), Set.of(tenant3)); + + assertThat(event.getAffectedTenants()).containsExactlyInAnyOrder(tenant1, tenant3); + } + + @Test + void sharedQueueChanged_returnsNull() { + PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID)), Collections.emptySet()); + + assertThat(event.getAffectedTenants()).isNull(); + } + + @Test + void sharedAndIsolatedQueuesChanged_returnsNull() { + PartitionChangeEvent event = ruleEngineEvent(Set.of( + queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID), + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1)), Set.of(tenant3)); + + assertThat(event.getAffectedTenants()).isNull(); + } + + @Test + void noQueuesChanged_returnsNull() { + PartitionChangeEvent event = ruleEngineEvent(Collections.emptySet(), Set.of(tenant3)); + + assertThat(event.getAffectedTenants()).isNull(); + } + + @ParameterizedTest + @EnumSource(value = ServiceType.class, names = "TB_RULE_ENGINE", mode = EnumSource.Mode.EXCLUDE) + void otherServiceType_returnsNull(ServiceType serviceType) { + QueueKey queueKey = new QueueKey(serviceType, DataConstants.MAIN_QUEUE_NAME, tenant1); + PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, + Map.of(queueKey, Collections.emptySet()), Collections.emptyMap(), Set.of(tenant3)); + + assertThat(event.getAffectedTenants()).isNull(); + } + + private PartitionChangeEvent ruleEngineEvent(Set changedQueueKeys, Set managedStatusChangedTenants) { + Map> newPartitions = changedQueueKeys.stream() + .collect(Collectors.toMap(queueKey -> queueKey, queueKey -> Collections.emptySet())); + return new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Collections.emptyMap(), managedStatusChangedTenants); + } + + private QueueKey queueKey(String queueName, TenantId tenantId) { + return new QueueKey(ServiceType.TB_RULE_ENGINE, queueName, tenantId); + } + +} diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java index 9ec169df9b..a2a6b59c36 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbDeviceStateNodeTest.java @@ -159,7 +159,7 @@ public class TbDeviceStateNodeTest { given(ctxMock.isLocalEntity(eq(nonLocalDeviceId2))).willReturn(false); // WHEN - node.onPartitionChangeMsg(ctxMock, new PartitionChangeMsg(ServiceType.TB_RULE_ENGINE)); + node.onPartitionChangeMsg(ctxMock, PartitionChangeMsg.forAllTenants(ServiceType.TB_RULE_ENGINE)); // THEN assertThat(rateLimits) From ed77b56100e87cbfa2e1e3344925e1b9f0372976 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 14:23:30 +0200 Subject: [PATCH 5/7] Fixed flaky AgentControllerTest getAgentInfosByIds test /api/agentInfos?agentIds=... is served by a derived JPA 'id IN (...)' query with no ORDER BY, so PostgreSQL may return rows in any order (e.g. physical tuple order after an UPDATE). The test asserted infos.get(0) == first and infos.get(1) == second, and failed whenever the rows came back reversed. Match the returned infos by id instead. --- .../server/controller/AgentControllerTest.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java index 5e1123d037..a929c654e7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AgentControllerTest.java @@ -12,13 +12,18 @@ import org.thingsboard.server.common.data.agent.AgentAppEvent; import org.thingsboard.server.common.data.agent.AgentAppEventInfo; import org.thingsboard.server.common.data.agent.AgentInfo; import org.thingsboard.server.common.data.agent.AgentInstructions; +import org.thingsboard.server.common.data.id.AgentId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -104,10 +109,12 @@ public class AgentControllerTest extends AbstractControllerTest { List infos = doGetTyped("/api/agentInfos?agentIds=" + first.getId().getId() + "," + second.getId().getId() + "," + UUID.randomUUID(), new TypeReference<>() {}); + // The endpoint does not guarantee result order (SQL "id IN (...)" without ORDER BY), so match by id Assert.assertEquals(2, infos.size()); - Assert.assertEquals(first.getId(), infos.get(0).getId()); - Assert.assertEquals(first.getName(), infos.get(0).getName()); - Assert.assertEquals(second.getId(), infos.get(1).getId()); + Map infosById = infos.stream().collect(Collectors.toMap(AgentInfo::getId, Function.identity())); + Assert.assertEquals(Set.of(first.getId(), second.getId()), infosById.keySet()); + Assert.assertEquals(first.getName(), infosById.get(first.getId()).getName()); + Assert.assertEquals(second.getName(), infosById.get(second.getId()).getName()); } @Test From f823a7412364f636a6447e1cbeae7d00a7fc825c Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 14:24:18 +0200 Subject: [PATCH 6/7] Fix flaky QrCodeSettingsControllerTest deep link host test WhiteLabelingControllerTest saves the system-level login white-labeling params with baseUrl "https://domain.com" and never restores them. The params persist in the shared test database, so when QrCodeSettingsControllerTest runs later in the same JVM, getBaseUrl() resolves the system base URL to domain.com and testGetMobileDeepLink fails with expected "localhost" but was "domain.com". Reset system white-labeling settings after every WhiteLabelingControllerTest test, and reset them in QrCodeSettingsControllerTest setup as well. --- .../server/controller/QrCodeSettingsControllerTest.java | 3 ++- .../server/controller/WhiteLabelingControllerTest.java | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java index c2e2b953b2..15fe14f895 100644 --- a/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/QrCodeSettingsControllerTest.java @@ -53,7 +53,8 @@ public class QrCodeSettingsControllerTest extends AbstractControllerTest { @Before public void setUp() throws Exception { - loginSysAdmin(); + // Deep link host is derived from the login white-labeling base URL; start from system defaults + resetSysAdminWhiteLabelingSettings(); MobileApp androidApp = validMobileApp( "my.android.package", PlatformType.ANDROID); StoreInfo androidStoreInfo = StoreInfo.builder() diff --git a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java index 83eb9384bf..8574bd7bd0 100644 --- a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java @@ -36,7 +36,11 @@ public class WhiteLabelingControllerTest extends AbstractControllerTest { WhiteLabelingDao whiteLabelingDao; @After - public void afterTest() { + public void afterTest() throws Exception { + // System-level login/white-labeling params are shared by every test class in the same DB; + // restore defaults so the base URL set here (e.g. "https://domain.com") does not leak. + resetSysAdminWhiteLabelingSettings(); + if (tenantId != null) { WhiteLabelingCompositeKey key = new WhiteLabelingCompositeKey(tenantId, WhiteLabelingType.MAIL_TEMPLATES); if (whiteLabelingDao.findById(SYS_TENANT_ID, key) != null) { From 4294c3a20cd84a2ace2920789295ac33f9dcdea7 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Sun, 18 Oct 2026 19:20:46 +0200 Subject: [PATCH 7/7] rule-engine: drop managed-status tracking from partition change events The tracking compensated for isManagedByCurrentService reporting isolated tenants of a profile without dedicated servers as not managed (a dedicated server for any other profile flipped it). That root cause is fixed in #16345, after which a tenant's managed status changes only together with its own queue ownership, and its queue keys are already in the partition change event. Replace the test that pinned the old flip with one that checks the affected tenants when a dedicated server for the tenant's own profile joins and leaves. --- .../discovery/HashPartitionServiceTest.java | 26 ++++++++------- .../queue/discovery/HashPartitionService.java | 33 +------------------ .../discovery/event/PartitionChangeEvent.java | 17 +--------- .../event/PartitionChangeEventTest.java | 22 ++++--------- 4 files changed, 23 insertions(+), 75 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java index 32059096f4..c05423756d 100644 --- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java @@ -370,24 +370,21 @@ public class HashPartitionServiceTest { } @Test - public void testPartitionChangeEvent_includesIsolatedTenantWithChangedManagedStatus() { + public void testPartitionChangeEvent_affectedTenantsIncludeIsolatedTenantWhenItsDedicatedServerChanges() { ServiceInfo commonRuleEngine = ServiceInfo.newBuilder() .setServiceId("tb-rule-engine-1") .addAllServiceTypes(List.of(ServiceType.TB_RULE_ENGINE.name())) .build(); - TenantProfileId profileWithoutDedicatedServers = new TenantProfileId(UUID.randomUUID()); - TenantProfileId profileWithDedicatedServer = new TenantProfileId(UUID.randomUUID()); + TenantProfileId tenantProfileId = new TenantProfileId(UUID.randomUUID()); ServiceInfo dedicatedRuleEngine = ServiceInfo.newBuilder() .setServiceId("tb-rule-engine-isolated-1") .addAllServiceTypes(List.of(ServiceType.TB_RULE_ENGINE.name())) - .addAssignedTenantProfiles(profileWithDedicatedServer.toString()) + .addAssignedTenantProfiles(tenantProfileId.toString()) .build(); TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); - TenantId otherTenantId = TenantId.fromUUID(UUID.randomUUID()); - mockRoutingInfo(tenantId, profileWithoutDedicatedServers, true); - mockRoutingInfo(otherTenantId, profileWithDedicatedServer, true); - mockQueues(List.of(createQueue(TenantId.SYS_TENANT_ID, 10), createQueue(tenantId, 3), createQueue(otherTenantId, 3))); + mockRoutingInfo(tenantId, tenantProfileId, true); + mockQueues(List.of(createQueue(TenantId.SYS_TENANT_ID, 10), createQueue(tenantId, 3))); when(serviceInfoProvider.isService(eq(ServiceType.TB_RULE_ENGINE))).thenReturn(true); when(serviceInfoProvider.getAssignedTenantProfiles()).thenReturn(Collections.emptySet()); @@ -395,14 +392,19 @@ public class HashPartitionServiceTest { partitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList()); assertThat(partitionService.isManagedByCurrentService(tenantId)).isTrue(); + // a dedicated server for the tenant's own profile joins: the tenant is no longer managed here Mockito.reset(applicationEventPublisher); partitionService.recalculatePartitions(commonRuleEngine, List.of(dedicatedRuleEngine)); - - // tenantId's partitions stay on this server, but its managed status changes assertThat(partitionService.isManagedByCurrentService(tenantId)).isFalse(); verifyPartitionChangeEvent(event -> event.getServiceType() == ServiceType.TB_RULE_ENGINE && - event.getNewPartitions().keySet().stream().noneMatch(queueKey -> queueKey.getTenantId().equals(tenantId)) && - Set.of(tenantId, otherTenantId).equals(event.getAffectedTenants())); + Set.of(tenantId).equals(event.getAffectedTenants())); + + // the dedicated server leaves: the tenant is managed here again + Mockito.reset(applicationEventPublisher); + partitionService.recalculatePartitions(commonRuleEngine, Collections.emptyList()); + assertThat(partitionService.isManagedByCurrentService(tenantId)).isTrue(); + verifyPartitionChangeEvent(event -> event.getServiceType() == ServiceType.TB_RULE_ENGINE && + Set.of(tenantId).equals(event.getAffectedTenants())); } @Test diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java index 380d452f5e..57a8023548 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java @@ -108,8 +108,6 @@ public class HashPartitionService implements PartitionService { private List currentOtherServices; private final Map> tbTransportServicesByType = new HashMap<>(); private volatile Map> responsibleServices = Collections.emptyMap(); - // managed status of isolated tenants, as of the last published rule engine partition change event - private Map isolatedTenantsManagedStatus = Collections.emptyMap(); private HashFunction hashFunction; @@ -540,9 +538,7 @@ public class HashPartitionService implements PartitionService { .map(tpi -> tpi.getPartition().orElse(-1).toString()).sorted() .collect(Collectors.joining(", ")) + "]") .collect(Collectors.joining(System.lineSeparator()))); - Set managedStatusChangedTenants = ServiceType.TB_RULE_ENGINE.equals(serviceType) ? - updateIsolatedTenantsManagedStatus() : Collections.emptySet(); - PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions, managedStatusChangedTenants); + PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, newPartitions, oldPartitions); try { applicationEventPublisher.publishEvent(event); } catch (Exception e) { @@ -550,33 +546,6 @@ public class HashPartitionService implements PartitionService { } } - // An isolated tenant's managed status depends on responsibleServices, which can change - // while the tenant's own queue keys stay out of the partition change event. - // Returns the isolated tenants whose managed status changed since the previous call. - private synchronized Set updateIsolatedTenantsManagedStatus() { - Map managedStatus = new HashMap<>(); - partitionSizesMap.keySet().stream() - .filter(queueKey -> queueKey.getType() == ServiceType.TB_RULE_ENGINE && !queueKey.getTenantId().isSysTenantId()) - .map(QueueKey::getTenantId) - .distinct() - .forEach(tenantId -> { - try { - managedStatus.put(tenantId, isManagedByCurrentService(tenantId)); - } catch (Exception e) { - log.debug("[{}] Failed to check if tenant is managed by current service", tenantId, e); - } - }); - Set changed = managedStatus.entrySet().stream() - .filter(entry -> { - Boolean previous = isolatedTenantsManagedStatus.get(entry.getKey()); - return previous != null && !previous.equals(entry.getValue()); - }) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); - isolatedTenantsManagedStatus = managedStatus; - return changed; - } - private Set toTpiList(QueueKey queueKey, List partitions) { if (partitions == null) { return Collections.emptySet(); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java index a089195e98..460b1d9009 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEvent.java @@ -12,8 +12,6 @@ import org.thingsboard.server.queue.discovery.QueueKey; import java.io.Serial; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -30,25 +28,14 @@ public class PartitionChangeEvent extends TbApplicationEvent { private final Map> newPartitions; @Getter private final Map> oldPartitions; - @Getter - @ToString.Exclude - private final Set managedStatusChangedTenants; public PartitionChangeEvent(Object source, ServiceType serviceType, Map> newPartitions, Map> oldPartitions) { - this(source, serviceType, newPartitions, oldPartitions, Collections.emptySet()); - } - - public PartitionChangeEvent(Object source, ServiceType serviceType, - Map> newPartitions, - Map> oldPartitions, - Set managedStatusChangedTenants) { super(source); this.serviceType = serviceType; this.newPartitions = newPartitions; this.oldPartitions = oldPartitions; - this.managedStatusChangedTenants = managedStatusChangedTenants; } /** @@ -62,9 +49,7 @@ public class PartitionChangeEvent extends TbApplicationEvent { newPartitions.keySet().stream().anyMatch(queueKey -> queueKey.getTenantId().isSysTenantId())) { return null; } - Set affectedTenants = new HashSet<>(managedStatusChangedTenants); - newPartitions.keySet().forEach(queueKey -> affectedTenants.add(queueKey.getTenantId())); - return affectedTenants; + return newPartitions.keySet().stream().map(QueueKey::getTenantId).collect(Collectors.toSet()); } public Set getCorePartitions() { diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java index ca1a36e378..856d8b8167 100644 --- a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java +++ b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/event/PartitionChangeEventTest.java @@ -23,28 +23,20 @@ class PartitionChangeEventTest { private final TenantId tenant1 = TenantId.fromUUID(UUID.randomUUID()); private final TenantId tenant2 = TenantId.fromUUID(UUID.randomUUID()); - private final TenantId tenant3 = TenantId.fromUUID(UUID.randomUUID()); @Test void isolatedTenantQueuesChanged_returnsTheirTenants() { PartitionChangeEvent event = ruleEngineEvent(Set.of( queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1), queueKey(DataConstants.HP_QUEUE_NAME, tenant1), - queueKey(DataConstants.MAIN_QUEUE_NAME, tenant2)), Collections.emptySet()); + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant2))); assertThat(event.getAffectedTenants()).containsExactlyInAnyOrder(tenant1, tenant2); } - @Test - void managedStatusChangedTenantsAreIncluded() { - PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1)), Set.of(tenant3)); - - assertThat(event.getAffectedTenants()).containsExactlyInAnyOrder(tenant1, tenant3); - } - @Test void sharedQueueChanged_returnsNull() { - PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID)), Collections.emptySet()); + PartitionChangeEvent event = ruleEngineEvent(Set.of(queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID))); assertThat(event.getAffectedTenants()).isNull(); } @@ -53,14 +45,14 @@ class PartitionChangeEventTest { void sharedAndIsolatedQueuesChanged_returnsNull() { PartitionChangeEvent event = ruleEngineEvent(Set.of( queueKey(DataConstants.MAIN_QUEUE_NAME, TenantId.SYS_TENANT_ID), - queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1)), Set.of(tenant3)); + queueKey(DataConstants.MAIN_QUEUE_NAME, tenant1))); assertThat(event.getAffectedTenants()).isNull(); } @Test void noQueuesChanged_returnsNull() { - PartitionChangeEvent event = ruleEngineEvent(Collections.emptySet(), Set.of(tenant3)); + PartitionChangeEvent event = ruleEngineEvent(Collections.emptySet()); assertThat(event.getAffectedTenants()).isNull(); } @@ -70,15 +62,15 @@ class PartitionChangeEventTest { void otherServiceType_returnsNull(ServiceType serviceType) { QueueKey queueKey = new QueueKey(serviceType, DataConstants.MAIN_QUEUE_NAME, tenant1); PartitionChangeEvent event = new PartitionChangeEvent(this, serviceType, - Map.of(queueKey, Collections.emptySet()), Collections.emptyMap(), Set.of(tenant3)); + Map.of(queueKey, Collections.emptySet()), Collections.emptyMap()); assertThat(event.getAffectedTenants()).isNull(); } - private PartitionChangeEvent ruleEngineEvent(Set changedQueueKeys, Set managedStatusChangedTenants) { + private PartitionChangeEvent ruleEngineEvent(Set changedQueueKeys) { Map> newPartitions = changedQueueKeys.stream() .collect(Collectors.toMap(queueKey -> queueKey, queueKey -> Collections.emptySet())); - return new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Collections.emptyMap(), managedStatusChangedTenants); + return new PartitionChangeEvent(this, ServiceType.TB_RULE_ENGINE, newPartitions, Collections.emptyMap()); } private QueueKey queueKey(String queueName, TenantId tenantId) {