@@ -9,7 +9,7 @@ import { getErrorMessage } from '@sim/utils/errors'
99import { chunkArray , sleep } from '@sim/utils/helpers'
1010import { generateId } from '@sim/utils/id'
1111import { backoffWithJitter } from '@sim/utils/retry'
12- import { and , desc , eq , notInArray , sql } from 'drizzle-orm'
12+ import { and , desc , eq , notInArray , type SQL , sql } from 'drizzle-orm'
1313import { runWithOutboundOrganization } from '@/lib/core/network/context.server'
1414import { listSlackSearchMembers , type SlackSearchMember } from '@/lib/internal/slack/search-client'
1515import { loadSlackSearchCredential } from '@/lib/knowledge/application/slack-search/repository'
@@ -38,10 +38,16 @@ type Lease = {
3838}
3939
4040/**
41- * Leases due organizations: those with an enabled Slack Search bot, and those still holding
42- * identities from a bot since disabled . Each lease is fenced by its token, so a sweep that
41+ * Leases due organizations: those with an enabled Slack Search bot, and, at once, those whose
42+ * last bot was disabled or removed, so their identities go on the next sweep . Each lease is fenced by its token, so a sweep that
4343 * outlives its lease cannot overwrite the next one's work.
4444 */
45+ /** Whether the refresh row's organization has no enabled Slack Search bot left. */
46+ function botless ( organizationId : SQL ) {
47+ return sql `NOT EXISTS (SELECT 1 FROM ${ installation } i
48+ WHERE i.organization_id = ${ organizationId } AND i.enabled)`
49+ }
50+
4551async function leaseDue ( limit : number ) : Promise < Lease [ ] > {
4652 const leaseToken = generateId ( )
4753 return db . execute < Lease > ( sql `
@@ -50,14 +56,16 @@ async function leaseDue(limit: number): Promise<Lease[]> {
5056 LEFT JOIN ${ refresh } r ON r.organization_id = i.organization_id
5157 WHERE i.enabled AND (r.organization_id IS NULL OR r.next_refresh_at <= now())
5258 UNION
53- SELECT r.organization_id FROM ${ refresh } r WHERE r.next_refresh_at <= now()
59+ SELECT r.organization_id FROM ${ refresh } r
60+ WHERE r.next_refresh_at <= now() OR (r.lease_token IS NULL AND ${ botless ( sql `r.organization_id` ) } )
5461 LIMIT ${ limit }
5562 )
5663 INSERT INTO ${ refresh } (organization_id, next_refresh_at, lease_token)
5764 SELECT organization_id, now() + make_interval(secs => ${ LEASE_MS / 1000 } ), ${ leaseToken } FROM due
5865 ON CONFLICT (organization_id) DO UPDATE
5966 SET next_refresh_at = excluded.next_refresh_at, lease_token = excluded.lease_token
6067 WHERE ${ refresh . nextRefreshAt } <= now()
68+ OR (${ refresh . leaseToken } IS NULL AND ${ botless ( sql `${ refresh . organizationId } ` ) } )
6169 RETURNING organization_id AS "organizationId", lease_token AS "leaseToken"
6270 ` )
6371}
0 commit comments