Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions apps/sim/lib/concurrency/__tests__/leader-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,30 @@ describe('withLeaderLock', () => {
expect(onFollower.mock.calls.length).toBeGreaterThanOrEqual(2)
})

it('follower does a final read after timeout to catch a just-finished leader', async () => {
redisConfigMockFns.mockAcquireLock.mockResolvedValueOnce(false)

// pollInterval=5, maxWait=9 → loop exits after 2 in-loop polls (T+5, T+10);
// the third call (polls=3) is the post-deadline last-chance read.
let polls = 0
const onFollower = vi.fn(async () => {
polls += 1
if (polls <= 2) return null
return 'late-leader'
})

const result = await withLeaderLock<string>({
key: 'k',
pollIntervalMs: 5,
maxWaitMs: 9,
onLeader: async () => 'should-not-run',
onFollower,
})

expect(result).toBe('late-leader')
expect(onFollower).toHaveBeenCalledTimes(3)
})
Comment thread
waleedlatif1 marked this conversation as resolved.

it('follower returns null after timeout', async () => {
redisConfigMockFns.mockAcquireLock.mockResolvedValueOnce(false)

Expand Down
4 changes: 4 additions & 0 deletions apps/sim/lib/concurrency/leader-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ export async function withLeaderLock<T>(opts: LeaderLockOptions<T>): Promise<T |
if (value !== null) return value
}

// The leader may have persisted between our final poll and now; one last check.
const lastChance = await onFollower()
if (lastChance !== null) return lastChance

logger.warn('Follower timed out waiting for leader', { key, maxWaitMs })
return null
}
Loading