Skip to content

Commit efea9de

Browse files
fix(redis): reclaim a distributed lock that a timed-out acquire may have taken (#6864)
* fix(redis): reclaim a lock a timed-out acquire may have taken `acquireLock` awaited `SET NX` and let a rejection propagate. But a rejected SET does not mean the server declined it: the client is configured with `commandTimeout: 5000`, and ioredis gives up locally while the command can still reach Redis and take the lock. The caller never learns it won, so it never releases — and since every caller treats a throw as "did not acquire", nothing else releases it either. Every contender then skips until the TTL expires. Staging hit this on the Outlook polling cron: `acquireLock` threw `Command timed out`, the route returned 500, and the next scheduled poll and the Lambda retry both got `Polling already in progress - skipped` against a lock whose holder had never started polling. The 180s TTL cleared it. On failure, best-effort compare-and-delete through the existing `releaseLock`. That deletes only while this token still owns the key, so a lock another holder won in the meantime is untouched, and if Redis is still unreachable the TTL stays the backstop — the behavior without this cleanup. Control flow is unchanged for all nine call sites: the original error still propagates. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(redis): make the timed-out-acquire reclaim opt-in per caller Review caught that reclaiming unconditionally is unsafe for two caller classes, both of which exist today: Callers that fall open. `withLeaderLock` and the MCP OAuth refresh mutex catch a throw from `acquireLock` and run their work uncoordinated. If the SET landed, today the lock they hold keeps everyone else out while they run. Freeing it under them admits a second concurrent runner — for OAuth refresh that means two rotations of the same token and an `invalid_grant`. Callers whose lock value is not unique. The copilot chat lock keys on `streamId`, which is the client-supplied `userMessageId`. Two sends can carry the same value, so a compare-and-delete from a contender that timed out can match — and delete — the lock the active stream is holding. Reclaiming is therefore opt-in, and the option documents both preconditions it needs: a value unique to the holder, and a caller that does no work when acquisition throws. Default behavior is byte-for-byte what it was before. Opted in are the four cron/poll callers that satisfy both — webhook polling, resume polling, workspace-events polling, and Teams subscription renewal. Each mints its value with `generateShortId()` and returns 5xx rather than proceeding when acquisition throws. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 9ee1b81 commit efea9de

9 files changed

Lines changed: 123 additions & 10 deletions

File tree

apps/sim/app/api/cron/renew-subscriptions/route.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ describe('Teams subscription renewal route (fire-and-forget)', () => {
6363
expect(redisConfigMockFns.mockAcquireLock).toHaveBeenCalledWith(
6464
'teams-subscription-renewal-lock',
6565
expect.any(String),
66-
expect.any(Number)
66+
expect.any(Number),
67+
{ reclaimOnFailure: true }
6768
)
6869

6970
await flushMicrotasks()

apps/sim/app/api/cron/renew-subscriptions/route.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,9 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
252252
}
253253

254254
const lockValue = generateShortId()
255-
const locked = await acquireLock(LOCK_KEY, lockValue, LOCK_TTL_SECONDS)
255+
const locked = await acquireLock(LOCK_KEY, lockValue, LOCK_TTL_SECONDS, {
256+
reclaimOnFailure: true,
257+
})
256258
if (!locked) {
257259
return NextResponse.json(
258260
{ success: true, message: 'Renewal already in progress – skipped', status: 'skip' },

apps/sim/app/api/resume/poll/route.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
6262
const authError = verifyCronAuth(request, 'Time-pause resume poll')
6363
if (authError) return authError
6464

65-
const lockAcquired = await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS)
65+
const lockAcquired = await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS, {
66+
reclaimOnFailure: true,
67+
})
6668
if (!lockAcquired) {
6769
return NextResponse.json(
6870
{ success: true, message: 'Polling already in progress – skipped', requestId },

apps/sim/app/api/webhooks/poll/[provider]/route.test.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,13 @@ describe('webhook polling route (fire-and-forget)', () => {
6666
expect(response.status).toBe(202)
6767
const data = await response.json()
6868
expect(data).toMatchObject({ status: 'started' })
69+
// `reclaimOnFailure` is what stops a timed-out acquire from leaving a lock
70+
// no one owns, which skipped every poll until the TTL expired.
6971
expect(redisConfigMockFns.mockAcquireLock).toHaveBeenCalledWith(
7072
'gmail-polling-lock',
7173
expect.any(String),
72-
expect.any(Number)
74+
expect.any(Number),
75+
{ reclaimOnFailure: true }
7376
)
7477

7578
await flushMicrotasks()

apps/sim/app/api/webhooks/poll/[provider]/route.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ export const GET = withRouteHandler(
4040

4141
const LOCK_KEY = `${provider}-polling-lock`
4242
const lockValue = requestId
43-
const locked = await acquireLock(LOCK_KEY, lockValue, LOCK_TTL_SECONDS)
43+
const locked = await acquireLock(LOCK_KEY, lockValue, LOCK_TTL_SECONDS, {
44+
reclaimOnFailure: true,
45+
})
4446
if (!locked) {
4547
return NextResponse.json(
4648
{

apps/sim/app/api/workspace-events/poll/route.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ describe('workspace events polling route (fire-and-forget)', () => {
6262
expect(redisConfigMockFns.mockAcquireLock).toHaveBeenCalledWith(
6363
'workspace-events-no-activity-poll-lock',
6464
expect.any(String),
65-
expect.any(Number)
65+
expect.any(Number),
66+
{ reclaimOnFailure: true }
6667
)
6768

6869
await flushMicrotasks()

apps/sim/app/api/workspace-events/poll/route.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
3131
return authError
3232
}
3333

34-
const lockAcquired = await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS)
34+
const lockAcquired = await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS, {
35+
reclaimOnFailure: true,
36+
})
3537

3638
if (!lockAcquired) {
3739
return NextResponse.json(

apps/sim/lib/core/config/redis.test.ts

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ vi.mock('ioredis', () => ({
2525
}))
2626

2727
import {
28+
acquireLock,
2829
closeRedisConnection,
2930
extendLock,
3031
getRedisClient,
@@ -208,6 +209,72 @@ describe('redis config', () => {
208209
})
209210
})
210211

212+
describe('acquireLock', () => {
213+
const lockKey = 'outlook-polling-lock'
214+
const value = 'req-abc'
215+
const ttlSeconds = 180
216+
217+
it('returns true when SET NX takes the lock', async () => {
218+
mockRedisInstance.set.mockResolvedValueOnce('OK')
219+
220+
expect(await acquireLock(lockKey, value, ttlSeconds)).toBe(true)
221+
expect(mockRedisInstance.set).toHaveBeenCalledWith(lockKey, value, 'EX', ttlSeconds, 'NX')
222+
expect(mockRedisInstance.eval).not.toHaveBeenCalled()
223+
})
224+
225+
it('returns false without cleanup when the lock is already held', async () => {
226+
mockRedisInstance.set.mockResolvedValueOnce(null)
227+
228+
expect(await acquireLock(lockKey, value, ttlSeconds)).toBe(false)
229+
expect(mockRedisInstance.eval).not.toHaveBeenCalled()
230+
})
231+
232+
it('reclaims the lock it may have taken when SET times out and reclaim is on', async () => {
233+
// ioredis gives up client-side on `commandTimeout` while the command can
234+
// still land, so the lock would otherwise be held by a caller that never
235+
// learned it won and never releases it.
236+
mockRedisInstance.set.mockRejectedValueOnce(new Error('Command timed out'))
237+
mockRedisInstance.eval.mockResolvedValueOnce(1)
238+
239+
await expect(
240+
acquireLock(lockKey, value, ttlSeconds, { reclaimOnFailure: true })
241+
).rejects.toThrow('Command timed out')
242+
expect(mockRedisInstance.eval).toHaveBeenCalledWith(
243+
expect.stringContaining('del'),
244+
1,
245+
lockKey,
246+
value
247+
)
248+
})
249+
250+
it('leaves the lock alone by default so a fall-open caller keeps holding it', async () => {
251+
// `withLeaderLock` and the MCP OAuth mutex run their work anyway when
252+
// acquisition throws. Freeing the lock under them would let a second
253+
// runner in alongside, so reclaiming has to stay opt-in.
254+
mockRedisInstance.set.mockRejectedValueOnce(new Error('Command timed out'))
255+
256+
await expect(acquireLock(lockKey, value, ttlSeconds)).rejects.toThrow('Command timed out')
257+
expect(mockRedisInstance.eval).not.toHaveBeenCalled()
258+
})
259+
260+
it('surfaces the original failure when the cleanup also fails', async () => {
261+
mockRedisInstance.set.mockRejectedValueOnce(new Error('Command timed out'))
262+
mockRedisInstance.eval.mockRejectedValueOnce(new Error('Connection is closed'))
263+
264+
// The TTL stays the backstop; the caller must still see why acquiring failed.
265+
await expect(
266+
acquireLock(lockKey, value, ttlSeconds, { reclaimOnFailure: true })
267+
).rejects.toThrow('Command timed out')
268+
})
269+
270+
it('returns true as a no-op when the cache capability selects the database', async () => {
271+
mockEnv.REDIS_URL = undefined
272+
273+
expect(await acquireLock(lockKey, value, ttlSeconds)).toBe(true)
274+
expect(mockRedisInstance.set).not.toHaveBeenCalled()
275+
})
276+
})
277+
211278
describe('capability validation', () => {
212279
it('rejects a non-Redis URL before constructing a client', () => {
213280
mockEnv.REDIS_URL = 'https://cache.example.com'

apps/sim/lib/core/config/redis.ts

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,18 +235,51 @@ end
235235
* single-replica deployments to function without Redis. In multi-replica
236236
* deployments without Redis, the idempotency layer prevents duplicate processing.
237237
*/
238+
export interface AcquireLockOptions {
239+
/**
240+
* Release the lock this call may have taken when the SET itself rejects.
241+
*
242+
* A rejected SET does not mean the server declined it: `commandTimeout` gives
243+
* up client-side while the command can still reach Redis and take the lock,
244+
* leaving it held by a caller that never learned it won and so never releases
245+
* it. Every contender then skips until the TTL expires.
246+
*
247+
* Only opt in when BOTH hold, because the reclaim is unsafe otherwise:
248+
*
249+
* 1. `value` is unique to this holder. A value two holders can share — the
250+
* copilot chat lock keys on a client-supplied `userMessageId` — makes the
251+
* compare-and-delete match a lock another holder is actively using.
252+
* 2. A throw means the caller does no work. One that falls open and runs
253+
* anyway (`withLeaderLock`, the MCP OAuth refresh mutex) would keep running
254+
* while this frees its lock, admitting a second concurrent runner.
255+
*/
256+
reclaimOnFailure?: boolean
257+
}
258+
238259
export async function acquireLock(
239260
lockKey: string,
240261
value: string,
241-
expirySeconds: number
262+
expirySeconds: number,
263+
options?: AcquireLockOptions
242264
): Promise<boolean> {
243265
const redis = getRedisClient()
244266
if (!redis) {
245267
return true // No-op when Redis unavailable; idempotency layer handles duplicates
246268
}
247269

248-
const result = await redis.set(lockKey, value, 'EX', expirySeconds, 'NX')
249-
return result === 'OK'
270+
try {
271+
const result = await redis.set(lockKey, value, 'EX', expirySeconds, 'NX')
272+
return result === 'OK'
273+
} catch (error) {
274+
// Best effort, and the same compare-and-delete `releaseLock` runs on the
275+
// success path: it deletes only while `value` still owns the key. If Redis
276+
// is still unreachable the TTL stays the backstop, which is the behavior
277+
// without this cleanup.
278+
if (options?.reclaimOnFailure) {
279+
await releaseLock(lockKey, value).catch(() => {})
280+
}
281+
throw error
282+
}
250283
}
251284

252285
/**

0 commit comments

Comments
 (0)