π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: wake registered-only gateway connections during sync (#17536)
Rdmclin23005e6ab3ff7
diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.tsindex a799b8266d1..96e53e57a62 100644--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts@@ -338,7 +338,11 @@ describe('GatewayService', () => {expect(mockGatewayClient.connect).not.toHaveBeenCalled();});- it('skips providers already present in the registered-id snapshot without probing status', async () => {+ it('ensure-wakes a registered-only desired provider without probing status', async () => {+ // Registered-only (pruned from stats) used to be skipped outright, but a+ // stranded DO (alarm chain lost) looks exactly like this and sleeps+ // forever unless woken. The wake is an `ensure` connect, never a status+ // probe: parked connections answer 409 and keep their park.mockFindEnabledByPlatform.mockResolvedValue([{applicationId: 'app-1',@@ -350,11 +354,15 @@ describe('GatewayService', () => {]);mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });await service.ensureRunning();expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );});it('connects disconnected providers', async () => {@@ -571,9 +579,13 @@ describe('GatewayService', () => {await service.ensureRunning();- // Fail-open: no disconnect, provider stays in the desired set.+ // Fail-open: no disconnect, provider stays in the desired set. As a+ // desired registered-only id it may receive the idempotent ensure wake,+ // which preserves whatever state the gateway holds.expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).not.toHaveBeenCalledWith(expect.anything(), {+ ensure: false,+ });});it('does not repeatedly disconnect a gated provider absent from the gateway snapshot', async () => {@@ -947,17 +959,38 @@ describe('GatewayService', () => {);});- it('keeps registered-only ids without waking their connection DOs', async () => {+ it('ensure-wakes registered-only desired ids instead of leaving them stranded', async () => {mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>platform === 'discord' ? [provider] : [],);mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });await service.ensureRunning();expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ });++ it('keeps a parked registered-only connection parked (ensure 409 is not a status reset)', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [provider] : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockRejectedValue(new Error('409 connection parked'));++ await service.ensureRunning();++ // The 409 must not overwrite the bot's runtime status with a fresh state.+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ applicationId: 'app-1', status: 'starting' }),+ );expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();});@@ -1005,26 +1038,78 @@ describe('GatewayService', () => {ids: providers.map(({ id }) => id),});+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });+await service.ensureRunning();expect(mockGatewayClient.getStats).toHaveBeenCalledTimes(1);expect(mockGatewayClient.getRegisteredIds).toHaveBeenCalledTimes(1);expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ // Registered-only wakes are capped per round so a large fleet cannot+ // turn the reconcile into a wake storm; the remainder waits for the+ // next cron round.+ expect(mockGatewayClient.connect).toHaveBeenCalledTimes(50);expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();});+ it('samples registered-only wakes instead of always burning the cap on the same prefix', async () => {+ // A stable iteration order + head-first cap would starve ids after+ // position 50 forever when the early ones stay registered-only (parked+ // 409s). Force the sampler's rng to pick from the tail and assert the+ // selection is not the head prefix.+ const providers = Array.from({ length: 2000 }, (_, index) => ({+ ...provider,+ applicationId: `app-${index}`,+ id: `prov-${index}`,+ }));++ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? providers : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: providers.map(({ id }) => id),+ });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0.999_999);+ try {+ await service.ensureRunning();+ } finally {+ randomSpy.mockRestore();+ }++ expect(mockGatewayClient.connect).toHaveBeenCalledTimes(50);+ const wokenIds = new Set(+ mockGatewayClient.connect.mock.calls.map(+ (call) => (call[0] as { connectionId: string }).connectionId,+ ),+ );+ // rng pinned to ~1 β the sampler reaches the tail; the old head-first+ // cap could only ever pick prov-0..prov-49 and would return exactly+ // that prefix.+ expect(wokenIds.has('prov-1999')).toBe(true);+ const isHeadPrefix = [...wokenIds].every((id) => Number(id.split('-')[1]) < 50);+ expect(isHeadPrefix).toBe(false);+ });+it('uses registered ids as a complete existence snapshot when stats is unavailable', async () => {mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>platform === 'discord' ? [provider] : [],);mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });await service.ensureRunning();expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();- expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ // With no stats, every desired id is registered-only (status unknown) β+ // still handled via the capped ensure wake, never a per-DO status probe.+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({ connectionId: 'prov-1' }),+ { ensure: true },+ );expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();});diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex 5357a52d6aa..d3dd8b1557d 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -68,6 +68,37 @@ const GATEWAY_SYNC_CONCURRENCY = 8;*/const GATEWAY_SYNC_STALE_DISCONNECT_LIMIT = 50;+/**+ * Cap on registered-only wake-up connects per sync round. A registered-only id+ * (in the registry but pruned from live stats) is usually a parked or+ * self-waking dormant DO, but a stranded DO β alarm chain lost after a deploy+ * cancelled its in-flight alarm invocation β looks identical and sleeps+ * forever unless something wakes it. The `ensure` connect is that wake: parked+ * connections answer 409 and keep their park, healthy ones no-op. The cap+ * keeps a large parked backlog from turning every cron round into a fleet-wide+ * wake storm; the remainder is retried on later rounds.+ */+const GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT = 50;++/**+ * Uniformly sample up to `limit` ids via a partial Fisher-Yates shuffle.+ * Stateless by design β the gateway cron runs in fresh serverless invocations,+ * so a persisted round-robin cursor would need external storage; uniform+ * sampling gives every candidate an expected candidates/limit-round latency+ * without any state.+ */+const sampleIds = (ids: string[], limit: number): Set<string> => {+ if (ids.length <= limit) return new Set(ids);+ const pool = [...ids];+ const picked = new Set<string>();+ for (let i = 0; i < limit; i++) {+ const j = i + Math.floor(Math.random() * (pool.length - i));+ [pool[i], pool[j]] = [pool[j], pool[i]];+ picked.add(pool[i]);+ }+ return picked;+};+interface DesiredGatewayConnection {connectionMode: ConnectionMode;platform: string;@@ -219,6 +250,24 @@ export class GatewayService {let skipped = 0;let failed = 0;+ // Registered-only wake candidates are SAMPLED, not taken head-first: the+ // desired map iterates in a stable order, and parked connections (409,+ // stay registered-only until their 7d expiry) would otherwise burn the+ // whole cap on the same prefix every round, starving stranded DOs that+ // sort after position N. Uniform sampling reaches every candidate within+ // an expected candidates/limit rounds with no persisted cursor.+ const registeredOnlyCandidates = [...desired.values()]+ .map(({ provider }) => provider.id)+ .filter(+ (id) => (actual?.connections.has(id) ?? false) && actual?.connections.get(id) === null,+ );+ const registeredOnlyWakeIds = sampleIds(+ registeredOnlyCandidates,+ GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT,+ );+ const registeredOnlyDeferred = registeredOnlyCandidates.length - registeredOnlyWakeIds.size;+ let registeredOnlyWakes = 0;+await pMap(desired.values(),async ({ connectionMode, platform, provider }) => {@@ -234,14 +283,27 @@ export class GatewayService {// Registered ids are the gateway's authoritative existence set. Use// the status already present in live stats to recover an explicitly- // disconnected connection, but never wake registered-only DOs merely- // to inspect their runtime status.+ // disconnected connection. Registered-only ids (status null β pruned+ // from stats) get a capped ensure-connect wake instead of a skip:+ // see GATEWAY_SYNC_REGISTERED_ONLY_WAKE_LIMIT. Never probe per-DO+ // status here.const exists = actual?.connections.has(provider.id) ?? false;const snapshotStatus = actual?.connections.get(provider.id);if (exists && snapshotStatus !== 'disconnected') {- skipped++;- log('Gateway sync: %s already registered, skipping', provider.id);- return;+ if (snapshotStatus !== null) {+ skipped++;+ log('Gateway sync: %s already registered, skipping', provider.id);+ return;+ }+ if (!registeredOnlyWakeIds.has(provider.id)) {+ log(+ 'Gateway sync: %s registered-only, not sampled this round, deferring',+ provider.id,+ );+ return;+ }+ registeredOnlyWakes++;+ log('Gateway sync: %s registered-only, ensure-waking', provider.id);}// Without a complete registry snapshot, absence from live stats does@@ -300,7 +362,7 @@ export class GatewayService {);log(- 'Gateway sync complete in %dms: desired=%d actual=%s snapshotComplete=%s connected=%d skipped=%d deferred=%d gated=%d gatedDisconnected=%d stale=%d failed=%d',+ 'Gateway sync complete in %dms: desired=%d actual=%s snapshotComplete=%s connected=%d skipped=%d deferred=%d gated=%d gatedDisconnected=%d stale=%d failed=%d registeredOnlyWakes=%d registeredOnlyDeferred=%d',Date.now() - startedAt,desired.size,actual ? actual.connections.size : 'unavailable',@@ -312,6 +374,8 @@ export class GatewayService {gatedDisconnected,stale,failed,+ registeredOnlyWakes,+ registeredOnlyDeferred,);}