Skip to content

Commit ceecf6f

Browse files
authored
fix(polling): hold IMAP's cursor at a refused email and tighten polling test fidelity (#10747)
* fix(polling): hold IMAP's cursor at a refused email and tighten polling test fidelity * fix(polling): save the exact first-poll IMAP search window when a refusal holds mail
1 parent 0fe5fbb commit ceecf6f

5 files changed

Lines changed: 157 additions & 20 deletions

File tree

‎apps/sim/lib/webhooks/polling/auto-disable.integration.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,9 @@ describe('markWebhookSuccess', () => {
112112

113113
await markWebhookSuccess(id, logger)
114114

115-
expect(await readWebhook(id)).toMatchObject({ failedCount: 0, providerConfig: CONFIG })
115+
const row = await readWebhook(id)
116+
expect(row.failedCount).toBe(0)
117+
expect(row.providerConfig).toEqual(CONFIG)
116118
})
117119

118120
it('resets the count of a webhook with no config without touching it', async () => {

‎apps/sim/lib/webhooks/polling/imap.test.ts‎

Lines changed: 94 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -116,27 +116,57 @@ describe('IMAP runtime polling policy', () => {
116116
})
117117

118118
describe('IMAP admission refusal', () => {
119-
const { mockUpdateWebhookProviderConfig } = webhooksPollingUtilsMockFns
119+
const { mockUpdateWebhookProviderConfig, mockMarkWebhookSuccess } = webhooksPollingUtilsMockFns
120120
const mockProcessEvent = webhooksProcessorMockFns.mockProcessPolledWebhookEvent
121121

122-
/** A mailbox holding two new messages, fetched through the client `createSecureImapClient` returns. */
123-
function mailboxWithTwoMessages() {
122+
/** Mailboxes holding new messages, served by the client `createSecureImapClient` returns. */
123+
function mailboxesWith(uidsByMailbox: Record<string, number[]>) {
124+
let open = ''
124125
mockHasImapEnvironmentReferences.mockReturnValue(false)
125126
mockCreateSecureImapClient.mockResolvedValue({
126127
connect: vi.fn(async () => {}),
127128
logout: vi.fn(async () => {}),
128-
mailboxOpen: vi.fn(async () => ({ uidValidity: 7 })),
129-
search: vi.fn(async () => [41, 42]),
129+
mailboxOpen: vi.fn(async (path: string) => {
130+
open = path
131+
return { uidValidity: 7 }
132+
}),
133+
search: vi.fn(async () => uidsByMailbox[open]),
130134
fetch: async function* () {
131-
for (const uid of [41, 42]) {
135+
for (const uid of uidsByMailbox[open]) {
132136
yield { uid, envelope: { subject: `message ${uid}` }, bodyStructure: {} }
133137
}
134138
},
135139
})
136140
}
137141

142+
const mailboxWith = (uids: number[]) => mailboxesWith({ INBOX: uids })
143+
144+
const usageLimitRefusal = {
145+
success: false,
146+
statusCode: 402,
147+
code: 'USAGE_LIMIT_EXCEEDED',
148+
error: 'Usage limit reached.',
149+
}
150+
151+
function poll(providerConfig: Record<string, unknown>) {
152+
return imapPollingHandler.pollWebhook({
153+
webhookData: {
154+
id: 'webhook-1',
155+
providerConfig: {
156+
host: 'imap.example.com',
157+
username: 'user',
158+
password: 'secret',
159+
...providerConfig,
160+
},
161+
} as never,
162+
workflowData: { id: 'workflow-1', workspaceId: 'workspace-1' } as never,
163+
requestId: 'request-1',
164+
logger: mockLogger as never,
165+
})
166+
}
167+
138168
it('keeps the UIDs when admission capacity refuses mail after earlier mail in the batch succeeded', async () => {
139-
mailboxWithTwoMessages()
169+
mailboxWith([41, 42])
140170
mockProcessEvent.mockResolvedValueOnce({ success: true }).mockResolvedValueOnce({
141171
success: false,
142172
statusCode: 429,
@@ -165,4 +195,61 @@ describe('IMAP admission refusal', () => {
165195
expect(mockMarkWebhookFailed).not.toHaveBeenCalled()
166196
expect(mockUpdateWebhookProviderConfig).not.toHaveBeenCalled()
167197
})
198+
it('saves the UIDs up to the email a usage-limit refusal stopped at, after earlier mail succeeded', async () => {
199+
const lastCheckedTimestamp = '2026-12-01T00:00:00.000Z'
200+
mailboxWith([41, 42, 43])
201+
mockProcessEvent
202+
.mockResolvedValueOnce({ success: true })
203+
.mockResolvedValueOnce(usageLimitRefusal)
204+
205+
const result = await poll({ lastProcessedUidByMailbox: { INBOX: 40 }, lastCheckedTimestamp })
206+
207+
expect(result).toBe('skipped')
208+
expect(mockProcessEvent).toHaveBeenCalledTimes(2)
209+
expect(mockMarkWebhookFailed).not.toHaveBeenCalled()
210+
expect(mockMarkWebhookSuccess).toHaveBeenCalledWith('webhook-1', mockLogger)
211+
expect(mockUpdateWebhookProviderConfig).toHaveBeenCalledExactlyOnceWith(
212+
'webhook-1',
213+
expect.objectContaining({ lastProcessedUidByMailbox: { INBOX: 41 }, lastCheckedTimestamp }),
214+
expect.anything()
215+
)
216+
})
217+
218+
it('keeps a later mailbox where it was when the refusal lands on its first email', async () => {
219+
mailboxesWith({ INBOX: [41, 42], Archive: [7, 8] })
220+
mockProcessEvent
221+
.mockResolvedValueOnce({ success: true })
222+
.mockResolvedValueOnce({ success: true })
223+
.mockResolvedValueOnce(usageLimitRefusal)
224+
225+
const result = await poll({
226+
mailbox: ['INBOX', 'Archive'],
227+
lastProcessedUidByMailbox: { INBOX: 40, Archive: 6 },
228+
lastCheckedTimestamp: '2026-12-01T00:00:00.000Z',
229+
})
230+
231+
expect(result).toBe('skipped')
232+
expect(mockUpdateWebhookProviderConfig).toHaveBeenCalledExactlyOnceWith(
233+
'webhook-1',
234+
expect.objectContaining({ lastProcessedUidByMailbox: { INBOX: 42, Archive: 6 } }),
235+
expect.anything()
236+
)
237+
})
238+
239+
it('saves the exact first-poll search window while a refusal holds its mail', async () => {
240+
mailboxWith([41, 42])
241+
mockProcessEvent
242+
.mockResolvedValueOnce({ success: true })
243+
.mockResolvedValueOnce(usageLimitRefusal)
244+
245+
await poll({})
246+
247+
const client = await mockCreateSecureImapClient.mock.results[0].value
248+
const [criteria] = client.search.mock.calls[0] as [{ since: Date }]
249+
const [, saved] = mockUpdateWebhookProviderConfig.mock.calls[0]
250+
const savedMs = Date.parse(
251+
String((saved as { lastCheckedTimestamp?: string }).lastCheckedTimestamp)
252+
)
253+
expect(savedMs - 60_000).toBe(criteria.since.getTime())
254+
})
168255
})

‎apps/sim/lib/webhooks/polling/imap.ts‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ import {
2727
} from '@/lib/webhooks/polling/utils'
2828
import { processPolledWebhookEvent } from '@/lib/webhooks/processor'
2929

30+
/** How far back the first poll of a mailbox (with no stored check time) searches. */
31+
const FIRST_POLL_LOOKBACK_MS = 24 * 60 * 60 * 1000
32+
/** How far before the stored check time each later search starts. */
33+
const SINCE_BUFFER_MS = 60_000
34+
3035
interface ImapWebhookConfig {
3136
host: string
3237
port: number
@@ -142,6 +147,7 @@ export const imapPollingHandler: PollingProviderHandler = {
142147
await client.connect()
143148

144149
const result = await fetchNewEmails(client, config, logger)
150+
const { firstPollSince } = result
145151
emails = result.emails
146152
latestUidByMailbox = result.latestUidByMailbox
147153
uidValidityByMailbox = result.uidValidityByMailbox
@@ -165,7 +171,7 @@ export const imapPollingHandler: PollingProviderHandler = {
165171

166172
logger.info(`Found ${emails.length} new emails for webhook ${webhookId}`)
167173

168-
const { processedCount, failedCount } = await processEmails(
174+
const { processedCount, failedCount, refusedAt } = await processEmails(
169175
emails,
170176
webhookData,
171177
workflowData,
@@ -175,6 +181,27 @@ export const imapPollingHandler: PollingProviderHandler = {
175181
logger
176182
)
177183

184+
if (refusedAt !== undefined) {
185+
// A refusal that holds until a person acts, after earlier emails completed: save each
186+
// mailbox's cursor right before the refused email, and pin the `since` window this
187+
// search used so it still reaches that email once the refusal lifts.
188+
await updateImapState(
189+
webhookId,
190+
highestUidByMailbox(emails.slice(0, refusedAt)),
191+
config.lastCheckedTimestamp ??
192+
new Date(firstPollSince.getTime() + SINCE_BUFFER_MS).toISOString(),
193+
config,
194+
logger,
195+
uidValidityByMailbox
196+
)
197+
await client.logout()
198+
await markWebhookSuccess(webhookId, logger)
199+
logger.info('Execution admission refused the webhook; left its items for a later poll', {
200+
webhookId,
201+
})
202+
return 'skipped'
203+
}
204+
178205
await updateImapState(
179206
webhookId,
180207
latestUidByMailbox,
@@ -213,6 +240,15 @@ export const imapPollingHandler: PollingProviderHandler = {
213240
},
214241
}
215242

243+
/** The highest UID among `emails` in each mailbox they come from. */
244+
function highestUidByMailbox(emails: ReadonlyArray<{ uid: number; mailboxPath: string }>) {
245+
const highest: Record<string, number> = {}
246+
for (const { uid, mailboxPath } of emails) {
247+
highest[mailboxPath] = Math.max(uid, highest[mailboxPath] ?? 0)
248+
}
249+
return highest
250+
}
251+
216252
async function updateImapState(
217253
webhookId: string,
218254
uidByMailbox: Record<string, number>,
@@ -275,10 +311,13 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
275311

276312
const maxEmails = config.maxEmailsPerPoll || 25
277313
let totalEmailsCollected = 0
314+
/** One window for every mailbox, so a poll held by a refusal can save exactly what it searched. */
315+
const firstPollSince = new Date(Date.now() - FIRST_POLL_LOOKBACK_MS)
278316

279317
for (const mailboxPath of mailboxes) {
280318
if (totalEmailsCollected >= maxEmails) break
281319

320+
const mailboxEmails: typeof emails = []
282321
try {
283322
const mailbox = await client.mailboxOpen(mailboxPath)
284323

@@ -314,11 +353,10 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
314353

315354
if (config.lastCheckedTimestamp) {
316355
const lastChecked = new Date(config.lastCheckedTimestamp)
317-
const bufferTime = new Date(lastChecked.getTime() - 60000)
356+
const bufferTime = new Date(lastChecked.getTime() - SINCE_BUFFER_MS)
318357
searchCriteria = { ...searchCriteria, since: bufferTime }
319358
} else {
320-
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000)
321-
searchCriteria = { ...searchCriteria, since: oneDayAgo }
359+
searchCriteria = { ...searchCriteria, since: firstPollSince }
322360
}
323361

324362
let messageUids: number[] = []
@@ -340,7 +378,7 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
340378
{ uid: true, envelope: true, bodyStructure: true, source: true },
341379
{ uid: true }
342380
)) {
343-
emails.push({
381+
mailboxEmails.push({
344382
uid: msg.uid,
345383
mailboxPath,
346384
envelope: msg.envelope,
@@ -355,9 +393,11 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
355393
} catch {
356394
logger.warn(`Error processing mailbox ${mailboxPath}`)
357395
}
396+
// Ascending UIDs, so a batch stopped by a refusal can save its cursor right before that email.
397+
emails.push(...mailboxEmails.sort((a, b) => a.uid - b.uid))
358398
}
359399

360-
return { emails, latestUidByMailbox, uidValidityByMailbox }
400+
return { emails, latestUidByMailbox, uidValidityByMailbox, firstPollSince }
361401
}
362402

363403
function getMailboxesToCheck(config: ImapWebhookConfig): string[] {
@@ -516,7 +556,7 @@ async function processEmails(
516556
const lockState: { lock: MailboxLockObject | null } = { lock: null }
517557

518558
try {
519-
for (const email of emails) {
559+
for (const [index, email] of emails.entries()) {
520560
try {
521561
await pollingIdempotency.executeWithIdempotency(
522562
'imap',
@@ -609,7 +649,10 @@ async function processEmails(
609649
processedCount++
610650
} catch (error) {
611651
if (holdsCursorPastCompletedItems(error)) throw error
612-
if (isUncountedPollFailure(error) && processedCount === 0) throw error
652+
if (isUncountedPollFailure(error)) {
653+
if (processedCount === 0) throw error
654+
return { processedCount, failedCount, refusedAt: index }
655+
}
613656
logger.error(`Error processing email ${email.uid}`)
614657
failedCount++
615658
}
@@ -622,5 +665,5 @@ async function processEmails(
622665
}
623666
}
624667

625-
return { processedCount, failedCount }
668+
return { processedCount, failedCount, refusedAt: undefined }
626669
}

‎apps/sim/lib/webhooks/polling/utils.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ export function isUncountedPollFailure(error: unknown): boolean {
9797
* after earlier items completed, leaving its cursor for the next poll. Only for a stop that clears
9898
* within minutes: the completed items' duplicate checks then still hold when the next poll fetches
9999
* them again. A refusal that holds until a person acts can outlast those checks, so after a
100-
* completed item it is counted as an item failure instead.
100+
* completed item the poller keeps only what it can prove complete: IMAP saves its UIDs up to
101+
* the refused email, and Gmail and Outlook, whose cursors cannot stop mid-batch, count it as an
102+
* item failure.
101103
*/
102104
export function holdsCursorPastCompletedItems(error: unknown): boolean {
103105
return (

‎packages/testing/src/mocks/webhooks-polling-utils.mock.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,15 @@ class PollAdmissionRefusedError extends Error {
2525

2626
/**
2727
* Faithful copy of the production egress-outage test (`asOrchestrationError(error)?.code ===
28-
* 'unavailable'`): an `OutboundRoutingError` other than `MISSING_SCOPE`, or an
29-
* `OrchestrationError` coded `unavailable`, anywhere in the cause chain.
28+
* 'unavailable'`): an `OutboundAdmissionError`, an `OutboundRoutingError` other than
29+
* `MISSING_SCOPE`, or an `OrchestrationError` coded `unavailable`, anywhere in the cause chain
30+
* before a `PayloadSizeLimitError`, which classifies the error first.
3031
*/
3132
function isSimOutage(error: unknown): boolean {
3233
let current: unknown = error
3334
while (current instanceof Error) {
35+
if (current.name === 'OutboundAdmissionError') return true
36+
if (current.name === 'PayloadSizeLimitError') return false
3437
if (current.name === 'OutboundRoutingError') {
3538
if ((current as Error & { code?: string }).code !== 'MISSING_SCOPE') return true
3639
}

0 commit comments

Comments
 (0)